text:
Regular Expression Syntax and Semantics
=======================================

This document describes the syntax and semantics of the regular expressions parsed by Thexa's `re` and `cs` quasi-quoters. A general understanding of regular expressions is assumed, and indeed the syntax is largely a subset of the syntax used by typical regex libraries.

Characters
----------

In this document, *character* refers to a single Unicode *code point* (the same as a `Char` in Haskell). This is important because some sequences of code points (known as *grapheme clusters*) may be rendered as a single glyph, making them look like a single character even though they are comprised of multiple code points (for example, emojis). If this sort of construct is used within a character set, it becomes confusing because, although your editor may render a single glyph, multiple code points will actually be added to the character set.

Additionally, note that no normalization (in the sense of Unicode normalization) is done on the input, so if you want to match multiple grapheme clusters that are equivalent under normalization, you must do that manually.

Whitespace
----------

All whitespace in a regular expression is ignored, with the exception of an escaped space character (see **CharEscape**) or when included in strings (see **RegexString**). This includes all characters in the Unicode "Space Separator" Category, as well as the ASCII control characters for tab (`0x9`), newline (`0xA`), vertical tab (`0xB`), form feed (`0xC`), and carriage return (`0xD`).

Regular Expressions
-------------------

> **Regex** :
>>  ( _RegexAtom_ _RegexQuantifier_? )\* ( `|` _Regex_ )?
>
> **RegexAtom** :
>>  `(` _Regex_ `)` | `[` _CharSet_ `]` | _RegexChar_ |
>>  _RegexString_ | _UnicodePropertyEscape_ | _RegexSplice_ | _CharSetSplice_
>
> **RegexChar** :
>>  _RegexEscape_ | \[^`(){}[]*+?|"\`\]

At its most basic, a regex matches a particular sequence of characters; e.g., the regex `abc` matches the string `abc`. Any non-whitespace character without special meaning in the regex syntax is interpreted as itself. The list of characters with special meaning is given in the second pattern of **RegexChar**.

A regex can be empty, in which case it will only match the empty string. Or, if you consider a regex in terms of matching a subset of a string, it will always match immediately without consuming any input.

Regex *alternation* is introduced by separating two regexes with the `|` character, in which case the regex will match if and only if at least one of the alternatives matches; e.g., the regex `ab|cd` will match the string `ab` and the string `cd`.

It is also possible to match any character that is contained in a *character set*. This is done using the **CharSet** syntax enclosed in square brackets.

Enclosing a regex in parentheses is useful to affect the way it is parsed (see the section on quantifiers), but otherwise has no semantic meaning for the enclosed regex.

> **RegexString** :
>>  `"` ( \[^`"\`\] | _CharEscape_ | `\"` )\* `"`

A string enclosed in double-quotes can be used to match a literal string of characters without escaping special characters or ignoring whitespace. The only characters which must be escaped within a string are `\` and `"`.

> **RegexQuantifier** :
>>  `*` | `+` | `?` | _RegexRepeater_
>
> **RegexRepeater** :
>>  `{` ( _Number_ | _Number_ `,` _Number_ | _Number_ `,` | `,` _Number_ ) `}`
>
> **Number** :
>>  \[`0`-`9`\]\+

A *quantifier* can be used as a suffix to allow a regex to match multiple times. Note that the quantifier only applies to the previous **RegexAtom**, not the entire preceding regex. So `ab+` matches `abb` but not `abab`. To apply it to a larger regex, simply enclose the regex in parentheses or use a double-quoted string.

The most general form of the quantifier is the **RegexRepeater** enclosed in curly braces:

- `{n}`: matches exactly `n` repetitions
- `{n,}`: matches at least `n` repetitions
- `{n,m}`: matches at least `n` repetitions and at most `m` repetitions (it is an error if `m < n`)
- `{,m}`: equivalent to `{0,m}`

The other quantifiers can be expressed in terms of the general repeater, and are provided for convenience:

- `*`: equivalent to `{0,}`
- `+`: equivalent to `{1,}`
- `?`: equivalent to `{0,1}`

Character Sets
--------------

> **CharSet** :
>>  `^`? _CharSetAtom_\* | _CharSetAtom_\+ _CharSetDiff_?
>
> **CharSetAtom** :
>>  `[` _CharSet_ `]` | _CharSetRange_ | _CharSetChar_ | _UnicodePropertyEscape_ | _CharSetSplice_
>
> **CharSetChar** :
>>  _CharSetEscape_ | \[^`[]^-\`\]

A *character set* is exactly what it sounds like: a set of characters. A charset matches a character if and only if that character is in the set. Syntactically, a charset is written as a sequence of characters; each character in the sequence is added to the set. So `[ab]` matches `a` or `b` but not `c`.

Characters which have special meaning within a charset must be escaped; the list of these characters is given in the second pattern of **CharSetChar**. Note that characters that are special within a regex but not special within a charset do not have to be escaped (and in fact cannot be escaped).

Like a regex, a charset can be empty. However, an empty charset doesn't match any characters, so a regex containing an empty charset can never match any string. Since this is almost certainly never intended, the library will report an error if an empty charset is used in a regex.

Charsets can be nested using square brackets. This is rarely necessary, but potentially useful for readability or when using the `^` operator.

A charset is negated when it begins with `^`. In this case, the charset is the set complement of the charset following the `^`, e.g. `[^ab]` matches any character *except* for `a` and `b`. Since the subsequent charset can be empty, `[^]` can be used to match any character.

> **CharSetRange** :
>>  _CharSetChar_ `-` _CharSetChar_

Ranges can be used to represent a set of contiguous characters, e.g. `[a-c]` will match `a`, `b`, or `c`. This works by taking the integer code points of the start and end characters, and including every code point in between them, so to avoid confusion it is best to only use this for well known character ranges (like `a-z` or `0-9`) or with explicit code point escapes (like `\x00-\xFF`).

> **CharSetDiff** :
>>  `^` _CharSetAtom_\*

Charsets also support set difference using the `^` operator to separate two charsets. Such a charset matches characters that are in the first set but not in the second, e.g. `[[a-d] ^ b]` matches `a`, `c`, and `d`.

Note that to avoid ambiguity, it is not allowed to combine multiple `^` operations in a single charset, like in `[^ x ^ y ^ z]`. However, multiple uses are allowed if they are explicitly nested, like in `[^[x ^ [y ^ z]]]`.

Escaped Characters
------------------

> **RegexEscape** :
>>  _CharEscape_ | `\` \[`(){}[]*+?|" `\]
>
> **CharSetEscape** :
>>  _CharEscape_ | `\` \[`[]^- `\]

Characters with special meaning can be escaped by putting `\` in front of them. Escapes are parsed as a single token, so the `\` and the escaped character cannot be separated by whitespace. Note that the space character (`0x20`) can also be escaped in order to match a space character that would otherwise be ignored. Other whitespace characters must be escaped using a **CharEscape**.

> **CharEscape** :
>>  `\n` | `\t` | `\r` | `\f` | `\v` | `\0` | `\\` |\
>>   _ControlCodeEscape_ | _AsciiEscape_ | _UnicodeEscape_

These special escapes map to particular characters:

- `\0`: null character (`0x0`)
- `\t`: tab (`0x9`)
- `\n`: newline (`0xA`)
- `\v`: vertical tab (`0xB`)
- `\f`: form feed (`0xC`)
- `\r`: carriage return (`0xD`)
- `\\`: backslash (`0x5C`)

> **ControlCodeEscape** :
>>  `\x{` _AsciiControlCode_ `}`
>
> **AsciiControlCode** :
>>  `NUL` | `SOH` | `STX` | `ETX` | `EOT` | `ENQ` | `ACK` | `BEL` | `BS` | `HT` | `LF` | \
>>  `VT` | `FF` | `CR` | `SO` | `SI` | `DLE` | `DC1` | `DC2` | `DC3` | `DC4` | `NAK` | \
>>  `SYN` | `ETB` | `CAN` | `EM` | `SUB` | `ESC` | `FS` | `GS` | `RS` | `US` | `DEL`

Any ASCII control code (code points `0x0`-`0x1F`, `0x7F`) can be escaped using the abbreviation of the control code between `\x{` and `}`. Note that there can be no whitespace in the `\x{` token, but whitespace is ignored between the braces as long as it comes before or after the **AsciiControlCode** token.

> **AsciiEscape** :
>>  `\x` _HexDigit_ _HexDigit_
>
> **UnicodeEscape** :
>>  `\u{` `0x`? _HexDigit_\+ `}`
>
> **HexDigit** :
>>  [`0`-`9` `a`-`f` `A`-`F`]

It is also possible to use an escape to explicitly specify a particular code point by number. The most general form of this is the **UnicodeEscape**, where a hexadecimal number between `\u{` and `}` is used to specify the numeric code point. This hexadecimal number can optionally start with `0x` for clarity, but it is interpreted as hexadecimal either way. It is an error if the number is larger than `0x10FFFF`, the maximum Unicode code point.

Similarly to the **ControlCodeEscape**, there can be no whitespace in the `\u{` token, but whitespace is ignored between the braces as long as it comes before or after the hexadecimal number.

A shorthand version of this is available for code points in the range `0x0`-`0xFF`. It uses `\x` followed by exactly two hexadecimal digits (this is parsed as a single token, so no whitespace is allowed within it). This is called an **AsciiEscape** because it has enough range to express any ASCII character (i.e., the Basic Latin block in Unicode), but it can also be used for characters in the Latin-1 Supplement block.

> **UnicodePropertyEscape** :
>>  `\p{` _UnicodeProperty_ `}`
>
> **UnicodeProperty** :
>>  [`a`-`z` `A`-`Z` `0`-`9` `_` `-`]\+

Entire sets of Unicode characters can be matched based on some property that they satisfy. The following properties are supported:

- **General_Category**: the property can be the name of a Unicode General Category. Both the long and abbreviated names from the [General Category Table](http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table) are supported. So to match characters in the Math Symbol category, you would write `\p{Math_Symbol}` or `\p{Sm}`. The specific code points for each category are taken from the [DerivedGeneralCategory](unicode/DerivedGeneralCategory.txt) file.

- **Script**: the property can be the name of a Unicode Script. So to match any Greek character, you would write `\p{Greek}`. The specific names and code points for each script are taken from the [Scripts](unicode/Scripts.txt) file.

- **Block**: the property can begin with `In` followed by the name of a Unicode Block, except with spaces replaced by underscores. So to match any character in the Latin-1 Supplement block, you would write `\p{InLatin-1_Supplement}`. The specific names and code points for each block are taken from the [Blocks](unicode/Blocks.txt) file.

Splices
-------

> **RegexSplice** :
>>  `{{` _HaskellVar_ `}}`
>
> **CharSetSplice** :
>>  `[:` _HaskellVar_ `:]`

When creating a lexer, it can be useful to factor out common portions of a regex into a Haskell variable. These variables can then be *spliced* into a regex or charset quasi-quote using this splicing syntax. The variable must be in scope at the site of the quasi-quote usage.

The **HaskellVar** production corresponds to the **qvarid** production in the [Haskell syntax reference](https://www.haskell.org/onlinereport/haskell2010/haskellch10.html), and can therefore be qualified with a module name.

The variable must have the type `Regex` or `CharSet` when used in a **RegexSplice** or **CharSetSplice**, respectively. Note that this means that a `CharSet` variable cannot be spliced directly into a regex using the **RegexSplice** syntax, but must use the **CharSetSplice** syntax. This syntax was chosen to resemble POSIX character classes in other regex syntaxes.

Note that the splice delimiters are parsed as a single token, and thus cannot have whitespace between the two characters. Additionally, in accordance with the **qvarid** production, there can be no whitespace inside the **HaskellVar**; all other whitespace between the delimiters is ignored as usual.

Finally, there is an ambiguity between the **CharSetSplice** syntax and a **CharSet** beginning with `:` (e.g., in `[:]`). This is resolved in favor of treating `[:` as a single token that begins a splice, so whitespace must be used to split up the token (like `[ : ]`).

Omissions
---------

As is typical for a lexer, these regexes are intended to be compiled into a simple finite state machine, and don't support more advanced regex features such as lookahead, lookbehind, capture groups, or backreferences. This includes other features that rely on lookahead or lookbehind, such as matching the beginning or end of a line with `^` or `$`, or using `\b` to match word boundaries.

There are also no built-in character classes such as `\s` or `[[:space:]]` to match whitespace characters. These are intended to be replaced by splices. Note also that `.` matches a literal period character rather than matching any character (or any non-newline character, depending on the regex engine settings). To match any character, use `[^]` (or `[^\n]`) instead.

Future Work
-----------

- Allow intersections in **CharSet** via the `&&` operator.

repository: syntheorem/thexa

repo_name: syntheorem/thexa


text:
- `nautilus_py_grammars` directory contains grammar files used in [nautilus](https://github.com/nautilus-fuzz/nautilus/tree/master/grammars)
- `nautilus_py_grammar_to_json.py` can convert a nautilus grammar file to the JSON grammar format used in this project

    ```bash
    python nautilus_py_grammar_to_json.py /path/to/input/file /path/to/output/file
    ```

## Known Issues/Tips

### Avoid Left Recursion

As mentioned in [Issue #28](https://github.com/AFLplusplus/Grammar-Mutator/issues/28), using left recursion in the grammar file results in the wrong alternative numbers, which are used as "rule_id" in the grammar mutator. Simple grammars with left recursion can be converted to right recursion. Please try to avoid using left recursion for now.

### Hex Character

As mentioned in [Issue #29](https://github.com/AFLplusplus/Grammar-Mutator/issues/29), JSON does not support hex escape like `\xNN` (see more details [here](https://www.json.org/json-en.html)). To embed hex characters in the grammar file, one workaround is to use the Unicode escape in JSON by converting `\xNN` to `\u00NN`.

An example, `test_hex.json`, is included in this directory:

```json
{
    "<start>": [["hex: ", "<hex>"]],
    "<hex>": [["\u0000"], ["\u0001"], ["\u0002"], ["\u0003"], ["\u0004"], ["\u0005"], ["\u0006"], ["\u0007"],
              ["\u0008"], ["\u0009"], ["\u000a"], ["\u000b"], ["\u000c"], ["\u000d"], ["\u000e"], ["\u000f"],
              ["\u0010"], ["\u0011"], ["\u0012"], ["\u0013"], ["\u0014"], ["\u0015"], ["\u0016"], ["\u0017"],
              ["\u0018"], ["\u0019"], ["\u001a"], ["\u001b"], ["\u001c"], ["\u001d"], ["\u001e"], ["\u001f"]]
}
```

Note that, this workaround only works for ASCII characters (i.e., `\u0000` \~ `\u00ff`). Otherwise, the grammar file cannot be processed.

References: [post1](https://www.utf8-chartable.de/), [post2](https://stackoverflow.com/a/59624562), [post3](https://stackoverflow.com/a/66601996), and [post4](https://stackoverflow.com/questions/66601743/python3-str-to-bytes-convertation-problem).

repository: AFLplusplus/Grammar-Mutator

branch_name: refs/heads/stable

extension: md

gha_language: Python

license_type: permissive

repo_name: AFLplusplus/Grammar-Mutator


text:
## Merging
Merge a branch into the current branch

    git merge <OTHERBRANCHNAME>

Merge multiple branches into the current branch

    git merge <BRANCHONE> <BRANCHTWO> <BRANCHTHREE> <BRANCHFOUR>

Or squashing all the commits into one, even if a fast forward:

    git merge <BRANCHONE> --squash

### Merge Conflicts
Merge conflict. How do we fix it? How do we continue?

    git add
    git merge --continue

Or aborting

    git merge --abort

Merge with rebase is a better option for maintaining linear history

Merge without commit

    git merge --no-commit

Using the `ours` strategy

    git merge -s ours <sombranch>

Using the `recursive` strategy with `ours` or `theirs` suboptions. [Details here](http://www.kernel.org/pub/software/scm/git/docs/git-merge.html).

    git merge -Xtheirs <sombranch>

## Visualizing Merges
Show the current branch's merge status

    git show-branch

Show every branch's merge status

    git show-branch --all

Show the contents further back the parent tree

    git show-branch --more=5

Show a max of 10 entries from no more than 1 hour ago for the master branch

    git show-branch --reflog="10,1 hour ago" --list master

Show three branches and their merge status

    git show-branch master feature1 feature2

### Understanding the branch visualizations
* The branch head that is pointed at by HEAD is prefixed with an asterisk * character
* Other heads are prefixed with a ! character.
* Following these N lines, one-line log for each commit is displayed, indented N places.
    * If a commit is on the I-th branch, the I-th indentation character shows a + sign
    * Otherwise it shows a space (does not exist here).
            * Merge commits are denoted by a - sign.

## Rebase
Linearize the branch commits. Rebranches at the latest <source branch name> and replays committed branch work on top of that.

    git rebase <source branch name>

Or perform the rebase interactively, where you can change the order of the commits

    git rebase -i <branchname>

If conflicts occur:

    git add
    git rebase --continue

Or if you want to bail out, a similar command to aborting a merge:

    git rebase --abort

You can squash multiple commits into one commit with the interactive rebase. Simple mark a commit as squashed.

Commands:

    p, pick = use commit
    e, edit = use commit, but stop for amending
    s, squash = use commit, but meld into previous commit
    Or if you remove a line, that commit will be excluded from the rebase.

## Rerere
If you merge a branch often, you don't want to keep telling Git how to merge it every time you merge. With rerere enabled (just an option switch), it will remember your resolutions and use them next time to minimize your effort.

    git config --global rerere.enabled 1

## External Merge Tools
Setup diff in `~/.gitconfig` global configuration file:

    #[diff]
    #	tool = adifftool
    #	external = git-difftool--helper

or

    [difftool "adifftool"]
    	cmd = araxis-difftool.sh \"$LOCAL\" \"$REMOTE\" \"$MERGED\"
    [difftool]
    	prompt = false

    #Automatically do all merges with this mergetool
    [merge]
    	tool = amergetool
    [mergetool "amergetool"]
    	cmd = araxis-mergetool.sh \"$PWD/$LOCAL\" \"$PWD/$BASE\" \"$PWD/$REMOTE\" \"$PWD/$MERGED\"
    [mergetool]
    	prompt = false

Using Araxis for diffing

    git difftool HEAD HEAD^ -- test2.txt

repository: begriffs/git-workshop

branch_name: refs/heads/master

repo_name: begriffs/git-workshop


text:
There are struct tags you can use for you input.

* `block`: Represents a unit of your block like `acl`, `sub`, etc...
* `label`: The label of your block.
* `flat`: Represents a expression field
* `comment`: Get comments
* `attr`: (Default) Attribute of your block

## Releases

Release tag will be based on [Semantic Versioning 2.0.0](https://semver.org/).
See the [CHANGELOGS.md](./CHANGELOGS.md)

## How to Contribute

I am always welcome for any contributions.

* Raise a Issue.
* Create a PR.

Simple:)

## License

go-vcl is released under the MIT license.
© 2019 KeisukeYamashita.

## Author

* [KeisukeYamashita](https://github.com/KeisukeYamashita)

<!-- badge links -->

[dependabot]: https://dependabot.com
[dependabot-badge]: https://badgen.net/badge/icon/Dependabot?icon=dependabot&label&color=blue

[license]: LICENSE
[license-badge]: https://img.shields.io/badge/license-Apache%202.0-%23E93424

[godoc]: https://godoc.org/github.com/KeisukeYamashita/go-vcl
[godoc-badge]: https://img.shields.io/badge/godoc.org-reference-blue.svg

[go-report-card]: https://goreportcard.com/report/github.com/KeisukeYamashita/go-vcl
[go-report-card-badge]: https://goreportcard.com/badge/github.com/KeisukeYamashita/go-vcl

[deepsource]: https://deepsource.io/gh/KeisukeYamashita/go-vcl/?ref=repository-badge
[deepsource-badge]: https://static.deepsource.io/deepsource-badge-light.svg

[github-actions]: https://github.com/KeisukeYamashita/go-vcl/actions
[github-actions-badge]: https://github.com/KeisukeYamashita/go-vcl/workflows/Test/badge.svg

[golangci]: https://golangci.com/r/github.com/KeisukeYamashita/go-vcl
[golangci-badge]: https://golangci.com/badges/github.com/KeisukeYamashita/go-vcl.svg

repository: KeisukeYamashita/go-vcl

branch_name: refs/heads/main

gha_language: Go

repo_name: KeisukeYamashita/go-vcl


text:
Flyweight
=========

Intent
------

Use sharing to support large numbers of fine-grained objects
efficiently.

(A flyweight is a shared object that can be used in multiple contexts
simultaneously. The flyweight acts as an independent object in
each context - it's indistiguishable from an instance of the object
that's not shared. Flyweights cannot make assumptions about the
context in which they operate. The key concept here is the
distinction between intrinsic and extrinsic state. Intrinsic state
is stored in the flyweight; it consists of information that's
independent of the flyweight's context, thereby making it sharable.
Extrinsic state depends on and varies with the flyweight's context
and therefore can't be shared. Client objects are responsible
for passing extrinsic state to the flyweight when it needs it.)

Applicability
-------------

The *Flyweight* pattern's effectiveness depends heavily on how
and where it's used.

Apply the *Flyweight* pattern when *all* of the following are true:
- an application uses a large number of objects;
- storage costs are high because of the sheer quantity of objects;
- most object state can be made extrinsic;
- many groups of objets may be replaced by relatively few shared
  objects one extrinsic state is removed;
- the application doens't depend on object identity
  (since flyweight objects may be share, identity tests will return
   true for conceptually distinct objects).

Structure
---------

```
 ----------------------   flyweights     -----------------------------
 | FlyweightFactory   |<>--------------->| Flyweight                 |
 ----------------------                  -----------------------------
 | GetFlyweight(key) o|                  | Operation(extrinsicState) |
 --------------------|-                  -----------------------------
   ^                 |                           |
   |  --------------------------------\          |
   |  | if (flyweight[key] exists) {   \         |
   |  |   return existing flyweight;    |        |
   |  | }                               |        |
   |  | else {                          |        |
   |  |   create new flyweight;         |        |
   |  |   add it to pool of flyweights; |        |
   |  |   return the new flyweight;     |        |
   |  -----------------------------------        ^
   |                                            / \
   |                       --------------------------------
   |                       |                              |
   |        ---------------------------    ---------------------------
   |      ->| ConcreteFlyweight       |  ->|UnsharedConcreteFlyweight|
   |      | ---------------------------  | ---------------------------
   |      | |Operation(extrinsicState)|  | |Operation(extrinsicState)|
   |      | ---------------------------  | ---------------------------
   |      | | IntrinsicState          |  | | allState                |
   |      | ---------------------------  | ---------------------------
 -------- |                              |
 |Client|---------------------------------
 --------
```

Participants
------------

- *Flyweight*
  - declares an interface through which flyweights can receive
    and act on extrinsic state.
- *ConcreteFlyweight*
  - implements the Flyweight interface and adds storage for intrinsic
    state, if any; a *ConcreteFlyweight* object must be shareable;
    any state it stores must be intrinsic; that is, it must be
    independent of the ConcreteFlyweight object's context.
- *UnsharedConcreteFlyweight*
  - not all Flyweight subclasses need to be shared; the Flyweight
    interface enables sharing; it doesn't enforce it; it's common for
    *UnsharedConcreteFlyweight* objects to have ConcreteFlyweight
    objects as children at some level in the flyweight object
    structure.
- *FlyweightFactory*
  - create and manages flyweight objects;
  - ensures that flyweights are shared properly; When a client
    requests a flyweight, the FlyweightFactory object supplies an
    existing instance or creates one, if none exits.
- *Client*
  - maintains a reference to flyweight(s);
  - computes or stores the extrinsic state of flyweight(s).

Collaborations
--------------

- State that a *flyweight* need to function must be characterized as
  either intrinsic or extrinsic. Intrinsic state is stored in the
  *ConcreteFlyweight* object; extrinsic state is stored or computed
  by *Client* objects. *Client*s pass this state to the *flyweight*
  when they invoke its operations.
- *Client*s should not instantiate *ConcreteFlyweight*s directly.
  *Client*s must obtain *ConcreteFlyweight* objects exclusively from
  the *FlyweightFactory* object to ensure they are shared properly.

Implementation
--------------

Consider the following issues when implementing the Flyweight pattern:
- *Remoing extrinsic state.*
  The pattern's applicability is determined largely by how easy
  it is to identify extrinsic state and remove it from shared objects.
  Removing extrinsic state won't help reduce storage costs
  if there are as many different kind of extrinsic state as
  there are objects before sharing. Ideally, extrinsic state can
  be computed from a separate object structure, one with far smaller
  storage requirements.
- *Managing shared objects.*
  Because objects are shared, clients shouldn't instantiate them
  directly. FlyweightFactory lets clients locate a particular
  flyweight. FlyweightFactory objects often use an associative
  store to let clients look up flyweights of interest.

license: MIT

repository: ordinary-developer/education

repo_name: ordinary-developer/education


text:
# Smooth and inertial scrolling for IntelliJ based IDE's

IntelliJ plugin that provides smooth scrolling. It also provides acceleration effects
with easing so you can "fling" like on a cell phone.

I have tested it with touchpads and mouse wheels on IntelliJ Community
and Android Studio. Hopefully, it will work on any IntelliJ product.

There are several options available under Tools -> Smooth Scroller Options...

![options image](.github/options.png)

Between these and the touchpad/mouse settings on your hardware, you should be able to get good performance.

You can find the plugin [here](https://plugins.jetbrains.com/plugin/8246).

Inspired by: [smooth-scroll-plugin](https://github.com/hccampos/smooth-scroll-plugin)
Thanks Hugo!

repository: RyanTheTechMan/smooth-scroller

repo_name: RyanTheTechMan/smooth-scroller


text:
@cheatsheetSection
Directive and component change detection and lifecycle hooks
@cheatsheetIndex 8
@description
(implemented as class methods)

@cheatsheetItem
`constructor(myService: MyService, ...) { ... }`|`constructor(myService: MyService, ...)`
The class constructor is called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.

@cheatsheetItem
`onChanges(changeRecord) { ... }`|`onChanges(changeRecord)`
Called after every change to input properties and before processing content or child views.

@cheatsheetItem
`onInit() { ... }`|`onInit()`
Called after the constructor, initializing input properties, and the first call to onChanges.

@cheatsheetItem
`doCheck() { ... }`|`doCheck()`
Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.

@cheatsheetItem
`afterContentInit() { ... }`|`afterContentInit()`
Called after onInit when the component's or directive's content has been initialized.

@cheatsheetItem
`afterContentChecked() { ... }`|`afterContentChecked()`
Called after every check of the component's or directive's content.

@cheatsheetItem
`afterViewInit() { ... }`|`afterViewInit()`
Called after afterContentInit when the component's view has been initialized. Applies to components only.

@cheatsheetItem
`afterViewChecked() { ... }`|`afterViewChecked()`
Called after every check of the component's view. Applies to components only.

@cheatsheetItem
`onDestroy() { ... }`|`onDestroy()`
Called once, before the instance is destroyed.

filename: lifecycle hooks.md


text:
---
layout: post
title:  "seneca and alan watts on dying and living"
date:   2016-12-24
categories: jekyll update
---
there is some tension between these three quotes below, but they're related for me. the first two are from seneca's letter to lucilius titled ['on taking one's own life.'](https://en.wikisource.org/wiki/Moral_letters_to_Lucilius/Letter_77). the last is a quote from a popular talk by alan watts on [the acceptance of death and the meaning of life](https://www.youtube.com/watch?v=M7KRgluYeps).

> "An ordinary journey will be incomplete if you come to a stop in the middle of it, but life is never incomplete if it is an honourable one.  –– [seneca, letter LXXVII](https://en.wikisource.org/wiki/Moral_letters_to_Lucilius/Letter_77)

> "Every life without exception is a short one... As it is with a play, so it is with life – what matters is not how long the acting lasts, but how good it is. It is not important at what point you stop. Stop wherever you will – only make sure that you round it off with a good ending." –– [seneca, letter LXXVII](https://en.wikisource.org/wiki/Moral_letters_to_Lucilius/Letter_77)

> “No one imagines that a symphony is supposed to improve as it goes along, or that the whole object of playing is to reach the finale. The point of music is discovered in every moment of playing and listening to it. It is the same, I feel, with the greater part of our lives, and if we are unduly absorbed in improving them we may forget altogether to live them.” –– [alan w. watts](www.goodreads.com/author/show/1501668.Alan_W_Watts)

as i sort of stew (in the best way) in my thinking about death this week, i keep coming back to an idea about living and dying. what keeps sticking is that we must be (culturally) afraid of dying because we haven't figured out how to live.

seneca's line about life being complete as long as it's honorable definitely reminds me of how i think about [living each day](http://lqb2writes.tumblr.com/post/141849731677/timelines-of-change-living-everyday-like-its-the). the 2nd and 3rd quotes are, to me, similarly about the important of knowing how to live well.

there is a strange, but coherent irony in our fear of death as it manifests in our continued avoidance of the one question that would end that fear. how should one live?

**writing data**

writing | 9:22
spell-check, link-finding, & formatting | 14:30
{:.mbtablestyle}

extension: markdown


text:
# Introduction

**Hi everybody and welcome to this first tutorial !** This will be the first chapter of the tutorial covering the development of the "Geo App".

> What is the "*Geo App*" about ?
>
> The "*Geo App*" is a web browser game built as a single page JavaScript application. Two modes will be implemented, relax and challenge.
> The relax mode will display the country's information when the user selects it on the map.
> The challenge mode will ask the user to find a randomly selected country in the world map.

The code is available on GitHub (tuto-geo-app) else [download .zip][1]

In order to achieve this project, we will use the following libraries / tools:

*   [Backbone Marionette][2] *v1.7.3*
*   [Bootstrap 3][3] *v3.1.1*
*   [Handlebars][4] *2\.0.0-alpha.2*
*   [Less][5] *v1.7.0*
*   [Requirejs][6] *v2.1.11*
*   [Leaflet][7] *v0.7.3*

## Who is this tutorial for ?

The targeted audience of this tutorial will be mainly developers, students in programming, geeks... The code will be explained and commented so you can read over and complete your understanding of the logic. It is recommended that you have at least a basic understanding of JavaScript, HTML and CSS.

## What is this tutorial about ?

This tutorial will go through the different steps of development of a *single page web application*.

Comments will cover the following aspects:

*   How to *use the different libraries* listed previously
*   How to *structure the application code* so that it does not turn into a single file of 300000 lines.
*   How to use *custom JS events* to avoid a maze of function and callback.
*   How to avoid having a single HTML file with an endless list of scripts tags.

## What is this tutorial NOT about ?

This tutorial is not covering the basics of HTML, CSS or JavaScript. You will be expected to be familiar with the basics of web development.

# Getting started

First let's start by setting up the development environment.

## Text editor / IDE

Let's start simple with a simple text editor or IDE. You won't need any specific IDE to write the code. However, Windows Notepad may not help you a lot / (at all).
If you are not sure on which one you should use, I would recommend the following ones:

*   [Sublime Text][8]: **(+)** *free, lightweight, customizable, simple* || **(-)** *feature available through plugins*
*   [IntelliJ][9] / [WebStorm][10] **(+)** *very good auto-complete / intellisense feature for CSS and JS* || **(-)** *heavy, advanced features require license*

## CLI tools

The project will require a CLI (Command Line Interface) to run different commands. If you have Windows, I recommend **NOT** using the cmd.exe but rather another alternative.
Since you probably have Git, you may have Git Bash installed also, it will be enough to run the commands we need.

## Node and NPM packages

In the tutorial, we will use nodejs and npm so you will need to install it.

> [Nodejs][11] *(v0.10.26 used)*

At the end of the installation you should be able to run:

    node --version

From there, install handlebars and less using the following commands:

### **Linux**

    sudo npm install -g less
    sudo npm install -g handlebars

### **MS Windows**

    npm install -g less
    npm install -g handlebars

Note: Handlebar version will be discussed in the chapter dedicated to its use. If you wish to install a specific version, use the following command:

    npm install -g <name>@<version>

See more in [NPM install docs][12]

## Virtual server

The application will be AJAX based content loading, we need a web server. You can use the server of your choice. As indication, the tuto has been realized using both [Lampp][13] and [Xampp][14]. *It is recommended to use Apache aliases to map different URLs to different location in your drive. It allows to keep your work tidy without having to put everything inside the htdocs folder.*

Good, you should now be ready to get your hands into some code !

# Application base

You will find the code for the application *base* on Github.

## Purpose

This version is the foundation of the future code, all configured to run normally. It has none of the feature implemented, it is a basic skeleton where the application will be built from.

## Folder structure

The application's folder structure has been planned for further expansion. This is why the application has been structured in the following way:

[expand title="Expand folder structure"]

    tuto-geo-app/
      css/
        images/ /* CSS related images */
        /* less and css files here */
      js/
        geoapp/
          /* Geo App JS code here */
        main.js /* require js config */
      vendor/
        backbone/
        bootstrap/
        jquery/
        marionette/
        require/
        underscore/
        /* more 3PPs will be added as we go along */

[/expand]

### css/

This folder will store the styles for the application container.

Important: None of the application specific styling should go in this folder. The aim is to ensure the application modularity and avoid dependencies others than 3PPs outside the application folder.
As for the folder structure, the CSS folder is planned for further expansion with application specific style sheets on the application folder.

### js/

This folder contains application specific JavaScript code along with the requirejs configuration. All the application code is grouped in the *geoapp* folder.
In the case we want to add a second application, the code would go in *secondApplicationName* folder.

### vendor/

Grouped in this folder will be all the 3PPs used for this project.

## Code at a glance

### main.js

[expand title="Expand code"]

    require.config({
        name: 'main',
        baseUrl: 'js/geoapp/',
        paths: {
            // Vendors
            'jquery': '../../vendor/jquery/jquery.min',
            'underscore': '../../vendor/underscore/underscore.min',
            'text': '../../vendor/require/text',
            'backbone': '../../vendor/backbone/backbone.min',
            'backbone.wreqr': '../../vendor/marionette/backbone.wreqr.min',
            'backbone.babysitter': '../../vendor/marionette/backbone.babysitter.min',
            'marionette': '../../vendor/marionette/backbone.marionette.min',
            //App
            'GeoApp': './GeoApp',
        },
        shim: {
            'jquery': {
                exports: '$'
            },
            'underscore': {
                exports: '_'
            },
            'backbone': {
                deps: ['underscore', 'jquery'],
                exports: 'Backbone'
            },
            'marionette': {
                deps: ['jquery', 'underscore', 'backbone'],
                exports: 'Backbone.Marionette'
            }
        }
    });

[/expand]

The require.config object configures the following options:

*   The `baseUrl` will used when we will query the different files. It is set here to *js/geoapp/* which is the application script folder.
*   The list of paths works as follow `"moduleName" : "path/to/module/js/file/without/extension"` We set here the default name and relative path of the different 3PPs

Shim object configure the dependencies and export for the non AMD modules

[expand title="Expand code"]

    /* global define */
    define([ // start of the module definition
        'GeoApp'
    ], function(geoAppInstance) { // load the application object
        'use strict';
        geoAppInstance.start(); // start the application
    }); // end of the module

[/expand]

On the previous code snippet you can see the define function. You will provide here the dependencies of your module, they will be available through the function arguments.
Here *GeoApp* is defined as dependency and made available by *geoAppInstance.*

### GeoApp.js

[expand title="Expand code"]

    /* global define */
    define([
        'marionette'
    ], function (Marionette) {
        'use strict';

        var geoApp = new Marionette.Application(),      // instantiate new application
            DummyView = Marionette.ItemView.extend({    // extend view to add customized content
                template: function () {                 // template will provide the view with content
                    return 'Congratulation !!! the application has started';
                }
            });

        // define the application container, refers here to the #appContainer in index.html
        geoApp.addRegions({
            appContainer: '#appContainer'
        });

        // instantiate and show our custom DummyView
        geoApp.appContainer.show(new DummyView());

        // return the application instance without calling start, start is called in the main.js
        // this allows later to create a more global application manager and run multiple applications based on the #hash value
        return geoApp;
    });

[/expand]

# Introduction to Handlebars Templates

> *Why should I use a template where a simple HTML string build does the job?*
>
> *Well, the choice is all yours, but a good few points may change your mind:*

*   It is good practice to keep the markup separated from the logic, so you end up with cleaner code
*   It is easier to reuse and adapt
*   Using this method, you will be able to pass variables to your template saving you from having to write supplementary code
*   From a security aspect, Handlebars escapes string variables; this lowers the risk of injection
*   more...

You will see in this page how to create an HTML template using Handlebars (.hbs file) and use it in your application with Requirejs. Splitting the HTML templates in different files allows for more modularity and reusability of your code.

The code for the examples and template configuration is available on Github. We will cover how to display the template in the application on the next chapter.

Handlebars will be used in two parts. First we will *compile* the templates using the CLI, then we will use it in the JavaScript code (*runtime*).

As we precompile the templates in AMD modules, the Handlebars used in the project is Runtime and AMD, if you wish to download a newer version, make sure to get the Runtime and AMD as well.

## Compile the Templates

Compiling template or static HTML could sound strange but the idea behind is to transform the markup in a JS function where a string is returned. It will make much more sense when we will use them later on in the tutorial.

Note: You should have Handlebars installed with *npm* before continuing (see Getting Started).

The templates should be saved in a dedicated folder, it makes the compilation process easier. In this project, templates are saved under `js/geoapp/templates`.
Open the CLI and navigate to the `js/geoapp/` folder. Then run the following command to compile all template in the folder:

    handlebars -a -m templates/*.hbs -f compiledTemplates.js
    handlebars <params> <input> -f <outputFile>

*   params:
    *   **--amd** / **-a** is used to get the templates compiled as AMD
    *   **--min** / **-m** minifies the js output.
*   input:
    *   **templates/*.hbs** select all .hbs files inside \*templates\* folder
*   outputFile:
    *   **compiledTemplates.js** will be generated in the current location (e.g. js/geoapp/)

You should read Handlebars and Handlebars precompilation for more details.

### Examples

In the following examples we will compile some templates for the next chapter.

[expand title="_geoAppLayout.hbs"]

[/expand]

[expand title="_mainView.hbs"]

Geo Map

[/expand]

[expand title="_sideBarView.hbs"]

Country name

Score

Player's score

[/expand]

Note: There is apparently a bug in the compiler that cause the template to be invalid if it is compiled alone. The simplest solution is to create a dummy hbs file if you have a single template in a folder.

# Application UI Design

> UI: User Interface

## UI Layout

Let's visualize how the application UI will be structured.

[][15]

*   Left side: it will display the country name to select and the map in which the player will make the selection.
*   Right side: it will contain the scores and additional information about the country to find. Planned also, additional options for multi languages support.

## HTML mock up

Before entering into deep JS coding, we will build a mock up of the result page.
This will allow us to plan for many aspects of the application that do not require JS to be running like:

*   The styling of the page
*   The usability of the design and page structure
*   The cross device compatibility, here we use bootstrap to help building the layout

[][16][][17]

[expand title="HTML mock-up"]

    <!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Tutorial - Geo app</title>
        <link href="PATH/TO/bootstrap.min.css" rel="stylesheet">
        <link href="PATH/TO/style.css" rel="stylesheet">

Country name

Geo Map

--MAP--

Score

                                0
                                0

More Info

Capital City

                            Main language

                                A: surface
                                Cur: currency

                                Pop: population

[/expand]

[expand title="CSS mock-up"]

    body {
        background-color: #efefef
    }

    .mr-topNavLogo {
        margin: 0 15px;
        width: 60px;
        background: url("images/logo.png") no-repeat center;
        background-size: contain
    }

    .mr-pageBody {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        overflow-y: auto;
        padding-top: 70px;
        background: url("images/texture-grey.png");
        box-shadow: 0 0 15px 5px #808080
    }

    .mr-geoappSide-playerScore .label {
        font-size: 2.6rem;
        white-space: normal;
        overflow-wrap: break-word
    }

    @media (min-width: 992px) {
        .mr-geoappSide-playerScore .label {
            margin-bottom: 8px;
            font-size: 1.6rem
        }

        .mr-geoappSide-playerScore .label:last-of-type {
            margin-bottom: 0
        }
    }

    .mr-geoappSide-countryInfo .lead {
        margin-bottom: 6px
    }

[/expand]

This template does not represent necessarily the end result but it contains most of the future layout.

In the next chapter, we will structure the application code using (finally :P) Marionette js.

# Application core

The code for this chapter is available on Github

## Introduction

You will see in this page how to structure the application using Application, Layout and View combined with the compiled templates discussed previously. Application, Layout and View (soon more) are Marionette js classes.

## Marionette.Application

The Marionette Application is where everything starts. From this class you will instantiate the different parts of your application. In our case, we will call a layout GeoAppLayout. Later on, we will add more functionalities.

    var geoApp = new Marionette.Application();
    // instantiate new Marionette application

    // define the application container,
    // refers here to the #appContainer in index.html
    geoApp.addRegions({
        appContainer: '#appContainer'
    });

    // instantiate and show the GeoAppLayout
    geoApp.appContainer.show(new GeoAppLayout());

Note: Dislike the other elements of Marionette, the Application is not extended. We instantiate it directly before calling the `app.start()` method.

## Marionette.Layout

The Marionette Layouts are used here to structure multiple Views and sub layouts.

The GeoAppLayout will instantiate two sub layouts that represent the main parts of the application (see UI and comments in code).

    return Marionette.Layout.extend({

        // set the template to use in this view, file name is used as identifier
        template: template['_geoAppLayout.hbs'],

        regions: {
            // split the application screen in two regions, identifier point to the element in the template
            mainRegion: '.mr-geoappMainHolder',
            sideRegion: '.mr-geoappSideHolder'
        },
        onShow: function () {
            // instantiate and show layout
            this.mainRegion.show(new MainLayout());
            this.sideRegion.show(new SideLayout());
        }
    });

The other two layouts are very similar to this example.

## Marionette.ItemView

The Marionette ItemViews will be used as interface between the DOM elements (template markup) and the core logic.

On the following example, we see the player's score view.

    return Marionette.ItemView.extend({

        // set the template to use in this view, file name is used as identifier
        template: template['_playerScoreView.hbs']
    });

The views will be associated with Models and Handlebars templates in the chapter covering the game core.

The next chapter will show how we integrate the map and the events generated by the user's interactions.

# Integrating Leaflet Map

The code for this chapter is available on Github

## Introduction

We will be using [Leaflet][7] to display our application map. The library has a lot of tutorials to explain different features. One of the feature which will be key for the application is the ability to display clickable areas over the map. This is done using GeoJson. (see [GeoJson Leaflet tuto][18]).

## Display the Map

### Setting up the View for the Map

Under the folder `view/main/` we create a new View called `MapView`. It will be used from the logic side of the application to get the element which will contain the map.

    return Marionette.ItemView.extend({

        // Backbone automatically wrap the View into a div tag, we need that tag to be position relative and taking full height of its parent.
        // It is possible to specify the tag name and class name in the View and remove the root element of the template.
        // However, I don't like to mix markup and styling with logic side of the code.
        // This css class name only provides the position and height.
        className:'mr-geoapp-elt',

        // set the template to use in this view, file name is used as identifier
        template: template['_mapView.hbs'],

        // Set the ui elements that we will use
        ui: {
            map: '.mr-geoappMain-map'
        },

        getMapElement: function () {
            return this.ui.map;
        }
    });

### Adding the logic for the map

In order to create, configure and interact with the Map, we create a new file into `region/main/` called MapRegion.

[expand title="MapRegion code"]

    return  Marionette.Region.extend({

        el: '.mr-geoappMain-mapHolder',

        onShow: function (view) {

            // view.getMapElement() will return the map element in the template
            // we need to use get(0) because of JQuery, as the element returned is the Jquery wrapped element.
            var mapElt = view.getMapElement().get(0),
                map = Leaflet.map(mapElt, {
                    center: [50, 0],    // center the map over Europe region
                    maxBounds: [        // set the map bounds so that the user cannot navigate outside the map
                        [90, 180],
                        [-90, -180]
                    ],
                    zoom: 3,            // set the zoom, minZoom and maxZoom
                    minZoom: 2,
                    maxZoom: 8
                });

            // see tutorial at
            // http://leafletjs.com/examples/quick-start.html
            //
            // you can create your custom map here:
            // https://www.mapbox.com/

            Leaflet.tileLayer('http://{s}.tiles.mapbox.com/v3/YOUR-MAP-ID/{z}/{x}/{y}.png', {
                maxZoom: 10
            }).addTo(map);

            // Leaflet tuto:
            // http://leafletjs.com/examples/choropleth.html
            function onEachFeature(feature, layer) {
                layer.on({
                    mouseover: highlightFeature,
                    mouseout: resetHighlight,
                    click: clickEvt
                });
            }

            function resetHighlight(e) {
                geojson.resetStyle(e.target);
            }

            var geojson = Leaflet.geoJson(worldGeoJson, {
                style: style,
                onEachFeature: onEachFeature
            }).addTo(map);
        }
    });

    function style() {
        // Set the area with a transparent background, bordered with dash colored in #aaa
        return {
            fillColor: 'transparent',
            weight: 1,
            opacity: 1,
            color: '#aaa',
            dashArray: '3'
        };
    }

    function clickEvt(e) {
        // We will handle the click event here
        // This currently displays the name of the clicked area
        console.log('Click on ' + e.target.feature.properties.name);
    }

    function highlightFeature(e) {
        var layer = e.target;

        // When the user mouses over a specific area, this one gets the background changed to #ccc and the border weight increased.
        layer.setStyle({
            fillColor: '#ccc',
            weight: 2,
            color: '#888',
            fillOpacity: 0.5
        });

        if (!Leaflet.Browser.ie && !Leaflet.Browser.opera) {
            layer.bringToFront();
        }
    }

[/expand]

The Region is a Marionette js classes. It allows to separate the View from the logic part. See comments in the code for more details.

The Leaflet GeoJson tutorial covers the functionalities added on this chapter. If you encounter any difficulties, it is a good resource to use.

## Useful links

[Leaflet quick start tuto][19]
[Leaflet GeoJson tuto][20]
[Leaflet API][21]
[Create your custom map with Mapbox][22]

# Game Logic core and data

The code for this chapter is available on Github

## Introduction

This chapter covers the way we will combine the map and the game logic.
We will see as well how to decouple our modules using the JS custom events and how to combine the model with handlebars template.

## Game data Model

### Game model

The Backbone.Model is used to store the game related data:

* score (correct / error)
* country name
* country info

See Backbone doc What is a Model ?

[expand title="Game Model code"]

    return Backbone.Model.extend({
        // Set the default values for the game score
        defaults: {
            score: {
                correct: 0,
                error: 0
            },
            countryName: '',
            countryInfo: {}

        },
        //---------------------------------------
        getScore: function () {
            return this.get('score');
        },
        //---------------------------------------
        increaseCorrect: function () {
            scoreUpdate.call(this, 1, 0);
        },
        increaseError: function () {
            scoreUpdate.call(this, 0, 1);
        },
        //---------------------------------------
        setCountryName: function (countryName) {
            this.set('countryName', countryName);
        },
        resetScore: function () {
            this.setScore({
                correct: 0,
                error: 0
            });
        },
        setScore: function (score) {
            this.set('score', score);
        },
        setCountryInfo: function (countryInfo) {
            this.set('countryInfo', countryInfo);
        }
        //---------------------------------------
    });

    function scoreUpdate(c, e) {
        var oldScore = this.getScore(),
            newScore = {
                correct: oldScore.correct + c,
                error: oldScore.error + e
            };
        this.setScore(newScore);
    }

[/expand]

The game controller will manage the model and update it at the different phases of the game.
Every time an attribute of the model is updated, an event is triggered. The Marionette View classes are listening to these events; this allow us to update the value displayed on the UI with a minimum code.

### Model / View update

This feature is based on the template that we covered previously.

[expand title="GameController code"]

{{countryName}}

[/expand]

The `{{countryName}}` represents the name of the model attribute.
As we instantiate the View in the Layout, we supply the model instance.

[expand title="CountryNameView code"]

    return Marionette.ItemView.extend({

        // set the template to use in this view, file name is used as identifier
        template: template['_countryNameView.hbs'],

        initialize: function(){
            // Listen to the change event on the coutryName attribute of the Model.
            // render will be called every time the value of the countryName changes
            this.model.on('change:countryName', this.render, this);
        }
    });

[/expand]

As it is explained in the comments, `model.on('evt:attributeName', callback)` allows us to listen to the proper events and avoid re-rendering the template for nothing.

## Supply the Model to the View

One of the question you could have is *"How should I set the Model to the different Views?"*.

We will use Backbone Wreqr. More specifically, we will use the Request-Response and Vent functionality.

### Request-Response

It allows us to create a getter through JS custom event. We will use it for the Model but also for the GeoJson data.

> *Why would we want to put the GeoJson with the Controller?*

> The reasons are quite simple:
> * The data about countries are related to the GeoJson by the country ID. The logic of the game controller depends on it, the countries displayed must be in the country data and vice versa.
> * The GeoJson is a standard, we could replace the map by another 3PP and display the GeoJson data on top of it.

The following code snippet shows how to initiate the channel with the Request-Response (reqres) for the instance of Game Model

    var gameChannel = Wreqr.radio.channel('game');

    gameChannel.reqres.setHandler('gameModel', function () {
        return this.gameModel;
    }, this);

The model is then requested the following way in the Layout:

    var gameModel = Wreqr.radio.reqres.request('game', 'gameModel');

### Vent

The different parts of the application can communicate simply through events.

The Map region needs to communicate the selected country ID to the Controller which checks it:

    var mapChannel = Wreqr.radio.channel('map');
    // on the click event handler
    mapChannel.vent.trigger('countrySelected', e.target.feature.id);

On the Controller side, we need to listen to that event:

    var mapChannel = Wreqr.radio.channel('map');
    mapChannel.vent.on('countrySelected', evaluateSelection, this);

`evaluateSelection` is the callback that will evaluate the country ID.

## Game Controller

What is the
Marionette.Controller ?

> A Controller is a white-label Marionette Object. Its name can be a cause for confusion, as it actually has nothing to do with the popular MVC architectural pattern. Instead, it's better to think of the Controller as a base object from which you can build.

> Controllers should be used when you have a task that you would like an object to be responsible for, but none of the other Marionette Classes quite make sense to do it. It's a base object for you to use to create a new Class altogether.

*Marionette doc*

We will use the Controller class to group all game related logic. This way, we separate it from the Views and it would be easier to reuse it later in another application.

[expand title="GameController code"]

    return Marionette.Controller.extend({

        // All the game business is abstracted in this Controller.
        // The targeted result is to separate the game logic from the Views,
        // so that it is very easy to reuse in another Application.

        initialize: function () {
            this.gameModel = new GameModel();
            this.countriesIdArr = Object.keys(countriesData);

            // Use Backbone.Wreqr for the event mechanism
            // https://github.com/marionettejs/backbone.wreqr
            var mapChannel = Wreqr.radio.channel('map'),
                gameChannel = Wreqr.radio.channel('game');

            //-----------------------------------------------
            mapChannel.vent.on('countrySelected', evaluateSelection, this);
            //-----------------------------------------------
            mapChannel.reqres.setHandler('mapGeoJson', function () {
                return worldGeoJson;
            });
            //-----------------------------------------------
            gameChannel.reqres.setHandler('gameModel', function () {
                return this.gameModel;
            }, this);
        },
        selectNewCountry: function () {
            this.currentId = getRandomId.call(this);
            var newCountry = countriesData[this.currentId],
                countryData = {
                    capital: newCountry.capital,
                    currency: newCountry.currency,
                    language: newCountry.language,
                    area: (newCountry.area !== -1) ? newCountry.area : null
                };
            this.gameModel.setCountryName(newCountry.name);
            this.gameModel.setCountryInfo(countryData);
        },
        startGame: function () {
            // When the game starts, set the score to zero, and select a new country to find
            this.gameModel.resetScore();// The score reset will be part of a next coming feature
            this.selectNewCountry();
        }
    });

    function evaluateSelection(selectedCountryId) {
        if (this.currentId === selectedCountryId) {
            this.gameModel.increaseCorrect();
            this.selectNewCountry();
        } else {
            this.gameModel.increaseError();
        }
    }

    function getRandomId() {
        /*jshint validthis: true */

        // The jshint validthis: true is necessary when it will come to code quality testing using JSHint,
        // This step will come at a later stage.

        var max = this.countriesIdArr.length,
            randomIndex = Math.floor(Math.random() * (max - 1));
        // Return a randomly selected country from the list.
        return this.countriesIdArr[randomIndex];
    }

[/expand]

The MapRegion will trigger an event every time the user selects a country providing the country ID. The Controller needs to listen to this event and checks the ID against the ID of the country to find. It updates the score depending on the result.

# Congratulations !!!

You reached the end of this tutorial. You should now have a working application similar to:

More features will be added later such as multi language support, relax and challenge mode, etc.

Many thanks for reading, I hope you enjoyed it and that it brought you additional knowledge about ways to build JS applications.

repository: marc-ed-raffalli/tuto-geo-app

repo_name: marc-ed-raffalli/tuto-geo-app


text:
---
###############
# DO NOT EDIT
layout: proposal
###############

###############
# TO EDIT
# pub title
title: "Inclusive Mixed Reality: Merging the Real and the Virtual Worlds"

# publication image
image:
 name: vr-blind-date-show.png
 alt-text: "Two people with a VR headset" # provide a short description for the image #a11y

# short description of the publication
motivation: "Hybrid spaces have been emerging as a way to bridge the gap between physical and virtual interactions, offering a flexible - and potentially inclusive - approach to socializing. For instance, a pair with mixed-visual abilities (one blind and one sighted person) could visit a museum where one explores it virtually while the other is in the real-world. While such hybrid environments are incorporating virtual and augmented reality technologies to enhance the user experience, they often exclude blind participants, who are unable to engage with visual stimuli used in these spaces."

work: "In this topic, you will explore how to support Inclusive Mixed-Reality experiences for people with mixed visual abilities, showcasing it in a proof-of-concept scenario (e.g., a museum, an escape room, or another option). The work will include developing environments with Unity, working with VR headsets and/or AR, and involving blind people in user studies."

# people associated with the publication
people:
 - jpvg
 - afpr

###
---

gha_language: HTML


text:
# Cereal

[![Python package](https://github.com/jcarbaugh/cereal/actions/workflows/pythonpackage.yml/badge.svg)](https://github.com/jcarbaugh/cereal/actions/workflows/pythonpackage.yml)

Serialize objects, dicts, and [Django models](https://djangoproject.com)  to JSON with ease.

I occasionally need to make very small APIs, maybe just an endpoint or two to provide a bit of data to a client. It always seems like overkill to use Django REST framework when a simple View will do. Unfortunately, the DRF serializer is really good and hand coding an object-to-JSON map can be fragile and gross. Cereal was created to be that trusty serializer when that's all you need.

## Installation

Cereal is available on [PyPI](https://pypi.org/project/pycereal):

```shell
pip install pycereal
```

or

```shell
pipenv install pycereal
```

## Serializers

### Fields

If you've ever used Django's [ModelForms](https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/), Cereal should seem fairly familiar to you. A Serializer defines a set of attributes (Fields) that will be… serialized… into JSON.

```python
import cereal

class ArticleSerializer(cereal.Serializer):
    title = cereal.Field()

data = {
    'id': 1,
    'title': 'An Important Headline',
}

ArticleSerializer().serialize(data)
```

This will result in the JSON object:

```json
{
    "title": "An Important Headline"
}
```

### Customizing fields

Sometimes there's a need to transform a value before it is converted to JSON. Cereal provides an opportunity to hook into serialization by adding methods named with the `serialize_<field>` format. The method will receive the data structure that is being serialized as the sole argument.

```python
import cereal

class ArticleSerializer(cereal.Serializer):
    title = cereal.Field()

    def serialize_title(self, obj):
        return obj['title'].upper()

data = {
    'id': 1,
    'title': 'An Important Headline',
}

ArticleSerializer().serialize(data)
```

Which will generate:

```shell
{
    "title": "AN IMPORTANT HEADLINE"
}
```

The field methods can also be used to create completely new values.

```python
import cereal

class AuthorSerializer(cereal.Serializer):
    full_name = cereal.Field()

    def serialize_full_name(self, obj):
        return f"{obj['first_name']} {obj['last_name']}"

data = {
    'first_name': 'Corey',
    'last_name': 'Spaceman',
}

AuthorSerializer().serialize(data)
```

The generated JSON:

```json
{
    "full_name": "Corey Spaceman"
}
```

The JSON only includes the custom *full_name* Field, which is computed using the *serialize_full_name* method, and not the *first_name* or *last_name* attributes. Of course, you can include all of the attributes too by defining them as Fields as well.

### Serializing objects

The examples so far have involved serializing a dict to JSON, but the *json* module already does this, so what's the point? Cereal handles objects the exact same way as it does dicts.

```python
import cereal

class Article:
    def __init__(self, _id, title):
        self.id = _id
        self.title = title

class ArticleSerializer(cereal.Serializer):
    title = cereal.Field()

obj = Article(1, 'An Important Headline')
ArticleSerializer().serialize(obj)
```

The resulting JSON shouldn't be much of a surprise.

```json
{
    "title": "An Important Headline"
}
```

### Nested attributes

The world is an imperfect place and not all of your data will be in a simple, flat structure. SerializerField can be used to attach another serializer to handle a nested data structure.

```python
import cereal

class UserSerializer(cereal.Serializer):
    name = cereal.Field()

class ArticleSerializer(cereal.Serializer):
    title = cereal.Field()
    author = cereal.SerializerField(UserSerializer)

data = {
    'id': 1,
    'title': 'An Important Headline',
    'author': {
        'id': 2,
        'name': 'Corey',
    }
}

ArticleSerializer().serialize(data)
```

```json
{
    "title": "An Important Headline",
    "author": {
        "name": "Corey"
    }
}
```

### Dates and datetimes

If you've spent much time with the *json* module, you're probably quite familiar with date serialization errors. JSON does not have native support for dates, so they have to be transformed into string values, but *json* doesn't do this automatically. Cereal has built-in support for dates and datetimes, generating ISO 8601-formatted strings that will be used as the value.

```python
import datetime
import cereal

class EventSerializer(cereal.Serializer):
    timestamp = cereal.Field()

data = {
    'timestamp': datetime.datetime(2018, 3, 8, 11, 57, 23, 129307)
}

EventSerializer().serialize(data)
```

```json
{
    "timestamp": "2018-03-08T11:57:23.129307"
}
```

### Renaming Fields

Sometimes all you want to do is rename a field, not change the value. The Field object takes an optional `from_attr` parameter that can override the attribute from which the value is obtained.

```python
import cereal

class Author:
    def __init__(self, first_name):
        self.first_name = first_name

class AuthorSerializer(cereal.Serializer):
    firstName = cereal.Field(from_attr='first_name')

obj = Author('Scarlett')
AuthorSerializer().serialize(obj)
```

The resulting JSON shouldn't be much of a surprise.

```json
{
    "firstName": "Scarlett"
}
```

### Custom type handlers

As with dates, other data types outside of what is natively supported by JSON need to be converted to one of the native types during serialization. Cereal allows you to define handlers for additional data types to convert to a valid JSON format. The handler is a callable that receives the value and returns a value corresponding to a native JSON type.

```python
import uuid
import cereal

def uuid_handler(u):
    return u.hex

class UUIDSerializer(cereal.Serializer):
    id = cereal.Field()

ser = UUIDSerializer()
ser.add_handler(uuid.UUID, uuid_handler)
ser.serialize({'id': uuid.uuid4()})
```

You guessed it, the JSON:

```json
{
    "id": "45ebb187dbc240cabb07b775f63efd6f"
}
```

### Single value vs. list of values

When serializing an attribute, the content can either be a single value or an array of values. The corresponding JSON will likewise be either a single value or an array of values. All of the values of the array will be transformed the same way an individual value would be, either through the default Field behavior, using the custom serialization method, the default SerializerField behavior, or a custom type handler. To be safe, just make sure all items in the array are of the same type and that type would serialize correctly as a single value.

Similarly passing a list or tuple of objects to the serializer will return the serialized versions of them as a JSON array. All of the objects must be of the same type (or work with the serializer).

### Serialize to a dict instead of JSON

Cereal first converts an object to a dict before converting to JSON. If you would like this dict instead of a string of JSON, pass `raw=True` to the serializer.

```python
serializer.serialize(obj, raw=True)
```

## Special Fields

### Constants

The ConstantField allows you to insert a new, constant value into the JSON.

```python
import cereal

class HumanSerializer(cereal.Serializer):
    name = cereal.Field()
    wants_tacos = cereal.ConstantField(True)

data = {
    'name': 'Corey Spaceman',
}

HumanSerializer().serialize(data)
```

```json
{
    "name": "Corey Spaceman",
    "wants_tacos": true
}
```

### Iterators

The IteratorField allows you to define a generator, use a list, or pass any type of iterable that will be used to generate values. Each serialized object will pull a new value from the iterator. If the iterator is exhausted, *None* will be used.

```python
from itertools import count
import cereal

class ThingSerializer(cereal.Serializer):
    id = cereal.Field()
    offset = cereal.IteratorField(count())

ser = ThingSerializer()
ser.serialize({'id': 1})
ser.serialize({'id': 2})
```

```json
{
    "id": 1,
    "offset": 0
}
{
    "id": 2,
    "offset": 1
}
```

## Django Model Serialization

While Cereal is usable in any Python project, I really made it to be used with Django projects. So, given my previous mention of being inspired by Django ModelForms, Cereal allows you to define a model that automatically defines the fields that will be serialized.

```python
import cereal
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=128)

class PostSerializer(cereal.Serializer):
    exclude = ('id',)

    class Meta:
        model = Post

post = Post.objects.create(title='Breaking News')
PostSerializer().serialize(post)
```

```json
{
    "title": "Breaking News"
}
```

In this example, we're inheriting the fields of the Post model, but excluding the *id*.

Beyond incorporating the fields from the model, the Serializer functions the same as any other non-model Serializer. You can define additional Fields and custom field serializer methods that modify both model fields and any others.

## Deserialization

You may be wondering "What about deserialization?" Well, I had no need for it, so I didn't build it. Contributions are welcome, though!

repository: jcarbaugh/cereal

gha_license_id: MIT

repo_name: jcarbaugh/cereal


text:
## TL500 Cluster Setup

    ⛷ NOTE ⛷ - You need an OpenShift 4.8+ with cluster-admin privileges.

Just like we practice through out the course, we keep the cluster configuration as code in a GitHub repository: https://github.com/rht-labs/enablement-framework

This repository has two part:
- Helm charts to deploy some cluster-wide toolings
- CodeReady Workspaces setup

Let's clone the repository and prepare the cluster:

```bash
git clone https://github.com/rht-labs/enablement-framework
cd enablement-framework
```

#### Helm Charts for Toolings
Here is the list of the tools and objects we deploy for TL500 setup:
* IPA - for user management
* CodeReady Workspaces - for developer environment.
* GitLab - as Git server
* SealedSecrets - for storing the secrets publicly safely.
* StackRox - for image security exercises
* User Workload Monitoring - enable application metrics gathering. It is needed for `Return of the Monitoring` section.
* Logging - another cluster wide operator needs to be install beforehand
* Namespaces
* RBAC definition for attendees

[todo] add helm install commands...

#### CodeReady Workspaces Setup
During the exercises, we use different commandlines like `oc`, `mvn`, `kube-linter` and many others. We have a container image that has all these necessary CLIs and, the configuration (Dockerfile) is under `codereadyworkspaces/stack/` folder.

We utilize GitHub Actions in order to build and store this image publicly.

We have a `do500-devfile.yaml` which is the _as code_ definition of our workspace. We refer to the container image inside the devfile:

```yaml
...
  - type: dockerimage
    alias: stack-do500
    image: quay.io/rht-labs/stack-do500:3.0.8
...
```

We have the explanation of how to get your own CodeRead Workspaces environment in the [first chapter](1-the-manual-menace/1-the-basics).

repository: jackroberts-gh/tech-exercise

repo_name: jackroberts-gh/tech-exercise


text:
- **what**: a chat bot for Facebook Messenger
-  **why**: because the world needs more to-do lists
-  **how**: [Node.js](https://nodejs.org/en/), [mongoDB](https://www.mongodb.com/), [Heroku](https://www.heroku.com/home), [FbMessenger](https://developers.facebook.com/docs/messenger-platform)

> *Quas is still in development. :bug: Please refer to [release history](https://github.com/thawsitt/quas/releases) for feature updates. To contribute, fork this repo and make a pull request. Thanks for stopping by. :sparkles:*

repository: Cloudxtreme/quas

repo_name: Cloudxtreme/quas


text:
---
layout: post101
title:  Working with Clusters
categories: XAP101ADM
parent: gigaspaces-management-center.html
weight: 500
---

Creating a cluster, replication options, load-balancing options, failover options, verifying and editing cluster definitions, visualizing clusters.

{%fpanel%}

[Cluster view](./cluster-view---gigaspaces-browser.html){%wbr%}
Using Cluster View areas: Cluster Tree, visual display, legend, and information panel.

[Failover group](./failover-group---gigaspaces-browser.html){%wbr%}
A failover group defines failover between spaces in the cluster.

[Load balancing group](./load-balancing-group---gigaspaces-browser.html){%wbr%}
A load-balancing group defines load-balancing between spaces in the cluster.

[Replication group](./replication-group---gigaspaces-browser.html){%wbr%}
Common settings, sync/async replication, transmission policies, filters, recovery options.

{%endfpanel%}

repository: barakb/gigaspaces-wiki-jekyll

repo_name: barakb/gigaspaces-wiki-jekyll


text:
# Change Log

All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

## [10.0.9](https://github.com/explodingcamera/next-plugin-styled-components/compare/v10.0.6...v10.0.9) (2021-03-17)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

## [10.0.6](https://github.com/explodingcamera/next-plugin-styled-components/compare/v10.0.5...v10.0.6) (2021-01-29)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

## [10.0.3](https://github.com/explodingcamera/next-plugin-styled-components/compare/v10.0.2...v10.0.3) (2020-12-10)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

## [10.0.2](https://github.com/explodingcamera/next-plugin-styled-components/compare/v2.1.0...v10.0.2) (2020-11-19)

### Bug Fixes

* ensure compatibility with latest nextjs version ([ffe9108](https://github.com/explodingcamera/next-plugin-styled-components/commit/ffe910824eb50ba46e2656cd634a45dd919db343))

# [2.1.0](https://github.com/explodingcamera/next-plugin-styled-components/compare/v2.0.0...v2.1.0) (2020-11-17)

### Bug Fixes

* fix compatibility with latest next.js version ([df4a41c](https://github.com/explodingcamera/next-plugin-styled-components/commit/df4a41cb3c627c6952940cf5c7b992233b79866a))

# [2.0.0](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.3.0...v2.0.0) (2020-08-05)

### Features

* BREAKING: rewrite to support newest next.js version ([b7cff35](https://github.com/explodingcamera/next-plugin-styled-components/commit/b7cff35faa65bc598dc047a2b73cc7a6bca33cee))

# [1.3.0](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.2.1...v1.3.0) (2020-03-20)

### Bug Fixes

* compatibility with next 9.3 ([42983bd](https://github.com/explodingcamera/next-plugin-styled-components/commit/42983bdee85f4add9ef0c33d2fc629f1bf91d850))

## [1.2.1](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.2.0...v1.2.1) (2020-03-07)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

# [1.2.0](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.1.0...v1.2.0) (2020-03-02)

### Features

* simplify installation, update dependencies ([1ab6a7d](https://github.com/explodingcamera/next-plugin-styled-components/commit/1ab6a7d7e93d4853d8d98ba5772289d918e20e2e))

# [1.1.0](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.0.4...v1.1.0) (2020-01-28)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

## [1.0.4](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.0.3...v1.0.4) (2020-01-21)

### Bug Fixes

* support node 13.x ([f9f50de](https://github.com/explodingcamera/next-plugin-styled-components/commit/f9f50de16bb213379632d1eedef85d25853905e9))

## [1.0.3](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.0.2...v1.0.3) (2020-01-17)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

## [1.0.2](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.0.1...v1.0.2) (2020-01-17)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

## [1.0.1](https://github.com/explodingcamera/next-plugin-styled-components/compare/v1.0.0...v1.0.1) (2020-01-17)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

# 1.0.0 (2020-01-17)

**Note:** Version bump only for package @explodingcamera/next-plugin-styled-components

gha_language: JavaScript


text:
#ABA Registration Pipeline

Accompanies the paper entitled "Laminar and Dorsoventral Molecular Organization of the Medial Entorhinal Cortex Revealed by Large-scale Anatomical Analysis of Gene Expression"

Helen L. Ramsden, Gülşen Sürmeli, Steven G. McDonagh and Matthew F. Nolan

All images used were acquired from the Allen Brain Atlas: http://mouse.brain-map.org/

## Notes

The Ipython notebook and accompanying files contain the workflow for registering images using the ABA. You can view this notebook here: http://nbviewer.ipython.org/github/MattNolanLab/Ramsden_MEC/blob/master/ABA%20Registration%20Pipeline.ipynb

Each code block in the notebook should be able to be run independently in a particular session, though of course some depend on others having been run at some point in the past (such as image download).

Some elements were run using Matlab, other scripts call ImageJ (where indicated) so you will need to have these installed on your computer, and you will also need to specify the path to them.

The only stage that is very difficult to run on a desktop computer is group registration.

The Example_Results folder contains the results of an example run with just 10 images. For this run we started with a list of genes of interest and our group-registered images for each section.

Please email helenlram [at] zoho [dot] com if you have any queries.

## Licence

Copyright (c) 2014, Helen Ramsden
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.


text:
# ChrTranEncryptDecryptClass

> VBA Class to encrypt/decrypt texts.

## Definition
**ChrTranEncryptDecryptClass** is a VBA Class module (.cls) that allows encrypt/decrypt text strings.

> Es necesario tener conocimientos básicos de programación de Clases VBA (POO, Programación Orientada a Objetos).
> It's necessarily knowdlement of Class VBA programation (POO, Object Oriented Programming)

Works under MS Excel(c) version 2007+. Do not require installation, just import the class to your project, instance the class and use its interfaces.

## Use mode
  1.  [Download ChrTranEncryptDecryptClass.cls](./project-dist/ChrTranEncryptDecryptClass_v1.0.0.cls).
  2.  Open a new Excel's macro enabled workbook.
  3.  Open the Visual Basic Editor (VBE) of VBA or press **Ctrl+F11**
  4.  Go to menu ***File > Importa File*** or press ***Ctrl+M***, then search the file **ChrTranEncryptDecryptClass.cls** and import it to the VBA project.
  5.  Create a new ChrTranEncryptDecryptClass object and call its methods and...
      ```vb
        Dim MyEncDec as ChrTranEncryptDecryptClass
        Dim MyText as String, MyEncryptedText as String

        let MyText = "Some text to encrypt"
        set MyEncDec = New ChrTranEncryptDecryptClass

        let MyEncryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyText) ' MyEncryptedText holds now the encrypted text.
      ```
  6. Enjoy **ChrTranEncryptDecryptClass**!

## About ChrTranEncryptDecryptClass methods
  1. ***CHRTRANGenerateRandomKey:*** Allows to get a string between 1-10 random characters that can serve as encryption keys. It has three optional parameters:

      1.  ***LowWord***: a number (>= 65 and <= 90) that corresponds with the initial ASCII characters range.
      2.  ***UpWord***: a number (<= 90 and >= 65) that corresponds with the final ASCII characters range.
      3.  ***xLenght***: a constant: *ctedKeyLengthRandom*, for random chars between 1 - 10 or *ctedKeyLength1 ... ctedKeyLength10*. By default: ctedKeyLength5 (five chars string).

      Use example:
      ```vb
        Dim MyEncDec as ChrTranEncryptDecryptClass
        Dim MyRndText as String

        set MyEncDec = New ChrTranEncryptDecryptClass
        let MyRndText = MyEncDec.CHRTRANGenerateRandomKey() ' MyRndText holds now a random string chars.
        ...
      ```
  2. ***CHRTRANEncryptDecrypt:*** Allows encryption/decryption string texts. Has six parameters, five of them are optionals:

      1.  ***UserText***: The text to encrypt/decrypt.
      2.  ***UserKey***: Optional. The text key to decrypt *UserText*. if you omit the value, a random key between 1 - 10 characters will be generated. if the encryption key was generated by the algorithm, *UserKey* is not required to decrypt.
      3.  ***EncDec***: Optional. A constant: *ctedEncrypt*, to decrypt, or *ctedDecrypt*, to decrypt. By default: *ctedDecrypt*.
      4.  ***RndKeyLength***: Optional. A constant that determines the length of the random key generated by the algorithm, possible values: *ctedKeyLengthRandom*, to random lenght between 1 - 10 or *ctedKeyLength1 ... ctedKeyLength10*. By default: ctedKeyLength5 (five characters in string). Do not required to decrypt.
      5.  ***RndKeyPosition***: Optional. A constant to determine the random key position in the resultant encrypted text. Do not required to decrypt. Possible values: *ctedRandom* (by default), to random position, or *ctedLeft, ctedRight*: left or right of the resultant text.
      6.  ***ResultType***: Optional. A constant that allows the result text type. Possible values: *ctedStatic* (by default), gets text with fixed content, or *ctedDymamic*, the result text will always have random characters, if it is used in encryption, wil be required in decryption.

      Example use:
      ```vb
        Dim MyEncDec as ChrTranEncryptDecryptClass
        Dim MyText as String, MyKey as String, MyEncryptedText as String, MyDecryptedText as String

        set MyEncDec = New ChrTranEncryptDecryptClass
        let MyKey = "myk3y"
        let MyText = "Some text to encrypt"

        ' Encrypt/Decrypt with own key. Static result.
        let MyEncryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyText, MyKey) ' GOHHIHHGLHGFGJGHHKHGFHHOHHKGJGHHKHHFGJGHGFHGOHFNHHIHIFHHGHHK
        let MyDecryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyEncryptedText, MyKey) ' "Some text to encrypt"

        ' Encrypt/Decrypt with keyt aleatoria. Static result.
        let MyEncryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyText) ' PFOHJ#$GLIGNGGNNGNGGGHGOLGNGHFFGOLGGHGOLGOGGGHGNGGOFGMOGOJHFGGOHGOL
        let MyDecryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyEncryptedText) ' "Some text to encrypt"

        ' Encrypt/Decrypt with own key. Dynamic result.
        let MyEncryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyText, MyKey, ResultType:=ctedDymamic) ' owppqppotponoroppsponppwppsoroppsppnoroponpowpnvppqpqnppopps
        let MyDecryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyEncryptedText, MyKey, ResultType:=ctedDymamic) ' "Some text to encrypt"

        ' Encrypt/Decrypt with random key. Dynamic result.
        let MyEncryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyText, ResultType:=ctedDymamic) ' #TRLWR$QVWQYSQXUQXUQQVRPPQXURPTRPPQQVRPPQYUQQVQXUQYTQXSQYXRPUQYVRPP
        let MyDecryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyEncryptedText, ResultType:=ctedDymamic) ' "Some text to encrypt"

        ' Encrypt/Decrypt with random key. Static result, position key: left.
        let MyEncryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyText, RndKeyPosition:=ctedLeft) ' #TRLWR$QVWQYSQXUQXUQQVRPPQXURPTRPPQQVRPPQYUQQVQXUQYTQXSQYXRPUQYVRPP
        let MyDecryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyEncryptedText) ' "Some text to encrypt"

        ' Encrypt/Decrypt with random key. Static result, position key: right.
        let MyEncryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyText, RndKeyPosition:=ctedRight) ' QUXQYWQXQQWVQPWQYQQWVQYUQYQQPWQYQQXVQPWQWVQXUQWTQXYQYVQXWQYQ$KVHKI#
        let MyDecryptedText = MyEncDec.CHRTRANEncryptDecrypt(MyEncryptedText) ' "Some text to encrypt"

        set MyEncDec = nothing
      ```

## Collaborate in GitHub:
The **ChrTranEncryptDecryptClass's** source code is in: [project-dev directory](./project-dev/ChrTranEncryptDecryptClass.cls) in official repository.

As soon as you download the source code, you can collaborate with improvements in the algorithm, always under the [License terms](./LICENSE), [The Code of Conduct](./CODE_OF_CONDUCT.md) and the [Contributing terms](./CONTRIBUTING.md).

## Website

[ChrTranEncryptDecryptClass](https://roccouu.github.io/ChrTranEncryptDecryptClass/docs/index.html)

## Tutorial

[ChrTranEncryptDecryptClass Tutorial](https://roccouu.github.io/ChrTranEncryptDecryptClass/docs/index.html#/tutorial)

## Documentation

[ChrTranEncryptDecryptClass Documentation](https://roccouu.github.io/ChrTranEncryptDecryptClass/index.html#/docs/index.html#/documentation)

## Contributing

See [CONTRIBUTING guides](./CONTRIBUTING.md)

## Spanish Readme

[README.md](./README.md)

## License

[MIT](./LICENSE) © |<EMAIL_ADDRESS>| 2020 - 2021 | Potosí - Bolívia

repository: Roccouu/ChrTranEncryptDecryptClass

repo_name: Roccouu/ChrTranEncryptDecryptClass


text:
---
layout: default
title: "Adding an app to your Harvest instance"
author: caljess599
category: "tutorial"
published: true
---

*Guest article written by [@caljess599](https://github.com/caljess599) on GitHub.*

---

Since Harvest is a set of Django apps, you can add any Django app to your project. As a beginner with databases, I wanted to add a tool that would allow me to import data into my Harvest project.

Please note, I'm using the SQLite database that comes preattached to the Harvest project.

### Where to install packages?

You need to install a package inside the virtual environment belonging to your Harvest project. That way the Harvest instance knows to load it.

### Virtual Environment Wrapper (virtualenvwrapper)

This is a handy tool that allows the user to easily find and manage virtual environments. [Installation instructions](http://virtualenvwrapper.readthedocs.org/en/latest/install.html)

Harvest works nicely with this tool: once you have installed and configured this tool, you can `init` a Harvest project with the `--venv-wrap` option and it will place the virtual environment where you've specified in your virtualenvwarpper configuration. That makes it really easy to find and control the environment.

### Where and how to install a Python package

If your package is on the Python Package Index (PyPI), then installation can be done through `pip`, the same command-line tool that you used to install Harvest. [Installation instructions](https://django-import-export.readthedocs.org/en/latest/installation.html)

Simply navigate to the directory where your virtual environments are located and activate (if the first time) or bring up (the virtualenvwrapper command is `workon projectname`. When the virtual environment is up, you can now install packages and they will go into that virtual environment.

### Adding your app to `INSTALLED_APPS`

Now, in your Harvest project's `global_settings.py` file, you'll need to add the name of your app to the list under `INSTALLED_APPS`. Then refer to the documentation of your particular package as to what else you need to create/modify in order to access the functionality of your specific package.

### What the import_export package does

Harvest is my first experience with database work. My current goal is to explore the tool itself, so for that purpose using the attached SQLite database is adequate. In order to populate this database with my own data, I needed a package that made this easier than writing my own python script.

There are several packages in the PyPi that offer this functionality. I choose this package because it had good documentation and supported the importaton of many different file types. (It also supports data export, but Harvest has that functionality included already).

### After you install the import_export package

As this is an admin tool, you'll need to create (if you haven't already done so) an `admin.py` file among your project files.

The `ResourceClass` and `AdminClass` that you specify in this file allows the import_export tool how to work with your model.

```python
from django.contrib import admin
from projectname.models import Practice
from import_export import resources
from import_export.admin import ImportExportModelAdmin

