text:
# TODOs

## Blockers

- ~~enhance list and single post page layout~~

User

- ~~Enhance labels in auth page (use register rather than sign up)~~
- ~~Add fields in register form~~
- ~~Claims~~
- add sync with firebase
- add artist page

## Bugs

- ~~main date is broken on post~~
- ~~finalise post dao -> ID issue~~
- ~~implement corresponding tests~~
- ~~update, delete, list,~~ tags
- full select on double click

## Features

- ~~comment~~
- chat
- ~~todos~~
- images
- video
- add search, enhance filtering
- better management of the session time out

## Layout

- top header
  - menu
  - become small on scrolling
- media queries
- ~~video~~
- prevent breaking the layout when images are not there

## Cards

- ~~enhance list and single post page layout~~
- First, check the [doc](https://material.io/guidelines/components/cards.html#cards-behavior)
- manage images
- ~~add comments~~
- limit desc size

## Hover buttons

- ~~Cancel in card edit~~
- auto save
- tooltips
- ~~snackbars for error and save feedback to user~~
- Enhance snack bar:
  - differenciate errors and OK
  - retrieve relevant message
  - queue multiple message

## Edition

- bind CTRL-S
- Enhance error msg and save feedback
- ~~bind submit button with enter keystroke on login page~~
- full text & images are selected when navigating using double click
- ~~rather store name than display name in author field~~
- export mongoDB content as JSON

## Auth

- longer session
- renew
- add gmail, facebook, mail validity check?
- log API requests in a separate mongodb bucket

Markdown editor

- maximize usable space
- stable layout
- media query

## Dev Ops

- Downgrad react version
- Stabilise distribution
- define deployment
- make CLI command for ~~start~~, backup and import posts

## Users

- Settings update
- User management
- ~~claims, display or not~~
- Add tests to check claims on post & delete

## Backend

- clean comments on post delete

repository: bsinou-agent/vitrnx

repo_name: bsinou-agent/vitrnx


text:
# Questions and Answers related to C-19 (ncov).

- What kind of virus is it?
- What other species apart from humans does it infect (mammals, birds)?
- What are its cousins (e.g., SARS, MERS)?
- What are all the symptoms?
- What is the progression of symptoms (broken down by age)?
- How does it spread? (e.g., via droplets and surfaces)
- How long can it survive on surfaces?
- How rapidly does it spread (virulence, Umea research, etc)?
- Where did it originate?
- A table of countires, # of infected, # of deaths, # of severe cases broken down by age, gender, nationality, underlying condition?
- Is there a pattern in the death rates? What are the most vulnerable populations?
- Is the mortality rate and severity consistent across all countries?
- When and where was the first documented case?
- What is the rate of reinfection? What is the severity of reinfection (mortality rate, etc)?
- Why are children and younger adults asymptomatic and are not as affected as older populations?
- How long does it take for symptoms to appear from the time of infection?
- What is the co-pathogenesis (what underlying conditions are worst)?
- How quickly does it progress from first symptoms to severe ones? What fraction of cases results in severe ones?

## Genetics & Biochemistry
- Which of the host cells have similar receptors as c19 (S-proteins)?
- What causes RBD to switch from down to up?
- What are the sites of attack (on c19 and host cells)? Are they the same across all species?
- How similar is its shell to SARS and MERS?

## Testing
- How is c19 treated?

## Treatment
- What currently available drugs are effective against it?
- How about a pneumonia vaccine (if most people get pneumonia)?
- What is the optimum number of ICU per population at different virulence rates?

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
## Assets

This folder contains the meshes and [URDF](http://wiki.ros.org/urdf/Tutorials) files of the objects. dVRK meshes are
modified from [AMBF](https://github.com/WPI-AIM/ambf). Note that PyBullet computes the forward and inverse kinematics
when the links are in sequential order, which is not the property in the original AMBF files. So we modify the link
frames to enable this feature. Besides, most of the objects are modeled using [Blender](https://www.blender.org/).
Furthermore, to make the physics simulation more stable, especially if there are physical contacts, we
use [V-HACD](https://github.com/kmammou/v-hacd) to decompose the visual meshes into convex parts for the collision
computation.

license: MIT

repository: WELLBEINGLWB/SurRoL

branch_name: refs/heads/main

gha_license_id: MIT

repo_name: WELLBEINGLWB/SurRoL


text:
# CLI Hooks

A collection of useful hook scripts for Ionic apps.

## Install

```bash
$ npm i @ionic/cli-hooks
```

## Use

Modify your `ionic.config.json` file to add a `hooks` object:

```json
  "hooks": {
    "<hook>": [
<EMAIL_ADDRESS>    ]
  }
```

Replace `<hook>` with the name of the hook you want to use and `<file>` with
the file name within this package.

See [CLI Hook
documentation](https://ionicframework.com/docs/cli/configuring.html#hooks) for
details.


text:
---
layout: post
title:      "Looking Back, Looking Ahead..."
date:       2018-09-16 07:04:55 +0000
permalink:  looking_back_looking_ahead
---

Whew! After 13 months, it is hard to believe my time at Flatiron School is winding down. I just submitted my React final project and passing the assessment, I will be finished with the course. Looking back, I am amazed at the journey and how far I've come.

As I finished the final project I became aware of how my confidence in my coding abilities has grown over the course of the program. As I finish, I eagerly await the job search and look forward to continuing to build my skillset. In addition to the job search activities, some of the major things I plan on working on after graduation include:
* Building out functionality on my React project and deploying it via Heroku.
* Refining my other four Flatiron School projects.
* Practicing algorithms and data structures in preparation for technical job interviews.

Can't wait to get started!

extension: markdown


text:
Renesas M16C programmer
=======================

This is the code for a Renesas M16C SerialIO programmer, based on an iCEStick FPGA devboard and Python host software.

Its most interesting feature is being able to crack the security PIN of the bootloader using a simple timing attack on the busy line.

To build and connect the adapter to the target, see adapter/README.md.

To run the host software to dump the target flash, see host/README.md.

The code has been tested to work against a Renesas M306K9FCLRP pulled from a Toshiba R100 Portege laptop.

License
-------

All the code in this repository is licensed under a BSD-style 2-clause license.


text:
# slideshow-on-idle

This script runs image slideshow using feh image viewer after defined idle time. It can be used as screensaver.

####Usage:
```
slideshow-on-idle [-v] <idle time seconds> <slideshow delay seconds> [files/directories/URLs ...]
```

repository: StepanOrt/slideshow-on-idle

repo_name: StepanOrt/slideshow-on-idle


text:
# Release Management

## Overview

This document describes Gatekeeper project release management, which includes release versioning, supported releases, and supported upgrades.

## Legend

- **X.Y.Z** refers to the version (git tag) of Gatekeeper that is released. This is the version of the Gatekeeper image and the Chart version.
- **Breaking changes** refer to schema changes, flag changes, and behavior changes of Gatekeeper that may require a clean installation during upgrade, and it may introduce changes that could break backward compatibility.
- **Milestone** should be designed to include feature sets to accommodate 2 months release cycles including test gates. GitHub's milestones are used by maintainers to manage each release. PRs and Issues for each release should be created as part of a corresponding milestone.
- **Patch releases** refer to applicable fixes, including security fixes, may be backported to support releases, depending on severity and feasibility.
- **Test gates** should include soak tests and upgrade tests from the last minor version.

## Release Versioning

All releases will be of the form _vX.Y.Z_ where X is the major version, Y is the minor version and Z is the patch version. This project strictly follows semantic versioning.

The rest of the doc will cover the release process for the following kinds of releases:

**Major Releases**

No plan to move to 4.0.0 unless there is a major design change like an incompatible API change in the project

**Minor Releases**

- X.Y.0-alpha.W, W >= 0 (Branch : master)
    - Released as needed before we cut a beta X.Y release
    - Alpha release, cut from master branch
- X.Y.0-beta.W, W >= 0 (Branch : master)
    - Released as needed before we cut a stable X.Y release
    - More stable than the alpha release to signal users to test things out
    - Beta release, cut from master branch
- X.Y.0-rc.W, W >= 0 (Branch : master)
    - Released as needed before we cut a stable X.Y release
    - soak for ~ 2 weeks before cutting a stable release
    - Release candidate release, cut from master branch
- X.Y.0 (Branch: master)
    - Released every ~ 3 months
    - Stable release, cut from master when X.Y milestone is complete

**Patch Releases**

- Patch Releases X.Y.Z, Z > 0 (Branch: release-X.Y, only cut when a patch is needed)
    - No breaking changes
    - Applicable fixes, including security fixes, may be cherry-picked from master into the latest supported minor release-X.Y branches.
    - Patch release, cut from a release-X.Y branch

## Supported Releases

Applicable fixes, including security fixes, may be cherry-picked into the release branch, depending on severity and feasibility. Patch releases are cut from that branch as needed.

We expect users to stay reasonably up-to-date with the versions of Gatekeeper they use in production, but understand that it may take time to upgrade. We expect users to be running approximately the latest patch release of a given minor release and encourage users to upgrade as soon as possible.

We expect to "support" n (current) and n-1 major.minor releases. "Support" means we expect users to be running that version in production. For example, when v3.3.0 comes out, v3.1.x will no longer be supported for patches, and we encourage users to upgrade to a supported version as soon as possible.

## Supported Kubernetes Versions

Gatekeeper is assumed to be compatible with the [current Kubernetes Supported Versions](https://kubernetes.io/releases/patch-releases/#detailed-release-history-for-active-branches) per [Kubernetes Supported Versions policy](https://kubernetes.io/releases/version-skew-policy/).

For example, if Gatekeeper _supported_ versions are v3.7 and v3.8, and Kubernetes _supported_ versions are v1.22, v1.23, v1.24, then all supported Gatekeeper versions (v3.7, v3.8) are assumed to be compatible with all supported Kubernetes versions (v1.22, v1.23, v1.24). If Kubernetes v1.25 is released later, then Gatekeeper v3.7 and v3.8 will be assumed to be compatible with v1.25 if those Gatekeeper versions are still supported at that time.

If you choose to use Gatekeeper with a version of Kubernetes that it does not support, you are using it at your own risk.

## Upgrades

Users should be able to run both X.Y and X.Y + 1 simultaneously in order to support gradual rollouts.

## Acknowledgement

This document builds on the ideas and implementations of release processes from projects like Kubernetes and Helm.

repository: open-policy-agent/gatekeeper

gha_language: Go

repo_name: open-policy-agent/gatekeeper


text:
# html5

Any **flare** components are entirely established on top of the *html5*-library.

The *html5* library is flare's core module and key feature, and manages access to the browser's DOM and its items, by implementing a Python object wrapper class for any HTML-element. Such an element is called *widget*. For example, `html5.Div()` is the widget representing a div-element, or `html5.A()` a widget representing an a-element. Widgets can be sub-classed into specialized components, which contain other widgets and components and interact together.

The document's body and head can directly be accessed by the static widgets `html5.Head()` and `html5.Body()`.

All these widgets are inheriting from an abstract widget wrapper called `html5.Widget`. `html5.Widget` is the overall superclass which contains most of the functions used when working with DOM elements. Therefore, all widgets are usually handled the same way, except leaf-type widgets, which may not contain any children.

## First steps

When working with native HTML5 widgets, every widget must be created separately and stacked together in the desired order. This is well known from JavaScript's createElement-function.

Here's a little code sample.

```python
from flare import html5

# Creating a new a-widget
a = html5.A()
a["href"] = "https://www.viur.dev"  # assign value to href-attribute
a["target"] = "_blank"              # assign value to target-attribute
a.addClass("link")                  # Add style class "link" to element

# Append text node "Hello World" to the a-element
a.appendChild(html5.TextNode("Hello World"))

# Append the a-widget to the body-widget
html5.Body().appendChild(a)
```

Summarized:

- `html5.Xyz()` creates an instance of the desired widget (the notation is that the first letter is always in uppercase-order, the rest is hold in lowercase-order, therefore e.g. `html5.Textarea()` is used for a textarea)
- Attributes are accessible via the attribute indexing syntax, like `widget["attribute"]`. There are some special attributes like `style` or `data` that are providing a dict-like access, so `widget["style"]["border"] = "1px solid red"` is used.
- Stacking is performed with `widget.appendChild()`. There's also `widget.prependChild()`, `widget.insertBefore()` and `widget.removeChild()` for further insertion or removal operations.
- To access existing child widgets, use `widget.children(n)` to access the *n*-th child, or without *n* to retrieve a list of a children.

## Parsing widgets from HTML-code

Above result can also be achieved much faster, by using the build-in [HTML5-parser and renderer](#html-parser-reference).

```python
from flare import *

html5.Body().appendChild(
    "<a href='https://www.viur.dev' target='_blank' class='viur'>Hello World</a>"
)
```

That's quite simpler, right? This is a very handy feature for prototyping and to quickly integrate new HTML layouts.

`Widget.appendChild()` and other, corresponding functions, allow for an arbitrary number of elements to be added. HTML-code, widgets, text or even lists or tuples of those can be given, like so

```python
ul = html5.Ul()
ul.appendChild("<li class='is-active'>lol</li>")
ul.prependChild(html5.Li(1337 * 42))
ul.appendChild("<li>me too</li>", html5.Li("and same as I"))
```

The HTML parser can also do more: When component classes (any class that inherits directly from html5.Widget, like html5.Div or so) are decorated with the [html5.tag](#html5tag)-decorator, these are automatically made available in the HTML-parser for recognition.

## Inheritance is normal

In most cases, both methods shown above are used together where necessary and useful. Especially when creating new components with a custom behavior inside your app, knowledge of both worlds is required.

To create new components, inheriting from existing widgets is usual. If we would like to add our link multiple times within our app, with additional click tracking, we can make it a separate component, like so:

```python
import logging
from flare import *

class Link(html5.A):  # inherit Link from html5.A widget
    def __init__(self, url, *args, target="_blank", **kwargs):
        super().__init__()
        self.addClass("link")
        self["href"] = url
        self["target"] = "_blank"

        self.appendChild(*args, **kwargs)
        self.sinkEvent("onClick")

    def onClick(self, event):
        logging.info(f"The link to {self['href']} has been clicked")

html5.Body().appendChild(
    # Create a link with text
    Link("https://www.viur.dev", "ViUR Framework"),

    "<br>",

    # Create link with logo
    Link("https://www.python.org", """
        <img src="https://www.python.org/static/community_logos/python-powered-h-50x65.png"
            title="Python Programming Language">
    """)
)
```

In this example, we just made our first custom component: The `Link`-class can be arbitrarily used.

## Widget basics

Following sections describe the most widely used functions of the `html5.Widget`-class which are inherited by any widget or huger component in flare.

### Constructor

All widgets share the same `__init__`-function, having the following signature:

```python
def __init__(self, *args, appendTo=None, style=None, **kwargs)
```

- `*args` are any positional arguments that are passed to `self.appendChild()`. These can be either other widgets or strings containing HTML-code. Non-container widgets like `html5.Br()` or `html5.Hr()` don't allow anything passed to this parameter, and throw an Exception.
- `appendTo` can be set to another html5.Widget where the constructed widget automatically will be appended to. It substitutes an additional `appendChild()`-call to insert the constructed Widget to the parent.
- `style` allows to specify CSS-classes which are added to the constructed widget using
- `**kwargs` specifies any other parameters that are passed to `appendChild()`, like variables.

### Insertion and removal

These methods manipulate the DOM and it's nodes

#### appendChild()

Appends another html5.Widget as child to the parent element:

```python
self.appendChild("""<ul class='navlist'></ul>""")
self.nav.appendChild("""<li>Navigation Point 1</li>""")
```

#### prependChild()

Prepends a new child to the parent element
```python
self.appendChild("""<ul class='navlist'></ul>""")
navpoint2 = self.nav.appendChild("""<li>Navigation Point 2</li>""")
navpoint2.prependChild(("""<li>Navigation Point 1</li>"""))
```

#### replaceChild()

Same as appendChild(), but removes the current children of the Widget first.

#### insertBefore()

Inserts a new child element before the target child element

```python
self.appendChild("""<ul class='navlist'></ul>""")
navpoint = self.nav.appendChild("""<li>Navigation Point 1</li>""")
navpoint3 = self.nav.appendChild("""<li>Navigation Point 3</li>""")
navpoint2 = self.nav.insertBefore("""<li>Navigation Point 2</li>""", navpoint3)
```

If the child element that the new element is supposed to be inserted before does not exist, the new element is appended to the parent instead.

#### removeChild(), removeAllChildren()

Either reemoves one child from the parent element or all available children.

### Visibility and usability

Widgets can be switched hidden or disabled. Form elements, for example, might be disabled when a specific condition isn't met. These functions here help to quickly change visibility and usability of widgets, including their child widgets.

#### hide(), show()

Hides or shows a widget on demand.

To check whether a widget is hidden or not, evaluate `widget["hidden"]`. In the HTML-parser, this flag can be set using the `hidden` attribute, e.g. `<div hidden>You can't see me.</div>`.

#### enable(), disable()

Enable or disable the widget in the DOM. Useful for forms and similar UI applications.

To check whether a widget is disabled or not, evaluate `widget["disabled"]`. In the HTML-parser, this flag can be set using the `disabled` attribute, e.g. `<div disabled>I'm disabled</div>`.

### class-attribute modification

These methods are helpful for adding CSS-classes quickly.

#### addClass()

Adds a class to the html5.Widget and checks to prevent adding the same class multiple times.
```
nav = self.appendChild("""<ul></ul>""")
nav.addClass('navlist')
```

Adding a class multiple times might be wanted and is valid. In this case, modify the widget's `class`-attribute directly by assigning a list to it.

#### removeClass()

Checks if the widget has that class and removes it
```
nav = self.appendChild("""<ul class='big-red-warning-border-color'></ul>""")
nav.removeClass('big-red-warning-border-color')
```

#### toggleClass()

Toggles a class *on* or *off*, depending on whether it has the specified class already or not.

#### hasClass()

Checks if the element has a given class or not. Returns True if class name is found and False otherwise.
```
nav = self.appendChild("""<ul class='big-red-warning-border-color'></ul>""")
if nav.hasClass('big-red-warning-border-color'):
    print("Help! There is a big red border around this element! Remove the class so we can feel safe again")
```

## HTML parser reference

### Data-based rendering

#### Using variables

Any variables provided via kwargs to [html5.fromHTML()](#html5fromhtml) can be inserted in attributes or as TextNode-elements with their particular content when surrounded by `{{` and `}}`. Inside this notation, full Python expression syntax is allowed, so that even calculations or concatenations can be done.

```python
html5.Body().appendChild("""
    <div class="color-{{ l[1] + 40 }}">{{ d[ "world" ] + "World" * 3 }} and {{ d }}</div>
""", l=[1,2,3], d={"world": "Hello"})
```

renders into

```html
<div class="color-42">HelloWorldWorldWorld and {'world': 'Hello'}</div>
```

#### flare-if, flare-elif, flare-else

The attributes `flare-if`, `flare-elif` and `flare-else` can be used on all tags for conditional rendering.

This allows for any simple Python expression that evaluates to True or any computed non-boolean value representing True.

```python
html5.Body().appendChild("""
    <div>begin</div>
    <div flare-if="i <= 10">i is just low</div>
    <div flare-elif="i <= 50 and j >=100">i and j have normal values</div>
    <div flare-elif="i > 50 and j >= 50">i and j have moderate values</div>
    <div flare-else>i and j are something different</div>
    <div>end</div>
""", i=50, j=151)
```

As variables, any arguments given to [html5.fromHTML()](#html5fromhtml) (or related functions) as kwargs can be used.

### html5.parseHTML()

```python
def parseHTML(html: str, debug: bool=False) -> HtmlAst
```

Parses the provided HTML-code according to the tags registered by html5.registerTag() or components that use the [html5.tag](#html5tag)-decorator.

The function returns an abstract syntax tree representation (HtmlAst) of the HTML-code that can be rendered by [html5.fromHTML()](#html5fromhtml).

### html5.fromHTML()

```python
def fromHTML(html: [str, HtmlAst], appendTo: Widget=None, bindTo: Widget=None, debug: bool=False, **kwargs) -> [Widget]
```

Renders HTML-code or compiled HTML-code (HtmlAst).

- appendTo: Defines the Widget where to append the generated widgets to
- bindTo: Defines the Widget where to bind widgets using the `[name]`-attribute to
- debug: Debugging output
- **kwargs: Any specified kwargs are available as [variables to any expressions](#using-variables).

HTML-code can optionally be pre-compiled with [html5.parseHTML()](#html5parsehtml), and then executed multiple times (but with different variables) by fromHTML. This is useful when generating lists of same elements with only replaced variable data.

### @html5.tag

Decorator to register a sub-class of `html5.Widget` either under its class-name, or an associated tag-name.

Examples:
```python
from flare import html5

# register class Foo as <foo>-Tag
@html5.tag
class Foo(html5.Div):
    pass

# register class Bar as <baz>-Tag
@html5.tag("baz")
class Bar(html5.Div):
    pass
```

repository: xnopasaranx/flare

repo_name: xnopasaranx/flare


text:
# Setup Ionic 3 - Lazy Loading Modules/Routes
https://www.youtube.com/watch?v=7j-P-ElAqe8

# Angular2 Organization using barrels {}
http://tattoocoder.com/angular2-barrels/

## Fecth data from server
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

## Cordova Plugins in Ionic 2 with Ionic Native
https://www.joshmorony.com/using-cordova-plugins-in-ionic-2-with-ionic-native/

# Migrate from AngularJS
[Incrementally upgrade an AngularJS application to Angular](https://angular.io/docs/ts/latest/guide/upgrade.html)

[Migrating Angular 1 Applications to Latest Angular in 5 Simple Steps
](https://vsavkin.com/migrating-angular-1-applications-to-angular-2-in-5-simple-steps-40621800a25b)
[Intro to ECMAScript 6 and Angular 2](https://www.joshmorony.com/intro-to-ecmascript-6-and-angular-2-for-ionic-developers/)
[New Angular 2 Concepts & Syntax](https://www.joshmorony.com/ionic-2-first-look-series-new-angular-2-concepts-syntax/)

# Ionic 3
[Ionic 3 Lazy Loading](https://docs.google.com/document/d/1vGokwMXPQItZmTHZQbTO4qwj_SQymFhRS_nJmiH0K3w/edit#heading=h.2k1n0klvkce3)

[Steps to Upgrade to 3.0](https://github.com/driftyco/ionic/blob/master/CHANGELOG.md#steps-to-upgrade-to-30)
[Ionic and Lazy Loading Pt 1](http://blog.ionic.io/ionic-and-lazy-loading-pt-1/)
[Upgrade to Ionic 3 Lazy Loading (With Script!)](https://ionicacademy.com/ionic-3-lazy-loading/)

# Misc
[External JavaScript dependencies in Typescript and Angular 2](https://weblog.west-wind.com/posts/2016/Sep/12/External-JavaScript-dependencies-in-Typescript-and-Angular-2#De-referencingGlobals)

[New Split Pane, Ionic 2.2.0](http://blog.ionic.io/ionic-2-2-0-is-out/)
[New Responsive Grid, Ionic 2.1.0](http://blog.ionic.io/build-awesome-desktop-apps-with-ionics-new-responsive-grid/)
[VirtualScroll](https://www.joshmorony.com/boosting-scroll-performance-in-ionic-2/)

http://ionicframework.com/docs/
https://angular.io/docs/ts/latest/quickstart.html
Learn TypeScript:  https://www.tutorialspoint.com/typescript/index.htm

Angular2 *ngIf check object array length in template
http://stackoverflow.com/questions/37543362/angular2-ngif-check-object-array-length-in-template
Angular 4 *ngIf/Else
http://tylerscode.com/2017/03/angular-4-ngifelse/
[Angular cheatsheet](https://angular.io/cheatsheet)

# Optimize Ionic 2 app for Production
https://blog.khophi.co/optimize-ionic-2-app-production/

# Ionic and Forms
https://ionicframework.com/docs/resources/forms/
https://scotch.io/tutorials/angular-2-form-validation
https://toddmotto.com/angular-2-forms-template-driven
https://www.joshmorony.com/advanced-forms-validation-in-ionic-2

## Template-driven form

## Model-driven form (reactive)
https://toddmotto.com/angular-2-forms-reactive
http://tphangout.com/angular-2-reactive-forms/

## Why your cancel button submit the html form
https://log.rowanto.com/why-your-cancel-button-submit-the-html-form/

# Ionic 2 using custom css

## If custom css is within a node_module
http://thebrockellis.com/2017/03/23/primeng-Schedule-In-Ionic
https://chriztalk.com/ionic-2-font-awesome/

## If custom css could be copied in src/assets folder

> Add a folder css in the src/assets folder. Put your css file there. In the src/index.html file, add this line  <link href="assets/css/yourCssFileName.css" rel="stylesheet"> Then you can refer to anything in the css file in your other pages as what you normally do with web pages.

Source: https://stackoverflow.com/a/39940441

# Ionic 2 and External Libraries
Use typings https://mhartington.io/post/ionic2-external-libraries/
and check [Ionic 3.3.0](https://github.com/ionic-team/ionic/releases/tag/v3.3.0)

> Another optional step is to remove the src/declarations.d.ts file. This is a legacy file introduced early with ionic-angular projects to improve compatibility between TypeScript and third-party libraries. Due to improvements in TypeScript, this file is no longer necessary. By removing this file, the TypeScript compiler will be able to provide more accurate error messages for import statements.

## ionicons
http://ionicframework.com/docs/ionicons/

# Getting Started w/Angular 2.x+/4.0
https://angular.io/docs/ts/latest/tutorial/

## Angular 2 template syntax demystified
https://blog.thoughtram.io/angular/2015/08/11/angular-2-template-syntax-demystified-part-1.html

## ng-click and ng-if in Angular2
http://jilles.me/ng-click-and-ng-if-in-angular2/

## NgIf Else lands in Angular 2.x+/4.0
https://medium.com/aviabird/ngif-else-lands-in-angular-2-0-a242940e54ff

## Using Http to Fetch Remote Data
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

## Two Ways to Pass Data from one component to another
https://dzone.com/articles/angular-2-two-ways-to-pass-data
### Usage of @Input decorator

### Usage of inputs array

# Protecting Your App With Ionic Auth Guard "ionViewCanEnter()"

> The Ionic Auth Guards are the Ionic version of the [Angular Navigation Guards](https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html).
But Angular uses a different kind of routing (more of the classic URL routing style) than Ionic, which uses a simplified routing system targeted more towards mobile and the logic of different pages and viewcontroller.

https://devdactic.com/ionic-auth-guards/

# lifecycle ionic vs angular
[Angular lifecycle hooks](https://angular.io/guide/lifecycle-hooks)
https://github.com/ionic-team/ionic/issues/10081
http://blog.ionic.io/navigating-lifecycle-events/
https://stackoverflow.com/questions/43279265/which-view-lifecycle-to-use-in-an-ionic-2-project
https://saniyusuf.com/ionic-by-component-page-lifecycle/

# Ionic and Firebase: Email/Password Authentication
https://aaronczichon.de/2017/03/07/ionic-firebase-authentication/
https://progblog.io/Angular-2-Firebase-Tutorial-Part-4-Adding-Email-Password-Authentication/
https://progblog.io/Angular-2-Firebase-Tutorial-Part-2-Adding-Authentication/
https://javebratt.com/ionic-firebase-authentication/
http://tphangout.com/ionic-2-authentication-using-firebase/
https://aaronczichon.de/2017/03/07/ionic-firebase-authentication/
http://jasonwatmore.com/post/2016/09/29/angular-2-user-registration-and-login-example-tutorial
https://www.djamware.com/post/586bb16680aca70c73934116/ionic-2-firebase-email-authentication-tutorial
https://chriztalk.com/ionic-3-and-firebase-authentication/

[Ionic Auth Service](https://www.raymondcamden.com/2016/11/04/an-example-of-the-ionic-auth-service-with-ionic-2)

## Structure your data
https://firebase.google.com/docs/database/web/structure-data

# Ionic Starter
https://github.com/ionic-team/ionic-starter-super
# Furthermore
http://masteringionic.com/
https://progblog.io/
https://dev.to/hitman666/how-to-get-started-with-ionic-framework-3-on-mac-and-windows


text:
# [GetCultured](https://getcultured.herokuapp.com/) (RoR Microverse Capstone Project)

## GetCultured is a lifestyle blog site where people all over the world can view, like, and write articles about their culture, food, lifestyle, etc.

## Project Description

#### In this project, I designed my own online lifestyle publication with this [design](https://www.behance.net/gallery/14554909/liFEsTlye-Mobile-version) as a reference.

#### This sleek and modern website was built with a mobile-first approach, while applying fluid design principles. It is fully-responsive across all screen sizes - mobile, tablet, and desktop. Here, users can sign up, log in, write articles with multiple categories, and like other articles.

#### The purpose of this project was to demonstrate mastery of Ruby and RoR fundamentals. It has the following features:
- Uses MVP architectural pattern, with RESTFUL routes configured
- Utilizes controllers to intercept user requests, following Rails CRUD best practices/conventions
- Uses scopes and helpers to keep clode clean
- Uses view templates for HTML with embedded data
- Connected to Postgres Database and Active Storage for image attachments
- Has ActiveRecord validations and authentication via Devise
- Avoids n+1 queries problem
- Contains unit tests (Rspec)
- Deployed on Heroku

![readme-screenshot](https://user-images.githubusercontent.com/62937819/126404066-a1466bef-3bb2-4849-8fdf-ad329997fd5c.png)

## Live Demo

[Live Demo Link](https://getcultured.herokuapp.com/)

Check out my video presentation [here](https://www.loom.com/share/78f4ca36d77f4ec3bac8cb44a3278971?sharedAppSource=personal_library).

## Built with

- Ruby
- Ruby On Rails
- JavaScript
- Tailwind
- HTML
- CSS/SCSS
- JQuery
- Lots of :heart:

## Getting Started

To get a local copy up and running follow these simple steps:

## Setup

Before you can run the program, you need to make sure [Ruby](https://www.ruby-lang.org/en/) is installed on your computer. Then install gems with:

```
yarn install
```
```
bundle install
```
Then set up the database by running:
```
rails db:reset
```
```
rails db:seed
```

## Usage

Start server with:
```
rails s
```
Then open http://localhost:3000/ in your browser.

## Testing

You can run the following commands on your terminal to test the code:

> 1. run `gem install rspec`
> 2. run `rspec` within the root folder

## Author

Feel free to reach out. I'm always happy to connect :slightly_smiling_face:

👤 **Nikolas Escobal**

[](https://github.com/nikoescobal)
[](https://twitter.com/nikoescobal)
[](https://www.linkedin.com/in/nikolas-escobal/)

## 🤝 Contributing

Contributions, issues and feature requests are welcome!

Feel free to check the [issues page](issues/).

## Show your support

Give a ⭐ if you dig this project!

## Acknowledgments

- Microverse
- The Odin Project
- [Nelson Sakwa for the design inspiration](https://www.behance.net/sakwadesignstudio)
- [Damien](https://github.com/dkan), [Albert](https://github.com/albertpadin), [Paolo](https://www.linkedin.com/in/paolo-samontanez/), [Mkrtich](https://github.com/MkrtichSargsyan/), and [Chad](https://github.com/somoye123/) for the support. :heart:

## 📝 MIT License

This project makes use of the MIT license.

repository: euqueme/student-capstone

repo_name: euqueme/student-capstone


text:
# Minesweeper

Simple Javascript implementation of Minesweeper game.

## Getting Started

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

### Prerequisites

Python must be installed on your computer. Volume must be turned on on your device.

* Python comes pre-installed on Mac.
* [Install Python on Windows](https://www.howtogeek.com/197947/how-to-install-python-on-windows/)

### Installing

Download Repo from Github

```
1. Under repository name, click Clone or download
2. In the clone with HTTPs section, click clipboard to copy the clone URL for the repository
3. Open Terminal
4. Change to your preferred destination for cloning directions
	ex: cd Documents/
5. Type git clone, and then paste the URL from step 2.
	ex: git clone https://github.com/vibrantlife/minesweeper.github.com
6. Press Enter
```

## Deployment
```
1. Open Terminal
2. Enter python -m SimpleHTTPServer
```

## Acknowledgements

After conducting research from the resources below. I found my solution:

* [Flexbox Documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox)
* [Responsive Tables with CSS](https://wisdmlabs.com/blog/responsive-tables-using-css-div-tag/)
* [Logic for Minesweeper Game](https://www.techrepublic.com/article/building-a-minesweeper-type-game-in-javascript/)
* [Selecting Random Cells](https://stackoverflow.com/questions/34308247/select-random-table-cells-with-js)
* [Button Hover Affects](https://codepen.io/ritchiejacobs/pen/qEJjBM)

## Built With

* [jQuery](https://jquery.com/)
* [FontAwesome](https://fontawesome.com/)

## License

This project is licensed under the MIT License

repository: vibrantlife/minesweeper

repo_name: vibrantlife/minesweeper


text:
# Apollo Open Engine

Work in Progress alternative to the commercial available apollo-engine based on the same protocol.

```js
const apolloServer = new ApolloServer({
    ...
    engine: {
      endpointUrl: 'http://localhost:8000',
      apiKey: 'fake:key', // currently doesent matter
      sendReportsImmediately: true // helps with debugging
    },
    ...
  });
```

## Install

```bash
npm install
```

## Start

Guide how to run Apollo Open Engine

### Options

```bash
# Available 'fatal', 'error', 'warn', 'info', 'debug', 'trace' or 'silent'.
LOG_LEVEL=trace
```

```bash
npm start
```

# Test

```bash
npm test
```


text:
## About
As part of the Text Analysis Module from the [CAS Machine Intelligence](https://weiterbildung.zhaw.ch/de/school-of-engineering/programm/cas-machine-intelligence.html) at [ZHAW](https://www.zhaw.ch), I wrote a paper in german to get familiar with the Topi Text Summarization.

## Dependencies
* pandoc
* TeX distribution (only for PDF)
* bibtex file (generated with Zotero)
* Sublime Text 3 (ST3)
  * Markdown Extended
  * CiteBibtex
  * Pandoc

## Hints
in SublimeText 3:
* `F10` shows the entries from the bibtex.bib
* "CiteBibtex: extract citations in current file" -> extracts the used citations and stores them in a local bibex file
* "Pandoc" -> "PDF" creates the PDF file from the markdown file

on the command line run the following command to create the PDF document from the markdown file:
```
pandoc TextSummarization.mdown --latex-engine=xelatex --filter pandoc-citeproc -o Text\ Summarization\ \(Marcel_Canclini\).pdf
```


text:
# Traditional Optimal Embedding
This page discusses and provides algorithms for estimating optimal parameters to do Delay Coordinates Embedding (DCE) with.

The approaches can be grouped into two schools:
1. **Traditional** (also called **independent**), where one tries to independently find the best value for a delay time `τ` and an embedding dimension `d`.
2. **Unified**, where at the same time an optimal combination of `τ, d` is found, and is discussed in the [Unified Optimal Embedding](@ref) page.

The independent approach is something "old school", while recent scientific research has shifted almost exclusively to unified approaches.

## Optimal delay time
```@docs
estimate_delay
exponential_decay_fit
```
### Mutual Information
```@docs
mutualinformation
```

## Optimal embedding dimension
```@docs
optimal_traditional_de
delay_afnn
delay_ifnn
delay_fnn
delay_f1nn
DelayEmbeddings.stochastic_indicator
```

## Example
```@example MAIN
using DynamicalSystems, PyPlot

ds = Systems.roessler()
# This trajectory is a chaotic attractor with fractal dim ≈ 2
# therefore the set needs at least embedding dimension of 3
tr = trajectory(ds, 1000.0; dt = 0.05)
x = tr[:, 1]

dmax = 7
fig = figure()
for (i, method) in enumerate(["afnn", "fnn", "f1nn", "ifnn"])
    # Plot statistic used to estimate optimal embedding
    # as well as the automated output embedding
    𝒟, τ, E = optimal_traditional_de(x, method; dmax)
    plot(1:dmax, E; label = method, marker = "o", ms = 5, color = "C$(i-1)")
    optimal_d = size(𝒟, 2)
    scatter(optimal_d, E[optimal_d]; marker = "s", s = 100, color = "C$(i-1)")
end
legend(); xlabel("embedding dimension")
ylabel("estimator")
tight_layout()
fig.savefig("estimateD.png"); nothing # hide
```
![](estimateD.png)


text:
# Changelog

#### 2.0.2

> 250 Bytes.

* Removed optional argument to `String.prototype.charCodeAt()`.
* Removed redundant case from for-loop increment ternary (credit goes to
  [@rdebath](https://github.com/rdebath) for finding that!)

```js
/**
 * @param   {string}            a
 *                              The input brainfuck code.
 * @param   {ArrayLike<number>} t
 *                              The tape. An empty array by default.
 * @param   {() => number}      u
 *                              The user input function.
 * @return  {string}            The printed characters.
 */
module.exports = function*(a, t=[], u) {
    for (i=n=p=0, c=1; c; i+=n>=0?1:-1)
                          // ^^^^^^^^^ Much shorter!
        (
            n += (c = a[i]) == "["
                ? n
                    ? 1
                    : !t[p]
                : c == "]"
                    ? n
                        ? -1
                        : -!!t[p]
                    : 0
        ) || (
            t[p += c == ">" ? 1 : c=="<"?-1:0] =
                (t[p] || 0)
                +
                (c == '+'
                    ? 1
                    : c == '-'
                        ? -1
                        : 0
                ),
            c == '.'
                ? yield String.fromCharCode(t[p])
                : c == ','
                    ? t[p] = u().charCodeAt() // <- `0` is not necessary.
                    : 0
        )
}
```

#### 2.0.1

> 256 Bytes.

* Fixed nested loop issues!

This version just fixes the nested loop bug. It is a major version as I should
have made the previous version a major version. The bug was found by
[@rdebath](https://github.com/rdebath).

```js
/**
 * @param   {string}            a
 *                              The input brainfuck code.
 * @param   {ArrayLike<number>} t
 *                              The tape. An empty array by default.
 * @param   {() => number}      u
 *                              The user input function.
 * @return  {string}            The printed characters.
 */
module.exports = function*(a, t=[], u) {
    for (i=n=p=0, c=1; c; i+=n>0?1:n<0?-1:1)
        (
            n += (c = a[i]) == "["
                ? n
                    ? 1
                    : !t[p]
                : c == "]"
                    ? n
                        ? -1
                        : -!!t[p]
                    : 0
        ) || (
            t[p += c == ">" ? 1 : c=="<"?-1:0] =
                (t[p] || 0)
                +
                (c == '+'
                    ? 1
                    : c == '-'
                        ? -1
                        : 0
                ),
            c == '.'
                ? yield String.fromCharCode(t[p])
                : c == ','
                    ? t[p] = u().charCodeAt(0)
                    : 0
        )
}
```

#### 1.1.0

> 245 Bytes.

* Function is now a generator that yields on every character print (".").
* Initial tape type and contents can be modified by providing it as the second
  argument to the function. By default, the tape is an empty array, which is
  what it was previously.
* Re-structured the for-loop contents into one large expression.
* Updated tests.

```js
/**
 * @param   {string}            a
 *                              The input brainfuck code.
 * @param   {ArrayLike<number>} t
 *                              The tape. An empty array by default.
 * @param   {() => number}      u
 *                              The user input function.
 * @return  {string}            The printed characters.
 */
module.exports = function*(a, t=[], u) {
    for (i=n=p=0, c=1; c; i+=n||1)
        (
            n += (c = a[i]) == "["
                ? n
                    ? 1
                    : !t[p]
                : c == "]"
                    ? n
                        ? 1
                        : -!!t[p]
                    : 0
        ) || (
            t[p += c == ">" ? 1 : c=="<"?-1:0] =
                (t[p] || 0)
                +
                (c == '+'
                    ? 1
                    : c == '-'
                        ? -1
                        : 0
                ),
            c == '.'
                ? yield String.fromCharCode(t[p])
                : c == ','
                    ? t[p] = u().charCodeAt(0)
                    : 0
        )
}
```

#### 1.0.2

> 256 Bytes.

* Moved function arguments to for-loop initialisation. This stops developers
  from modifying the interpreter's initial values (such as the tape).
* Removed tape index 0 initialisation value.
* Transformed bracket for-loops into a series of nested ternary statements.
* Re-structured for-loop variable initialisations.
* Re-structured input and output commands into an inline ternary expression.
* Realised I don't need to split the input code into its individual characters.
  `a[i]` is the same as `[...a][i]`, if `a` is a `string`. 🤦

```js
/**
 * @param   {string}        a
 *                          The input brainfuck code.
 * @param   {() => number}  u
 *                          The user input function.
 * @return  {string}        The printed characters.
 */
// Variable initialisation has been moved from the function arguments to the
// for-loop initialiser.
module.exports = (a, u) => {
    for (t = [i=n=p=0], c = 1, s = ''; c; i += n || 1){
        c = a[i]; // <- No longer expanding `a` every loop!
        // Holy mother of ternary statements...
        if (n += c=="["?n?1:!t[p]:c=="]"?n?1:-!!t[p]:0) continue;
        t[p += c==">"?1:c=="<"?-1:0] = (t[p] || 0) + (c=='+'?1:c=='-'?-1:0);
        c == '.' ? s += String.fromCharCode(t[p]) : c==','?t[p]=u().charCodeAt(0):0
    }return s}
```

#### 1.0.1

> 292 Bytes.

I restructured the for-loop management by integrating each for-loop into the
primary character iteration loop.
Previously, the interpreter would wait until it reached a `[` and then, if
necessary, individually increment `i` to the index of the next un-nested `]`.
However, this required a second loop within the primary character iteration
loop, which uses a lot of characters! Now, the bracket nesting level is always
known, and `i` is incremented by the current "character-skip" direction,
removing the need for two nested loops.

```js
/**
 * @param   {string}        a
 *                          The input brainfuck code.
 * @param   {() => number}  u
 *                          The user input function.
 * @param   {number[]}      t
 *                          The data tape.
 * @param   {string}        c
 *                          The current character.
 * @param   {number}        p
 *                          The pointer index.
 * @param   {string}        s
 *                          The return value.
 * @return  {string}        The printed characters.
 */
module.exports = (a, u, t=[0], c=1, p=0, s='') => {
    b=[...a];

    // Notice how we are now initialising `n` in the character iteration
    // for-loop and using it to determine how to modify `i`, rather than
    // specifically waiting until we hit a bracket and explicitly skipping
    // characters using a nested loop.
    for (i = 0, n = 0; c; i += n || 1){
        c = b[i];
        if (c == '[') n = n ? n + 1 : +!t[p]
        if (c == ']') n = n ? n + 1 : -!!t[p]
        if (n) continue;

        t[p += c==">"?1:c=="<"?-1:0] = t[p] || 0;
        t[p] += c == '+' ? 1 : (c == '-' ? -1 : 0);
        if (c == '.') s += String.fromCharCode(t[p]);
        if (c == ',') t[p] = u().charCodeAt(0);
    }
    return s
}
```

#### 1.0.0

> 329 Bytes.

Initial release.

```js
/**
 * @param   {string}        a
 *                          The input brainfuck code.
 * @param   {() => number}  u
 *                          The user input function.
 * @param   {number[]}      t
 *                          The data tape.
 * @param   {string}        c
 *                          The current character.
 * @param   {number}        p
 *                          The pointer index.
 * @param   {string}        s
 *                          The return value.
 * @return  {string}        The printed characters.
 */
module.exports = (a, u, t=[0], c, p=0, s='') => {
    b = [...a];
    n = 0;
    for (i = 0; i < b.length; i++) {
        c = b[i];
        t[p+=c==">"?1:c=="<"?-1:0]=t[p]||0;
        t[p]+=c=='+'?1:(c=='-'?-1:0);

        if (c == '.') s += String.fromCharCode(t[p]);
        if (c == ',') t[p] = u().charCodeAt(0);
        if (c == '[' && !t[p])
            for (n=1; n > 0; i++)
                n -= b[i] == ']' ? 1 : 0;
        if (c == ']' && t[p])
            for (n = 1; n > 0; i--)
                n -= b[i] == '[' ? 1 : 0;
    }
    return s
}
```


text:
---
title: TypeScript
---

> [TypeScript](https://www.typescriptlang.org/) is a typed superset of JavaScript that compiles to plain JavaScript.

For a large number of enterprises' applications, TypeScript's static type checking, intellisense, friendly IDE are valuable. For more please see [System Research Report For TypeScript](https://juejin.im/post/59c46bc86fb9a00a4636f939).

However, we've met some problems influencing users' experience when developing Egg in TypeScript:

- The most outstanding Loader Mechanism (Auto-loading) makes TS not analyze dependencies in static.
- How to validate and show intellisense in `config.{env}.js`, when we modify settings by plugin and these configurations are automatically merged?
- During the period of developing, `tsc -w` is created as an independent process to build up codes, it makes us entangled about where to save the temporary files, and the complicated `npm scripts`.
- How to map to the TS source files instead of compiled js files in unit tests, coverage tests and error stacks online?

This article mainly describes:

- **Developing principles of TS for the application layer.**
- **How do we solve the problem for developers with the help of the tool chain so that they have no scene about it and keep in consistency**

For more about this tossing process, please see [[RFC] TypeScript tool support](https://github.com/eggjs/egg/issues/2272).

---

## Quick Start

A quick initialization through the boilerplate:

```bash
$ mkdir showcase && cd showcase
$ npm init egg --type=ts
$ npm i
$ npm run dev
```

The boilerplate above will create a very simple example, for a detailed one please see [eggjs/examples/hackernews-async-ts](https://github.com/eggjs/examples/tree/master/hackernews-async-ts)

![tegg.gif](https://user-images.githubusercontent.com/227713/38358019-bf7890fa-38f6-11e8-8955-ea072ac6dc8c.gif)

---

## Principles of Catalogs

**Some constraints:**

- We've no plans for re-writing Egg in TS yet.
- Egg itself, with its plugin, will have corresponding `index.d.ts` for users to use easily.
- TypeScript only belongs to a communication practice. We support it to some extent with our tool chain.
- TypeScript's version MUST BE 2.8 at least.

There's no obvious difference between TS's project and Egg's in js:

- The suffix is `ts` in `typescript` style
- `typings` folder is used to put `d.ts` files (most of them are automatically created)

```bash
showcase
├── app
│   ├── controller
│   │   └── home.ts
│   ├── service
│   │   └── news.ts
│   └── router.ts
├── config
│   ├── config.default.ts
│   ├── config.local.ts
│   ├── config.prod.ts
│   └── plugin.ts
├── test
│   └── **/*.test.ts
├── typings
│   └── **/*.d.ts
├── README.md
├── package.json
├── tsconfig.json
└── tslint.json
```

### Controller

```typescript
// app/controller/home.ts
import { Controller } from 'egg';

export default class HomeController extends Controller {
  public async index() {
    const { ctx, service } = this;
    const page = ctx.query.page;
    const result = await service.news.list(page);
    await ctx.render('home.tpl', result);
  }
}
```

### Router

```typescript
// app/router.ts
import { Application } from 'egg';

export default (app: Application) => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
};
```

### Service

```typescript
// app/service/news.ts
import { Service } from 'egg';

export default class NewsService extends Service {
  public async list(page?: number): Promise<NewsItem[]> {
    return [];
  }
}

export interface NewsItem {
  id: number;
  title: string;
}
```

### Middleware

```typescript
// app/middleware/robot.ts

import { Context } from 'egg';

// Your own middleware here
export default function fooMiddleware() {
  return async (ctx: Context, next: any) => {
    // Get configs like this：
    // const config = ctx.app.config;
    // config.xxx....
    await next();
  };
}
```

When some property's name in config matches your middleware files's, Egg will automatically read out all of its sub properties.

Let's assume you've got a middleware named `uuid`, and its config.default.js is:

```javascript
'use strict';

import { EggAppConfig, PowerPartial } from 'egg';

export default function(appInfo: EggAppConfig) {
  const config = {} as PowerPartial<EggAppConfig>;

  config.keys = appInfo.name + '123123';

  config.middleware = ['uuid'];

  config.security = {
    csrf: {
      ignore: '123',
    },
  };

  const bizConfig = {
    local: {
      msg: 'local',
    },

    uuid: {
      name: 'ebuuid',
      maxAge: 1000 * 60 * 60 * 24 * 365 * 10,
    },
  };

  return {
    ...config,
    ...bizConfig,
  };
}
```

In `uuid` middleware:

```typescript
// app/middleware/uuid.ts

import { Context, Application, EggAppConfig } from 'egg';

export default function uuid(
  options: EggAppConfig['uuid'],
  app: Application,
): any {
  return async (ctx: Context, next: () => Promise<any>) => {
    // The 'name' is just the sub prop in uuid in the config.default.js
    console.info(options.name);
    await next();
  };
}
```

**Notice: The return value of any middleware must be `any` now, otherwise there's a compiling error about the compatibility of context between Koa's context in route.get/all and Egg's Context.**

### Extend

```typescript
// app/extend/context.ts
import { Context } from 'egg';

export default {
  isAjax(this: Context) {
    return this.get('X-Requested-With') === 'XMLHttpRequest';
  },
};

// app.ts
export default (app) => {
  app.beforeStart(async () => {
    await Promise.resolve('egg + ts');
  });
};
```

### Config

Config is a little complicated, because it supports:

- In Controller and Service, we need "multi-layer" intellisense configurations, they are automatically related to each other.
- In Config, `config.view = {}` will also support intellisense.
- In `config.{env}.ts`, we can use customized configuration settings with intellisense in `config.default.ts`.

```typescript
// app/config/config.default.ts
import { EggAppInfo, EggAppConfig, PowerPartial } from 'egg';

export default (appInfo: EggAppInfo) => {
  const config = {} as PowerPartial<EggAppConfig>;

  // Override the configs of framework and plugins
  config.keys = appInfo.name + '123456';
  config.view = {
    defaultViewEngine: 'nunjucks',
    mapping: {
      '.tpl': 'nunjucks',
    },
  };

  // Configs of application
  const bizConfig = {};
  bizConfig.news = {
    pageSize: 30,
    serverUrl: 'https://hacker-news.firebaseio.com/v0',
  };

  // We merge the business logic's configs into AppConfig as the return value
  return {
    // If we directly return you config and merge it into EggAppConfig, there'll be a circulate type error
    ...(config as {}),
    ...bizConfig,
  };
};
```

**Notice: We need `egg-ts-helper` to merge the returned config type from `config.default.js` into egg's `EggAppConfig`.**

When `EggAppConfig` is merged with the returned type of `config.default.ts`, we can also get the intellisenses of our customized configs in `config.default.ts` like this following:

```typescript
// app/config/config.local.ts
import { EggAppConfig } from 'egg';

export default () => {
  const config = {} as PowerPartial<EggAppConfig>;
  // Now we can get the intellisenses of 'news'
  config.news = {
    pageSize: 20,
  };
  return config;
};
```

Remarks:

- `Conditional Types` is the KEY to solving config's intellisense.
- Anyone if interested in this, have a look at the implement of `PowerPartial` at [egg/index.d.ts](https://github.com/eggjs/egg/blob/master/index.d.ts).

```typescript
// {egg}/index.d.ts
type PowerPartial<T> = {
  [U in keyof T]?: T[U] extends {} ? PowerPartial<T[U]> : T[U];
};
```

### Plugin

```javascript
// config/plugin.ts
import { EggPlugin } from 'egg';

const plugin: EggPlugin = {
  static: true,
  nunjucks: {
    enable: true,
    package: 'egg-view-nunjucks',
  },
};

export default plugin;
```

### Lifecycle

```typescript
// app.ts
import { Application, IBoot } from 'egg';

export default class FooBoot implements IBoot {
  private readonly app: Application;

  constructor(app: Application) {
    this.app = app;
  }

  configWillLoad() {
    // Ready to call configDidLoad,
    // Config, plugin files are referred,
    // this is the last chance to modify the config.
  }

  configDidLoad() {
    // Config, plugin files have loaded.
  }

  async didLoad() {
    // All files have loaded, start plugin here.
  }

  async willReady() {
    // All plugins have started, can do some thing before app ready.
  }

  async didReady() {
    // Worker is ready, can do some things
    // don't need to block the app boot.
  }

  async serverDidReady() {
    // Server is listening.
  }

  async beforeClose() {
    // Do some thing before app close.
  }
}
```

### Typings

The folder is the principle of TS, where `**/*.d.ts` are automatically recognized.

- Put developers' hand-writing suggestions in `typings/index.d.ts`.
- Tools will automatically generate `typings/{app,config}/**.d.ts`. Please DO NOT change manually (See below).

---

## Developing period

### ts-node

`egg-bin` has built [ts-node](https://github.com/TypeStrong/ts-node) in, and `egg loader` will automatically load `*.ts` and compile them in memory during the period of development.

Now `dev` / `debug` / `test` / `cov` are supported.

Developers only need to config in `package.json` simply:

```json
{
  "name": "showcase",
  "egg": {
    "typescript": true
  }
}
```

### egg-ts-helper

Due to the automatic loading mechanism, TS cannot analyze dependencies in static or relationship intellisense.

Luckily, TS has many tricks to cope with it. We can use [Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) to write `d.ts` as a helper.

E.g: `app/service/news.ts` will automatically load `ctx.service.news` and recognize it, if you write like this below:

```typescript
// typings/app/service/index.d.ts
import News from '../../../app/service/News';

declare module 'egg' {
  interface IService {
    news: News;
  }
}
```

It's a bit too bothering to write them manually, so we offer you a tool [egg-ts-helper](https://github.com/whxaxes/egg-ts-helper), with which we can analyze and generate `d.ts` files automatically.

What we do is just to do some configs in `package.json`:

```json
{
  "egg": {
    "declarations": true
  },
  "scripts": {
    "dev": "egg-bin dev",
    "test-local": "egg-bin test",
    "clean": "ets clean"
  }
}
```

The corresponding `d.ts` files are automatically generated in `typings/{app,config}/` during the developing period. **DO NOT modify manually in case of being overwritten**.

The tool nowadays can support egg projects in ts and js with intellisenses.

### Unit Test and Cov

Unit Test is a MUST in development:

```typescript
// test/app/service/news.test.ts
import assert from 'assert';
import { Context } from 'egg';
import { app } from 'egg-mock/bootstrap';

describe('test/app/service/news.test.js', () => {
  let ctx: Context;

  before(async () => {
    ctx = app.mockContext();
  });

  it('list()', async () => {
    const list = await ctx.service.news.list();
    assert(list.length === 30);
  });
});
```

Run commands as what you do before, and we've built `Error stacks and coverages` in.

```json
{
  "name": "showcase",
  "egg": {
    "declarations": true
  },
  "scripts": {
    "test": "npm run lint -- --fix && npm run test-local",
    "test-local": "egg-bin test",
    "cov": "egg-bin cov",
    "lint": "tslint ."
  }
}
```

### Debug

There's no main difference for debugging in TS, it can reach correct positions through `sourcemap`.

```json
{
  "name": "showcase",
  "egg": {
    "declarations": true
  },
  "scripts": {
    "debug": "egg-bin debug",
    "debug-test": "npm run test-local -- --inspect"
  }
}
```

- [Debugging in VSCode](https://eggjs.org/zh-cn/core/development.html#%E4%BD%BF%E7%94%A8-vscode-%E8%BF%9B%E8%A1%8C%E8%B0%83%E8%AF%95)
- [History of Debugging Egg in VSCode](https://github.com/atian25/blog/issues/25)

---

## Deployment

### Building

- In a PROD env, we tend to build ts to js, and recommend to build on `ci` and make packages.

Configs in `package.json` :

```json
{
  "devDependencies": {
    "@eggjs/tsconfig": "^1.0.0"
  },
  "egg": {
    "typescript": true,
    "declarations": true
  },
  "scripts": {
    "start": "egg-scripts start --title=egg-server-showcase",
    "stop": "egg-scripts stop --title=egg-server-showcase",
    "tsc": "ets && tsc -p tsconfig.json",
    "ci": "npm run lint && npm run cov && npm run tsc",
    "clean": "ets clean"
  }
}
```

And the corresponding `tsconfig.json`:

```json
{
  "extends": "@eggjs/tsconfig",
  "exclude": ["app/public", "app/web", "app/views"]
}
```

**Notice: When ts and js files are with the same name, egg will first load js ones. So during the development period, `egg-ts-helper` will be automatically called to clear up all the js files with the same names, of course you can use `npm run clean` to clear them manually.**

### Error Stacks

Codes online are js after compilation, however what we expect is to see error stacks pointing at TS source codes. So:

- When buiding the project, we should insert info of `sourcemap` in `inlineSourceMap: true`.
- For developers, there's no need to worry about correcting the positions to the right error stacks in a built-in `egg-scripts`.

For more detailed info:

- [https://zhuanlan.zhihu.com/p/26267678](https://zhuanlan.zhihu.com/p/26267678)
- [https://github.com/eggjs/egg-scripts/pull/19](https://github.com/eggjs/egg-scripts/pull/19)

---

## Guides to the Developments of Plugin/Framework

**Principles:**

- DO NOT recommend to develop plugin/framework in TS directly, we should publish them in js to npm.
- When you write a plugin/framework, the corresponding `index.d.ts` should be included.
- By [Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) we can inject the functions of plugin/framework into Egg.
- All are mounted on `egg` module, DO NOT use the outer layer.

### Plugin

Styles can be referred from the automatically generated `egg-ts-helper`:

```typescript
// {plugin_root}/index.d.ts

import 'egg';
import News from '../../../app/service/News';

declare module 'egg' {
  // extended service
  interface IService {
    news: News;
  }

  // extended app
  interface Application {}

  // extended context
  interface Context {}

  // extended your own configs
  interface EggAppConfig {}

  // extend customize env
  type EggEnvType = 'local' | 'unittest' | 'prod' | 'sit';
}
```

### The Outer Framework

Definitions:

```typescript
// {framework_root}/index.d.ts

import * as Egg from 'egg';

// With 'import' to include the outer framework's plugin.
import 'my-plugin';

declare module 'egg' {
  // Extend egg like plugin...
}

// Export the whole Egg
export = Egg;
```

For developers, they can directly import your framework:

```typescript
// app/service/news.ts

// Developers can get all intellisense after they import your framework
import { Service } from 'duck-egg';

export default class NewsService extends Service {
  public async list(page?: number): Promise<NewsItem[]> {
    return [];
  }
}
```

## Frequently-asked questions

Here're some questions asked by many people with answers one by one:

### `ts` won't be loaded when running `npm start`

`npm start` actually runs `egg-scripts start`, however we ONLY integrate `ts-node` in our `egg-bin`, it means ts won'be loaded until we use `egg-bin`.

`egg-scripts` is the cli for PROD, and we suggest you compiling all the ts to js before running because of robustness and capbility. That's the reason why we don't suggest you using `ts-node` to run the application in PROD.

On the contrary, `ts-node` can reduce the cost of management for compiled files from `tsc`in DEV, and the performance loss can almost be ignored, so `ts-node` is integrated into `egg-bin`.

**In summary: Please use `tsc`to compile all ts files into js through `npm run tsc`, and then run `npm start`.**

### There's no loaded objects when using egg's plugin

There're mainly two reasons causing this problem:

**1. No related defination `d.ts` file for the plugin**

If you want to load some object into egg, you MUST follow the `Plugin / Framework Development Instructions` below by making a declaration file into your own plugin.

You can also create a new declaration file to solve this problem when you are eager to deploy to PROD. Suppose I'm using the plugin of `egg-dashboard` and it has a loading object in egg's app without any declarations, so if you directly use `app.dashboard`, there'll be a type error occuring, and you want to solve it eagerly, you can create `index.d.ts` in 'typings' by writing this following:

```typescript
// typings/index.d.ts

import 'egg';

declare module 'egg' {
  interface Application {
    dashboard: any;
  }
}
```

Now it's solved! Of course your PRs for plugins without declaration files are welcomed to help others!

**2. egg's plugin has the declaration but not loaded**

If the egg's plugin has the right declaration, we need to import it exclipitly and ts can load the related object.

If you use `egg-ts-helper`, it will automatically generate the exclipit importing declarations according to what plugins you've enabled in the application. If you don't use that, you have to import the declaration of plugins manually.

```typescript
// typings/index.d.ts

import 'egg-dashboard';
```

**Notice: You MUST use 'import' in `d.ts`, because most of egg's plugins are without main entry points. There'll be errors occuring if you import directly in ts.**

### `paths` is invalid in `tsconfig.json`

Strictly speaking, this has nothing to do with egg but with many people's questions, and we'll give our answer to it. The reason is `tsc` WON'T convert the import path when compiling ts to js, so when you config `paths` in `tsconfig.json` and if you use `paths` to import the related modules, you are running the high risk that you cannot find them when compiled to js.

The solution is either you don't use `paths`, or you can ONLY import some declarations instead of detailed values. Another way is that you can use [tsconfig-paths](https://github.com/dividab/tsconfig-paths) to hook the process logic in node's path module to support `paths` in `tsconfig.json`.

You can directly import `tsconfig-paths` in `config/plugin.ts`, because `plugin.ts` is ALWAYS loaded firstly in both App and Agent.

```typescript
// config/plugin.ts

import 'tsconfig-paths/register';

...
```

### How to write unit tests for declarations of egg's plugins?

Many contributors don't know how to write unit tests for their plugin's declaration files, so we also have a discussion about it here:

When you finish writing a declaration for an egg's plugin, you can write your own application in `test/fixures` (you can refer [https://github.com/eggjs/egg-view/tree/master/test/fixtures/apps/ts](https://github.com/eggjs/egg-view/tree/master/test/fixtures/apps/ts)). Do remember to add `paths`configs into `tsconfig.json` to do imports in the fixture. Take `egg-view` as an example:

```json
    "paths": {
      "egg-view": ["../../../../"]
    }
```

Do remember DO NOT CONFIG `"skipLibCheck": true` in the `tsconfig.json`, and if you set it to true, `tsc`will ignore the type checks when compiling, and there's no meaning for unit tests for your plugin's declarations.

In the end, add a test case to check whether your declaration works properly or not. See `egg-view` example below:

```js
describe('typescript', () => {
  it('should compile ts without error', () => {
    return (
      coffee
        .fork(require.resolve('typescript/bin/tsc'), [
          '-p',
          path.resolve(__dirname, './fixtures/apps/ts/tsconfig.json'),
          '--noEmit',
        ])
        // .debug()
        .expect('code', 0)
        .end()
    );
  });
});
```

Some other unit test projects as your references:

- [https://github.com/eggjs/egg](https://github.com/eggjs/egg)
- [https://github.com/eggjs/egg-view](https://github.com/eggjs/egg-view)
- [https://github.com/eggjs/egg-logger](https://github.com/eggjs/egg-logger)

### Slow Compilation?

According to our practice, ts-node is a better solution nowaday because we don't execute
tsc in a new terminal, and we can accept the start speed (only for ts-node@7, because the
new version has removed the cache and it makes the speed too slow ([#754](https://github.com/TypeStrong/ts-node/issues/754)), so that's why we don't upgrade it).

But if your project is extreamly huge, ts-node's performance will be tight as well.
So here're our optimizations for you:

#### Close typecheck

Most of time in compilation is type checking, so if we close it there'll be
a bit improvements for performance, with the environment variable
`TS_NODE_TRANSPILE_ONLY=true` when starting your app. E.g:

```bash
$ TS_NODE_TRANSPILE_ONLY=true egg-bin dev
```

Or you can just make tscompiler as the "Compiling-Only" for tscompiler.

```json
// package.json
{
  "name": "demo",
  "egg": {
    "typescript": true,
    "declarations": true,
    "tscompiler": "ts-node/register/transpile-only"
  }
}
```

#### Switch for a high efficient compiler

Besides ts-node, There're also many projects supporting ts compilation,
such as esbuild, we can install it first [esbuild-register](https://github.com/egoist/esbuild-register)

```bash
$ npm install esbuild-register --save-dev
```

And then config `tscompiler` like this:

```json
// package.json
{
  "name": "demo",
  "egg": {
    "typescript": true,
    "declarations": true,
    "tscompiler": "esbuild-register"
  }
}
```

Then you can use esbuild-register to compile (notice: esbulild-register can't
do typecheck).

> Same for swc, if you want to use it after installation [@swc-node/register](https://github.com/Brooooooklyn/swc-node#swc-noderegister), and then config in tscompiler.

#### Use tsc

If you still cannot bear the speed of the dynamic compilation, you can directly
use tsc. This means you don't need to config typescript to true in package.json,
but just start a new terminal to execute tsc.

```bash
$ tsc -w
```

And then start the egg.

```bash
$ egg-bin dev
```

We suggest you can add configs for `**/*.js` at .gitignore to avoid
submitting the generated js files to the remote.

repository: eggjs/egg

gha_language: JavaScript

repo_name: eggjs/egg


text:
# ESP32 Higrow Soil Sensor

## Overview

This app is an alternative firmware for the ESP32 based Higrow
soil sensor from Luca Fabbri based on Mongoose OS

## How to install this app

- Install [mos tool](https://mongoose-os.com/software.html)
- Download GIT repository and unpack into your mos apps directory
- Start mos tool

repository: dheiss/higrow-mqtt

repo_name: dheiss/higrow-mqtt


text:
---
description: GetTransaction
---

# hmy\_getTransactionByHash

Get a transaction by its hash.

## Parameters

1. `String` - The transaction hash.

## Returns

* `hash` - `String`: Hash of the transaction.
* `nonce` - `Number`: The number of transactions made by the sender prior to this one.
* `blockHash` - `String`: Hash of the block where this transaction was in. `null` when it's pending.
* `blockNumber` - `Number`: Block number where this transaction was in. `null` when it's pending.
* `transactionIndex` - `Number`: Integer of the transaction's index position in the block. `null` when its pending.
* `from` - `String`: Address of the sender.
* `to` - `String`: Address of the receiver.
* `value` - `String`: Value transferred in ATTO.
* `gasPrice` - `String`: Gas price provided by the sender.
* `gas` - `Number`: Gas provided by the sender.
* `input` - `String`: The data sent along with the transaction.

**Sample Curl Request**

```bash
curl -d '{
    "jsonrpc":"2.0",
    "method":"hmy_getTransactionByHash",
    "params":[
      "0x1dff358dad4d0fc95b11acc9826b190d8b7971ac26b3f7ebdee83c10cafaf86f"
    ],
    "id":1
}'
```

**Sample Curl Response**

```javascript
{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "blockHash": "0xd6db4b8e899b25c584384a1369082c79f1a4a4d1c28a49d082507c4bce2a389e",
        "blockNumber": "0x14",
        "from": "0x806171f95c5a74371a19e8a312c9e5cb4e1d24f6",
        "gas": "0x5208",
        "gasPrice": "0x0",
        "hash": "0x1dff358dad4d0fc95b11acc9826b190d8b7971ac26b3f7ebdee83c10cafaf86f",
        "input": "0x",
        "nonce": "0x0",
        "to": "0xd7ff41ca29306122185a07d04293ddb35f24cf2d",
        "transactionIndex": "0x0",
        "value": "0x1158e460913d00000",
        "v": "0x1c",
        "r": "0x4ee6562ebdc9cbb3ed0ce2c57ededd95573cea1749e79e8fdf8f98e8788dd944",
        "s": "0x30194af0e6b01a8b3aefb2ad01c896a20aa20a9ebb7a67ae9bb21783f75f9fd"
    }
}
```

repository: harmony-one/docs-home

repo_name: harmony-one/docs-home


text:
# ionicons-inline

> Use Ionicons in Sass as inline SVG, no images or webfonts needed

ionicons-inline lets you use [Ionicons] in your CSS without images or webfonts. It embeds the icons as embedded SVG's via data URI's. This is based on ionicons v5.2.3.

[ionicons]: https://ionicons.com/

<!-- [ionicons]: https://ionicframework.com/docs/ionicons/ -->

## Example

```scss
button::before {
  content: '';
  @include ion-add-outline(16px, #aaddff);
}
```

Returns:

```scss
button::before {
  content: '';
  display: inline-block;
  vertical-align: middle;
  background: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%3E%3Cpath%20d%3D%22M256%2048C141.1%2048%2048%20141.1%2048%20256s93.1%20208%20208%20208%20208-93.1%20208-208S370.9%2048%20256%2048zm0%20398.7c-105.1%200-190.7-85.5-190.7-190.7S150.9%2065.3%20256%2065.3%20446.7%20150.9%20446.7%20256%20361.1%20446.7%20256%20446.7z%22%2F%3E%3Cpath%20d%3D%22M264%20128h-16v120H128v16h120v120h16V264h120v-16H264z%22%2F%3E%3Cstyle%3Epath%7Bfill%3A#aaddff%3B%7D%3C%2Fstyle%3E%3C%2Fsvg%3E')
    center center / 16px 16px no-repeat;
  height: 16px;
  width: 16px;
}
```

## Why?

Unlike the default ionicons distribution, this lets you only bundle the icons you need. You also don't need to load the 70kb+ ionicons package. This is great if you only need a few icons from the set.

## Usage

Install it as an npm package. It's preferred you use `--exact`, because icons may change per version.

```sh
npm install --save --save-exact ionicons-inline # via npm
yarn add --exact ionicons-inline                # via yarn
```

##### Importing

Import it in your CSS. The way to do this differs in a lot of ways, but in general, one of these ought to work.

```scss
@import 'ionicons-inline/dist/ionicons';
@import '~ionicons-inline/dist/ionicons';
@import '../node_modules/ionicons-inline/dist/ionicons';
```

##### Mixin: ion-icon

Just use a mixin named `ion-<iconname>`. See [Ionic framework icons](https://ionicframework.com/docs/ionicons/).

```scss
.icon {
  @include ion-add-outline(16px, #aaddff);
}
```

##### Function: ion-icon-image

This sets many properties (width, height, background-image, background-size, background-position, background-repeat, display, vertical-align). If you only want to set background-image, you can use:

```scss
.icon {
  background-image: ion-add-outline-image(16px, #aaddff);
}
```

## Prior art

- [iconfonts](https://github.com/rstacruz/iconfonts) also lets you selectively embed just a few CSS declarations. However, it still needs to load the 70kb+ ionicons file.

## Thanks

**ionicons-inline** © 2018, Rico Sta. Cruz. Released under the [MIT] License.<br>
Authored and maintained by Rico Sta. Cruz with help from contributors ([list][contributors]).

> [ricostacruz.com](http://ricostacruz.com)  ·
> GitHub [@rstacruz](https://github.com/rstacruz)  ·
> Twitter [@rstacruz](https://twitter.com/rstacruz)

[![](https://img.shields.io/github/followers/rstacruz.svg?style=social&label=@rstacruz)](https://github.com/rstacruz)
[![](https://img.shields.io/twitter/follow/rstacruz.svg?style=social&label=@rstacruz)](https://twitter.com/rstacruz)

[mit]: http://mit-license.org/
[contributors]: http://github.com/rstacruz/ionicons-inline/contributors

repository: rstacruz/ionicons-inline

repo_name: rstacruz/ionicons-inline


text:
## 2.5 Systems with Generic Operations

outline

[TOC]

The key idea is to link the code that specifies the data operations to the several representatisons by means of generic interface procedures.

 First time, we get complex data; second time, we get rectangular data.

magnitude is dispatched to each case.

##### Exercise 2.78

```lisp
(define (attach-tag type-tag contents)
  (if (eq? type-tag 'scheme-number) contents)
  (cons type-tag contents))
(define (type-tag datum)
  (cond ((number? datum) datum)
    ((pair? datum) (car datum))
    (error "Bad tagged datum -- TYPE-TAG" datum)))

(define (contents datum)
  (cond ((number? datum) datum)
    ((pair? datum) (cdr datum))
    (error "Bad tagged datum -- CONTENTS" datum)))
```

##### Exercise 2.79

Generic equality predicate equ?

```lisp
(define (install-scheme-number-package)
  (define (tag x)
    (attach-tag 'scheme-number x))
  (put 'equ? '(scheme-number scheme-number)
       (lambda (x y) (tag (= x y))))
  'done)

(define (install-rational-package)
  ;; internal procedures
  (define (numer x) (car x))
  (define (denom x) (cdr x))

  ;; interface to rest of the system
  (define (tag x) (attach-tag 'rational x))
  (put 'equ? '(rational rational)
       (lambda (x y) (tag (and (= (numer x) (numer y))
                               (= (denom x) (denom y))))))
  'done')

(define (install-complex-package)
  ;; interface to rest of the system
  (define (tag z) (attach-tag 'complex z))
  (put 'equ '(complex complex)
       (lambda (x y)
               (tag (and (= (real-part x) (real-part y))
                         (= (imag-part x) (imag-part y))))))
  'done)
```

##### Exercise 2.80

```lisp
(define (install-scheme-number-package)
  (define (tag x)
    (attach-tag 'scheme-number x))
  (put '=zero? 'scheme-number
       (lambda x (tag (= x 0))))
  'done)

(define (install-rational-package)
  ;; internal procedures
  (define (numer x) (car x))
  (define (denom x) (cdr x))

  ;; interface to rest of the system
  (define (tag x) (attach-tag 'rational x))
  (put '=zero? 'rational
       (lambda x (tag (and (= (numer x) 0)
                           (not (= (denom x) 0))))))
  'done')

(define (install-complex-package)
  ;; interface to rest of the system
  (define (tag z) (attach-tag 'complex z))
  (put '=zero? 'complex
       (lambda x (tag (and (= (real-part x) 0)
                           (= (imag-part x) 0)))))
  'done)
```

### 2.5.2 Combining Data of Different Types

**cross-type operations**

One way to handle cross-type operations is to design a different procedure for each possible combination of types ofr which the operation is valid.

expamlpe:

```lisp
;; to be included in the complex package
(define (add-complex-to-schemenum z x)
  (make-from-real-imag (+ (real-part x) x)
                       (imag-part z)))
(put 'add '(complex scheme-number)
     (lambda (z x) (tag (add-complex-to-schemenum z x))))
;; work but cumbersome
```

#### Coercion // n. 强迫；强制；高压政治；威压

Taking advantage of additional structure that may be latent in our type system.

Often the different data types are not completely independent, and there may be ways by which objects of one type may be viewed as being of another type. This process is called coercion.

Exemple, we can view the ordinary number as a complex number whose imaginary part is zero.（有点像弱类型语言的隐性类型转换）

```lisp
(define (secheme-number->complex n)
  (make-complex-from-real-imag (contents n) 0))

(put-coercion 'scheme-numer 'complex scheme-number->complex)

(define (apply-generic op . args)
  (let ((type-tags (map type-tag args)))
       (let ((proc (get op type-tags)))
            (if proc
                (apply proc (map contents args))
                (if (= (length args) 2)
                    (let ((type1 (car type-tags))
                          (type2 (cadr type-tags))
                          (a1 (car args))
                          (a2 (cadr args)))
                         (let ((t1->t2 (get-coercion type1 type2))
                               (t2->t1 (get-coercion type2 type1)))
                              (cond (t1->t2
                                        (apply-generic op (t1->t2 a1) a2))
                                (t2->t1
                                 (apply-generic op a1 (t2->t1 a2)))
                                (else
                                 (error "No method for thes types"
                                        (list op type-tags))))))
                    (error "No method for these types"
                           (list op type-tags)))))))
```

使用 coercion 灵活了许多，但对于 n 个 type 大概需要编写 n^2 个 coercion procedure。而且合适的类型转换取决于类型本身，而非 procedure。从另一个角度看，也许我们的 coercion scheme 通用性还不够。毕竟如果两种数据类型如果不能互相转换，也有可以同时转换为第三种数据类型进行运算。下面我们将讨论这个问题。

#### Hierarchies of types

- hierarchies of types
- subtype
- supertype
- tower, each type has at most one supertype and at most one subtype.

Advantage

- we need not explicitly define a special coercion procedure integer->complex. (Exercise 2.83 and Exercise 2.84)
- we can easily implement the notion that every type "inherits" all operations defined on a supertype.
- It gives us a simple way to "lower" a data object to the simplest representation. (Exercise 2.85)

#### Inadequacies of hierarchies 层次结构的不足

- In general, atype may have more than one subtype.
- In addition, a type may have more than one supertype.
- This umlitple-supertypes issue is particularly thorny, since it means that there is no unique way to "raise" a type in the hierarchy.
- Dealing whith large numbers of interrelated types while still preserving modularity in the design of large systems is very difficult, and is an area of much current research.

##### Exercise 2.81

```lisp
(define (scheme-number->scheme-number n) n)
(define (complex->complex z) z)
(put-coercion 'scheme-number 'scheme-number
              scheme-number->scheme-number)
(put-coercion 'complex 'complex complex->complex)
```

a.

当调用 apply-generic 处理两个 scheme-number 或者两个 complex，而在 table 中找不到对应的 procedure时，apply-generic 会尝试将第一个参数转换为第二个参数的类型，然后再从 coercion-table 中查找相应的 procedure，如果没有找到，就尝试将第二个参数转换为第一个参数的类型，然后再从 coercion-table 中查找相应的 procedure，如果还是没有找到，则放弃。

```lisp
(define (exp x y) (apply-generic 'exp x y))

;; flollowing added to Scheme-number package
(put 'exp '(scheme-number scheme-number)
     (lambda (x y) (tag (expt x y)))) ; using primitive expt
```

当我们调用 exp 处理两个 complex 时，会因为在 table 中找不到处理对应 type 的 procedure，而得到错误信息 "No method for thes types"。

b.

Louis 是错的。处理相同数据类型参数的 procedure 应该都放在 table 里面，如果在 table 中找不到可用的 procedure，就直接抛出 "No method for thes types" ，而不是尝试类型转换后在 coercion-table 中寻找可用的 procedure。

c.

```lisp
(define (apply-generic op . args)
  (let ((type-tags (map type-tag args)))
       (let ((proc (get op type-tags)))
            (if proc
                (apply proc (map contents args))
                (if (= (length args) 2)
                    (let ((type1 (car type-tags))
                          (type2 (cadr type-tags))
                          (a1 (car args))
                          (a2 (cadr args)))
                         (if (= type1 type2)
                             (error "No method for thes types"
                                        (list op type-tags))
                             (let ((t1->t2 (get-coercion type1 type2))
                                   (t2->t1 (get-coercion type2 type1)))
                                  (cond (t1->t2
                                         (apply-generic op (t1->t2 a1) a2))
                                    (t2->t1
                                     (apply-generic op a1 (t2->t1 a2)))
                                    (else
                                     (error "No method for thes types"
                                            (list op type-tags)))))))
                    (error "No method for these types"
                           (list op type-tags)))))))
```

##### Exercise 2.82

apply-generic 如何处理 coercion 的多参数情况。一个策略是将所有参数 coerce 为第一个参数的类型，如果失败就 coerce 为第二个参数的类型，知道所有参数类型都失败。给出例子证明这个策略（类似上面两个参数版本的策略）通用性不足。（提示：table 中某些混合类型的操作是无效的）

##### Exercise 2.83

For each type (except complex), design a procedure that raises objects of that type on level in the tower.

```lisp
(define (raise x) (apply-generic 'raise x))

;; in the integer package
(put 'raise 'integer (lambda n (make-rational n 1)))

;; in the rational package
(define (rational->real r) (make-real (/ (numer r) (denom r))))
(put 'raise 'rational rational->real)

;; in the rational package
(define (real->complex r) (make-complex-from-imag r 0))
(put 'raise 'real real->complex)
```

##### Exercise 2.84

```lisp
(define (apply-generic op . args)
  ;; find the highest type level of a list of arguments
  (define (heighest-type-level args)
    (if (null? args)
        0
        (let ((level (type-level (car args)))
              (heighest (highest-type-level (cdr args))))
             (if (> level highest)
                 level
                 highest))))
  ;; raise arg to the same level as target-type-level
  (define (raise-to arg target-type-level)
    (define (raise-iter current-arg)
      (let ((arg-level (type-level current-arg)))
           (cond ((= arg-level target-type-level) current-arg)
             ((< arg-level target-type-leve)
                 (raise-iter (apply-generic 'raise current-arg)))
             (else (error "Cannot raise argumnet to lower type target"
                          arg target-type-level)))))
    (raise-iter arg))

  ;; raise all args to a common type (the highest in the tower of types) and apply the operator to them
  (define (apply-with-raise-types args)
    (let ((target-type-level (highest-type-level args)))
         (apply apply-generic
                op
                (map (lambda arg
                             (raise-to arg target-type-level))
                     args))))
  (let ((type-tags (map type-tag args))
        (proc (get op type-tags)))
       (if proc
           (apply proc (map contents args))
           (apply-with-raised-types args))))

(define (type-level z) (apply-generic 'type-level z))
(pute 'type-level 'integer (lambda x 1))
(pute 'type-level 'rational (lambda x 2))
(pute 'type-level 'rea (lambda x 3))
(pute 'type-level 'complex (lambda x 4))
```

##### Exercise 2.85

> https://wizardbook.wordpress.com/2010/12/08/exercise-2-85/

##### Exercise 2.86

> https://wizardbook.wordpress.com/2010/12/09/exercise-2-86/

url: https://raw.githubusercontent.com/WeJie/sicp/6f1a64b08b00f4c6dfaf164d71dfba77874eb7d0/chapter 2/2.5 Systems with Generic Operations.md

repository: WeJie/sicp

filename: 2.5 Systems with Generic Operations.md

repo_name: WeJie/sicp


text:
# Snake
>  The old  game classic "Snake" in Python

This is a very simple Python implementation of the game "Snake" using the curses UI framework.

![](snake.png)

## Installation

You have to install the required packages defined in `requirements.txt`. Consider using a virtual environment or container environment to avoid installing the packages globally which might break other projects.

`$ pip install -r requirements.txt`

## How to play?

Start the game by typing:

`python -m snake`

You can control the snake using the following keys:

|  Action  |  Key       |
| -------- | ---------- |
| Up       | `↑` or `w` |
| Down     | `↓` or `a` |
| Left     | `←` or `s` |
| Right    | `→` or `d` |
| Quit     | `p`        |

## Release History

* 0.2
    * ADD: LICENSE and README
* 0.1
    * ADD: Initial implementation of snake

## Meta

Dennis Loeben –<EMAIL_ADDRESS>
Distributed under the MIT license. See ``LICENSE`` for more information.

[https://github.com/dennisloe85/snake]


text:
# Contributing to gramhopper
Thanks for getting interested in contributing to gramhopper! :clap::clap:

This document is a set of guidelines to help you contribute.

## Reporting bugs
Bug reports are the easiest contributions one can do, and maybe the most important ones.

Before [reporting a bug](https://github.com/OrBin/gramhopper/issues/new), please make sure (as much as you can) that
this is really an issue caused by a bug in gramhopper.

When reporting a bug, please provide as much information as possible, to help us identify and solve it easily.
Please follow the bug report template (which appears when creating an issue) and fill all applicable fields

## Contributing code

### Find an issue to work on
Look at issues tagged with [good first issue](https://github.com/OrBin/gramhopper/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22+) label and find one you'd like to work on.

### How to build and test
We use [Invoke](http://docs.pyinvoke.org) CLI to execute development tasks like test, build, lint, etc.

#### Building
To build, run:
```bash
invoke build
```
You can also use flags with this command:
* Use `--no-package` to avoid building the package.
* Use `--no-docker-image` to avoid building the docker image.
* Use `--docs` to build the documentation, too.
* You can combine these flags however you want.

#### Testing
To run tests, run:
```bash
invoke test
```
Testing Telegram bots require a bot token, so we provide a pre-created token that's already configured for you.

To override this token, set the environment variable `TOKEN` before running tests.

The same applies for a chat ID to test with, which you can override with the environment variable `CHAT_ID`.

### Follow the style guide
Our code generally follows PEP8, with some exceptions.
We use some linters to make sure we keep following the required style. To run them all, run:
```bash
invoke lint
```
If you have a lint error, fix it; don't add a comment to ignore it.

### Commit messages
Please write informative, detailed (but not too detailed) commit messages.
Preferably, start your commit message with tagging the issue you are working on, for example: *`#40 Created a sphinx page for filter triggers`*.

### Submit a pull request
If you're done coding and you've run the build, test and lint tasks, go ahead and [submit a new pull-request](https://github.com/OrBin/gramhopper/compare).

After you submit your pull request, verify that all status checks (CI build checks) are passing.

## Improving documentation
Improving documentation is a great way to contribute, too!

Our documentation is built using [Sphinx](http://www.sphinx-doc.org/).
It is based on RST files located in [`docs/`](https://github.com/OrBin/gramhopper/tree/dev/docs/source) directory, and on docstrings in the python code.

Find [here](https://github.com/OrBin/gramhopper/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3Adocumentation+) issues related to documentation.

#### Building the documentation
To build the documentation, run:
```bash
invoke build-docs
```
The build output will be in `docs/build` directory.

To clear the documentation build outputs, run:
```bash
invoke clean --docs
```

## Code of conduct
This project is governed by the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to follow this code.

repository: OrBin/gramhopper

branch_name: refs/heads/dev

gha_language: Python

repo_name: OrBin/gramhopper


text:
# Kubesecret - Safe kubernetes secret management

[![npm package](https://img.shields.io/npm/v/@bufferapp/kubesecret)](https://www.npmjs.com/package/@bufferapp/kubesecret)

## Purpose and motivation

Managing kubernetes secrets is a non standard process. Companies have many possible ways in which they can be managed. Sometimes though, a simple approach of `kubectl` is the most practical to reach out to.

That said, we've found that `kubectl apply -f` or even `kubectl edit` can present challenges. In the case of the former it can be easy to end up with files that were out of sync and unintended changes to secrets can happen. With the latter, encoding erros or manual file modifications can be serious enough to take down an entire application.

But even more, when trying to look at the data available the process can be tedious (`kubectl get secret <secret> | ....  | base64 --decode` or similar bashing).

We are making `kubesecret` to give team members a guided approach to performing CRUD operations on secrets in kubernetes. In the future the capabilities of the tool might be extended to do things such as finding where a secret/secret key is being used. Finally, we are aiming to make the behaviour extendable from the start via the use of plugins.

## Using

**Please note that this tool runs ON TOP of `kubectl`. You need to have `kubectl` installed and running on your OS before using this tool**

### npm

```
npm install -g @bufferapp/kubesecret
```

Now run `kubesecret help` to explore what you can do!

### Download the binary

* Go to the releases, and download the binary for the OS of your choice.
* Place the binary somewhere on your `$PATH`.
* Run it using `kubesecret help` to see what you can do with it.

A note on windows support

While Windows support is currently not supported, we'll be taking care to try and not introduce patterns that exclude windows. We make no guarantees and you are free to run `node_modules/pkg/lib-es5/bin.js -t node10-win-x64` to get yourself a Windows binary and test things out.

## Developing the tool

* Download the repo
* Run `npm install`. The tool is being developed using node `v10.x.x`
* Code away
* To test changes without building the binary run `node scripts/kubesecret.js`
* Install it globally on your machine using `npm link`

### Publish to npm

Use `npm version` to update the version name, add a commit and tag that commit prior to publishing.
For example:

```
npm version 0.5.0
npm publish
```

Or if you want to publish a beta version, manually update the `package.json` version
(e.g. `0.5.0-beta1`) and run this command:

```
npm publish --tag beta
```

## License

MIT

repository: bufferapp/kubesecret

repo_name: bufferapp/kubesecret


text:
### [CVE-2019-12394](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-12394)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

Anviz access control devices allow unverified password change which allows remote attackers to change the administrator password without prior authentication.

### POC

#### Reference
- https://www.0x90.zone/multiple/reverse/2019/11/28/Anviz-pwn.html

#### Github
No PoCs found on GitHub currently.

repository: trickest/cve

gha_language: HTML

repo_name: trickest/cve


text:
#### Complete Summary of the Mandatory Requirements

1.  One status in `CareTeam.status`
-   CareTeam.status is bound to [CareTeamStatus] value set
1.  One reference to a patient in `CareTeam.subject`
1.  One participant role for each careteam member in
    `CareTeam.participant.role`
    -  CarePlan.participant.role is bound to the [CareTeam Provider Role
Value Set] value set.
1.  Careteam members in `CareTeam.participant.member`

 [CareTeamStatus]: valueset-daf-careteam-status.html
 [CareTeam Provider Role Value Set]: valueset-daf-core-careteam-provider-roles.html


text:
# remark

[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]

[**unified**][unified] processor to parse and serialize Markdown.
Built on [micromark][].
Powered by [plugins][].
Part of the [unified][] collective.

*   API by [**unified**][unified]
*   Parses Markdown to a syntax tree with [`remark-parse`][parse]
*   [**mdast**][mdast] syntax tree
*   [Plugins][] transform the tree
*   Serializes syntax trees to Markdown with [`remark-stringify`][stringify]

Don’t need the parser?
Or compiler?
[That’s OK: use **unified** directly][unified-usage].

## Install

[npm][]:

```sh
npm install remark
```

## Use

[See **unified** for more examples »][unified]

###### Common example

This example lints Markdown and turns it into HTML.

```js
var remark = require('remark')
var recommended = require('remark-preset-lint-recommended')
var html = require('remark-html')
var report = require('vfile-reporter')

remark()
  .use(recommended)
  .use(html)
  .process('## Hello world!', function (err, file) {
    console.error(report(err || file))
    console.log(String(file))
  })
```

Yields:

```txt
1:1  warning  Missing newline character at end of file  final-newline  remark-lint

⚠ 1 warning
```

```html
<h2>Hello world!</h2>
```

###### Settings through data

This example prettifies Markdown and configures [`remark-stringify`][stringify]
through [data][].

```js
var remark = require('remark')

remark()
  .data('settings', {emphasis: '*', strong: '*'})
  .process('_Emphasis_ and __importance__', function (err, file) {
    if (err) throw err
    console.log(String(file))
  })
```

Yields:

```markdown
*Emphasis* and **importance**
```

###### Settings through a preset

This example prettifies Markdown and configures [`remark-parse`][parse] and
[`remark-stringify`][stringify] through a [preset][].

```js
var remark = require('remark')

remark()
  .use({settings: {emphasis: '*', strong: '*'}})
  .process('_Emphasis_ and __importance__', function (err, file) {
    if (err) throw err
    console.log(String(file))
  })
```

Yields:

```markdown
*Emphasis* and **importance**
```

## API

[See **unified** for API docs »][unified]

## Security

As Markdown is sometimes used for HTML, and improper use of HTML can open you up
to a [cross-site scripting (XSS)][xss] attack, use of remark can also be unsafe.
When going to HTML, use remark in combination with the [**rehype**][rehype]
ecosystem, and use [`rehype-sanitize`][sanitize] to make the tree safe.

Use of remark plugins could also open you up to other attacks.
Carefully assess each plugin and the risks involved in using them.

## Contribute

See [`contributing.md`][contributing] in [`remarkjs/.github`][health] for ways
to get started.
See [`support.md`][support] for ways to get help.
Ideas for new plugins and tools can be posted in [`remarkjs/ideas`][ideas].

A curated list of awesome remark resources can be found in [**awesome
remark**][awesome].

This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.

repository: kyleterry/sufr

repo_name: kyleterry/sufr


text:
# FlowBinding Navigation

This module provides bindings for the **AndroidX Navigation** library.

## Transitive Dependency

`androidx.navigation:navigation-runtime`

## Download

```groovy
implementation "io.github.reactivecircus.flowbinding:flowbinding-navigation:${flowbinding_version}"
```

## Available Bindings

```kotlin
fun NavController.destinationChangeEvents(): Flow<DestinationChangeEvent>
```

repository: ReactiveCircus/FlowBinding

gha_language: Kotlin

repo_name: ReactiveCircus/FlowBinding