text:
# DQNAgent

DQNAgent implements the deep Q-network (DQN) algorithm algorithm from
["Human level control through deep reinforcement learning" ](https://deepmind.com/research/dqn/)
(Mnih et al., 2015).

# Examples

Here is an example of training and evaluating DQN in the Pong-v0 environment:

```shell
$  python tf_agents/examples/dqn/mnih15/dqn_train_eval_atari.py  \
     --num_iterations=12500000 \
     --root_dir=$HOME/tmp/dqn/pong_v0/

# To view progress in TensorBoard use another terminal and execute.
$  tensorboard --logdir $HOME/tmp/dqn/pong_v0/
```

Note: [Issue #475](https://github.com/tensorflow/agents/issues/475):
The default setup does not checkpoint the policy or data. If the pipeline gets
preempted, training and evaluation will start over. You may observe more than
one learning curve in this situation. If you enable policy checkpointing, the
learner will reload the most recent saved policy. However, because we are not
yet checkpointing the data from Reverb, we refill the table with the data
collected by the current policy. We lose the data collected with older policies.
This will result in distortions in the return that we will address in the future.

# Validation and Performance

To validate TF-Agents’ DQN implementation, we ran DQN on Pong-v0 using the
hyperparameters from "Human level control through deep reinforcement learning"
(Mnih et al., 2015). The table below is a summary of the results listing the
mean of 5 experiments after 12.5M env steps which amounts to 50M frames
(4 frames per env step). The graph that follows is the mean with the min/max
range.

Env                     | Measurement 1 | Tensorboard
----------------------- | ------------- | -----------
Pong-v0 (Atari)         | 18.8@50M      | [tensorboard.dev](https://tensorboard.dev/experiment/pIkiBSxqQvecWWARJ1Y8uA/#scalars&runSelectionState=eyJkcW5fcG9uZ18wMi90cmFpbiI6ZmFsc2UsImRxbl9wb25nXzAxL3RyYWluIjpmYWxzZSwiZHFuX3BvbmdfMDAvdHJhaW4iOmZhbHNlLCJkcW5fcG9uZ18wMy90cmFpbiI6ZmFsc2UsImRxbl9wb25nXzA0L3RyYWluIjpmYWxzZX0%3D)

![alt_text](https://raw.githubusercontent.com/tensorflow/agents/master/docs/images/dqn_readme/pong-v0_graph.png "Pong-v0 Mean and min/max graph.")

## Reproduce results

To reproduce the numbers we suggest using the commands below, which use the
`head` of TF-Agents.

**Step 1:** Create a
[Google Deep Learning VM instance](https://cloud.google.com/ai-platform/deep-learning-vm/docs/tensorflow_start_instance).
The only things used from the Deep Learning VM are Docker and optionally
tensorboard which is used outside the Docker container. We are using the image
because it also includes NVIDIA Drivers and we use the same VM for GPU testing.

```shell
$  export IMAGE="c6-deeplearning-tf2-ent-2-3-cu110-v20200826-debian-9"
$  export ZONE=<Your Zone, e.g. europe-west2-b>
$  export PROJECT=<Your Project>
$  export INSTANCE_NAME=dqn-training

# 32 vCPU
$  gcloud compute instances create $INSTANCE_NAME \
    --project=$PROJECT \
    --zone=$ZONE \
    --machine-type=n1-standard-32 \
    --maintenance-policy=TERMINATE \
    --image=$IMAGE \
    --image-project=ml-images \
    --boot-disk-size=100GB \
    --boot-disk-type=pd-ssd
    --scopes=https://www.googleapis.com/auth/cloud-platform

# Login to the cloud instance.
$  gcloud compute ssh --zone $ZONE --project $PROJECT $INSTANCE_NAME
```

**Step 2:** Build a
[Docker](https://github.com/tensorflow/agents/tree/master/tools/docker) to be
used for the experiment. These steps take place on the instance that was
created in step 1.

```shell
$  git clone https://github.com/tensorflow/agents.git && cd agents

# Core tf-agents docker.
$  docker build -t tf_agents/core \
     --build-arg tf_agents_pip_spec=tf-agents-nightly[reverb] \
     - < tools/docker/ubuntu_tf_agents

```

**Step 3:** Download ROMs and extend core image to include them.

For current details on installing ROMs for atari-py read
[the OpenAI instructions](https://github.com/openai/atari-py/blob/master/README.md).
As of 12-AUG-2021 the suggestion from OpenAI is to:

```shell
# Need to install unrar from the non-free Debian Repo.
$  sudo apt-add-repository non-free
$  sudo apt-get update

# Get all available ROMs.
$  wget http://www.atarimania.com/roms/Roms.rar && unrar x Roms.rar

# After unzipping the Pong ROM is located at:
#  `HC ROMS/BY ALPHABET/S-Z/Video Olympics - Pong Sports.bin`
$  mkdir ./tools/docker/roms
$  mv HC\ ROMS ./tools/docker/roms

```

The ROMs need to be moved to `./tools/docker/roms` to be picked up by the docker
build process.

```shell
# Extend the core image to include atari ROMs.
# Note that the ROMs need to have already been downloaded and put into
# ./tools/docker/roms
$  docker build -t tf_agents/atari -f ./tools/docker/ubuntu_atari \
     ./tools/docker
```

**Step 4:** Create a tmux session and start the train and eval.

```shell
# Using tmux keeps the experiment running if the connection drops.
$  tmux new -s bench

# Runs DQN on Pong in the docker instance.
$  docker run --rm -it -v $(pwd):/workspace -w /workspace/ tf_agents/atari \
     python3 tf_agents/examples/dqn/mnih15/dqn_train_eval_atari.py  \
       --num_iterations=12500000 \
       --root_dir=./logs/dqn_pong_01/
```

**Step 5 (Optional):** Use [tensorboard.dev](https://tensorboard.dev/) to track
progress and save the results.

```shell
# To upload the results to tensorboard.dev (public) exit out of the tmux session
# and start another session uploading the results. This command is run outside
# of Docker and assumes tensorboard is installed on the host system.
# ctrl + b followed by d will detach from the session
$  tmux new -s tensorboard
$  tensorboard dev upload --logdir=./logs/
```

**Addendum**

Below is the git hash and version of TensorFlow used to get the results above.
This is here as an audit trail. The files have since moved making using this
hash even less advisable.

```shell
# After checking out the code above and before building the docker execute the following:
$  git reset --hard 55fb34fabba14512e9b090743277764129573fec
```

`tf-nightly==2.5.0.dev20201215` was used to generate the results.

repository: tensorflow/agents

gha_language: Python

repo_name: tensorflow/agents


text:
# DropboxFS

An in-browser filesystem for [BrowserFS], backed by Dropbox through the [Dropbox.js] library.

[browserfs]: https://github.com/jvilk/BrowserFS
[dropbox.js]: https://github.com/dropbox/dropbox-js

license: MIT

repository: jvilk/dbfs

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: jvilk/dbfs


text:
@guide: Development tasks and tooling
category: 4. Annexes
authors:
  - "@robotlolita"
---

[Folktale uses GNU Make for development tooling](guides.setting-up-a-development-environment.html). From
there you can compile the source code, run tests, perform cleanup routines, or
check your source code for style errors.

Note: **before you can do anything in Folktale you must initialise the documentation tools**:

```shell
$ git submodule init
$ git submmodule update
$ make tools
```

Running `make` or `make help` will show you all of the available development
tasks.

Running `make compile` will compile the source code using Babel.
After this you can import the objects in the REPL and interact with them.

Running `make compile-annotated` will compile the source code with the special documentation
marks. You can either use `make documentation` to generate HTML docs from that, or
`require('./documentation')` in a Node REPL to read the docs from there.

Running `make test` will compile the project and run all of the tests. Running
`make test-all` will also test the examples in the documentation. You can run
tests in a PhantomJS (a headless WebKit browser) using `make test-browser`.

Running `make lint` will check all of the source code for style
inconsistencies. The coding style used by Folktale is described later in this
document.

Finally, running `make clean` will remove any compiled files from your working
directory, but will keep all other files intact. You can always run `make
compile` again to re-build the project.

repository: niilante/folktale

repo_name: niilante/folktale


text:
# Campus Navigator

A web application designed to orient students to the MSU Denver and other campuses.

## Developed Using

* This project was initially made with the MERN Stack (MongoDB/Express/React/Node.js), but has since changed to accomodate our restrictions and requirements:
    * Front End
        * [React](https://reactjs.org/) - A JavaScript library for building user interfaces. Developed and maintained by and maintained by and maintained by and maintained by and maintained by and maintained by and maintained by Facebook
        * [Create React App](https://github.com/facebook/create-react-app) - Boilerplate code and a React development environment.
    * Back End
        * [Firebase](https://firebase.google.com/) - A mobile and web application development platform and back end-as-a-service provided by Google
    * Version Control
        * [Git](https://git-scm.com/) - Our VCS
        * [GitHub](https://github.com/) - A web-based hosting service for version control.

## Team 2
* Jeremy Oliver
* Ryan Hiller
* Ben Mettlach
* Aldo Jarmillo
* Tate Wongweeratorn
* Justin Treece
* Wesley Kramer

## Disclaimer
This project was initially created by Team 2 for the Fall 2018 CS 3250 class at MSU Denver

repository: RyanHiller/Campus-Navigator

repo_name: RyanHiller/Campus-Navigator


text:
---
title:  Dynamical Systems in Biology
author: Janine Egert, Daniel Lill, Daniel Kaschek, Mirjam Fehling-Kaschek
date: 23rd April 2019
---

# Tutorial 0

## Exercise 1 - Installation

* Go to [Github.com](https://www.github.com) and open an account
* Install [JuliaPro](https://juliacomputing.com/products/juliapro.html): Open a terminal and execute the following commands.

    ```
    cd
    git clone https://github.com/dlill/DynSysBio2019
    cd DynSysBio2019
    sh ./installJuliaPro.sh
    ```

    Follow the instructions given during the installation.

* Launch JuliaPro by executing the following command in a terminal

    ```
    ~/JuliaPro/JuliaPro-<IP_ADDRESS>/Launch_JuliaPro & exit
    ```

* Have a quick look at some examples in `~/DynSysBio2019/Examples/FirstSteps.jl`

## Exercise 2 - Getting to know Julia

Create a new folder `~/DynSysBio2019_programming`.
Create a new file `~/DynSysBio2019_programming/tutorial0.jl` to solve the following questions in this script.

1. Create a 3x3 matrix  $ A = \begin{pmatrix}1&2&3\\4&5&6\\7&8&9\end{pmatrix} $
1. Multiply each element of `A` by 2
1. Create a 3x3 matrix $ B = \begin{pmatrix}1&4&7\\2&5&8\\3&6&9\end{pmatrix}$
1. Divide `A` by `B` element-wise.
1. Replace all entries A==5 by A = 0
1. Create a 3x3 Identity Matrix by Matrix-multiplying `B` with its inverse.
1. Create a vector `v` containing the numbers 1 to 10
    1. By using `[...]`
    1. By using `collect`
    1. By using a `for`-loop
    1. By using a `while`-loop

## Exercise 3 - Newton method

Given the ODE for the Verhulst model

$$
\dot{x} = f(x,\vec{p}) = p_1 x \left( 1-\frac{x}{p_2} \right)
$$

find the points $\bar{x}$ where $\dot{x}=0$, numerically.

* Write one function `vh_ode(x, p)` and one function `vh_ode_jacobian(x,p)` returning $f(x,\vec{p})$ and $f'(x,\vec{p})$, respectively.
* Implement the newton method $x_{n+1} = x_n - \frac{f(x_n,\vec{p})}{f'(x_n,\vec{p})}$ in a function `newton(x0, p; prec = 1e-8)` with initial value `x0`, parameter vector `p` and precision `prec`.
    Stop the iterations when $|x_{n+1}−x_n| < prec$ is reached.
* Test the newton solver with different starting values $x0$ for different parameter sets $\vec{p}$.
    * Compare the results to the analytic solution

[Illustration of Newton’s method](https://en.wikipedia.org/wiki/Newton's_method#/media/File:NewtonIteration_Ani.gif)


text:
# Share plugin

---

## Deprecation Notice

This plugin has been replaced by the [Flutter Community Plus
Plugins](https://plus.fluttercommunity.dev/) version,
[`share_plus`](https://pub.dev/packages/share_plus).
No further updates are planned to this plugin, and we encourage all users to
migrate to the Plus version.

Critical fixes (e.g., for any security incidents) will be provided through the
end of 2021, at which point this package will be marked as discontinued.

---

[![pub package](https://img.shields.io/pub/v/share.svg)](https://pub.dev/packages/share)

A Flutter plugin to share content from your Flutter app via the platform's
share dialog.

Wraps the ACTION_SEND Intent on Android and UIActivityViewController
on iOS.

## Usage

To use this plugin, add `share` as a [dependency in your pubspec.yaml file](https://flutter.dev/docs/development/packages-and-plugins/using-packages/).

## Example

Import the library.

``` dart
import 'package:share/share.dart';
```

Then invoke the static `share` method anywhere in your Dart code.

``` dart
Share.share('check out my website https://example.com');
```

The `share` method also takes an optional `subject` that will be used when
sharing to email.

``` dart
Share.share('check out my website https://example.com', subject: 'Look what I made!');
```

To share one or multiple files invoke the static `shareFiles` method anywhere in your Dart code. Optionally you can also pass in `text` and `subject`.
``` dart
Share.shareFiles(['${directory.path}/image.jpg'], text: 'Great picture');
Share.shareFiles(['${directory.path}/image1.jpg', '${directory.path}/image2.jpg']);
```

repository: buaashuai/plugins

gha_language: Dart

repo_name: buaashuai/plugins


text:
# NfsShares

## Caveats:
- FreeNAS requires that all POST and PUT API calls have a trailing slash.
- FreeNAS API describes quota, refquota, reservation and refreservation as string, but they return int. You can apparently send things like 10GiB and get an integer response

repository: fishman/go-freenas

repo_name: fishman/go-freenas


text:
# OpenTelemetry

**This library is under development, it's not yet production ready**

This is Open Telemetry SDK for Elixir.

## Installation

Install the latest version of `open_telemetry` in your `mix.exs` file.

```elixir
def deps do
  [
    {:open_telemetry, "~> 0.1.0"}
  ]
end
```

Check out the documentation in
[https://hexdocs.pm/open_telemetry](https://hexdocs.pm/open_telemetry).

Library published on [HexDocs](https://hex.pm/packages/open_telemetry).

branch_name: refs/heads/main


text:
#  Wp Dev Environment
I created this beacause I wanted to skip the boring setup of a proper environment to develop wordpress themes and plugins.

It has PHP My Admin access and automated database backups.

This `docker-compose.yml` file includes four images:

- `mariadb`
- `phpmyadmin/phpmyadmin`
- `bitnami/wordpress:latest`
- `databak/mysql-backup`

## Before you start

What you need to get up and running:
 - Any linux distro
 - Docker
 - A nginx proxy. See: https://github.com/jwilder/nginx-proxy

>Note: This was made for Linux so if you are on Windows or macOs you'll have to tweak one thing or another

## How-to

1. First of all, clone this repo in your project folder:

    ```
    $ git clone https://github.com/gustavo-a/wp-dev-environment.git /path/to/your/project
    ```

2. Then you need to set up a `.env` file with your project name. This will be your local domain.

    ```
    PROJECT_NAME=yourprojectname
    ```

3. Make the necessary changes to the `docker-compose.yml` file.

4. Execute `make init` on your terminal to start the setup.
This command will start your container, delete the `.git` folder and fix some permissions.

## I've done it! Now what?

You can access your wordpress site at `yourprojectname.local`.

You can access PHP My Admin at `phpmyadmin.yourprojectname.local`.

You can edit your php settings in the `config/php/php.ini` file.

You can edit your apache settings in the `config/apache/httpd.conf` file.

## Shortcuts

I've also added some shortcuts to the `Makefile`

- `make bash` run bash terminal inside the container
- `make stop` stops the container
- `make start` starts the container
- `make remove` removes the container along with its volumes and delete the backups

license: Unlicense

repository: gustavo-a/wp-dev-environment

repo_name: gustavo-a/wp-dev-environment


text:
[![Build Status](https://github.com/wrike/metrics/workflows/build/badge.svg)](https://github.com/wrike/metrics/)

### The Dart command line tool which helps to improve code quality

### Simple usage:
```bash
pub global activate metrics
metrics lib
```

repository: sinegovsky-ivan/metrics

gha_license_id: MIT

repo_name: sinegovsky-ivan/metrics


text:
# Gibberish Microservice

REST-powered microservice for analyzing text and returning if it is likely gibberish or not.
The repository also contains a client to perform requests to the service.

It is important to notice that this service provides no support for authentication or caching. It is also completely stateless, making it ideal to be used in the backend. A possible "frontend" implementation can be found in [Analysis API](https://gitlab.com/shitposting/analysis-api).

## Endpoints

- Gibberish endpoint: `<bind-address>/gibberish`
- Health check: `<bind-address>/healthy`

## Returned data

The data returned by the server is in the form:

```go
type GibberishResponse struct {
    IsGibberish bool
}
```

## Environment options

- Service bind address and port: `"GB_BIND_ADDRESS"` (defaults to `localhost:10002`).
- Path to knowledge base file: `GB_KNOWLEDGE_PATH` (defaults to `knowledge.json`).

repository: shitpostingio/gibberish-microservice

repo_name: shitpostingio/gibberish-microservice


text:
---
layout: page
title:  "About me"
---

I am currently a software engineer at Google in Cambridge, MA.  I was previously a graduate student in the [Operations Research Center at MIT](http://www.mit.edu/~orc/), graduating in 2014.  I worked with [Itai Ashlagi](http://web.mit.edu/iashlagi/www/) and [David Gamarnik](http://www.mit.edu/~gamarnik/home.html), doing research in applied probability, stochastic processes, and integer programming. Much of my time was spent working on problems related to living donor kidney exchange.  Here are my [Google Scholar page](http://scholar.google.com/citations?user=8wAjOQkAAAAJ&hl=en), my [Github page](https://github.com/rma350), and my [Assembla page](https://www.assembla.com/profile/rma350?public=true).

I grew up in Otego, NY. My parents still live there.  My dad built this boat:

It is for sale.  Using the boat, he caught this fish:

That could be you!  There is more information about the boat [here](http://andersonboatworks.wordpress.com/).

My dad also runs a small independent publishing company, [Otego Publishing](http://otegopublishing.wordpress.com/).

extension: markdown


text:
+++
author = ["Marty Schoch"]
date = "2015-09-28T10:40:38-04:00"
title = "Deferred Cleanup, Checking Errors, and Potential Problems"
+++

The *defer* statement in Go is frequently used to ensure that once a resource has been acquired, it will be properly cleaned up.  In its simplest form it works exactly as you expect.  But, as you move to more advanced usages there are some things to watch out for.  I'd like to share one that I recently ran into while writing Bleve test cases.

### Basics

The power of the *defer* statement in Go is that it lets you put the acquisition and cleanup of a resource side by side.  When you read code later, it's easy to see that the correct behavior is guaranteed.  Let's take a look at a simple example:

```
func main() {
	r, err := Open("a")
	if err != nil {
		log.Fatalf("error opening 'a'\n")
	}
	defer r.Close()
}

type Resource struct {
	name string
}

func Open(name string) (*Resource, error) {
	return &Resource{name}, nil
}

func (r *Resource) Close() error {
	log.Printf("closing %s\n", r.name)
	return nil
}
```
[Run this in the Go Playground](http://play.golang.org/p/fYB2alVcIw)

The main function shows some very common behavior.  Open a resource, check for an error, then *defer* Closing the resource.  When we run this, we get the expected behavior:

```
2009/11/10 23:00:00 closing a
```

### Opening another Resource, Reusing the Variable

Let's make the example a bit more complex.  Now, after closing the resource, we will open another one (with a different name).  Can we reuse the same variable?

```
func main() {
	r, err := Open("a")
	if err != nil {
		log.Fatalf("error opening 'a'\n")
	}
	defer r.Close()

	r, err = Open("b")
	if err != nil {
		log.Fatalf("error opening 'b'\n")
	}
	defer r.Close()
}
```
[Run this in the Go Playground](http://play.golang.org/p/Bal_y0nv4U)

When I was new to Go and first encountered this code I wasn't sure if this would work.  I knew that *defer* would not execute until the end of main, but would it close 'a' AND 'b'?  Or would it close 'b' twice?  If we run it we see:

```
2009/11/10 23:00:00 closing b
2009/11/10 23:00:00 closing a
```

So, it does work, this is the expected output.  Some of you may be wondering, but *why* does it work?  As the Go blog [Defer, Panic, and Recover](http://blog.golang.org/defer-panic-and-recover) explains,

> "A deferred function's arguments are evaluated when the defer statement is evaluated."

In our case, the method receiver 'r' for the Close() method behaves just like an argument.  So the 'r' is evaluated at the time the defer statement is evaluated, and *NOT* when the statement is executed.  In Bleve code we saw this pattern occur frequently in test cases.  We would acquire a resource, take some action, close the resource, check the state of things, then repeat the process.

### errcheck?

Last February I had the amazing opportunity to attend [GopherCon India](http://www.gophercon.in/).  One of the many things I learned while there was of a tool called [errcheck](https://github.com/kisielk/errcheck).  The idea of the tool is simple, it looks at your Go code and identifies places where you're not checking a returned error.  This seemed like such an obvious thing to do, so I ran it on the entire Bleve codebase.  We found several clear cases where an error was returned, and we would not propagate the error back to the caller.

But what happens if we run *errcheck* on the code we just wrote above?

```
github.com/mschoch/defertest/main.go:10:15	defer r.Close()
github.com/mschoch/defertest/main.go:16:15	defer r.Close()
```

The Close() method returns an error.  Although it's not used in this contrived example, I coded it that way on purpose as that is very common in the real world.  Does checking this error matter?  If closing the first resource results in an error, should you try to close the second one?  In the abstract these are interesting philosophical questions, but let's assume we do want to check the errors.  How would we do it?  My first attempt looked like this:

```
func main() {
	r, err := Open("a")
	if err != nil {
		log.Fatalf("error opening 'a'\n")
	}
	defer func() {
		err := r.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()

	r, err = Open("b")
	if err != nil {
		log.Fatalf("error opening 'b'\n")
	}
	defer func() {
		err := r.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()
}
```
[Run this in the Go Playground](http://play.golang.org/p/_MPUl6zWjF)

I added an anonymous function which invokes r.Close(), checks the error, and if its non-nil we exit the program through log.Fatal().  It seems like such a simple change, but we've introduced a severe bug into the code.  In our case we can see it clearly since we're printing out the name of the resource being closed:

```
2009/11/10 23:00:00 closing b
2009/11/10 23:00:00 closing b
```

Oops!  We're now closing the 'b' resource twice, and never closing the 'a' resource.  This is a severe problem, closing 'b' a second time may not be well defined behavior, and not closing 'a' may leak resources.

Where did we go wrong?  Remember the rule we were given was:

> "A deferred function's arguments are evaluated when the defer statement is evaluated."

And in our new code, the deferred function has no arguments, and no method receiver.  We're now relying the anonymous function referring to 'r'.  The Go spec says:

> "...they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible."

So, now it's fairly clear what happened.  At the time the *defer* statement was evaluated, the arguments were evaluated, but there were none.  Then at the end of the function, the deferred function is executed, and *now* as the anonymous functions are executed, 'r' is evaluated, and in both cases it refers to 'b'.

### The Fix

Option 1, we can rewrite the *defer* statement to pass 'r' as an argument:

```
func main() {
	r, err := Open("a")
	if err != nil {
		log.Fatalf("error opening 'a'\n")
	}
	defer func(r *Resource) {
		err := r.Close()
		if err != nil {
			log.Fatal(err)
		}
	}(r)

	r, err = Open("b")
	if err != nil {
		log.Fatalf("error opening 'b'\n")
	}
	defer func(r *Resource) {
		err := r.Close()
		if err != nil {
			log.Fatal(err)
		}
	}(r)
}
```

This does give the correct output:

```
2009/11/10 23:00:00 closing b
2009/11/10 23:00:00 closing a
```

But, to be honest, it's rather verbose.  In many cases it may just be simpler to use a different variable name.  Option 2, use a new variable for the second resource:

```
func main() {
	r, err := Open("a")
	if err != nil {
		log.Fatalf("error opening 'a'\n")
	}
	defer func() {
		err := r.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()

	r2, err := Open("b")
	if err != nil {
		log.Fatalf("error opening 'b'\n")
	}
	defer func() {
		err := r2.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()
}
```

**UPDATE: 2015-09-29**

Users [discussing this on Reddit](https://www.reddit.com/r/golang/comments/3mqxar/deferred_cleanup_checking_errors_and_potential/) proposed a third option.  Create a named cleanup function and use the existing io.Closer interface:

```
func main() {
	r, err := Open("a")
	if err != nil {
		log.Fatalf("error opening 'a'\n")
	}
	defer Close(r)

	r, err = Open("b")
	if err != nil {
		log.Fatalf("error opening 'b'\n")
	}
	defer Close(r)
}

func Close(c io.Closer) {
	err := c.Close()
	if err != nil {
		log.Fatal(err)
	}
}
```
[Run this in the Go Playground](http://play.golang.org/p/ZjlavK1r6N)

As I mentioned earlier, in Bleve this pattern only seems to arise in test cases.  I suspect in real code you'd be more likely to already be using more descriptive identifiers.

### Summary

To me the lesson here is that we had a simple pattern for deferred cleanup that worked.  I even explicitly took the time to verify that it cleaned up the correct resources when I reused variables.  Then I took the seemingly natural step to make sure we check all the returned errors.  But, I was a bit careless and overlooked that the deferred anonymous function can have significantly different behavior.  It wasn't until I observed problems that I went back to recheck my assumptions and track down the problem.

gha_language: JavaScript


text:
---
layout: default
---

# 1998-09-18 - Re: Questions for Magaziner?

## Header Data

From: Steve Bellovin<EMAIL_ADDRESS>To: "John Kelsey"<EMAIL_ADDRESS>Message Hash: 04dd29ac919d0b7eeccd469dcd60cbd0bc8fac026fff8beec677452a85d65928

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1998-09-18 05:52:37 UTC

Raw Date: Fri, 18 Sep 1998 13:52:37 +0800

## Raw message

```
{% raw  %}From: Steve Bellovin<EMAIL_ADDRESS>Date: Fri, 18 Sep 1998 13:52:37 +0800
To: "John Kelsey"<EMAIL_ADDRESS>Subject: Re: Questions for Magaziner?
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

It is, of course, worth remembering that Magaziner is pretty much on
our side on this issue.  He just hasn't been able to win over Freeh,
Reno, Clinton, etc.

{% endraw %}
```

## Thread

+ Return to [September 1998](/archive/1998/09)

+ Return to "[Steve Bellovin <smb@research.att.com>](/authors/steve_bellovin_smb_at_research_att_com_)"

+ 1998-09-18 (Fri, 18 Sep 1998 13:52:37 +0800) - Re: Questions for Magaziner? - _Steve Bellovin<EMAIL_ADDRESS>


text:
---
layout: post
title: "DeepBall: Deep Neural-Network Ball Detector"
date: 2019-02-19 21:57:48
categories: arXiv_CV
tags: arXiv_CV Object_Detection CNN Classification Detection
author: Jacek Komorowski, Grzegorz Kurzejamski, Grzegorz Sarwas
mathjax: true
---

* content
{:toc}

##### Abstract
The paper describes a deep network based object detector specialized for ball detection in long shot videos. Due to its fully convolutional design, the method operates on images of any size and produces \emph{ball confidence map} encoding the position of detected ball. The network uses hypercolumn concept, where feature maps from different hierarchy levels of the deep convolutional network are combined and jointly fed to the convolutional classification layer. This allows boosting the detection accuracy as larger visual context around the object of interest is taken into account. The method achieves state-of-the-art results when tested on publicly available ISSIA-CNR Soccer Dataset.

##### Abstract (translated by Google)

##### URL
[http://arxiv.org/abs/1902.07304](http://arxiv.org/abs/1902.07304)

##### PDF
[http://arxiv.org/pdf/1902.07304](http://arxiv.org/pdf/1902.07304)


text:
# TSSPA
[![Build Status](https://img.shields.io/travis/Jandou6/tsspa/master.svg)](https://travis-ci.org/Jandou6/tsspa/branches)
[![GitHub license](https://img.shields.io/github/license/jandou6/tsspa.svg)](https://github.com/nhnent/tui.calendar/blob/master/LICENSE)

TSSPA can generate  SPA Web in [Typescript](http://www.typescriptlang.org/) + [React](https://reactjs.org/) + [Webpack](http://webpack.github.io/)

[中文说明](https://github.com/Jandou6/tsspa/blob/master/docs/Readme-zh.md)

## How to use
1. get tsspa
```bash
npm install tsspa -g
```

2. generate you project such as:
```bash
tsspa -i my_project
```

3. you can see `my_project` had been created.Then you can:

    1. open the project that you created :
    ```bash
    open my_project
    ````

    2. use `yarn` or `npm` to install Dependencies.
    ```bash
    yarn install
    ````
    3. use webpack to start server for this project.
    ```bash
    yarn dev
    ```
    4. now you can open [http://localhost:8080](http://localhost:8080) in your browser.

## TODO
- [x] clean all the warnings
- [x] add prod/dev config
- [x] add react-loadable
- [x] add command to generate view template.
- [x] build in CI.
- [x] 中文 Readme
- [x] publish in npm.
- [ ] add e2e test.

## License
[MIT](https://github.com/Jandou6/tsspa/blob/master/LICENSE)

Copyright (c) 2018-present, Jandou


text:
## Project 3: Query a Digital Music Store Database

In this project, you will query the Chinook Database. The Chinook Database holds information about a music store. For this project, you will be assisting the Chinook team with understanding the media in their store, their customers and employees, and their invoice information.

[Link to report](https://github.com/boa2017/Udacity-Data-Foundations-Nanodegree/blob/master/Project%203/Project%203%20Report.pdf)

[Database used](https://github.com/boa2017/Udacity-Data-Foundations-Nanodegree/blob/master/Project%203/chinook.db)

[Queries used](https://github.com/boa2017/Udacity-Data-Foundations-Nanodegree/blob/master/Project%203/queries.txt)

path: /Project 3/README.md


text:
# Windows Log Analytics VM Agent Extension

## Display Name

Deploy Log Analytics Agent Extension for Windows VMs

## Mode

`Indexed`

## Description

Deploy Log Analytics agent for Windows VMs if the VM Image (OS) is in the list defined and the agent is not installed. The list of OS images will be updated over time as support is updated.

## References

[Built-In: Deploy Log Analytics agent for Windows VMs](https://github.com/Azure/azure-policy/blob/master/built-in-policies/policyDefinitions/Monitoring/LogAnalyticsExtension_Windows_VM_Deploy.json)

[Built-In: Deploy Dependency agent for Windows virtual machines](https://github.com/Azure/azure-policy/blob/master/built-in-policies/policyDefinitions/Monitoring/DependencyAgentExtension_Windows_VM_Deploy.json)


text:
# Friday Night Funkin' Elemental
Source code for the Friday Night Funkin' Elemental mod. Runs on Psych engine.

# What's New?

## Edited Vanilla Dialogue Box

While there is an exclusive dialogue box made for Psych Engine specifically, we have decided to run an edited version of the vanilla dialogue box mixed with some features from Mic'd up, adding support for custom CG cutscenes, voicelines, and sound effects.

## NEW WEEK:
### CHAPTER ONE

Meet Enzo, your old friend from highschool. He's here to investigate a perplexing purple gem that seems to glow whenever he's around it... can you out-rap him in this museum mishap?

Contains TWO new songs: Reunion, Myst

# We hope you enjoy!

repository: JoelioBrolio/FNF-Elemental

gha_language: Haxe

repo_name: JoelioBrolio/FNF-Elemental


text:
# Angular Best Practices

# Description

This `Readme` file and `./examples` folder  describe a collection of codestyle rules and architecture patterns for `Angular` for any project.
The goal is to describe the minimum of best practices for angular while adhering to the 80/20 Pareto law.
This guide is created for beginners in `Angular`.
So that a new programmer without practice could write good code and make a good architecture.

It will free a team lead from explaining those things which will make easier for them to change staff.
Eventually, this is necessary to comply with the principle — "if you put in the effort you'll do a better job".
Suggestions for improving this guide are welcome.

All examples are working. Examples from the `README` can be found in the project code.

Before starting learning the project, there are two things to keep in mind:

1. There are "unimportant things" - these are approaches in development refactoring of which doesn't take much time.
   For example, these include issues of naming folders, components, services, etc. It doesn't matter how exactly you'll call any files, and folders etc., much more important is that you and your team should make it the same way in the whole project.
2. There are "important things" - these are approaches in development refactoring of which takes a lot of time, it is often easier to rewrite some logic than to refactor it. As a rule, these include issues of architecture, correct usage of libraries and frameworks.

That's why you make "unimportant things" as you wish, but "important things" I suggest you do according to this manual.

Email: [evoytenkoapps<EMAIL_ADDRESS>
## Table of contents

- [Files](#files)
- [Project structure](#project-structure)
- [Interfaces](#interfaces)
- [Formatting](#formatting)
- [Packages](#packages)
- [Lint](#Lint)
- [Git](#git)
- [TypeScript](#TypeScript)
- [JavaScript](#javascript)
- [Angular](#Angular)
  - [Service mocking](#services-mocking)
  - [Template](#Template)
- [RxJs](#RxJs)
- [Architecture](#Architecture)
- [Comments](#Comments)
- [Css styles](#css-styles)
- [State manager](#state-manager)
  - [NGXS](#ngxs)
- [Forms](#forms)
  - [Formly](#formly)

## Files

Try to store each class, interface, enum, record in different files. The file shouldn`t have more than one entity

For `interfaces` that describes methods we should create a file with ending `***.interface.ts`, , like `simple.ts`, and name it `ISimple`

For `interfaces` that describes value object create a file with ending `***.ts`, like `simple.ts`

For `dictionary (record)` create a file with ending `***.ts`, like `simple.ts`

For `enum Simple` create a file with ending `***.ts`, like `simple.ts`

For `class Simple` create a file with ending `***.ts`, like `simple.ts`

## Project structure

Split the project logic into the modules. Give them a name according to the business rules without prefix `_`, fore example `user-info`

Group the folders inside module like this:

```
`_components` - components
    `_smart` - smart components
    `_dumb` - dumb components
`_providers` - providers
`_models` - models ( object value inetrfaces and classes )
`_pipes` - pipes
`_directives` - directives
`_guards` - guards
`_resolvers` - resolvers
`_store` - Redux ( ngxs example )
    `actions` = the models of actions
    `models` = the models of states and theris default values
    `states` =  the actions effects and their selectors
`_constants` - constants
`_services` - services
    `facade` - facade
    `api` - rest services
`user-info` - nested module
```

Give names to nested modules due to business logic.

`user-info`
`details`

Give names to components modules by business logic without `_`

Mocks store inside production folders

For example: [project-folder-sturcture](https://github.com/evoytenkoapps/angular-best-practices/tree/master/examples/src/app/components/project-folder-sturcture)

```
├───user-info
│   │   user-info.module.ts
│   │
│   ├───user-software
│   ├───_components
│   │   ├───_dumb
│   │   │   └───user-info-details
│   │   │           user-info-details.component.css
│   │   │           user-info-details.component.html
│   │   │           user-info-details.component.spec.ts
│   │   │           user-info-details.component.ts
│   │   │
│   │   └───_smart
│   │       └───user-info
│   │               user-info.component.css
│   │               user-info.component.html
│   │               user-info.component.spec.ts
│   │               user-info.component.ts
│   │
│   ├───_constants
│   ├───_directives
│   ├───_guards
│   ├───_models
│   ├───_pipes
│   ├───_providers
│   │       uesr-http.provider.ts
│   │       user-info.provider.ts
│   │
│   ├───_resolvers
│   ├───_services
│   │   ├───api
│   │   │       user-http-mock.service.ts
│   │   │       user-http-prod.service.ts
│   │   │       user-http.service.ts
│   │   │
│   │   └───facade
│   │           user-ngxs.facade.ts
│   │           user.facade.ts
│   │
│   └───_store
│       ├───actions
│       ├───models
│       └───states
└───user-story
```

## Interfaces

For example for `environment` describe its interface `Environment` and store inside `./environments/models/environment.ts`

If interface is used only in one component, then we may store it inside component.

If interface is used in several components, then we should store it in a separate file, like `./models/some-data`.

## Formatting

Use `prettier` for code formatting

Inside `./src` create a file and call it `.prettierrc.json`. Describe there all formatting settings as you wish. Probably your IDE will offer you to apply them, so do it.

Inside `./src` create a file and call it `.prettierignore`. Describe there paths for the files that you don't want to format

We configure the `IDE` so that formatting is applied on saving file event.

## Packages

Packages should be installed with opportunity to update the `patch` version. So you should set `~` before the package version in `package.json`, like `prettier": "~2.2.1`.
You may set it by default in `yarn` or `npm`.

## Lint

`Tslint` or `Eslint` should find code errors inside project for you. Use what the `Angular` version allows for you.

Install code check rules through third party packages, like `rxjs-tslint-rules`.

### Tslint

Add code check packages into `tslint.json`, property `extends`, like `"extends": ["tslint:recommended", "rxjs-tslint-rules"]`.
Then set what kind of rules you want to use. Add it inside property `rules`, like `"rxjs-no-unsafe-takeuntil": { "severity": "error" }`.

You may run code checking with command `ng lint --format prose`, and add it to `package.json`.

## Git

### CRLF LF

If you have git warning after use `git add .`, you may fix them inside file `.gitattributes`, add there a rule `* text=auto eol=lf`

## TypeScript

Use strict mode `"strict": true`

We specify access modifiers for all members and methods of classes, like `private, public, protected`.

We specify the data type for each property, constant, function argument, return value of a function, argument
functions `rxjs` operator exception complex operators` combine` and so on.

Try not to use optional setting operator `?` like `private a?: number;` because your code should be as strict as possible.

Don't use type `any` (use only while working with third-party libraries, if there is no way not to do it).

It is better to use `generic` when you need to use any types inside your model, instead of `any`.
When you have to use several types inside your model, you may use `type union` instead of `any`

Wrong code:

```
interface DraftDTO {
  id: number;
  body: any
}
const productBody: any =  { type: "product"}
const draftProduct: DraftDTO = { id: 1, body: productBody }
```

Nice code:

```
interface DraftDTO<T> {
  id: number;
  body: T
}

const productBody: ProductDTO =  { type: "product" }
const draftProduct: DraftDTO<ProductDTO> = { id: 1, body: productBody }

type CustomDraftBody = ProductDTO | SoftDTO;

const softBody: CustomDraftBody =  { type: "soft" }
const draftCustom: DraftDTO<CustomDraftBody> = { id: 1, body: softBody }
```

We avoid objects' mutations. You should add `readonly` modification to all properties of classes and interfaces. This will help to avoid mutating data from the child component of the parent and vice versa. Also, it helps when working with `OnPush` strategies, because you'll should copy all objects for changes, and change their reference at the end.

Add `Readonly<X>` for any objects when you can't set `readonly` for his properties.

Bad example:

```
requiremensDTO: IRequirementDTO[] = [];
const user = Readonly<User>
```

Good example:

```
requiremensDTO: Readonly<IRequirementDTO>[] = [];
const user = Readonly<User>
```

Don't use `var`. Always use `const` or `let` when you need to change reference.

Always use strict comparison `===`

When a class member will be not initialized inside constructor, for example value from `BehaviourSubject`, if strict mode is on `typescript`
will give an errors, then we mark it with the symbol `!`, otherwise we set `undefined` or` null`.

Example:

```
@Input() adress: string | undefined = undefined;

public userInfo!: UserInfo

ngOnInit(){
   this.userInfo$.pipe(takeUntil(this.destroy$)).subscribe(userInfo => this.userInfo = userInfo)
}
```

Don't call objects properties via string, because it breaks the `DRY` principle.
Also don't use routes as strings, put them into `enum` and use it.

Bad code:

```
// template
*ngIf="approveStatus['Deleted'] === 'deleted'"

// controller
public approveStatus: ApproveStatus
this.router.navigate(['projects'])

[routerLink]="/auth"
```

Good code:

```
// template
*ngIf="status === approveStatus.Approved"

// controller
public status: ApproveStatus
public approveStatus: typeof ApproveStatus = ApproveStatus;

this.router.navigate([Routes.PROJECTS])

[routerLink]="['/' + Routes.AUTH]"

// template
*ngIf="dwsUser.status === storeStatus.Loaded"

// controller
public dwsUser: DataWithStatus<User>
public storeStatus: typeof StoreStatus = StoreStatus;

```

Do not give names to entities beginning with verbs, use nouns.

Bad code:

```
export interface CreatePoTipInfoModel {
    header: string;
    message: string;
    }
```

Good code:

```
export interface ProductOwnerTipInfoCreateModel {
    header: string;
    message: string;
    }
```

When needs to get an object's values its better to make an type safety iterator, instated of manual announcement.

Wrong code:

```
     const loadingStatus: StoreStatus | undefined = [
       state.productsList.status,
       state.productsComposition.status,
       state.productsCompositionExtended.status,
       state.softList.status,
       state.softServicesWithoutProducts.status,
       state.listOfSoftAndServices.status,
       state.softComposition.status,
       state.productsWithoutSoftAndServices.status,
      ].find((currSatus: StoreStatus) => currSatus === StoreStatus.LOADING);
```

Nice code:

```
    const loadingStatus: StoreStatus | undefined = (Object.keys(state) as (keyof ProductsSoftServicesStateModel)[])
      .map((key) => state[key])
      .map((value) => value.status)
      .find((currSatus: StoreStatus) => currSatus === StoreStatus.LOADING);
```

If any external libraries allow to use generic its better to use it. For example `Angular Material` dialog uses generic.
Because type checks helps you to support and extened project code much easier.

Nice code:

```
// describe dialog component like this
export class InfoDialogComponent implements OnInit {
  public infoDialogModel: VmInfoDialogModel;

  constructor(
    private dialogRef: MatDialogRef<InfoDialogComponent, ConfirmDialogResultModel>
  )

    public onBtnClick(data: boolean): void {
        this.dialogRef.close({ isConfirmed: data });
  }

// open dialog like this
  public showAndGetData(data: VmInfoDialogModel): Observable<ConfirmDialogResultModel | undefined> {
    return this.dialog
      .open<InfoDialogComponent, VmInfoDialogModel, ConfirmDialogResultModel>(InfoDialogComponent, {
        data,
        disableClose: data.isDisableCloseOnBackClick,
      })
      .afterClosed();
  }
```

If any external libraries allow to use `Observable` its better to use it inside `guards` or on button clicks inside components.
For example `Angular Material` dialog uses `Observable` after `.afterClosed()` method.

Nice code:

```
      switchMap((isLoading) => {
        if (isLoading) {
          return this.infoDialogService.getConfirmation(this.infoDialogModel).pipe(
            map((result) => !result?.isConfirmed)
          );
        }
        return of(true);
      })
```

## JavaScript

Avoid `side effects`

If a function with an argument changes something, then we start calling it with the word `set`, like `setSometing(data: SomeType): void`

If a function without an argument changes something, then we call it from the word `change`, like `changeSometing(): void`

If a function gets a value, then we call it with the word `get`, whether there are arguments or not.
Examples

```
getSometing() : string
getSometing(data: SomeType) : string
```

Try to use array functions `filter`,` map`, `reduce`,` every`, `some` more often.
if you need to iterate over the array for the truth of a certain field
object and at the same time perform the action only if it is true, then
we use `find`. The code becomes cleaner and more readable.
For example, to change the array you do not need to use `foreEach + includes`, use` map + filter`

Wrong code:

```
  private getGroupTypes(filteredScoredContentEntries: ScoredContentEntry[]): GroupType[] {
    const groupTypes: GroupType[] = [];

    filteredScoredContentEntries.forEach((scoredContentEntry: ScoredContentEntry) => {
      const type: EntityResultItemType = this.getType(
        scoredContentEntry.contentEntry!.entityType as EntityType,
        scoredContentEntry.contentEntry!.entitySubType as number
      ) as EntityResultItemType;

      if (!groupTypes.includes(type.group)) {
        groupTypes.push(type.group);
      }
    });

    return groupTypes;
  }
```

Nice code:

```
  private getGroupTypes(filteredScoredContentEntries: ScoredContentEntry[]): GroupType[] {
    return filteredScoredContentEntries
      .map((scoredContentEntry: ScoredContentEntry) => {
        const type: EntityResultItemType = this.getType(
          scoredContentEntry.contentEntry!.entityType as EntityType,
          scoredContentEntry.contentEntry!.entitySubType as number
        );
        return type.group;
      })
      .filter((group, index, groups) => {
        return groups.indexOf(group) === index;
      });
  }
```

Wrong code:

```
    this.iterations = Object.keys(artifactNames).map(
      (key) => new ArtifactIteration(parseInt(key, 10), artifactNames[key as number])
    );
```

Nice code:

```
    this.iterations = Object.keys(artifactNames)
        .map((keyAsString) => parseInt(keyAsString, 10))
        .map((key) => new ArtifactIteration(key, artifactNames[key]));
```

Wrong code:

```
function getCurrentList(parentId: number, typeId: number): ArtifactType[] {
  let currentList = [];
  if (artifacts.allArtifacts.type.length > 0) {
    for (let artifactType of artifacts.allArtifacts.type) {
      if (artifactType.parentId === parentId) {
        currentList.push(artifactType);
      }
    }
  }
  currentList.sort((first, second) =>
    first.orderId < second.orderId ? -1 : 1
  );
  return currentList;
}
```

Nice code:

```
function getCurrentList(parentId: number, typeId: number): ArtifactType[] {
  return artifacts.allArtifacts.type
    .filter((artifactType) => artifactType.parentId === parentId)
    .sort((first, second) => (first.orderId < second.orderId ? -1 : 1));
}
```

Inside arrow functions, specify the name of the arguments according to logic, like `countersDTO`, ` maxDate`.
It would be clear to understand what they contain, for example . Don't call them unreadable, like `c`,`m`

Wrong code:
`if(arr.find( u => u.userName === 'Петрович' ))`

Nice code:
`if(users.find( user: User => user.userName === 'Петрович' ))`

All booleans values start to call with `is` or `has`

Wrong code:

```
showDeleted: boolean
```

Nice code:

```
isShowDeleted: boolean
```

Try don't give the simple names ( double interpretation ) to methods, properties, classes that makes specific things. For example, instead of `count` or` allItemsCount`, we try to use `totalFoundInSearch`, instead of` isEdit` -> `isShowDeleteAndCancel`

Don't use more than one ternary operator`?` at once. Instead, check it inside `if() {return} return`.
Wrong code:

```
return link.includes('groups')
      ? FDM_SEARCH_RESULT_GROUP.GROUPS
      : link.includes('domains')
      ? FDM_SEARCH_RESULT_GROUP.DOMAINS
      : link.includes('business-capabilities')
      ? FDM_SEARCH_RESULT_GROUP.BUSINESS_CAPABILITIES
      : FDM_SEARCH_RESULT_GROUP.GROUPS;
```

Nice code:

```
 if(link.includes('groups'))
    return FDM_SEARCH_RESULT_GROUP.GROUPS
 if(link.includes('domains'))
    return FDM_SEARCH_RESULT_GROUP.DOMAINS
 if(link.includes('business-capabilities'))
    return FDM_SEARCH_RESULT_GROUP.BUSINESS_CAPABILITIES
 return FDM_SEARCH_RESULT_GROUP.GROUPS
```

Don't use expressions over than 70 characters in arrays, object values, if() etc. Move them into separate constants or functions. When we assign expressions to constants, we increase their understanding and readability, and such code is much more easier to debug.

Wrong code:

```
    return {
      [FDM_SEARCH_RESULT_GROUP.GROUPS]: state.searchResults[FDM_SEARCH_RESULT_GROUP.GROUPS].filter(
        (domain) => domain.status !== DomainDTOStatus.Deleted
      ),
      [FDM_SEARCH_RESULT_GROUP.DOMAINS]: state.searchResults[FDM_SEARCH_RESULT_GROUP.DOMAINS].filter(
        (domain) => domain.status !== DomainDTOStatus.Deleted
      ),
      [FDM_SEARCH_RESULT_GROUP.BUSINESS_CAPABILITIES]: state.searchResults[
        FDM_SEARCH_RESULT_GROUP.BUSINESS_CAPABILITIES
      ].filter((capability) => capability.status !== CapabilityDTOStatus.Deleted),
      [FDM_SEARCH_RESULT_GROUP.TECH_CAPABILITIES]: state.searchResults[
        FDM_SEARCH_RESULT_GROUP.TECH_CAPABILITIES
      ].filter((capability) => capability.status !== CapabilityDTOStatus.Deleted),
    } as FdmSearchResults;
```

Nice code:

```
    const groups: DomainDTO[] = state.searchResults[FDM_SEARCH_RESULT_GROUP.GROUPS];
    const deletedDGroups: DomainDTO[] = groups.filter((domain) => domain.status !== DomainDTOStatus.Deleted);

    const domains: DomainDTO[] = state.searchResults[FDM_SEARCH_RESULT_GROUP.DOMAINS];
    const deletedDDomains: DomainDTO[] = domains.filter((domain) => domain.status !== DomainDTOStatus.Deleted);

    const businessCapabilities: CapabilityDTO[] = state.searchResults[FDM_SEARCH_RESULT_GROUP.BUSINESS_CAPABILITIES];
    const deletedBusinessCapabilities: CapabilityDTO[] = businessCapabilities.filter(
      (capability) => capability.status !== CapabilityDTOStatus.Deleted
    );

    const techCapabilities: CapabilityDTO[] = state.searchResults[FDM_SEARCH_RESULT_GROUP.TECH_CAPABILITIES];
    const deletedTechCapabilities: CapabilityDTO[] = techCapabilities.filter(
      (capability) => capability.status !== CapabilityDTOStatus.Deleted
    );

    return {
      [FDM_SEARCH_RESULT_GROUP.GROUPS]: deletedDGroups,
      [FDM_SEARCH_RESULT_GROUP.DOMAINS]: deletedDDomains,
      [FDM_SEARCH_RESULT_GROUP.BUSINESS_CAPABILITIES]: deletedBusinessCapabilities,
      [FDM_SEARCH_RESULT_GROUP.TECH_CAPABILITIES]: deletedTechCapabilities,
    } as FdmSearchResults;
```

Wrong code:

```
    if (
      (typeof data.currentValue && typeof data.previousValue) === 'string' &&
      (data.currentValue ? data.currentValue : '').length + data.previousValue.length > 0 &&
      data.key !== 'owner' &&
      data.key !== 'creationDate' &&
      data.key !== 'lastChangeDate' &&
      data.key !== 'type' &&
      data.key !== 'incomingLinksData' &&
      data.key !== 'status' &&
      data.key !== 'licensesData' &&
      data.key !== 'licenses' &&
      data.key !== 'tools' &&
      data.key !== 'toolsData'
    )
```

Nice code:

```
    const isValueIsString: boolean = (typeof data.currentValue && typeof data.previousValue) === 'string';
    const currentValue: number = data.currentValue ? data.currentValue.length : 0
    const isLengthNotZero: number = currentValue + data.previousValue.length > 0
    const isKeyNotExist: boolean =
      data.key !== 'owner' &&
      data.key !== 'creationDate' &&
      data.key !== 'lastChangeDate' &&
      data.key !== 'type' &&
      data.key !== 'incomingLinksData' &&
      data.key !== 'status' &&
      data.key !== 'licensesData' &&
      data.key !== 'licenses' &&
      data.key !== 'tools' &&
      data.key !== 'toolsData';

    if (isValueIsString && isLengthNotZero && isKeyNotExist)
```

Nice code:

```
 private filterList<T extends DomainDTO | CapabilityDTO>(list: T[], filters: FdmSearchFilters): T[] {
    return list.filter((entity): boolean => {
      const isCodeFound: boolean = !!entity.code?.toLowerCase().includes(filters.search.toLowerCase());
      const isNameFound: boolean = !!entity.name?.toLowerCase().includes(filters.search.toLowerCase());
      const isOwnerEqual: boolean = entity.owner === filters.owner?.rmsId;
      if (filters.search && filters.owner) {
        return (isCodeFound || isNameFound) && isOwnerEqual;
      }
      if (filters.owner) {
        return isOwnerEqual;
      }
      if (filters.search) {
        return isCodeFound || isNameFound;
      }
      return false;
    });
```

Instead of `Record`, we try to use the interface as an associative array, because you can specify the names of properties in it, which
will increase the readability of the code.

Wrong code:

```
sectionsCounters: Record<number, SectionCounters>;
```

Nice code:

```
sectionsCounters: { [classifierValueId: number]: SectionCounters }
```

Inside the method, you need to use only one nesting of curly braces, otherwise make an alternate of `if () {}` with nesting 1 or split the method into several methods.
look here https://www.youtube.com/watch?v=AkdEsCHt1cg&t=166s
Wrong code:

```
  @Action(AlertifyError)
  public alertifyError({}: StateContext<AlertifyStateModel>, { error }: AlertifyError): void {
    let message: string;
    if (error instanceof Error) {
    if (error instanceof ApiException) {
      if (error.response) {
        try {
          const parsedApiErrorResponse: { Message?: string } = JSON.parse(error.response);
          if (parsedApiErrorResponse && parsedApiErrorResponse.Message) {
            message = parsedApiErrorResponse.Message;
          } else {
            message = error.message;
          }
        } catch (_parseApiErrorResponseError) {
          message = error.message;
        }
      } else {
        message = error.message;
      }
    } else if (error instanceof Error) {
      message = error.message;
    } else {
      message = error;
    }
```

Nice code:

```
  @Action(AlertifyError)
  public alertifyError({}: StateContext<AlertifyStateModel>, { error }: AlertifyError): void {
    const message: string = this.getErrorMessage(error);
    AlertifyService.error(message);
  }

    private getErrorMessage(error: ApiException | Error | string): string {
    if (error instanceof ApiException) {
      return this.getApiErrorMessage(error);
    }
    if (error instanceof Error) {
      return error.message;
    }
    return error;
  }

    private getApiErrorMessage(error: ApiException): string {
    const parsedApiErrorMessage = this.tryParseApiErrorMessage(error.response);
    if (parsedApiErrorMessage !== null) {
      return parsedApiErrorMessage;
    }
    return error.message;
  }

    private tryParseApiErrorMessage(response: string): string | null {
    try {
      const parsedApiErrorResponse: { Message?: string } = JSON.parse(response);
      if (parsedApiErrorResponse && parsedApiErrorResponse.Message) {
        return parsedApiErrorResponse.Message;
      }
    } catch (_parseApiErrorResponseError) {}
    return null;
  }

```

Instead of `if else`, use `if return return`
Wrong code:

```
    if (!isReleaseExists && !isCacheExists) {
      return new ReleaseDTO();
    } else {
      return drafts[key];
    }
```

Nice code:

```
    if (!isReleaseExists && !isCacheExists) {
      return new ReleaseDTO();
    }
    return drafts[key];
```

We adhere to the law of `Demeter`. In other words, when accessing an object, a service, we use only one dot notation, like `someObject.someProperty`

We comply with the `DRY` law. In other words, do not use the same text, expression, piece of code twice. We move them into constants, `Enum`, `Class`, `function` etc ...

Mutations:

1. We don't make mutations inside components, it may cause problems with `onPush` strategy.
2. We do not change references to object`s properties from nested functions. Try to do that where object initialized. If the object is a member of the class, then
   it is desirable to change it inside called function.

Wrong code:

```
const a = {....}
  f1() {
    f2(){
      f3() { a.property = true }
      }
    }
```

Nice code:

```
  let a = {....}
  const property: boolean = f1();
  a = {...a, aSomeFiled: property }

  f1() { return f2(); }
  f2(){ return f3(); }
  f3(){ return true }

```

It's better to use `array destructuring` for some rxjs operators.

Wrong code:

```
return zip(isAdmin$, isOwner$).pipe(
  map((data) => { if(data[0]) {...} ...)})
 )
```

Nice code:

```
return zip(isAdmin$, isOwner$).pipe(
  map(([isAdmin, isOwner]) => { if(isAdmin) {...} ...)})
 )
```

## Angular

We use the `OnPush` strategy for all components by default. To do this by default, we specify this rule in `angular.json`

```
        "@schematics/angular:component": {
          "changeDetection": "OnPush"
        }
```

Follow by `the single responsobility principle` we split large components, services, templates into several smaller ones, they are easier to test and more pleasant to maintain.
We strive for `75` lines of code in the` html` template, otherwise we split it into several smaller ones (`smart` +` dumbs`).
We strive to `400` lines of code in components, services, directives, otherwise we break them down into several more
small.

We don't use `Promise`, only`RxJS`, because:

1. It is problematic to unsubscribe from `async / await`, since you need to constantly figure out the cancellation token. And in rxjs it's straight out of the box, everything is thought out.
2. It is easy to organize `timeout` / `retreat` using rxjs.
3. To start a request declaratively, using pipe ` | async`, without using lifecycle.
4. To make a request dependent on some state (filtering, pagination, search)

We do not inherit components from each other. If you need to bring the general into the code, then we use: services, directives, parent class etc.

We use the `trackBy` function for all` ngFor`. (see. `TrackByExampleComponent`)

We avoid cyclical dependencies of entities (services, classes). If they arise, and essence A depends on B, and B depends on A, then we aggregate them inside essence C (A, B). And after all we use C.

We give the names `Input`, `Output` so that it is clear from the outside which one they were performing.

Wrong code:

```
      <sol-release-details-actions
        [editMode]="isEdit"
        [canEdit]="true"
        [canDelete]="false"
        [canSave]="true"
        [canCancel]="true"
        [isDraftValid]="isDraftValid$ | async"
        (cancel)="onCancel()"
        (save)="onCreate()"
      ></sol-release-details-actions>
```

Nice code:

```
      <sol-release-details-actions
        [isShowEditAndDelete]="!isEdit"
        [isShowEdit]="true"
        [isShowDelete]="false"
        [isShowSave]="true"
        [isShowCancel]="true"
        [isSaveEnable]="isFormValid"
        (cancel)="onCancel()"
        (save)="onCreate()"
        (edit)="onEdit(release)"
      ></sol-release-details-actions>
```

For `dumb's` ` Input`, `Model`,` Output` names, we do not transfer the business logic from smart and vice versa.

Wrong code:

```
  [isDraftValid]="isDraftValid$ | async"
```

Nice code:

```
<app-dumb>
  [isSaveEnable]="isDraftValid$ | async"
</app-dumb>
```

Follow this order of declarations for component controller properties:

```
viewchild / viewchildren
input
output
(property) public
(property) private
constructor()
get
set
(method) public
(method) private
```

When creating the objects, we use the `OOP` approach. Since `Angular` is designed for OOP.
Therefore, we do not create objects through a function, but we make classes.
Wrong code:

```
  public licenseMock = (license?: Partial<ILicenseDTO>): ILicenseDTO => {
    const mock: ILicenseDTO = {
      id: license?.id || this.randomService.id(this.mockDataSyncService.licenseMap.ids),
      name: license?.name || this.randomService.title(),
      description: license?.description || this.randomService.description()
    };
    return mock;
  };
```

Nice code:

```
  public licenseMock = new LicenseMock(license?: Partial<ILicenseDTO>);
```

Do not use abbreviations in the names of the components, give the full name.

Wrong code:
`PoStepsCreateComponent`

Nice code:
`ProductOwnerStepsCreateComponent`

Don't name the components with verbs, start the name with the business entity.

Wrong code:
`CreateStepsComponent`

Nice code:
`StepsComponentCreate`

Do not assign names to properties that begin with verbs, let's start with nouns, or `is`.

Wrong code:

```
    @Input() createPoTipInfo: ProductOwnerTipInfoModel = {
        header: '',
        message: '',
    };
```

Nice code:

```
    @Input() productOwnerTipInfo: ProductOwnerTipInfoModel = {
        header: '',
        message: '',
    };
```

If the function's argument, function's result, class's property, etc. can be `null` or` undefined`, then we indicate it explicitly. Indicate what you expect or don't expect to receive, return `null` or`unefined (void)`.

Wrong code:

```
@Input() userName: string;
....
if(this.userName){
    .....
}
```

Nice code:

```
@Input() userName: string | null = null
....
if(this.userName){
    .....
}
```

If you need to track `@Input ()` changes, for example, run some logic, then you can use `setter` for this. It is not recommended using `OnChanges` for this, because by default it does not support type checking and this can lead to errors after input refactoring. But if you may have a `glitch` effect, it is better to use` ngOnChanges`, and you should definitely wrap `SimpleChanges` in` Generic`. For an example of a wrapper, see [input-changes-detection] (https://github.com/evoytenkoapps/angular-best-practices/tree/master/examples/src/app/components/input-changes-detection)

Wrong code:

```
  ngOnChanges(changes: SimpleChanges): void {
    const name = changes.userName?.currentValue;
    if(name){
        console.log('name inside changes was changed', name);
        this.userName = name;
    }
  }
```

Nice code:

```
  @Input()
  set userName(name: string | null) {
    console.log('name inside input was changed', name);
    if (name) {
      this.firstName = name;
    }
  }

  public firstName: string = '';
```

When need to set some value after `@Input` changes, its better to make `getter` instead of `ngOnChanges`

Wrong code:

```
  ngOnChanges(): void {
    this.isProductEditable = this.product.status === this.recordStatus.Approved && (!!this.isAdmin || !!this.isOwner);
  }
```

Nice code:

```
  public get isProductEditable(): boolean {
    return this.product.status === this.recordStatus.Approved && (!!this.isAdmin || !!this.isOwner);
  }
```

Let's give for `Input` and `Output` such names so that from the outside you can understand what kind of work they are doing. As a result, it should be clear without looking at them.

When you need to update or init data of any `ui` element, for example `mat-table`, you have to keep in mind, that this `ui` element creates after calling `ngAfterViewInit` life hook.
So to update its data you need to:

1. Store data inside parent component controller, inside `@Input()` , `subscription` or etc
2. Check is `ui` exist, then update its data
3. Set `ui` data inside `ngAfterViewInit`

Wrong example:

```
  @Input() set methods(methods: IMethodDTO) {
       this._methods = methods;

       this.setParametersDataSource(this._methods.parameters);
  }
```

Good example:

```
  @Input() set methods(methods: IMethodDTO) {
       this._methods = methods;

       if(this.tableParametrs){
          this.setParametersDataSource(this._methods.parameters);
        }
  }

  public ngAfterViewInit(): void {
      if(this.this._methods){
          this.setParametersDataSource(this._methods.parameters);
        }
  }

```

Use only one returning type inside `guard` or `resolver`, avoid of using type union.

Wrong Code:

```
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {}
```

Nice Code:

```
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {}
```

### Services mocking

In order not to depend on a third-party service, for example a backend, and receive any data during development, we should mock the receipt of data. For example if programmer want to get an error from backend, and check it on ui, he could mock some http.service and throw an exeption there.
To do this, you need to do the following:

1. Create a base abstract class `abstract class DataService`, describe the necessary methods in it.
2. We create the service `class DataHttpService extends DataService`, inherit from the abstract and write
   the desired implementation, for example put there real requests to backend.
3. Create a `class DataHttpMockService extends DataService` service, inherit from the abstract one and write the required implementation. The file is named by the mask `*****-mock.service.ts`
4. Injecting the abstract class `DataService` into the components or to other services.
5. We create the provider `DataServiceProvider` in a separate file. We write the contents of the provider like `export const DATA_SERVICE_PROVIDER: Provider = { provide: DataService, useValue: environment.isUseMock? new DataHttpMockService(): new DataHttpService ()}; `. We register the conditions for choosing `real` or` mock` in the providers. Using `useClass`
   or `useFactory`.
6. Insert the provider into the module `providers: [DATA_SERVICE_PROVIDER]`
7. We store `provider` in the` Providers` folder of this module.
8. We store the `Mock` in the same folder as the implementation.
9. It is preferable to inject abstractions over real implementations. Because passing the implementation can violate the Dependency Inversion Principle.

### Template

Specify the attributes of a template's tag in the following order:

1. directives
2. static attributes
3. css classes
4. inputs
5. outputs

Example:

```
<app-component *ngIf="true" id="1" class="app-component"  [data]="data" (data)=setData($event)>
</app-component>
```

For each component, where necessary, we try to create our own model. It is necessary to map it in the component above, both for `Input` and when receiving from `Output`.
For example, if the parent has an object with 5 properties, and the child needs only 4 properties, then in the child you need to create a custom interface with these 4 fields and wait for it to enter. Back conversion from 4 to 5 must be done by its parent.
(parent m1 to m2) m2 -> child, child m2 -> parent (parent m2 to m1 )

## RxJs

Always unsubscribe from the `subscription`.

Wrong code:

```
    this.api.getClassifiersTopShowOnGUI().pipe(
      map((response) => response.result)
    ).subscribe();
```

Nice code:

```
    this.api.getClassifiersTopShowOnGUI().pipe(
      map((response) => response.result),
      takeUntil(this.destroy$)
    ).subscribe();;
```

We do unsubscribe using `takeUntil()` and `ReplaySubject<void>(1)` or `UnsubscribeService` for unsubscribe.

Example:

```
  private destroy$: ReplaySubject<void> = new ReplaySubject<void>(1);

.pipe(
  .map(....)
  takeUntil(this.destroy$)
)
.subscribe(() => ....);

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
```

In order to unsubscribe, the operator `takeUntil (.....)` should be placed directly next to `subscribe()`, it should not be placed above.

Wrong code:

```
    this.uneditable$ = this.api.getClassifiersTopShowOnGUI().pipe(
      takeUntil(this.destroy$)
      map((response) => response.result)
    ).subscribe();
```

Nice code:

```
    this.uneditable$ = this.api.getClassifiersTopShowOnGUI().pipe(
      map((response) => response.result),
      takeUntil(this.destroy$)
    ).subscribe();
```

If the component does not subscribe using `subscribe()`, then to do unsubscribe is pointless.

Wrong code:

```
    this.uneditable$ = this.api.getClassifiersTopShowOnGUI().pipe(
      map((response) => response.result),
      takeUntil(this.destroy$)
    );
```

Nice code:

```
    this.uneditable$ = this.api.getClassifiersTopShowOnGUI().pipe(
      map((response) => response.result),
    );
```

Не делаем подписки в конструкторе, вместо этого делаем их в `OnInit` или `AfterViewInit` по ситуации.

Wrong code:

```
  constructor(
    private supportService: SupportService,
    private unsubscribeService$: UnsubscribeService
  ) {
    this.supportService.commonSupportAvailableState$.pipe(takeUntil(this.unsubscribeService$)).subscribe((state) => {
      this.isCommonSupportAvailable = state;
    });
  }
```

Пример лучше:

```
  ngOnInit(){
    this.supportService.commonSupportAvailableState$.pipe(takeUntil(this.unsubscribeService$)).subscribe((state) => {
      this.isCommonSupportAvailable = state;
    });
  }
```

Don't make `.subscribe (() => ....)` inside another subscription, like `.subscribe (() => subscribe ())`. If you needed
to get data from another stream inside subscription, then you should use `switchMap` or other rxjs higher-order operators.

Wrong code:

```
    this.isModuleEditor$.pipe(takeUntil(this.destroy$))
        // First subscription
        .subscribe((access) => {
                this.draftsService
                  .getDrafts(DraftStatuses.Created, this.user.userId)
                  .pipe(takeUntil(this.destroy$))
                  // Second subscription
                  .subscribe((result) => {
                    if (result) {
                      this.containersService.pendingDraftState.next(result ? result : []);
                    }
                  });
    });
```

Nice code:

```
    this.isModuleEditor$.pipe(
            switchMap(access => this.draftsService.getDrafts(DraftStatuses.Created, this.user.userId)),
            takeUntil(this.destroy$)
        )
          // Single subscription
          .subscribe((result) => {
            if (result) {
              this.containersService.pendingDraftState.next(result ? result : []);
            }
         });
```

To avoid `side effects`, we try not to call` subject.next()` inside the stream. Instead of using `subject`, put out
the common part of the stream in a `pipe()` and use it. Next, we expand the general part of the operator.

Wrong code:

```
dataSource$.pipe(....
                tap(data=> this.someSubject.next(data))
                );
```

Nice code:

```
const someSubjectAnalogStream$ = dataSource$.pipe(...);
const otherStream$ = dataSource$.pipe(...);
```

Inside rxjs streams you may to make assignments or call other methods only in the `tap` operator or `subscribe`.

In components, if you don't use ` | async` pipe, it is desirable to make an assignment or call other methods (side effect) in `subscribe` instead of` tap`. Otherwise use `tap`.

Wrong code:

```
  this.rmsEntitiesService.rmsContoursState$ .pipe(
    tap((contours) => {
      if (!contours) {
        this.getRmsContours();
      }
    }),
  takeUntil(this.destroy$)
  ).subscribe()
```

Nice code:

```
  this.rmsEntitiesService.rmsContoursState$ .pipe(
  filter (contours => !contours)),
  takeUntil(this.destroy$))
  .subscribe(() => this.getRmsContours()
  )
```

If the method needs to receive data from another stream, then you do not need to create a subscription in the method. We do this:

1. Create `subject`
2. We subscribe to him in any angular lifecycle method like `ngOnInit`, write the required stream in its` pipe ()` and using higher-order operators,
   for example `switchMap`.
3. Call `subject.next ()` in the method
4. Get the data in `subscribe ()`, or through `| async`

Example:

```
// Create a subject
const sub: Subject<number> = new Subject();
// Initialize main stream
const data$: Observable<number> = of(1);

// Make a subscription
ngOnInit{
  sub.pipe(switchMap(_ => data$),takeUntil(this.destroy$)).subscribe(console.log);
}

// Emit the subject inside method
public onClick(): void {
  this.sub.next();
}
```

Instead of `setTimeout ()` it is better to use `Subject.subscribe ()` and rxjs operator `delay`.

Wrong code:

```
  getClassifications() {
    setTimeout(() => {
        this.initFilters();
    }, 100);
  }
```

Nice code:

```
    ngOnInit{
        this.subject.pipe(delay(100),takeUntil(this.destroy$)).subscribe(()=> this.initFilters();)
    }

  public getClassifications(): void {
        this.subject.next();
  }
```

We do not make subscriptions in methods that are often called by the framework, for example `ngOnChanges`

Wrong code:

```
  ngOnChanges(changes: SimpleChanges): void {
      this.projectsService
        .getProject()
        .pipe(takeUntil(this.unsubscribeService$))
        .subscribe();
  }
```

Do not pass (Observable, Subject, etc ...) as arguments to the function and do not get the result of these functions. Instead, call these functions via chaining, using the `pipe operators`.

Wrong code:
Here we get the stream `itemsTypesWhereCountsIsGreaterThanZero` as the result of the function, and then pass it as an argument to another function` _getFilterModelFromItemTypes`.
Instead, you can chain them

```
  public getFilterModel(searchText: string): Observable<FilterModel> {
  .......
      const itemsTypesWhereCountsIsGreaterThanZero: Observable<
        ItemType[]
      > = this._getItemsTypesWhereCountsIsGreaterThanZero(allItemsTypesWithCounts);

      const filterModel: Observable<FilterModel> = this._getFilterModelFromItemTypes(
        itemsTypesWhereCountsIsGreaterThanZero
      );

      return filterModel;
    });
  }

  private _getItemsTypesWhereCountsIsGreaterThanZero(
    allItemsTypesWithCounts: Observable<ItemTypeWithTotalCount>[]
  ): Observable<ItemType[]> {
    return forkJoin(allItemsTypesWithCounts).pipe(
      map((itemsTypeWithCount: ItemTypeWithTotalCount[]) => .....
      )
    );
  }

    private _getFilterModelFromItemTypes(itemsTypesWhereCountsIsGreaterThanZero: Observable<ItemType[]>
  ): Observable<FilterModel> {
    return itemsTypesWhereCountsIsGreaterThanZero.pipe(
      map((itemsTypesWithCount: ItemType[]) => {
        ....
      })
    );
  }
```

Nice code:

```
  public getFilterModel(searchText: string): Observable<FilterModel> {
   .......
   return this._getItemsTypesWhereCountsIsGreaterThanZero(allItemsTypesWithCounts).pipe(
        switchMap((itemsTypesWhereCountsIsGreaterThanZero) => this._getFilterModelFromItemTypes( itemsTypesWhereCountsIsGreaterThanZero))
    )
    });
  }

  private _getItemsTypesWhereCountsIsGreaterThanZero(
    allItemsTypesWithCounts: Observable<ItemTypeWithTotalCount>[]
  ): Observable<ItemType[]> {
    return forkJoin(allItemsTypesWithCounts).pipe(
      map((itemsTypeWithCount: ItemTypeWithTotalCount[]) => .....
      )
    );
  }

    private _getFilterModelFromItemTypes(itemsTypesWhereCountsIsGreaterThanZero: Observable<ItemType[]>
  ): Observable<FilterModel> {
    return itemsTypesWhereCountsIsGreaterThanZero.pipe(
      map((itemsTypesWithCount: ItemType[]) => {
        ....
      })
    );
  }
```

## Architecture

Encapsulate components followed by the concept of `smart/dumbs components` see. [smart-dumb-concept](https://github.com/evoytenkoapps/angular-best-practices/tree/master/examples/src/app/components/smart-dumb-concept)

`smart`:

1. Communicates with services, for example `facade`, etc.
1. Contains business logic.
1. Responsible for routing.
1. Does not use `Input / Output`.
1. Can show data.
1. Contains the logic for processing nested components.

`dumb`:

1. Shows data.
1. Gets and sends data only to the parent or his children's.
1. Does not use any services.
1. Contains the logic for processing nested components.
1. Uses `Input \ Output`.

One smart may have only 5 nested `dumbs`, for example: `smart (dumb1 (dumb2 (dumb3 (dumb4 (dumb5)))))`, with more
it will be difficult to maintain `Input, Output, @ViewChild()`

We do data transfer between `parent - child` via` input + output`

If the parent needs to send an event or data to the child, then you should do this:

1. Create `abstract class`, for example like `TransferData`, and determine there methods.
1. Extends child component from `abstract class` and implement him.
1. Inside the parent we use `@ViewChild ('someid') transferData : TransferData `, and call abstract class methods.

Entities are sortred into three types:

1. `DTO` - what comes or goes to the backend, like `DataDTO`
2. `Model` - what is described our bussiness logic, like `DdataModel`, we use it as a`value object`, it must be without methods.
3. `Vm` - what is needed for the component, like `VmData`

Do not name the `dumb` properties of the component by business logic. Try to give them abstract names according to the `dumb` logic.

Wrong code:

```
    @Output() removeComponent: EventEmitter<void> = new EventEmitter<void>();
```

Nice code:

```
    @Output() deleteBtnChange: EventEmitter<void> = new EventEmitter<void>();
```

Followed by `dependency inversion` principle you should avoid direct injection your redux store, http-services inside each other or inside components.
So I offer to you to make an abstractions for each, like:

1. abstraction for state managers.
1. abstraction for any http or websocket services.
1. abstraction for any local or session storages services.
1. abstraction for any web worker services.

Also, you should store your domain model objects inside `app` module, fore example `/app/_models` or `/app/_core/_models`, and map backend's `dtos` into model inside `http.service` or etc.
Thus, you'll follow `dependency inversion` principle.

Instead of using `providedIn: 'root'` its better to provide services inside `core` or `app` modules. Because it will clearly show you where exactly services are provided, instead of putting them inside `_services` and adding `providedIn: 'root'`.

## Comments

If there is a bug in the code or a feature that, unfortunately, cannot be understood from the code, then we comment on it, or make a `TODO`.
In other cases, you do not need to write comments, you need to try to give unambiguous names for entities and functions for understanding.
Avoid double interpretations. To end up with self-documenting code. The code itself should read like a good book about your logic.
Alos comments should tell you why author choose that decision

Wrong code:

```
// Passing null to the tree
if (!moduleObject && !apiInterfaceObject && this.slCheckTreeService) {
  this.slCheckTreeService.selectNode(null);
}
```

Nice code:

```
// Remove selected items from the tree when nothing is selected
if (!moduleObject && !apiInterfaceObject && this.slCheckTreeService) {
  this.slCheckTreeService.selectNode(null);
}

// There is a nuance of ngxs, because it works outside the zone, the dialogue will not close. Need to call dialog in zone see https://github.com/ngxs/store/issues/1401#issuecomment-545180014
this.ngZone.run(() => {
  this.dialog.open(ConfirmationModalComponent, {
    panelClass: 'custom-dialog-container',
    data: infoData,
  });
});
```

## CSS styles

Specify component styles in the component styles file, like `*.component.css` or `*.component.scss`

When you needs to set up style for component's "root" tag, for example components inside `<router-outlet>` you may use pseudo class `:host` inside your `*.component.css` or `*.component.scss`

If you choose BEM as css guide, then you css classes should looks like that:

Example:

```
   main-button
   main-button--primary
   main-button__label
   main-button__label--secondary
```

**SVG**
Svg icons without logic we store inside `assets/icons`
Svg icons without logic we put into separate component

## State manager

If there is less than 10 `Business Models` that you have to store, then you may use services.
Otherwise, my advice for you is to use any state manager.
Also, if you are beginner as frontend engineer, then state manager its nice solution for you.
It doesn't matter which exactly state manager you will choose.

If we need to track the status of an object inside the store, then we wrap it in to `Generic`:

```
export enum StatusData {
  PENDING = 'PENDING',
  LOADING = 'LOADING',
  LOADED = 'LOADED',
  ERROR = 'ERROR',
  CANCEL = 'CANCEL',
}

export interface DataWithStatus<T> {
  readonly data: T;
  readonly status: StatusData;
}
```

And use like this:

```
export interface OpportunityModelStateModel {
  functionsAndSoft: DataWithStatus<FileToSave | null>;
}
```

Make all interaction with the `Store` through an abstract class, followed by `dipendency inversion` principle, we call it like ` ***. Facade.ts`, for example `UserInfoFacade` `user-info.facade.ts`.

1. Let's provide the facade at the module level.
2. Inject an abstract class into the component.
3. At the result component or service with business logic, should not have any imports from `state manager` library.

Give abstract names to the facade's methods, do not repeat names from yours current state manager.
For example, you can take the verbs like `create, read, update, delete, set, change, update, load` + `business model`.

Wrong code:

```
public abstract selectStatus(): Observable<StoreStatus>;
public abstract ofActionGetFormDataFromLocalStorageSuccessDispatched(): Observable<ICreatePOStepsModel>;
```

Nice code:

```
public abstract getStatus(): Observable<StoreStatus>;
public abstract loadedStepsFromLocalStorage(): Observable<ICreatePOStepsModel>;
```

### NGXS

Example [redux-store-ngxs](https://github.com/evoytenkoapps/angular-best-practices/tree/master/examples/src/app/redux-store-ngxs)

We store the entities in these folders:

`actions` = classes actions
`models` = state interfaces, classes and their default values
`States` = action effects and selectors

We do not make a one selector for several `smart`, if these smarts do not affect each other according to business logic. Otherwise, you can
make a single selector for each. Or, combine multiple selectors via `merge` operators, etc.

Wrong code:

```
    @Selector()
  public static active(state: ReleaseDetailsStateModel) {
    const { initial, drafts } = state;
    const key = `${initial?.id ?? NEW_KEY}`;
    const isReleaseExists = !!initial && initial.id > 0;
    const isCacheExists = drafts.hasOwnProperty(key);
    console.log('isReleaseExists', isReleaseExists, 'isCacheExists', isCacheExists);
    if (!isReleaseExists && !isCacheExists) {
      return new ReleaseDTO();
    } else if (!isReleaseExists && isCacheExists) {
      return drafts[key];
    } else if (isReleaseExists && !isCacheExists) {
      return initial;
    } else {
      return drafts[key];
    }
  }
```

Nice code:

```
  @Selector()
  public static getSelectedRelease(state: ReleaseDetailsStateModel): ReleaseDTO | null {
    const { drafts } = state;
    const selected: ReleaseDTO | null = state.initial;
    const draft: ReleaseDTO | null = selected ? drafts[selected.id] : null;
    return draft ? draft : selected;
  }

  @Selector()
  public static getNewReleaseDraft(state: ReleaseDetailsStateModel): ReleaseDTO | null {
    return state.drafts[ReleaseDetailsState.NEW_RELEASE_ID];
  }

    @Selector()
  public static isSelectedReleaseCached(state: ReleaseDetailsStateModel): boolean {
    const selected: ReleaseDTO | null = state.initial;
    return selected ? !!state.drafts[selected.id] : false;
  }
```

Name `actions` as you would for a functions, starting with a verb. Wrong code:

```
NewRelease
```

Nice code:

```
ResetSelectedRelease
LoadLinks
LoadLinksCancel
```

Give a names to action class as action type name.

Wrong code:

```
export class GetTribesSuccess {
  public static readonly type: string = ProductsCreateActions.GetTribesLoaded;
}
```

Nice code:

```
export class GetTribesLoaded {
  public static readonly type: string = ProductsCreateActions.GetTribesLoaded;
}
```

Inside `Redux dev tools` `moment` objects looks like a string, so be carefully during state inspection.

By default, `ngxs` works outside` ngZone`, so if you need to show dialogs, or other `ui` components from` action`, you may to do it inside `ngZone` explicitly.

Wrong code:

```
  @Action(AuthorizeError)
  public authorizeError({ setState, dispatch }: StateContext<AuthStateModel>, { error }: AuthorizeError): void {
         this.dialog.open(ConfirmationModalComponent, {
            panelClass: 'custom-dialog-container'
    }
  }
```

Nice code:

```
  @Action(AuthorizeError)
  public authorizeError({ setState, dispatch }: StateContext<AuthStateModel>, { error }: AuthorizeError): void {
     this.ngZone.run(() => {
        this.dialog.open(ConfirmationModalComponent, {
        panelClass: 'custom-dialog-container'
      });
    });
  }
```

## Forms

If you do not need to change the entire `model` inside forms, then we should create a custom interface, we may call it like `Vm****`. To do this you may create it, or pick it from another.

Example:

```
export interface VmReleaseFormModel
  extends Pick<
    Release,
    'name' | 'position' | 'description' | 'rmsReleaseId' | 'businessUnitId' | 'dateFrom' | 'dateTo' | 'installDate'
  > {}
```

### Formly

We set the model via `setter` with mandatory checking for` null` and cloning, because `formly` mutates the object at runtime, if the model arrives from the` store`, then there will be an error. Since `store` usually freezes its models

```
  @Input() set model(model: VmReleaseFormModel) {
    if (model) {
      this._model = { ...model };
    }
  }
```

Be sure to declare the default model and initialize it. Otherwise, the form will emit a model with one property the first time, which will lead to errors.

Be sure to set the values of the shape keys from the model using the special function, like `public static getFieldName = <T> (name: keyof T) => name;`.
We do this in order to rigidly synchronize the key-model bunch, otherwise formly will add incomprehensible properties to the model, and this will got to the store.

Example:

```
    this.fields = [
      {
        key: Utils.getFieldName<VmReleaseFormModel>('name'),
        type: 'input',
        className: 'col-6',
      ]
```

We emit the model only from `modelchange`, because it works only if the user changes the model himself or changes the options.
`ValueChange` is triggered more often than `modelchange`, so it will hinder us.
Ideally, the model should be issued only if the user changes something by hand.

Before emit model, clone it using `spread` or special libraries like `lodash`

Example:

```
  public onModelChange(model: ReleaseFormModel) {
    this.fdReleaseFormModelChange.emit({ data: { ...model }, status: this.formGroup.status as FORM_STATUS });
  }
```

When you change the options of the form, `modelchange` will be will work. To avoid this, we make such a thing:

```
  @Input() set isFormEnable(isEdit: boolean) {
    this._isFormEnable = isEdit;
    this.changeFormEnable(isEdit);
  }

  private changeFormEnable(isEnable: boolean): void {
    this.options.formState.disabled = !isEnable;
    const disableOptions = {
      onlySelf: true,
      emitEvent: false,
    };
    if (isEnable) {
      this.formGroup.enable(disableOptions);
      return;
    }
    this.formGroup.disable(disableOptions);
  }
```

It is necessarily to set your own interface for the form options, we should use types`typescript` + `strict mode`

Example:

```
interface ReleaseFormOptions extends FormlyFormOptions {
  formState: ReleaseFormState;
}

interface ReleaseFormState {
  disabled: boolean;
  minDate: moment.Moment;
}
  ......

 public options: ReleaseFormOptions = {
    formState: {
      disabled: true,
      minDate: moment(),
    },
  };
  .......
  expressionProperties: {
    'templateOptions.disabled': 'formState.disabled',
    'templateOptions.datepickerOptions.min': (release: ReleaseFormModel, releaseFormState: ReleaseFormState) => {
      return release.dateFrom ? release.dateFrom : releaseFormState.minDate;
    },
  },
```

We initialize the options, otherwise, when they are set for the first time, the `onModelChange` of the form will be triggered

We do not return new objects inside `expressionProperties`, instead we take them from the arguments, otherwise Formly will be
update your model endlessly and emit `valueChanges`.

Wrong code:

```
  'templateOptions.datepickerOptions.min': (release: ReleaseDTO, releaseFormState: ReleaseFormState) => {
    return release.dateFrom ? release.dateFrom : new Date();
  },
```

Nice code:

```
  'templateOptions.datepickerOptions.min': (release: ReleaseDTO, releaseFormState: ReleaseFormState) => {
    return release.dateFrom ? release.dateFrom : releaseFormState.minDate;
  }
```

repository: Best-of-Angular/angular-best-practices

repo_name: Best-of-Angular/angular-best-practices


text:
# Migration guide 3.1 -> 3.2

* Growl now uses css to display the severity icons instead of the previous Icon attributes.
* Password component sets feedback mode to false by default.
* Incell editing datatable requires editable attribute to be set true.
* ProgressBar’s oncomplete attribute is removed in favor of complete ajax behavior.
* Incell editing datatable requires editable attribute to be set true.

repository: primefaces/primefaces

gha_language: Java

repo_name: primefaces/primefaces


text:
These tables represent the values for units and their prefixes as specified in the draft [Units specification](http://specs.okfnlabs.org/units/). It contains:

- An inventory of standard units with unique identifiers
- A set of unit prefixes

repository: nimblelearn/datapackage-m

repo_name: nimblelearn/datapackage-m


text:
# Security Policy

## Supported Versions

| Version | Supported          |
| ------- | ------------------ |
| 2.9.x   | :white_check_mark: |
| < 2.9   | :x:                |

## Reporting a Vulnerability

We take all security bugs in `diff2html` seriously. Thank you for the help improving the security of `diff2html`. We
appreciate your efforts and responsible disclosure and will make every effort to acknowledge your contributions.

Report security bugs by emailing the lead maintainer at `rtfrodrigo [at] gmail [dot] com`.

The lead maintainer will acknowledge your email within 48 hours, and will send a more detailed response within 48 hours
indicating the next steps in handling your report. After the initial reply to your report, the security team will
endeavor to keep you informed of the progress towards a fix and full announcement, and may ask for additional
information or guidance.

Report security bugs in third-party modules to the person or team maintaining the module.

## Disclosure Policy

When the security team receives a security bug report, they will assign it to a primary handler. This person will
coordinate the fix and release process, involving the following steps:

- Confirm the problem and determine the affected versions.
- Audit code to find any potential similar problems.
- Prepare fixes for all releases still under maintenance. These fixes will be released as fast as possible.

## Comments on this Policy

If you have suggestions on how this process could be improved please submit a pull request.

gha_language: TypeScript


text:
# cyclone-based project

    This is the source code of $project_name
    $name <$email>

## About

This file has been created automatically by cyclone for $project_name.
It contains the following:

- ``start.sh``: simple shell script to start the development server
- ``$modname.conf``: configuration file for the web server
- ``$modname/``: web server code
- ``frontend/``: static files, templates and locales
- ``scripts/``: debian init scripts and other useful scripts

### Running

For development and testing:

    twistd -n cyclone --help
    twistd -n cyclone -r $modname.web.Application [--help]

    or just run ./start.sh

For production:

    twistd cyclone \
            --logfile=/var/log/$project.log \
            --pidfile=/var/run/$project.pid \
            -r $modname.web.Application

    or check scripts/debian-init.d and scripts/debian-multicore-init.d

## Customization

This section is dedicated to explaining how to customize your brand new
package.

### Databases

cyclone provides built-in support for SQLite and Redis databases.
It also supports any RDBM supported by the ``twisted.enterprise.adbapi``
module, like MySQL or PostgreSQL.

The default configuration file ``$modname.conf`` ships with pre-configured
settings for SQLite, Redis and MySQL.

The code for loading all the database settings is in ``$modname/config.py``
and is required by this application.

Take a look at ``$modname/storage.py``, which is where persistent database
connections are initialized.

This template uses the experimental ``$modname/txdbapi.py`` for interacting
with MySQL.

### Email

Please edit ``$modname.conf`` and adjust the email settings. This server
sends email on user sign up, and to reset passwords.

### Internationalization

cyclone uses the standard ``gettext`` library for dealing with string
translation.

Make sure you have the ``gettext`` package installed. If you don't, you won't
be able to translate your software.

For installing the ``gettext`` package on Debian and Ubuntu systems, do this:

    apt-get install gettext

For Mac OS X, I'd suggest using [HomeBrew](http://mxcl.github.com/homebrew>).
If you already use HomeBrew, run:

    brew install gettext
    brew link gettext

For generating translatable files for HTML and Python code of your software,
run this:

    cat frontend/template/*.html $modname/*.py | python scripts/localefix.py | xgettext - --language=Python --from-code=utf-8 --keyword=_:1,2 -d $modname

Then translate $modname.po, compile and copy to the appropriate locale
directory:

    (pt_BR is used as example here)
    vi $modname.po
    mkdir -p frontend/locale/pt_BR/LC_MESSAGES/
    msgfmt $modname.po -o frontend/locale/pt_BR/LC_MESSAGES/$modname.mo

There are sample translations for both Spanish and Portuguese in this package,
already compiled.

### Cookie Secret

The current cookie secret key in ``$modname.conf`` was generated during the
creation of this package. However, if you need a new one, you may run the
``scripts/cookie_secret.py`` script to generate a random key.

## Credits

- [cyclone](http://github.com/fiorix/cyclone) web server.

repository: drewp/cyclone

repo_name: drewp/cyclone


text:
## 0.0.2+1

* Fix a bug with not converting an iterable to a list.

## 0.0.2

* Delete fork after package migration is complete.
* Add a --dry_run flag.
* Improve heuristics for finding a package on GitHub.
* Allow updating packages without a CHANGELOG.md file.

## 0.0.1

* Initial version.


text:
HipstaDeploy
=========

A bash script for *generating* and *deploying* **static websites** on **[Amazon Cloudfront][1]**.

![Imgur](http://i.imgur.com/vSmiPIj.gif?1)

Why this stuff?
-----------

Deploying a static website (*blogs* are probably the best suited) on a **CDN** will give you **tremendous amounts of speed** from **all around the world** compared to a *dynamic* host for a relatively *cheap* price.

You can use **HipstaDeploy** with any kind of local blog installation like [Ghost][3], [Wordpress][4] or [Jekyll][5].

Requisites
-------

Right now **HipstaDeploy** expects you to have installed [s3_website][2]:

```ruby
gem install s3_website
```

Installation
---------

Just run this command if you wanna do a *quick* **Hipstallation**:

```bash
curl -s https://gist.githubusercontent.com/proudlygeek/9551019ff48053ae5bf3/raw/install.sh | sh
```

This will *download* the bash script into */usr/local/bin*, so check if is in your env **PATH** var.

You can check your installation by typing:

```bash
hipdep -h
```

If you prefer the *Good Old Ways* you can just clone this repository and run:

```bash
./deploy.sh
```

Usage
----

On the first run you'll have to create file named    's3_website.yml' with this command:

```bash
s3_website cfg create
```

Edit this file with your AWS Credentials:

```yaml
s3_id: YOUR_AWS_S3_ACCESS_KEY_ID
s3_secret: YOUR_AWS_S3_SECRET_ACCESS_KEY
s3_bucket: your.blog.bucket.com
```

Create a configuration Hipstafile and set your values:

```json
{
    "site_url": "http://localhost:2368",
    "output_folder": "_site",
    "publish_url": ""
}
```

Now just fire up HipstaDeploy with:

```bash
hipdep
```

HipstaDeploy will ask you if you want to deploy your static folder to Amazon CloudFront, say **Y** to rock on!

Your static files will be generated from URL **http//localhost:2368** (yes, that's a [Ghost][3] blog) and will be saved in a folder named **_site**.

You can override this behavior by using the **-u** and **-o** flags:

```bash
hipdep -u http://blog.local:8080 -o static_file
```

You can also specifiy your publish URL, which is used for RSS via the **-r** flag:

```bash
hipdep -r blog.site.com
```

License
-----
MIT

[1]:http://aws.amazon.com/cloudfront/
[2]:https://github.com/laurilehmijoki/s3_website
[3]:https://ghost.org/
[4]:https://www.wordpress.org
[5]:http://jekyllrb.com/

repository: Cloudxtreme/hipstadeploy

repo_name: Cloudxtreme/hipstadeploy


text:
# Fortran H5MD module

`fortran_h5md` is a Fortran module to facilitate the writing of
[H5MD](http://nongnu.org/h5md/) files. Minimal examples can be found in the
`examples` directory.

**Author:** Pierre de Buyl
**License:** BSD

gha_language: FORTRAN