class PracticeResource(resources.ModelResource):
    class Meta:
        model = Practice
        # The primary key must be explicity set if not 'id'
        import_id_fields = ['practice_id']

class PracticeAdmin(ImportExportModelAdmin):
    resource_class = PracticeResource
    list_display = ('practice_id', 'care_model', 'risk_profile', 'size')

admin.site.register(Practice, PracticeAdmin)
```

This setup will allow you to import from a file (many formats supported) where the header rows match your model's field names. If they do not match exactly, you'll need to specify what those names are (otherwise the tool doesn't know what data goes where). Please refer to the documentation for [further information](https://django-import-export.readthedocs.org/en/latest/index.html).

repository: chop-dbhi/harvest-site

branch_name: refs/heads/gh-pages

repo_name: chop-dbhi/harvest-site


text:
# hacks-blog-clone

> A simplistic clone of Mozilla's [hacks blog](https://hacks.mozilla.org/) built with WordPress & React

## development

1. set up a local WP site named `hacks-blog-clone` (see [this blog post](https://www.smashingmagazine.com/2018/04/wordpress-local-development-beginners-setup-deployment/))
2. install project dependencies (`npm i`)
3. run the site in development mode (`npm start`)

repository: shwilliam/hacks-blog-clone

repo_name: shwilliam/hacks-blog-clone


text:
# CurriedFunction

Represents single argument function. Provides static factories to create curried versions of multi argument functions.

## Currying

The concept is simple - it is transforming function taking multiple arguments into sequence of functions each taking single argument.

```php
$greeter = fn (string $greeting, string $name): string => "{$greeting} {$name}!";

$curriedGreeter = CurriedFunction::curry2($greeter);

$englishGreeter = $curriedGreeter("Hello"); // partial apply
echo $englishGreeter("John"); // Hello John!
echo $englishGreeter("Paul"); // Hello Paul!

$spanishGreeter = $curriedGreeter("Hola"); // partial apply
echo $spanishGreeter("Diego"); // Hola Diego!
```

You might wonder, where this can be useful. We can leverage this everywhere, where we expect single argument closure but we have two arguments function.

E.g.

```php
$strings = ArrayList::of('a', 'b');
$times1 = ArrayList::of(1, 2, 3);
$times2 = ArrayList::of(4);

$strRepeat = CurriedFunction::self::curry2(str_repeat(...));

$partiallyApplied = $strings->map($strRepeat);

// ArrayList::fromIterable(['a', 'aa', 'aaa', 'b', 'bb', 'bbb']
$fullyApplied1 = $partiallyApplied->flatMap(fn ($pa) => $times1->map($pa));

// ArrayList::fromIterable(['aaaa', 'bbbb']
$fullyApplied2 = $partiallyApplied->flatMap(fn ($pa) => $times2->map($pa));
```

API provides factories to curry functions with up to 30 arguments. Reason to have factories by number of arguments is to provide type safety.
If you use phpstan (which we strongly recommend), it can check all input parameters.

## Composition

Single argument functions are easy to compose. We provide `map` function for this purpose.

```php
$plusOne = fn (int $i): int => $i + 1;
$timesTwo = fn (int $i): int => $i * 2;

$plusOneThenTimesTwo = CurriedFunction::of($plusOne)->map($timesTwo);
$plusOneThenTimesTwo(5); // 12
```

`$f->map($g)` is equivalent of `g ∘ f` or `g(f(x))` in mathematics notation.

```php
$composed1 = $f->map($g);
$composed2 = fn ($x) => $g($f($x));
// $composed1 and $composed2 are equivalent
```

With phpstan, it also checks input / output arguments and creates typed version of composed function.
```php
function foo(string $s): int {
    return strlen($s);
}

/**
* @param int $i
* @return array<string>
 */
function bar(int $i): array {
    return array_fill(0, $i, 'a');
}
// accepts string and returns array<string>.
// composed type is CurriedFunction<string, array<string>> which is equivalent of callable(string): array<string>
$foobar = CurriedFunction::of(foo(...))->map(CurriedFunction::of(bar(...)));
$foobar('abc'); // ['a', 'a', 'a']
```

repository: bonami/collections

gha_language: PHP

repo_name: bonami/collections


text:
## SV-eQTL discovery

We used Matrix-eQTL to test for association between our SV genotypes and gene expression across samples from the GEUVADIS dataset (4 European populations + YRI).
The commands used to find eQTLs are in the [find-eqtls.R](find-eqtls.R) script.
The expression matrix (downloaded within the script) is available at [https://www.ebi.ac.uk/arrayexpress/files/E-GEUV-1/GD462.GeneQuantRPKM.50FN.samplename.resk10.txt.gz](https://www.ebi.ac.uk/arrayexpress/files/E-GEUV-1/GD462.GeneQuantRPKM.50FN.samplename.resk10.txt.gz).

## Joint eQTL discovery for SNVs, indels, and SVs

The SNVs and indels were downloaded from [http://ftp.1000genomes.ebi.ac.uk/vol1/ftp/data_collections/1000G_2504_high_coverage/working/20201028_3202_phased/][http://ftp.1000genomes.ebi.ac.uk/vol1/ftp/data_collections/1000G_2504_high_coverage/working/20201028_3202_phased/) and formatted using the [subset-vcf.py](subset-vcf.py) script:

```sh
## list samples to keep (those with expression data)
zcat GD462.GeneQuantRPKM.50FN.samplename.resk10.txt.gz | head -1 | cut -f 5- | sed 's/\t/\n/g' > sample.list
mkdir 1000gp-nygc-variants

for CHR in `seq 1 22`
do
	## download full VCF with phased SNVs and indels
    ~/.aspera/connect/bin/ascp -i ~/.aspera/connect/etc/asperaweb_id_dsa.openssh -Tr -Q -l 100M -P33001 -L- fasp-g1k@fasp.1000genomes.ebi.ac.uk:vol1/ftp/data_collections/1000G_2504_high_coverage/working/20201028_3202_phased/CCDG_14151_B01_GRM_WGS_2020-08-05_chr${CHR}.filtered.shapeit2-duohmm-phased.vcf.gz .
	## subset and format into 0/1/2 genotype
	zcat CCDG_14151_B01_GRM_WGS_2020-08-05_chr${CHR}.filtered.shapeit2-duohmm-phased.vcf.gz | python subset-vcf.py | gzip > 1000gp-nygc-variants/CCDG_14151_B01_GRM_WGS_2020-08-05_chr${CHR}.filtered.shapeit2-duohmm-phased.012.tsv.gz
	## remove full VCF
	rm CCDG_14151_B01_GRM_WGS_2020-08-05_chr${CHR}.filtered.shapeit2-duohmm-phased.vcf.gz
done
```

Once the SNV/indel data downloaded the eQTL discovery was performed using the commands in the [find-eqtls-all-variants.R](find-eqtls-all-variants.R) script.
It assumes the SV-only analysis was run first as it reuses some of its temporary files.

## eQTL results exploration

The [eqtl-summary.md](eqtl-summary.md) and [eqtl-summary-snv-indel-sv.md](eqtl-summary-snv-indel-sv.md) reports show p-value distribution, QQ plots and a summary of the eQTLs found in the two analysis mentioned above.

To compile the reports:

```
Rscript -e "rmarkdown::render('eqtl-summary.Rmd')"
Rscript -e "rmarkdown::render('eqtl-summary-snv-indel-sv.Rmd')"
```

## Description of eQTL files

The files used in this analysis are described in more details in [`files-README.md`](files-README.md).

repository: prometheusloong/giraffe-sv-paper

repo_name: prometheusloong/giraffe-sv-paper