text:
# redux-jive
Helpers for redux wiring

[![npm version](https://img.shields.io/npm/v/redux-jive.svg)](https://www.npmjs.com/package/redux-jive) [![Build Status](https://travis-ci.org/robbymurphy/redux-jive.svg?branch=master)](https://travis-ci.org/robbymurphy/redux-jive) [![Coverage Status](https://coveralls.io/repos/github/robbymurphy/redux-jive/badge.svg)](https://coveralls.io/github/robbymurphy/redux-jive) [![Greenkeeper badge](https://badges.greenkeeper.io/robbymurphy/redux-jive.svg)](https://greenkeeper.io/)

## Goal
The goal of this library is to remove the necessity for boilerplate code in redux projects.  Secondarily, the library aims to group actions and reducers and more tightly couple them.

## Examples

### Actions
```javascript
import { Actions } from 'redux-jive';

// action classes extend the Actions base class
class TodoActions extends Actions {
  // creates action { type: 'TodoActions.add', payload: todo }
  add(todo) {
    return todo;
  }

  markDone(todo) {
    return todo;
  }

  // functions that return promises will use the before/success/after reducer middleware
  addAsync(todo) {
    return api.post('/todos', todo);
  }
}

// actions are singletons
export default new TodoActions();
```
Extending the Actions base class wraps each of the action methods and creates the action object by convention from the name of the class and the method name.

### Reducer
```javascript
import { Reducer } from 'redux-jive';
import todoActions from './todoActions';

export class TodoReducer extends Reducer {
  constructor() {
    // provide a default state value of empty array
    super([]);

    // connect the actions with the reducer functions
    reduce(todoActions.add, this.handleAdd);
    reduce(todoActions.markDone, this.handleMarkDone);
    // asynchronous actions
    reduceAsync(todoActions.addAsync, this.handleBeforeAdd, this.handleAddSuccess, this.handleAddError);
  }

  // payload here is the todo that was added
  handleAdd(state, payload) {
    return [...state, payload];
  }

  handleMarkDone(state, payload) {
    return state.map(todo => todo.id === payload.id ? {...todo, done: true} : todo);
  }

  handleBeforeAdd(state, payload) {
    return state;
  }

  handleAddSuccess(state, payload) {
    return [...state, payload];
  }

  handleAddError(state, error) {
    return state;
  }
}
```

### Combining
```javascript
import { combineReducers } from 'redux-jive';
import TodoReducer from './TodoReducer';

// classical-style reducer functions can also be mixed in to the app
const adHocReducer = (state = {}, action) => {
  switch (action.type) {
    case 'MY_OTHER_ACTION':
      return {new: true, ...state};
    default:
      return state;
  }
};

const todoApp = combineReducers({
  todos: TodoReducer,
  adHoc: adHocReducer
});

export default todoApp;
```
Remember to add the asyncMiddleware if you are doing asynchronous calls
```javascript
import { createStore, applyMiddleware } from 'redux';
import { asyncMiddleware } from 'redux-jive';
import rootReducer from './reducers/index';

const store = createStore(
  rootReducer,
  applyMiddleware(asyncMiddleware)
);
```

repository: robbymurphy/redux-jive

gha_language: JavaScript

repo_name: robbymurphy/redux-jive


text:
## UnfulfillableQuantity

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**total_unfulfillable_quantity** | **int** | The total number of units in Amazon's fulfillment network in unsellable condition. | [optional]
**customer_damaged_quantity** | **int** | The number of units in customer damaged disposition. | [optional]
**warehouse_damaged_quantity** | **int** | The number of units in warehouse damaged disposition. | [optional]
**distributor_damaged_quantity** | **int** | The number of units in distributor damaged disposition. | [optional]
**carrier_damaged_quantity** | **int** | The number of units in carrier damaged disposition. | [optional]
**defective_quantity** | **int** | The number of units in defective disposition. | [optional]
**expired_quantity** | **int** | The number of units in expired disposition. | [optional]

[[FbaInventoryV1 Models]](../) [[API list]](../../Api) [[README]](../../../README.md)

repository: jlevers/selling-partner-api

branch_name: refs/heads/main

extension: md

gha_language: PHP

license_type: permissive

repo_name: jlevers/selling-partner-api


text:
#Timeline
---

###Description

This is timeline of main goals to achieve.

---

* 05/20/2016 - Complete the paper plan.
  * This includes:
    * A plan for database design
    * A sketchup of all the pages
    * All business logic, views, and forms planned out
    * All technology required finalized
* 05/28/2016 - Create the DB model and create tests for all the views that are going to be created.
* 06/04/2016 - Have the Views tested and implemented.
* 06/11/2016 - Start creating the frontend.
* 06/18/2016 - Connect the frontend and backend.
* 06/25/2016 - Application should be tested and ready to role out version 1.

license: MIT

branch_name: refs/heads/master


text:
---
title: Uncommunicative name
date: "2020-01-15"
description: Case of uncommunicative names
---

Let's see same cases of uncommunicative name

> Use meaningful and pronounceable variable names

Try to find descriptive names for variable names

bad ❌:

```js
const yyyymmdstr = () => moment().format("YYYY/MM/DD")
```

good ✅:

```js
const currentDate = moment().format("YYYY/MM/DD")
```

> Use searchable names

Give to constants name that specify what they are.

bad ❌:

```js
const timer = () => setTimeout(blastOff, 86400000) //what's 86400000???
```

good ✅:

```js
const timer = () => {
  const MILLISECONDS_IN_A_DAY = 86400000
  setTimeout(blastOff, MILLISECONDS_IN_A_DAY)
}
```

> Use explanatory variables

It's important that the code we do write is readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable.

bad ❌:

```js
const getAddress = () => {
  const address = "My house, Madrid 95014"
  const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/
  saveCityZipCode(
    address.match(cityZipCodeRegex)[1],
    address.match(cityZipCodeRegex)[2]
  )
}
```

good ✅:

```js
const address = () => {
  const address = "One Infinite Loop, Cupertino 95014"
  const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/
  const [, city, zipCode] = address.match(cityZipCodeRegex) || []
  saveCityZipCode(city, zipCode)
}
```

> Avoid Mental Mapping

Explicit is better than implicit, for example don't use just letters when your are iterating a an array

bad ❌:

```js
const location = () => {
  const locations = ["Austin", "New York", "San Francisco"]
  locations.forEach(l => {
    doStuff()
    doSomeOtherStuff()
    // ...
    // ...
    // ...
    // Wait, what is `l` for again?
    dispatch(l)
  })
}
```

good ✅:

```js
const locations = () => {
  const locations = ["Austin", "New York", "San Francisco"]
  locations.forEach(location => {
    doStuff()
    doSomeOtherStuff()
    // ...
    // ...
    // ...
    dispatch(location)
  })
}
```

> Give usefully name to functions

When you declare functions try to decelerate with descriptive names

bad ❌:

```js
const p = (a, b) => sqrt(pow(a, 2) + pow(b, 2))

const f = n =>
  [...Array(n)].reduce(
    (a, _, i) => a.concat(i > 1 ? a[i - 1] + a[i - 2] : i),
    []
  )
```

good ✅:

```js
const pythagorasTheorem = (cathetus1, cathetus2) =>
  sqrt(pow(cathetus1, 2) + pow(cathetus2, 2))

const fibonacci = fibonacciLength =>
  [...Array(fibonacciLength)].reduce(
    (accumulator, _, index) =>
      accumulator.concat(
        index > 1 ? accumulator[index - 1] + accumulator[index - 2] : index
      ),
    []
  )
```

repository: Girgetto/personal-blog

gha_license_id: MIT

repo_name: Girgetto/personal-blog


text:
# JRDNetWork

[![CI Status](https://img.shields.io/travis/weixin.gao/JRDNetWork.svg?style=flat)](https://travis-ci.org/weixin.gao/JRDNetWork)
[![Version](https://img.shields.io/cocoapods/v/JRDNetWork.svg?style=flat)](https://cocoapods.org/pods/JRDNetWork)
[![License](https://img.shields.io/cocoapods/l/JRDNetWork.svg?style=flat)](https://cocoapods.org/pods/JRDNetWork)
[![Platform](https://img.shields.io/cocoapods/p/JRDNetWork.svg?style=flat)](https://cocoapods.org/pods/JRDNetWork)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

JRDNetWork is available through [CocoaPods](https://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'JRDNetWork'
```

## Author

weixin.gao<EMAIL_ADDRESS>
## License

JRDNetWork is available under the MIT license. See the LICENSE file for more info.


text:
---
layout: post
title: clingo[LP]
permalink: /labs/clingoLP/
summary: clingo[LP] extends clingo with linear programming solving capabilities.
---

[`clingo[LP]`](https://github.com/potassco/clingoLP/) extends the ASP solver `clingo` with linear constraints as dealt with in Linear Programming (LP).

## Install

Install via conda:

+ `conda install -c potassco -c conda-forge clingo-lp`

## CPLEX

The clingolp propagator requires an LP solver.
The default is [lpsolve](https://sourceforge.net/projects/lpsolve/) but [cplex](https://www.ibm.com/support/knowledgecenter/SSSA5P_12.7.0/ilog.odms.cplex.help/CPLEX/GettingStarted/topics/set_up/Python_setup.html) can be used optionally.

IBM also provides a promotional version of `cplex` that is sufficient to solve small problems limited to 1000 variables and 1000 constraints.

+ `conda install -c ibmdecisionoptimization cplex`

To solve larger problems, you need to use the full version of CPLEX Studio.

## Syntax

LP constraints can be expressed as follows:

|LP constraints | ClingoLP Syntax|
|:--------------|:---------------|
|w1x1+...+wnxn >= k | `&sum{`w1`*`x1`;`...`;`wn`*`xn`} >=` k |
| domain(x)={l,...,u} | `&dom{`l`..`u`} =` x
| maximize: w1x1+...+wnxn | `&maximize{`w1`*`x1`;`...`;`wn`*`x1`}` (minimize analogous)

To avoid syntax clashes, you must quote `"` real numbers. Instead of `1.5` write `"1.5"`.

## General usage of clingo[LP]

Basic call:
`clingoLP <encoding> <instance> <options>`

Example:
`clingoLP example_encoding.lp example_instance.lp --show-lp-solution 0`

+ Options
  + --show-lp-solution
    + Show LP solution and value of objective function
  + --lp-solver=cplx
    + Selects a LP solver (default lp-solver=lps)
  + --accuracy=n
    + Prints n decimal positions (default accuracy=1)
  + --epsilon=n,m
    + Set epsilon to convert lhs > k into lhs >= k+n*10-m (default epsilon=1,3)
  + --strict
    + Enables strict semantics
  + --trace
    + Enables detailed output of theory propagation
  + --core-confl=n
    + Searches for core conflicts if at least n% of the theory atoms are decided (default core-confl=20)
  + --prop-heur=n
    + Starts a solve call of the LP solver if at least n% of the theory atoms are decided (default prop-heur=0)
  + --ilp
    + Sets the LP solver to solve an Integer Linear Programming (ILP) problem

  + All clingo options
  + Number of solutions controlled via clingo

## Publication

- Tomi Janhunen, Roland Kaminski, Max Ostrowski, Torsten Schaub, Sebastian Schellhorn and Philipp Wanko,
  [Clingo goes Linear Constraints over Reals and Integers]({{ site.publicationurl }}/#DBLP:journals/tplp/JanhunenKOSWS17), TPLP, 2017:
  [[Experiments]({{ site.resourceurl }}/clingo/experiments-clingoLC.tar.xz)]

gha_language: HTML


text:
# Golang Chrome Automation using ChromeDP

[![Build Status](https://travis-ci.org/ribice/golang-chrome-automation.svg?branch=master)](https://travis-ci.org/ribice/golang-chrome-automation)
[![Go Report Card](https://goreportcard.com/badge/github.com/ribice/golang-chrome-automation)](https://goreportcard.com/report/github.com/ribice/golang-chrome-automation)

This repo contains a small real world tool built using [chromedp](https://github.com/chromedp/chromedp).

It reads config data from config.json and launches Chrome.

Then it navigates to a Drupal website, logs-in and changes Bootstrap CDN settings.

Detailed explanation is available as a blog-post on my website - [LINK](https://ribice.ba/golang-chrome-automation/).

## License

golang-chrome-automation is licensed under the MIT license. Check the [LICENSE](LICENSE.md) file for details.

## Author

[Emir Ribic](https://ribice.ba)


text:
# Hibernate-redis
A library for using Redis as a second level distributed cache in Hibernate.
This is an open source project.

version : 1.0.0-SNAPSHOT

## Feature
* Implement hibernate entity & query results cache using redis
* Implement read-write strategy locking with [SETNX](http://redis.io/commands/setnx)

## System Requirements

JDK 1.6 or above.

## Using Hibernate-redis

* checkout this source

        git clone git@github.com:Jongtae/hibernate-redis.git

* install locally using maven' install commend:

        mvn install -DskipTests

* add dependency in your project pom.xml:

        <dependency>
          <groupId>net.daum.clix</groupId>
          <artifactId>hibernate-redis</artifactId>
        </dependency>

* configurate hibernate properties like this :

        <property name="hibernate.cache.use_second_level_cache">true</property>
      	<property name="hibernate.cache.use_query_cache">true</property>
    	<property name="hibernate.cache.region.factory_class">net.daum.clix.hibernate.redis.RedisRegionFactory
    	</property>
        <property name="redis.host">"redis.host"</property>

* set your additional redis properites optionally

        <property name="redis.port">"redis.port"</property>
        <property name="redis.timeout">"redis.timeout"</property>
        <property name="redis.password">"redis.password"</property>

## License

This software is licensed under the Apache 2 license, quoted below.

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

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

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


text:
# Machine learning Question & Answering

## Table of contents

### Shallow learning
In a very simplistic way, in shallow learning algorithms, input features are not "changed", so the algorithm try to search  different parameters and/or way to separate the observation in the dataset so that the resulting model can separate and predict new observations by using the parameters and patterns learned whil training time. In other words, the number of parameters is mostly bounded by the number of feautures (input dimension space).

  - [Collobrative filtering](collabb_filtering.md)
  - [decision tree and random forrest](decision_tree_and_rf.md)
  - [K-MEAN](kmean.md)
  - [KNN](knn.md)
  - [Linear regression](linear_regression.md)
  - [Logistic regression](logisitic_regression.md)
  - [Naive Bayes](naive_bayes.md)
  - [PCA](pca.md)
  - [Polynomial regression](polynomial_regression.md)
  - [SVM](svm.md)

### Deep learning(Neural Networks)
Comparing deep learning to shallow learning definition given above, again in a very simplistic term, the input features are now changing in many ways during training, that means the algorithm keep trying to change the input features to have a better representation of the input data, and this process of learning new useful features is repeated as many time as we want. The repetition of this process is what lead us to depp learning because the algorithm is "always" trying to learn new features based on the precedent created features. For every new set of features, new parameters are created and learned through traininig, deep learning is "just" a fancy way of saying the algorithm has lot of parameters.
  - [Auto encoders](nns.md)
  - [Neural Networks](nns.md)
  - [Convolutional Neural Networks](cnn.md)
  - [Recurrent Neural Networks](rnn.md)

### General knowlege
  - [Model analysis](model_analysis.md)
  - [Model training](model_training.md)

repository: bayethiernodiop/ML-question-answering

repo_name: bayethiernodiop/ML-question-answering


text:
A Meteor package containing Stripe.js (<https://stripe.com/docs/stripe.js>) and Stripe for Node.js (<https://github.com/abh/node-stripe>). Stripe.js is a direct copy of <https://js.stripe.com/v1/>.

## Usage

### Client

The same as in the Stripe docs (<https://stripe.com/docs/stripe.js>). Example for reference:

    Stripe.setPublishableKey('YOUR_PUBLISHABLE_KEY');

### Server

To initiate a Stripe object:

    var Stripe = StripeAPI('YOUR_SECRET_API_KEY');

And then use it:

    Stripe.charges.create({
		amount: 1000,
		currency: "USD",
		card: {
			number: "4242424242424242",
			exp_month: "03",
			exp_year: "2014"
		}
	}, function (err, res) {
		console.log(err, res);
	});

For a complete reference, please see the original: <https://github.com/abh/node-stripe>

repository: dwinston/payment-per-service

repo_name: dwinston/payment-per-service


text:
# PPP Logging backend

[![Build Status](https://scrutinizer-ci.com/g/ProjetPP/PPP-Logger/badges/build.png?b=master)](https://scrutinizer-ci.com/g/ProjetPP/PPP-Logger/build-status/master)
[![Code Coverage](https://scrutinizer-ci.com/g/ProjetPP/PPP-Logger/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/ProjetPP/PPP-Logger/?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/ProjetPP/PPP-Logger/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/ProjetPP/PPP-Logger/?branch=master)

# How to install

With a recent version of pip:

```
pip3 install git+https://github.com/ProjetPP/PPP-logger.git
```

With an older one:

```
git clone https://github.com/ProjetPP/PPP-Logger.git
cd PPP-Logger
python3 setup.py install
```

Use the `--user` option if you want to install it only for the current user.

# How to run the logger (for system administrators)

You can write your `config.json` file in a quite straightforward way, using
the file `example_config.json` as an example.

Then, just run:

```
PPP_LOGGER_CONFIG=/path/to/json/config.json gunicorn ppp_logger:app
```

# How to use the logger API (for frontend developpers)

Just send a POST request to your logger instance, with this content:

```
{"id": "<request id>", "question": "<the question the user wrote>",
"responses": [list of responses returned by the core]}
```

repository: ProjetPP/PPP-Logger

gha_language: Python

repo_name: ProjetPP/PPP-Logger


text:
---
id: keto-relation-tuple-create
title: keto relation-tuple create
description: keto relation-tuple create Create relationships from JSON files
---

<!--
This file is auto-generated.

To improve this file please make your change against the appropriate "./cmd/*.go" file.
-->
## keto relation-tuple create

Create relationships from JSON files

### Synopsis

Create relationships from JSON files.
A directory will be traversed and all relationships will be created.
Pass the special filename `-` to read from STD_IN.

```
keto relation-tuple create <relationships.json> [<relationships-dir>] [flags]
```

### Options

```
      --authority string                      Set the authority header for the remote gRPC server.
      --format string                         Set the output format. One of table, json, yaml, json-pretty, jsonpath and jsonpointer. (default "default")
  -h, --help                                  help for create
      --insecure-disable-transport-security   Disables transport security. Do not use this in production.
      --insecure-skip-hostname-verification   Disables hostname verification. Do not use this in production.
  -q, --quiet                                 Be quiet with output printing.
      --read-remote string                    Remote address of the read API endpoint. (default "<IP_ADDRESS>:4466")
      --write-remote string                   Remote address of the write API endpoint. (default "<IP_ADDRESS>:4467")
```

### Options inherited from parent commands

```
  -c, --config strings   Config files to load, overwriting in the order specified. (default [/home/runner/keto.yml])
```

### SEE ALSO

* [keto relation-tuple](keto-relation-tuple)	 - Read and manipulate relationships

repository: ory/docs

gha_language: TypeScript

repo_name: ory/docs


text:
# Talking Scores

## Prerequisites

1. A working Python 3 installation

## Installation

1. Create a virtual environment for the python requirements
   ```
   python -m venv .talkingscore-env
   ```
1. Install the required python modules
   ```
   pip install -r requirements
   ```

## Running a server

1. Ensure the virtual environment is active (you should see `(.talkingscores-env)` in your prompt).
    ```
    source .talkingscores-env/bin/activate
    ```
1. Run the local Django server.
    ```
    python ./manage.py runserver
    ```

repository: bentimms/talkingscores

repo_name: bentimms/talkingscores


text:
This inspection checks the version in an XQuery version declaration for
values supported by the selected XQuery processor.

Unsupported versions would raise `XQST0031` errors on the XQuery processor.

__Note:__ This inspection also checks that the XQuery version is the same
across MarkLogic transactions. Different versions would raise
`XDMP-XQUERYVERSIONSWITCH` errors on MarkLogic.

repository: rhdunn/xquery-intellij-plugin

gha_language: Kotlin

repo_name: rhdunn/xquery-intellij-plugin


text:
# Ecobici data listening

### Summary

`stations.py` send API requests for every docking station that is part of Buenos Aires' bicycle sharing system. It's purpose is to collect data on how many docked bicycles  and available positions are in each of the 198 stations. A comprehensive list of all docking stations to present can found in  `data/stations.json`

`weather.py`: gets the HTML of two weather stations sites, parses it with the use of BeautifulSoup and returns weather variables as temperature, wind, rain, etc.

Data collected by both scripts is ment to be use for docking stations usage prediction using machine learning in a latter proyect.

### How to use

Both scripts should be use with cron so they can be executed at time intervals. We suggest running `stations.py` every 5 minutes and `weather.py` every 30 minutes. For the `stations.py` add a 1 minute buffer after the 5 minute interval mark to make sure that server side data is updated since the server updates its data every five minutes. `crontab -e` file should look like this:

```
# m h  dom mon dow   command
1-59/5 * * * * python /path/to/script/stations.py
   */5 * * * * python /path/to/script/weather.py
```

Don't forget to set the appropiate permissions for both scripts.

```
sudo chmod +x script.py
```

repository: nonsignificantp/ecobici-API

repo_name: nonsignificantp/ecobici-API


text:
# Brutalist

The Gatsby starter with theme Brutalist. Kick off your project with this boilerplate ([live demo](http://ruslankhh.com/gatsby-starter-brutalist)).

_Have another more specific idea? You may want to check out our vibrant collection of [official and community-created starters](https://www.gatsbyjs.org/docs/gatsby-starters/)._

## 🚀 Quick start

1. **Create a Gatsby site.**

    Use the Gatsby CLI to create a new site, specifying the starter.

    ```sh
    # create a new Gatsby site using the starter
    npx gatsby new my-website https://github.com/ruslankhh/gatsby-starter-brutalist
    ```

2. **Start developing.**

    Navigate into your new site’s directory and start it up.

    ```sh
    cd my-website/
    gatsby develop
    ```

3. **Open the source code and start editing!**

    Your site is now running at `http://localhost:8000`!

    *Note: You'll also see a second link: `http://localhost:8000/___graphql`. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the [Gatsby tutorial](https://www.gatsbyjs.org/tutorial/part-five/#introducing-graphiql).*

    Open the `my-website` directory in your code editor of choice and edit `src/pages/index.js`. Save your changes and the browser will update in real time!

## 🎉 Features

- [ ] Easy editable content in **Markdown** files (posts, pages and parts)
- [ ] **SEO** (sitemap generation, robot.txt, meta and OpenGraph Tags)
- [ ] **Social** sharing (Twitter, Facebook, Google, LinkedIn)
- [ ] **Images** lazy loading and `webp` support (gatsby-image)
- [ ] Speedy, optimized **images** without the work (gatsby-image)
- [ ] Post **categories** (category based post list)
- [ ] **RSS** feed
- [ ] **PWA** (manifest, offline support, favicons)
- [ ] Google **Analytics**
- [ ] App **favicons** generator (node script)
- [ ] **CSS** with `PostCSS`
- [x] **Prettier** code formatting
- [ ] Static type-checking with **Typescript**
- [ ] Interactively develop and test UI components with **Storybook**
- [ ] Testing with **Jest**, **Enzyme**
- [ ] Continius Integration with **Travis CI**, **AppVeyor CI**

## 🎓 Learning Gatsby

Looking for more guidance? Full documentation for Gatsby lives [on the website](https://www.gatsbyjs.org/). Here are some places to start:

- **For most developers, we recommend starting with our [in-depth tutorial for creating a site with Gatsby](https://www.gatsbyjs.org/tutorial/).** It starts with zero assumptions about your level of ability and walks through every step of the process.

- **To dive straight into code samples, head [to our documentation](https://www.gatsbyjs.org/docs/).** In particular, check out the _Guides_, _API Reference_, and _Advanced Tutorials_ sections in the sidebar.

## Author

[Ruslan Khusnetdinov](https://github.com/ruslankhh)

## License

MIT

repository: ruslanxdev/gatsby-starter-brutalist

repo_name: ruslanxdev/gatsby-starter-brutalist


text:
# Docker example on Jetson Nano

## What is this ?

This is a Docker example to call TensorFlow with GPU in a container.
This example is tested on Jetson Nano with JetPack 4.2.

- Dockerfile ... Dockerfile to create an image including TensorFlow
- build.sh   ... build script to make Docker image
- run.sh     ... example to launch container
- home/      ... home directory mounted to /home/foo in the container

This example demonstrates an image recognition by Resnet50.

## Prerequisties

- Model: Jetson Nano
- Environment: JetPack 4.4.1
- Storage: at least 10GB of disk space

## Download example from github

```bash:terminal
git clone https://github.com/yamamo-to/jetson_nano.git
```

## Build Docker Image

Note that this build takes time. In my environment it takes about an hour.

```bash:terminal
cd jetson_nano/docker_example/jetpack4.4
./build.sh
```

## Launch Docker Container

```bash:terminal
./run.sh
```

## Run example

First, install pillow as below:

```bash:container
pip3 install pillow
```

Then, run the script:

```bash:container
python3 scripts/resnet50_keras.py data/boss.jpg
```


text:
# Sandbox Trainee Prominas View (Development w/ Template)
## José Júlio Alves Campolina

A CRUD view of the resources related to the project traineeprominas-jjac-sandbox.

This view consumes the **REST API** (https://traineeprominas-lpop-sandbox.herokuapp.com/api/v1/)

Obs:
* This is not the design used for viewing on *Heroku*. This is only the development project using COREUI Angular Template.
	 * The project used to connect to *Heroku* is called **traineeprominas-jjac-view-sandbox-template-heroku**

## About
For this project, the Angular was used to create the visualizations of each endpoint and to realize the CRUD

## Files
* /src - index, main, etc
* /src/model - user, teacher, course and student template
* /src/service - connection to CRUD routes of API
* /src/app/view - where components and html, css and ts files are located

## CORE UI Template - https://coreui.io/angular/


text:
# Test Helpers

This project contains any reusable components to help with testing.

## Integration Tests

Helpers for integration tests are in the /Integration folder.

### Overview

[dotnet-testcontainers](https://github.com/HofmeisterAn/dotnet-testcontainers) is used to manage starting/stopping Postgres and LocalStack containers.

TestContainers is used in 3 fixtures. These fixtures implement xunit's `IAsyncLifetime` and are run as `ICollectionFixture<T>`:

* `DlcsDatabaseFixture` - starts postgres image, instantiates `DlcsContext` and runs migrations. Public properties expose the `ConnectionString` for that instance and `DlcsContext` for managing/verifying data in tests. A random free port will be used and set in the connection string - this is handled by `dotnet-testcontainers`. Customer `99` is setup with a space, origin-strategy etc.
* `LocalStackFixture` -  starts localstack image, configures AWS clients + seeds basic resources (e.g. buckets/queues). Public properties expose AWS clients for use in tests any by `WebApplicationFactory`. Host port "0" is used and will bind to a free port, this is reflected in the `IAmazon*` client instances.
* `StorageFixtures` - this contains the above 2, exposed as public properties. Only one `ICollectionFixture` can be used per test class so this wraps both of the above.

`ProtagonistAppFactory` is a [`WebApplicationFactory`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing.webapplicationfactory-1?view=aspnetcore-6.0) that is consumed as a `ClassFixture<T>`. This will set environment to `"Testing"` and use any `appsetting.Testing.json` found in test project.

This has a couple of fluent helper methods to take connectionString and `LocalStackFixture` to replace any running instances in target `Startup`. Example setup:

```cs
[Trait("Category", "Integration")]
[Collection(StorageCollection.CollectionName)]
public class ExampleTests : IClassFixture<ProtagonistAppFactory<Startup>>
{
    private readonly DlcsDatabaseFixture dbFixture;
    private readonly HttpClient httpClient;
    private readonly IAmazonS3 amazonS3;

    public ExampleTests(ProtagonistAppFactory<Startup> factory, StorageFixture storageFixture)
    {
        // Store dbFixture to read/write in test assertions/setup
        dbFixture = storageFixture.DbFixture;

        // Store amazonS3 client configured to use LocalStack instance
        amazonS3 = storageFixture.LocalStackFixture.AWSS3ClientFactory();

        // Configure WebApplicationFactory
        httpClient = factory
            .WithConnectionString(dbFixture.ConnectionString)
            .WithLocalStack(storageFixture.LocalStackFixture)
            .WithConfigValue("Overridden-AppSetting", "Overwrites other app setting value")
            .WithTestServices(services =>
            {
                services.AddSingleton<IService, TestService>();
            })
            .CreateClient(new WebApplicationFactoryClientOptions {AllowAutoRedirect = false});

        // Clean down database
        dbFixture.CleanUp();
    }
```

### Identifiers

Care needs to be taken for the lifecycle of objects setup using CollectionFixtures as these will last for the run of all tests in a class.

One handy way is to use the name of the test in the Asset identifier to avoid collisions.

```cs
[Fact]
public async Task Test_Demonstrates_Thing()
{
    // Arrange
    var idRoot = $"99/1/{nameof(Test_Demonstrates_Thing)}";
    await dbContext.Images.AddTestAsset(AssetId.FromString(idRoot));

    // Test things...
}
```

### Handling Http Dependencies

There are a number of external dependencies that we communicate with via HTTP. These can be handled in 2 different ways:

* Mock Client: if we are using a Typed client we could use `.WithTestServices()` method on `ProtagonistAppFactory` to register a fake/mock version of the dependency and verify that appropriate requests are made. This only tests that calls to the client are correct, the client code would need to be tested separately.
* Api Stub: A library like [Stubbery](https://github.com/markvincze/Stubbery) can be used to control HTTP requests. There are examples of this in the code base but using Stubbery to create mock endpoints allows any error handling etc code to run.

### Troubleshooting

Stopping and starting the docker containers isn't always perfect - particularly if aborting tests without them completing. The following command will delete any of the test-containers running:

```bash
docker rm $(docker stop $(docker ps -q --filter label=protagonist_test))
```

repository: dlcs/protagonist

gha_language: C#

repo_name: dlcs/protagonist


text:
# 148. Sort List (Medium)

Given the head of a linked list, return the list after sorting it in ascending order.

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

### Example 1:

```
Input: head = [4,2,1,3]
Output: [1,2,3,4]
```

### Example 1:

```
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
```

### Example 3:

```
Input: head = []
Output: []
```

### Constraints:

- The number of nodes in the list is in the range [0, 5 * 10^4].
- -10^5 <= Node.val <= 10^5

## Solution

Quicksort using recursion using O(n log n) space, which doesn't pass OJ. Bottom-up merge sort it needs.

#Linked List #Sort


text:
# Based on k0st/zcash

Zcash inside docker

Image is based on the Ubuntu 16.04 base image

## Build

```
docker build -f Dockerfile --build-arg UID=$(id -u) --build-arg GID=$(id -g) --build-arg UNAME=$(id -n -u) -t zcash-cli .
```

## Docker image usage

```
docker run [docker-options] zcash-cli
```

## Examples

Typical basic usage (start zcashd daemon):

```
docker run -it zcash-cli zcashd
```

Typical usage to perform query:

```
docker run -d --name zcashcont zcash-cli zcashd
docker exec -u zcash zcashcont zcash-cli getbalance
```

### Todo
- [ ] Perform more testing

repository: dovbysh/docker-zcash

repo_name: dovbysh/docker-zcash


text:
# MSC2676: Message editing

Users may wish to edit previously sent messages, for example to correct typos.
This can be done by sending a new message with an indication that it replaces
the previously sent message.

This proposal is one in a series of proposals that defines a mechanism for
events to relate to each other.  Together, these proposals replace
[MSC1849](https://github.com/matrix-org/matrix-doc/pull/1849).

* [MSC2674](https://github.com/matrix-org/matrix-doc/pull/2674) defines a
  standard shape for indicating events which relate to other events.
* [MSC2675](https://github.com/matrix-org/matrix-doc/pull/2675) defines APIs to
  let the server calculate the aggregations on behalf of the client, and so
  bundle the related events with the original event where appropriate.
* This proposal defines how users can edit messages using this mechanism.
* [MSC2677](https://github.com/matrix-org/matrix-doc/pull/2677) defines how
  users can annotate events, such as reacting to events with emoji, using this
  mechanism.

## Background

Element-Web (then Riot-Web) and Synapse both implemented initial support for
message editing, following the proposals of MSC1849, in May 2019
([matrix-react-sdk](https://github.com/matrix-org/matrix-react-sdk/pull/2952),
[synapse](https://github.com/matrix-org/synapse/pull/5209)). Element-Android
and Element-iOS also added implementations around that time. Unfortunately,
those implementations presented the feature as "production-ready", despite it
not yet having been adopted into the Matrix specification.

The current situation is therefore that client or server implementations hoping
to interact with Element users must simply follow the examples of that
implementation. In other words, message edits form part of the *de-facto* spec
despite not being formalised in the written spec. This is clearly a regrettable
situation. Hopefully, processes have improved over the last three years so that
this situation will not arise again.  Nevertheless there is little we can do
now other than formalise the status quo.

This MSC, along with the others mentioned above, therefore seeks primarily to
do that. Although there is plenty of scope for improvement, we consider that
better done in *future* MSCs, based on a shared understanding of the *current*
implementation.

In short, this MSC prefers fidelity to the current implementations over
elegance of design.

## Proposal

### `m.replace` event relationship type

A new `rel_type` of `m.replace` is defined for use with the `m.relates_to`
field as defined in
[MSC2674](https://github.com/matrix-org/matrix-doc/pull/2674). This is
intended primarily for handling edits, and lets you define an event which
replaces an existing event.

Such an event, with `rel_type: m.replace`, is referred to as a "message edit event".

### `m.new_content` property

The `content` of a message edit event must contain a `m.new_content` property
which defines the replacement content. (This allows the normal `body` fields to
be used for a fallback for clients who do not understand replacement events.)

For instance, an `m.room.message` which replaces an existing event might look like:

```json
{
    "type": "m.room.message",
    "content": {
        "body": "* Hello! My name is bar",
        "msgtype": "m.text",
        "m.new_content": {
            "body": "Hello! My name is bar",
            "msgtype": "m.text"
        },
        "m.relates_to": {
            "rel_type": "m.replace",
            "event_id": "$some_event_id"
        }
    }
}
```

The `m.new_content` can include any properties that would normally be found in
an event's `content` property, such as `formatted_body`.

#### Encrypted events

If the original event was encrypted, the replacement should be too. In that
case, `m.new_content` is placed in the `content` of the encrypted payload. The
`m.relates_to` property remains unencrypted, as required by the
[relationships](https://spec.matrix.org/v1.3/client-server-api/#forming-relationships-between-events)
section of the Client-Server API specification.

For example, an encrypted replacement event might look like this:

```json
{
    "type": "m.room.encrypted",
    "content": {
        "m.relates_to": {
            "rel_type": "m.replace",
            "event_id": "$some_event_id"
        },
        "algorithm": "m.megolm.v1.aes-sha2",
        "sender_key": "<sender_curve25519_key>",
        "device_id": "<sender_device_id>",
        "session_id": "<outbound_group_session_id>",
        "ciphertext": "<encrypted_payload_base_64>"
    }
}
```

... and, once decrypted, the payload might look like this:

```json
{
    "type": "m.room.<event_type>",
    "room_id": "!some_room_id",
    "content": {
        "body": "* Hello! My name is bar",
        "msgtype": "m.text",
        "m.new_content": {
            "body": "Hello! My name is bar",
            "msgtype": "m.text"
        }
    }
}
```

Note that:
 * There is no `m.relates_to` property in the encrypted payload. (Any such
   property would be ignored.)
 * There is no `m.new_content` property in the cleartext `content` of the
   `m.room.encrypted` event. (Again, any such property would be ignored.)

For clarity: the payload must be encrypted as normal, ratcheting the Megolm session
as normal. The original Megolm ratchet entry should **not** be re-used.

#### Applying `m.new_content`

When applying a replacement, the `content` property of the original event is
replaced entirely by the `m.new_content`, with the exception of `m.relates_to`,
which is left *unchanged*. Any `m.relates_to` property within `m.new_content`
is ignored.

For example, given a pair of events:

```json
{
    "event_id": "$original_event",
    "type": "m.room.message",
    "content": {
        "body": "I *really* like cake",
        "msgtype": "m.text",
        "formatted_body": "I <em>really</em> like cake",
    }
}
```

```json
{
    "event_id": "$edit_event",
    "type": "m.room.message",
    "content": {
        "body": "* I *really* like *chocolate* cake",
        "msgtype": "m.text",
        "m.new_content": {
            "body": "I *really* like *chocolate* cake",
            "msgtype": "m.text",
            "com.example.extension_property": "chocolate"
        },
        "m.relates_to": {
            "rel_type": "m.replace",
            "event_id": "$original_event_id"
        }
    }
}
```

... then the end result is an event as shown below. Note that `formatted_body`
is now absent, because it was absent in the replacement event, but
`m.relates_to` remains unchanged (ie, absent).

```json
{
    "event_id": "$original_event",
    "type": "m.room.message",
    "content": {
        "body": "I *really* like *chocolate* cake",
        "msgtype": "m.text",
        "com.example.extension_property": "chocolate"
    }
}
```

Note that the `msgtype` property of `m.room.message` events need not be the
same as in the original event. For example, if a user intended to send a
message beginning with "/me", but their client sends an `m.emote` event
instead, they could edit the message to send be an `m.text` event as they had
originally intended.

### Validity of message edit events

Some message edit events are defined to be invalid. To be considered valid, all
of the following criteria must be satisfied:

 * The replacement and original events must have the same `type`.
 * Neither the replacement nor original events can be state events (ie, neither
   may have a `state_key`).
 * The original event must not, itself, have a `rel_type` of `m.replace`.
 * The original event and replacement event must have the same `sender`.
 * The replacement event (once decrypted, if appropriate) must have an
   `m.new_content` property.

The original event and replacement event must also have the same `room_id`, as
required by the
[relationships](https://spec.matrix.org/v1.3/client-server-api/#forming-relationships-between-events)
section of the Client-Server API specification.

If any of these criteria are not satisfied, implementations should ignore the
replacement event (the content of the original should not be replaced, and the
edit should not be included in the server-side aggregation).

### Server behaviour

#### Server-side aggregation of `m.replace` relationships

Note that there can be multiple events with an `m.replace` relationship to a
given event (for example, if an event is edited multiple times). These should
be [aggregated](https://spec.matrix.org/v1.3/client-server-api/#aggregations)
by the homeserver.

The format of the aggregation for `m.replace` simply gives gives the
`event_id`, `origin_server_ts`, and `sender` of the most recent replacement
event (as determined by `origin_server_ts`, falling back to a lexicographic
ordering of `event_id`).

This aggregation is bundled into the `unsigned/m.relations` property of any
event that is the target of an `m.replace` relationship. For example:

```json5

{
  "event_id": "$original_event_id",
  // ...
  "unsigned": {
    "m.relations": {
      "m.replace": {
        "event_id": "$latest_edit_event_id",
        "origin_server_ts":<PHONE_NUMBER>313,
        "sender": "@editing_user:localhost"
      }
    }
  }
}
```

If the original event is redacted, any `m.replace` relationship should **not**
be bundled with it (whether or not any subsequent edits are themselves
redacted). Note that this behaviour is specific to the `m.replace`
relationship.

#### Server-side replacement of content

Whenever an `m.replace` is to be bundled with an event as above, the server should
also modify the `content` of the original event according
to the `m.new_content` of the most recent edit (determined as above).

An exception applies to [`GET
/_matrix/client/v3/rooms/{roomId}/event/{eventId}`](https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3roomsroomideventeventid),
which should return the *unmodified* event (though the relationship should
still be bundled, as described above).

The endpoints where this behaviour takes place is the same as those where
aggregations are bundled, with the exception of
`/room/{roomId}/event/{eventId}`. This includes:

  * `GET /rooms/{roomId}/messages`
  * `GET /rooms/{roomId}/context/{eventId}`
  * `GET /rooms/{roomId}/relations/{eventId}`
  * `GET /rooms/{roomId}/relations/{eventId}/{relType}`
  * `GET /rooms/{roomId}/relations/{eventId}/{relType}/{eventType}`
  * `GET /sync` when the relevant section has a `limited` value of `true`
  * `POST /search` for any matching events under `room_events`.

### Client behaviour

Clients can often ignore message edit events, since any events the server
returns via the C-S API will be updated by the server to account for subsequent
edits.

However, clients should apply the replacement themselves when the server is
unable to do so. This happens in the following situations:

1. The client has already received and stored the original event before the message
   edit event arrives.

2. The original event (and hence its replacement) are encrypted.

Client authors are reminded to take note of the requirements for [Validity of
message edit events](#validity-of-message-edit-events), and to ignore any
invalid edit events that may be received.

### Permalinks

Permalinks to edited events should capture the event ID that the creator of the
permalink is viewing at that point (which might be a message edit event).

The client viewing the permalink should resolve this ID to the original event
ID, and then display the most recent version of that event.

### Redactions

When a message using a `rel_type` of `m.replace` is redacted, it removes that
edit revision. This has little effect if there were subsequent edits, however
if it was the most recent edit, the event is in effect reverted to its content
before the redacted edit.

Redacting the original message in effect removes the message, including all
subsequent edits, from the visible timeline. In this situation, homeservers
will return an empty `content` for the original event as with any other
redacted event. It must be noted that, although they are not immediately
visible in Element, subsequent edits remain unredacted and can be seen via API
calls. See [Future considerations](#future-considerations).

### Edits of replies

Some particular constraints apply to events which replace a
[reply](https://spec.matrix.org/v1.3/client-server-api/#rich-replies). In
particular:

 * There should be no `m.in_reply_to` property in the the `m.relates_to`
   object, since it would be redundant (see [Applying
   `m.new_content`](#applying-mnew_content) above, which notes that the original
   event's `m.relates_to` is preserved), as well as being contrary to the
   spirit of
   [MSC2674](https://github.com/matrix-org/matrix-spec-proposals/pull/2674)
   which expects only one relationship per event.

 * `m.new_content` should **not** contain any ["reply
   fallback"](https://spec.matrix.org/v1.3/client-server-api/#fallbacks-for-rich-replies),
   since it is assumed that any client which can handle edits can also
   display replies natively.

An example of an edit to a reply is as follows:

```json
{
  "type": "m.room.message",
  "content": {
    "body": "> <@richvdh:sw1v.org> ab\n\n * ef",
    "msgtype": "m.text",
    "format": "org.matrix.custom.html",
    "formatted_body": "<mx-reply><blockquote><a href=\"https://matrix.to/#/!qOZKfwKPirAoSosXrf:matrix.org/$1652807718765kOVDf:sw1v.org?via=matrix.org&via=sw1v.org\">In reply to</a> <a href=\"https://matrix.to/#/@richvdh:sw1v.org\">@richvdh:sw1v.org</a><br>ab</blockquote></mx-reply> * ef",
    "m.new_content": {
      "body": "ef",
      "msgtype": "m.text",
      "format": "org.matrix.custom.html",
      "formatted_body": "ef"
    },
    "m.relates_to": {
      "rel_type": "m.replace",
      "event_id": "$original_reply_event"
    }
  }
}
```

## Future considerations

### Ordering of edits

In future we may wish to consider ordering replacements (or relations in
general) via a DAG rather than using `origin_server_ts` to determine ordering -
particularly to mitigate potential abuse of edits applied by moderators.
Whatever, care must be taken by the server to ensure that if there are multiple
replacement events, the server must consistently choose the same one as all
other servers.

### Redaction of edits

It is highly unintuitive that redacting the original event leaves subsequent
edits visible to curious eyes even though they are hidden from the
timeline. This is considered a bug which this MSC makes no attempt to
resolve. See also
[element-web#11978](https://github.com/vector-im/element-web/issues/11978) and
[synapse#5594](https://github.com/matrix-org/synapse/issues/5594).

### Edits to state events

There are various issues which would need to be resolved before edits to state
events could be supported. In particular, we would need to consider how the
semantically-meaningful fields of the content of a state event relate to
`m.new_content`. Variation between implementations could easily lead to
security problems (See
[element-web#21851](https://github.com/vector-im/element-web/issues/21851) for
example.)

### Editing other users' events

There is a usecase for users with sufficient power-level to edit other peoples'
events. For now, no attempt is made to support this. If it is supported in the
future, we would need to find a way to make it clear in the timeline.

repository: matrix-org/matrix-spec-proposals

repo_name: matrix-org/matrix-spec-proposals


text:
lein-fregec
===========

A Leiningen plugin to compile Frege (http://www.frege-lang.org) code.

Usage - Simple
-----

The easiest way to use Leiningen with Frege (or with Clojure and Frege) is to take advantage of the `frege` template --
[frege-lein-template](https://github.com/Frege/frege-lein-template) -- to create a new Leiningen project for either a pure Frege project or a mixed Clojure / Frege project (with a Clojure main entry point):

    lein new frege myapp

This will create a folder called `myapp` containing a Leiningen project with an example of a pure Frege program in it. If you want a mixed Clojure / Frege project:

    lein new frege myapp -- :with-clojure

The Frege template will always set up a project with the most recent stable version of Frege. If you want to modify the `project.clj` file, read the section below on what settings are available.

Usage - Manual
-----

If you already have a Leiningen project, you can add this plugin as follows:

Add `[lein-fregec "3.24-7.100"]` to `:plugins` in your `project.clj`. The version of `lein-fregec` matches the version of the Frege compiler it is compatible with and uses.

Usage - Configuration & Execution
-----

Set `:frege-source-paths` to the location(s) of your Frege source files. Default is the current directory but I highly recommend using `src/frege` and structuring your projects that way (although the `hello` example relies on current directory). The template generates projects that either use `src` (pure Frege) or `src/frege` (mixed Clojure / Frege).

If you created `project.clj` manually, rather than via the `frege` template -- or you are upgrading an older `project.clj` file -- then you must tell the Frege compiler to target Java 7 explicitly, either in `project.clj`:

```clojure
:fregec-options ["-target" "1.7"]
```

or via the command line (see below for more about Frege compiler options):

```sh
lein fregec :target 1.7
```

That is added to `project.clj` automatically by the 3.24-7.100 version of the `frege` template.

Run `lein fregec` to compile Frege source files to `.class` files.

The output of compilation will go to the `:compile-path` directory, which defaults to `target/classes/` in Leiningen.

You may specify additional Frege compiler options via `:fregec-options` in `project.clj` (as a vector of strings) or via the command line. Note that command line options for Leiningen tasks start with `:` (and are converted to `-` options automatically):

```sh
lein fregec :v
```

This will pass `-v` to the Frege compiler (verbose mode). If you want to see the full list of options being passed to the Frege compiler, set the `DEBUG` environment variable to `true`:

```sh
DEBUG=true lein fregec
```

This will also display the exact version of the Frege compiler that the plugin is using.

Run `lein uberjar` to compile Frege source files and create a JAR file in the `target/` folder. You need to ensure that Frege compilation is part of the `:uberjar` profile in `project.clj`:

```clojure
:profiles {:uberjar {:aot :all
                     :prep-tasks ["fregec" "compile"]}}
```

This tells Leiningen to run the `fregec` task and the `compile` task before building the JAR file. That will run the Frege compiler and also compile any Clojure code in the project.

Also, in order to include the Frege runtime in the resulting JAR file, you will need the following dependency in your `project.clj` file:

```clojure
:dependencies [[org.frege-lang/frege "3.24-7.100]]
```

The version here should exactly match that displayed by `lein-fregec` when you use the `DEBUG=true` environment variable!

This tells Leiningen that your project depends on Frege, and it will package it into the standalone JAR it produces. The standalone JAR can be run as follows:

```sh
java -cp target/frege-hello-0.1.0-SNAPSHOT-standalone.jar Hello
```

This assumes your `project.clj` starts out like this:

```clojure
(defproject frege-hello "0.1.0-SNAPSHOT"
  ...)
```

You can also run your (pure Frege) code by specifying `:run` and the class name (followed by any arguments for your `main` method):

```sh
lein fregec :run Hello
```

Arguments to the Frege compiler should come before `:run` (and can use `:` or `-` to introduce them). Arguments to the program being run should come after the class name (and are passed exactly as-is).

If you have tests, you can run those using `:test`:

```sh
lein fregec :test HelloTest
```

This is equivalent to:

```sh
lein fregec :run frege.tools.Quick HelloTest
```

You can pass flags to QuickCheck like this:

```sh
lein fregec :test -v HelloTest
```

which is equivalent to:

```sh
lein fregec :run frege.tools.Quick -v HelloTest
```

There will also be a non-standalone JAR will which does not contain the Frege runtime.

An example of a pure Frege project can be found in the [hello directory](https://github.com/Frege/frege-lein-plugin/tree/master/hello) which is a self-contained Leiningen project with its own README.

An example of mixed Clojure / Frege usage can be found in the [example directory](https://github.com/Frege/frege-lein-plugin/tree/master/example) which is also a self-contained project.

License
-------

Copyright (c) 2014-2016 Sean Corfield

Distributed under the BSD License, the same as Frege.

repository: Frege/frege-lein-plugin

gha_language: Clojure

repo_name: Frege/frege-lein-plugin


text:
# Change Log

## Latest

## 7.1.1
- [patch] - Excluded `__html` from `@typescript-eslint/naming-convention`

## 7.1.0
- [minor] - This creates a new rule for enums and enum props

## 7.0.1
- [patch] - Fixed a typo in the rule name

## 7.0.0
- [major] - Updated the warns to errors and added new rules to account for the latest ts parse. Also updated ts parsers

## 6.2.0

- [minor] - Updated dependencies and fixed lint

## 6.1.0

- [minor] - Added `@typescript-eslint/naming-convention` with warnings
- [patch] - Removed `@typescript-eslint/camelcase`
- [patch] - Turned `no-use-before-define` off
- [patch] - Turned `react/jsx-sort-props` off
- [patch] - Turned `@typescript-eslint/no-unsafe-member-access` off
- [patch] - Turned `@typescript-eslint/no-use-before-define` off
- [patch] - Turned `@typescript-eslint/restrict-plus-operands` off
- [patch] - Turned `@typescript-eslint/no-unsafe-assignment` off
- [patch] - Replaced `interface-name-prefix` with `naming-convention`

## 6.0.0

- [major] - Updated typescript to 4, the next major version

## 5.0.0

- [major] - Moved temp warnings over to Errors for FE

## 4.1.0

- [minor] - Adding 2 rules for FE

## 4.0.0

- [patch] - Moving our warnings over to errors

## 3.1.2

- [patch] - Adding new warnings prior to a major bump

## 3.1.1

- [patch] - Updated dependencies

## 3.1.0

- [minor] - Added `appnexus/typescript`
- [patch] - Changed `promise/always-return` from error to off

## 3.0.1

- [patch] - Dependency updates

## 3.0.0

- [minor] - Frontend: `promise/always-return` no longer errors
- [minor] - `no-console` allows warn, info, error
- [major] - Added prettier and rules as warning

## 2.0.2

- [patch] - fixed experimentalObjectRestSpread error

## 2.0.0

- [major] - Upgraded dependencies
- [major] - warning promoted to errors

## 1.6.0

- [minor] - Added warning for `no-undef` to become error in next major release
- [minor] - Added warning for `jsx-quotes` to become error in next major release
- [minor] - Added warning for `react/prop-types` to become error in next major release

## 1.5.1

- Removed peerDependencies

## 1.5.0

- [minor] - Added js and jsx extensions to `import/resolver` settings in `frontend`

## 1.4.0

- [minor] - Removed `quote-props` lint rule

## 1.3.0

- [minor] - Changed `quote-props` to 'consistent-as-needed'
- [patch] - Allow indentation for case statements

## 1.2.0

- [minor] - Added warning for `quote-props` to become error in next major release

## 1.1.0

- Added Changelog
- [minor] - Dropping `space-infix-ops` rule for now
- [minor] - Removed unused `promise/no-native`
- [minor] - Removed `no-else-return`
- [minor] - Added warnings for rules added by `eslint:recommend` to become errors in next major release
- Now inherits from `eslint:recommend`

## 1.0.2

- First official release

repository: appnexus/eslint-config-appnexus

repo_name: appnexus/eslint-config-appnexus


text:
bible-reading-planner
=====================

Bible reading planner generates a list of verses to read each day.

A user supplies the sequence, reading amount, and duration of the reading plan.

[See it live](http://khornberg.github.com/bible-reading-planner)

## Releases

### 0.1.0
Inital release.

## Potential Additions

- i18n
- Progress tracking

## Credits

### Bible reading plan sequences
Uses [devkardia's](https://github.com/devkardia/bibleplan/tree/master/readingplans) plans and created [json versions](https://github.com/khornberg/readingplans/) of the reading plans.

### For the Application
[bible.js](https://github.com/johndyer/bibly)
[Twitter Bootstrap](http://getbootstrap.com)
[Twix](http://icambron.github.io/twix.js/)
[Moment](http://momentjs.com)
[FileSaver](http://eligrey.com/blog/post/saving-generated-files-on-the-client-side)

repository: khornberg/bible-reading-planner

repo_name: khornberg/bible-reading-planner


text:
# Greengrass Deployments

Deployment is the process to send components and apply the desired component configuration to a destination target device (at the edge), which can be a single Greengrass core device or a group of Greengrass core devices.

repository: rvaughan/til

repo_name: rvaughan/til


text:
# Human Emotion Recognition from Speech

## Motivation and Idea
Usually in TV shows some person will be playing background song(s) . He/She takes decison based on the topic being discussed in the room(say) . He plays songs of his own choice . The person need to be little knowledgeable to do this task . But being a human he / she might makes mistakes and needs better experience to learn .
My idea is to automate this process. So this application `plays` the `songs` based on the __emotions in the speech__ .

I have considered briefly 4 *Emotion classes*
* 1. Neutral
* 2. Angry
* 3. Happy
* 4. Sad

## Idea Implementation
I have built a **Deep Neural Network** of two hidden layers. For each class, I have considered 100 training examples of recorded human voices in .wav format . The model is trained with all the class datasets . I have used __LSTM neural networks__ as input layers. The output layer is just a 4 nodes layer which gives an array of probability values of each classes . The class having max-probability value is considered as the predicted output .
With epocs ``50`` the accuracy of ``0.91176`` is observed. Based on the models output the Emotion behind the voice is captured and a song from the pre-defined lib is played to either console the person or to entertain the person.

A sample prediction output will be
```
Iterations =  50 / 50

 32/271 [==>...........................] - ETA: 0s - loss: 0.0113 - acc: 1.0000
 64/271 [======>.......................] - ETA: 0s - loss: 0.0111 - acc: 1.0000
 96/271 [=========>....................] - ETA: 0s - loss: 0.0116 - acc: 1.0000
128/271 [=============>................] - ETA: 0s - loss: 0.0111 - acc: 1.0000
160/271 [================>.............] - ETA: 0s - loss: 0.0112 - acc: 1.0000
192/271 [====================>.........] - ETA: 0s - loss: 0.0114 - acc: 1.0000
224/271 [=======================>......] - ETA: 0s - loss: 0.0155 - acc: 0.9978
256/271 [===========================>..] - ETA: 0s - loss: 0.0151 - acc: 0.9980
271/271 [==============================] - 1s 4ms/step - loss: 0.0147 - acc: 0.9982

32/68 [=============>................] - ETA: 0s
68/68 [==============================] - 0s 1ms/step

32/68 [=============>................] - ETA: 0s
68/68 [==============================] - 0s 1ms/step
Accuracy = 0.9117647058823529
Prediction  array [0.1621124  0.00876429 0.80469954 0.02442372]

```
*This means that the model has predicted the given voice as **HAPPY** with ``91.176%`` accuracy*

## DataSets
This dataset is available here [Emo-db](http://www.emodb.bilderbar.info/download/)

## Tools and Technologies being used
* Python
  * Tensorflow
  * Numpy
  * Speechpy
  * Sklearn
* Pycharm IDE


text:
# Gigasecond

Given a moment, determine the moment that would be after a gigasecond
has passed.

A gigasecond is 10^9 (1,000,000,000) seconds.

## Setup

Go through the setup instructions for Java to install the necessary
dependencies:

[https://exercism.io/tracks/java/installation](https://exercism.io/tracks/java/installation)

# Running the tests

You can run all the tests for an exercise by entering the following in your
terminal:

```sh
$ gradle test
```

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the
`@Ignore("Remove to run test")` annotation.

## Source

Chapter 9 in Chris Pine's online Learn to Program tutorial. [http://pine.fm/LearnToProgram/?Chapter=09](http://pine.fm/LearnToProgram/?Chapter=09)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have
completed the exercise.


text:
# Accessibility Cases on Android
There are different kind of accessibility services that you can implement depends on your app's needs. I summarized them and a bunch of programming edge cases that I have had to face in multiple projects… almost all of them made me scream at least once.

* How to turn ON/OFF TalkBack accessibility service through my app
* How to send accessibility focus to a specific UI element after TalkBack gets started
* Accessibility with mvvm and delegate pattern
* Navigate through a Grid
* Navigating through Carousel (an horizontal RecyclerView)
* Disabling buttons with accessibility
* Different TalkBack ports and Android versions

### architecture
MVVM with accessibility interaction.

### Branches
* hello_accessibility: used to explain basic accessibility xml attributes.
* master: contains almost all edge cases explained in section 2 of <medium post>

### Libraries
* Dagger2
* AndroidX
* Android accessibility suite

### License
Copyright 2020 [Miguel Hincapie C]

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

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

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

https://stackoverflow.com/users/1332549/miguelhincapiec

https://github.com/miguelhincapie

https://www.linkedin.com/in/miguelhincapie/

repository: miguelhincapie/AccessibilityCases

repo_name: miguelhincapie/AccessibilityCases


text:
---
layout: page
show_meta: false
title: "Getting Started"
subheadline: "A Step-by-Step Guide"
teaser: "This step-by-step guide helps you to customize Feeling Responsive to your needs."
header:
   image_fullwidth: "header_homepage_13.jpg"
permalink: "/getting-started/"
---
1. Open `_config.yml` and work it through, it's well documented
1. Add your own `logo.png` to `/assets/img/`.
1. Open `_data/socialmedia.yml` and add your own social media links.
1. Open `_data/navigation.yml` and customize your navigation.
1. Open `_data/language.yml` and translate the theme if necessary.
1. Open `_data/services.yml` and customize links in the footer.
1. Open `_data/network.yml` and customize links in the footer.
1. Open `_data/authors.yml` and edit author information and set default author in `config.yml`.
1. [Read the documentation][1] to check out all features of *Feeling Responsive*.
1. Make it yours and add your own content.

Check out the documentation for all the tricks ›

 [1]: {{ site.url }}{{ site.baseurl }}/documentation/


text:
# Real Time Database

## Real Time Service

If you want to sync your store with your real time database, you can do that now with the `RealTimeService`.

If you want to initialize this service you can do so like in the example below:

```typescript
import { RealTimeConfig } from 'akita-ng-fire/rtdb';
import {Database} from '@angular/fire/database';

@Injectable({ provideIn: 'root' })
@RealTimeConfig({ nodeName: 'vehicles' })
class VehicleService extends RealTimeService<VehicleState> {
  constructor(store: VehicleStore, db: Database) {
    super(store, 'vehicles', db);
  }
}
```

- The first parameter is the akita store you want to link to this service.
- The second parameter is the name of the node.
- The third parameter is the Firebase Database, but it is optional.

### Sync node with the store

In order to sync your node with your store you need to call the `syncNodeWithStore` function.
This function returns an observable that you need to subscribe to.
We recommend subscribing to this observable in the `canActivate` function in a guard and
unsubscribing in the `canDeactivate` function.

### Hooks

This service has two hooks: `formatToDatabase` and `formatFromDatabase`.
These two hooks can be overwritten in your service and can be modified as you want.

repository: dappsnation/akita-ng-fire

repo_name: dappsnation/akita-ng-fire


text:
---
title: Failing is bad but Giving up is worse!
layout: post
author: jaymin.bhatt
permalink: /failing-is-bad-but-giving-up-is-worse!/
source-id: 1oPnnS9VA_rdzL2wBiKgzIS-EYpAiwSuMWoNwWHD_vzM
published: true
---

    Title
    Failing is bad but Giving up is worse!
    Date
    12/1/17

    Starting point:
    Understand how easy it is for majority of the teachers in the UK to let you give up

    Target for this lesson?
    Remember that Failing can be good sometimes but giving up is never a positive act

    Did I reach my target?
(add details to "Lesson Review")
    I reached my target after a talk from our teacher

    Lesson Review

    How did I learn? What strategies were effective?

    We watched a video, about a small boy trying to jump over a gymnastic apparatus. He attempted this jump many times but failed every time. Every time, he failed his teacher made him go back to the starting point and attempt the jump again and again until he succeeded. Honesty was a very important part of today's lesson. Our teacher, asked us questions about failure and giving up such as Have you ever given up on something before? If we had, which I’m everyone has done in their life, we had to be honest about it and actually learn something from this lesson and take away many important tips.

    What limited my learning? Which habits do I need to work on?

    I talked in the lesson, when I wasn’t meant to, so I need to make sure that I am listening so I don’t miss any important tips.

    What will I change for next time? How will I improve my learning?

    I need to make sure I listen, to take away key information that will help improve my learning but also to make my blogs more detailed and more interesting to read.

** **


text:
# The Apache NuttX Companion

This is the [Apache NuttX Companion](https://nuttx-companion.readthedocs.io), a warm and friendly guide to all
things [Apache NuttX](https://nuttx.apache.org)– how to install it, configure it, develop on it, debug it, improve
it, get help from its community, and generally have fun with this very capable, configurable,
fast, POSIX-compatible, internet-connected real-time operating system.

Hopefully this guide will complement the Apache NuttX documentation, filling in gaps when needed, and
providing more help for people interested in learning about NuttX.

You can see the HTML version of this book here: [Apache NuttX Companion](https://nuttx-companion.readthedocs.io).

## Building the Documentation

This book is written in [ReStructured Text (RST)](https://docutils.sourceforge.io/rst.html), and built using
the excellent [Sphinx](https://www.sphinx-doc.org/) documentation system.

To install it, first install Python 3.8 or later and [Pipenv](https://pipenv-fork.readthedocs.io/en/latest/).
Then do:

```
$ cd nuttx-companion
$ pipenv install
$ pipenv shell
$ cd docs
$ make html

```

The documentation will be in the `_build/html` directory. You can open `_build/html/index.html`.

## Contributing

If there's anything you would like to improve, send me an email or a pull request! See
[Contributing to the NuttX Companion](https://nuttx-companion.readthedocs.io/en/latest/user/contributing.html)
for more information.

cheers

adam

--

Adam Feuer

Seattle, WA, USA

repository: adamfeuer/nuttx-companion

repo_name: adamfeuer/nuttx-companion


text:
## bme590hrm
####**Heart Rate Monitor Assignment**

#####*Deepthi Nacharaju*

[![Build Status](https://travis-ci.org/Deepthi-Nacharaju/bme590hrm.svg?branch=master)](https://travis-ci.org/Deepthi-Nacharaju/bme590hrm)

**Notes on Operation:**
- Changing the butterworth cutoff frequency changes progam's ability to detect different types of peaks.
Frequently used values include *0.0045, 0.005 (default), 0.0055 and 0.006*. These can be changed in the
 main function as *filter_value*.

- If the maximum distance between two peaks is more than a specified distance from the average distance
(indicating wide distribution), peak detection will run again after adding 0.002 to the cutoff frequency.
This will cycle 3 times.

**Additional Capabilities:**

- Data identified as bad will print as such in the excel file

- Opens and writes to an excel file in data folder called *Beat_Tracking.xlsx*. Records number of beats found
over the entire interval. Then highlights the cell in different colors if different than the hand counted value
in the previous column. Use this to quickly determine how changes affect peak detection functionality across
all 30+ csv files.

- Running *main.py* from the terminal followed by a tuple with starting and ending time points will allow user to interactively change bpm calculation window.

For example:

```
python main.py (0, 60)
```
will choose 0 to 60 seconds. This can also be changed from within the main.py when calling *user_input()*

####MIT License

Copyright (c) [2018] [Deepthi Nacharaju]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
# 1. Overview

This package provides methods and resources related to the robot safety, specifically the risk management.
The main components of this package are the risk assessment and the risk mitigation. The risk management is implementing _fuzzy logic_ method and the risk mitigation is implementing _fuzzy logic_ and _reinforcement learning_ methods.

# 2. Risk Management

The risk management comprises the pipeline to address the safety. Here safety means the injury risk associated to the human and robot collaboration.

* The first component of the risk management is the **risk assessment**, which is responsible for analyzing all the existing risks in the scenario and evaluate the risk level.

The risk assessment rules are stored in the `assessment_rules.py`.

* The second component is the **risk mitigation**, which is responsible for reducing the risk based on the risk analysis.

The risk mitigation using fuzzy logic system is implemented in ´risk_mitigation_fls.py´ and the rules are stored in the `mitigation_rules.py`.

The risk mitigation using reinforcement learning with fully connected network is implemented in  `risk_mitigation_mlp.py`

The risk mitigation using reinforcement learning with convoloutional neural network is implemented in  `risk_mitigation_cnn.py`

The risk mitigation using reinforcement learning with hybrid network is implemented in  `risk_mitigation_hybrid.py`

# 3. Running the Risk Assessment and Mitigation (Risk Management)

Before running the risk assessment and risk mitigation module, make sure the simulation, navigation, and scene graph generator module is running.
The simulation scenario must be running and have the correct map. The map can be checked by running the navigation module:

```
roslaunch turtlebot2i_navigation turtlebot2i_navigation_single.launch
```
The scene graph generator can be run by calling:
```
rosrun turtlebot2i_scene_graph scene_graph_generator.py
```

The risk assessment can be run by executing the both commands:
```
rosrun turtlebot2i_safety risk_assessment.py
rosrun turtlebot2i_safety zone_generation.py
```

The risk mitigation can be run by executing one of the following commands:
```
rosrun turtlebot2i_safety risk_mitigation_fls.py
```
or you can replace `fls` with either `mlp`, `cnn`, or `hybrid` to run the reinforcement learning models.

Alternatively, it is possible to run the launch script (this script also runs the navigation and scenegraph generator modules along with the risk assessment and risk mitigation modules):
```
roslaunch turtlebot2i_safety turtlebot2i_safety_fls.launch
```
or
```
roslaunch turtlebot2i_safety turtlebot2i_safety_train_rl.launch
```

**The use case scenarios compatible to this package is located in the scenario folder (`scott-eu/simulation-ros/src/turtlebot2i/turtlebot2i_description/v-rep_model/warehouse_turtlebot2i.ttt`).**

# 4. Generating Rules for Risk Assessment or Management

New rules can be generated or the rule file can be appended to make the robot address new situations.
There are three ways to do that:

## 4.1. Directly edit the rule file (`assessment_rules.py` or `mitigation_rules`)

The new rule must have the following format:
```python
rule001 = ctrl.Rule(object_type['StaObj'] & object_distance['Near'] & object_direction['Front'] , object_risk['VeryHigh'])
```
The rule number must be increased accordingly.

## 4.2. Build a training dataset and train a fuzzy logic/neuro-fuzzy model

Follow the scripts in the `Labeling_tools` folder.

# 5. Training mode

To train the risk mitigation module using reinforcement learning, change the following variables in the file `risk_mitigation_XXX.py`:

On ReinforceAgent initialization:
```
self.load_model = False
self.load_episode = 0
```

On main:
```
training_mode = True
```

# 6. Safety Message

A custom message *safety_zone_msg* that informs the size of safety zones is provided. It formed by four fields:

- **Header:** Standard ROS header message.
- **clear_safety_zone_radius:** Radius size of the robot's most external safety zone.
- **warning_safety_zone_radius:** Radius size of the robot's intermediary safety zone.
- **critical_safety_zone_radius:** Radius size of the robot's most internal safety zone.

repository: qiuhualiu/scott-eu

repo_name: qiuhualiu/scott-eu


text:
snapscale/libraries/fc is the cell-level module of the SnapScale project, which defines the basic variable data structure in the SnapScale project, including String, Time, Publickey, Privatekey, Signature, Base series encoding, etc.
<br>

---

snapscale/libraries/fc 是SnapScale项目的单元级别模块，它定义了SnapScale项目中基本变量的数据结构，包括String，Time，Publickey，Privatekey，Signature，Base系列编码等。

repository: snapscale/fc

repo_name: snapscale/fc


text:
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/

title: "Project Euler Problem 1: Multiples of 3 and 5"
subtitle: ""
summary: ""
authors: [grae]
tags: [Euler]
categories: []
date: 2020-05-22T16:12:38-07:00
lastmod: 2020-05-22T16:12:38-07:00
featured: false
draft: false

# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
  caption: ""
  focal_point: ""
  preview_only: false

# Projects (optional).
#   Associate this post with one or more of your projects.
#   Simply enter your project's folder or file name without extension.
#   E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
#   Otherwise, set `projects = []`.
projects: []
---

This is a lovely [problem](projecteuler.net/problem=1) to start with. It has a straightforward brute-force loop solution as well as a nice analytic solution where you can calculate the solution directly without the need for much programming. And it's [fizzbuzz](https://en.wikipedia.org/wiki/Fizz_buzz#Programming)! What a great way to dive in.

## Who is this for?
A quick note: this series of posts is meant for people who already have a development environment set up and are familiar with the very basics of Python. If you've never written a line of Python before I recommend [Data Camp's Python introduction](https://learn.datacamp.com/courses/intro-to-python-for-data-science) or another free Python 3 tutorial that covers the basics of **variables**, **basic types** (ints, floats, strings, booleans), **operations**, **lists**, **dictionaries**, and **functions**. If you're an experienced programmer but new to Python check out the "official" [Python Tutorial](https://docs.python.org/3/tutorial/). And if you're comfy writing Python but don't have a good local development environment set up yet check out [Problem 0: Getting Started](/) [TODO].

Also, this is meant for people who enjoy solving or reading about [Project Euler](projecteuler.net) problems. PE has this to say about sharing solutions:

> We hope that you enjoyed solving this problem. Please do not deprive others of going through the same process by publishing your solution outside of Project Euler. Members found to be spoiling problems beyond #100 will have their accounts locked (see note).
>
> Note: The rule about sharing solutions outside of Project Euler does not apply to the first 100 problems, as long as any discussion clearly aims to instruct methods, not just provide answers, and does not directly threaten to undermine the enjoyment of solving later problems. Problems 1 to 100 provide a wealth of helpful introductory teaching material and if you are able to respect our requirements, then we give permission for them to be discussed elsewhere.

I take PE's requirements about sharing information seriously and hope you will too. I love that so much of the programming world happens in the open with public repos and such, but you won't find my work on problems 101+ here, on GitHub, or anywhere else public.

## The Problem
Ok, let's talk about threes and fives. Before we analyze it together, [take a few minutes alone with Problem 1](https://projecteuler.net/problem=1). Set up a Project Euler account if you haven't already. Consider how you _might_ solve it. Take a stab at writing a solution before moving on. I'll wait.

...

## Iterative Solutions
Great, you're back. Let's dive in. The most straightforward way to solve this problem is to look at every number from one to a thousand, test whether it's divisible by 3 or 5, and add it to our running total if it is:

```python {linenostart=199}
result = 0
integers = range(1, 1000)
for x in integers:
  if x % 3 == 0 or x % 5 == 0:
    result += x

print(result)
```

In this solution we initialize our result to `0`, use a `for` loop to iterate over every integer from `1` through `1000`, test whether it's divisible by `3` or `5` using the modulo operator (`%`) and add it to our `result` variable if it is. Bam.

### Using List Comprehensions
[List comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) can be an elegant and "pythonic" way to solve problems. Here's the same iterative solution above using a list comprehension rather than a loop.

```python
print(sum([x for x in range(1, 1000) if x % 3 == 0 or x % 5 == 0]))
```

Now isn't that short and sweet. I love list comprehensions. They can get ugly fast, and it's possible to overuse them, but comprehensions excel in cases like this where you can express a few lines of procedural code as a single thought.

### A More Functional Approach
Python isn't known for being a naturally functional language, but it's certainly possible to use it that way. You can use `filter()` in place of the comprehension above:

```python
print(sum(filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1, 1000))))
```

Looking at this approach next to the comprehension above it's easy to see why the comprehension is more idiomatic: it just reads easier.

And of course it's no fun to talk about functional programming without contorting `reduce()` into a solution:

```python
from functools import reduce
print(reduce(
    lambda x, y: x + y if y % 3 == 0 or y % 5 == 0 else x,
    range(1, 1000),
    0
))
```

With Python 3 `reduce()` is no longer a built-in function and instead needs to be imported from the `functools` library. That makes me sad. I can understand why (a comprehension is _almost_ always more practical), but speaking as an apostle of [_Reduce, God of Parentheses_](https://www.youtube.com/watch?v=Wl98eZpkp-c&feature=youtu.be&t=18) I have to say I miss having it an my fingertips.

# Analytic solution
The iterative solutions above all rely on generating a list of integers, checking them one by one, and adding them up. That works just fine when you're only counting to a thousand and you have modern computing resources at your fingertips. But things aren't always so easy. What if we were solving this for all integers up to a quadrillion? What if we were working in an environment with limited memory or compute? What if we needed to run this solution gajillions of times every second?

You might have heard a [famous anecdote about Gauss](https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss#Anecdotes) and how as a young kid he summed the numbers from 1 to 100 in just a few seconds. He didn't actually add all the numbers together, he recognized a pattern in the arithmetic progression 1, 2, 3, ... 99, 100 and used a formula instead. Specifically, you can "fold" the sequence and match pairs like 1 + 100, 2 + 99, 3 + 98, ... 49 + 52, 50 + 51. There are exactly 50 such pairs and each pair equals 101, so the total sum is 101 * 50 = 5,050.

This approach works with _any_ arithmetic progression. We could sum all multiples of 5 below a hundred by "folding" the sequence 5, 10, 15, ... 95, 100 and getting 10 pairs that equal 105 for a total sum of 1,050.

In general, the formula to calculate the [sum of an arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression#Sum) is: `number_of_terms * (first_term + last_term) / 2`.

How does this apply to our fizzbuzz problem? The integers we're summing don't form a nice arithmetic progression. And we can't just add the sum of multiples of three to the sum of multiples of five, because that would double-count numbers like 15 and 30. And 45. And 60. See a pattern?

The trick is in recognizing that we're dealing with _three_ arithmetic progressions.  If we want the sum of all numbers that are a multiple of three _or_ a multiple of five, we can find that by adding `sum(multiples_of_three` to `sum(multiples_of_five)` and then _subtracting_ `sum(multiples_of_fifteen)`.

```python
def simple_arithmetic_series(step, limit):
    first = step
    count = (limit - 1) // step
    last = step * count
    return count * (first + last) / 2

multiples_of_3 = simple_arithmetic_series(3, 1000)
multiples_of_5 = simple_arithmetic_series(5, 1000)
multiples_of_15 = simple_arithmetic_series(15, 1000)

print(multiples_of_3 + multiples_of_5 - multiples_of_15)
```

# Evil optimization
The analytic solution involves a lot more typing and it isn't as simple to read and understand, so why is it better?

Well, it _isn't_ better. There are tradeoffs between the analytic solution and the iterative solution. Neither is inherently better. Deciding which approach is better for you depends on your context.

In the context of this specific problem, _the iterative solution works just fine_. It's faster to conceive and implement, it's easier to understand, and less code is less chance for things to break.

This is an example of **premature optimization**, and as Donald Knuth famously said, "[premature optimization is the root of all evil](https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize)". Spending time optimizing things we don't need to isn't just a waste of time better spent elsewhere, it also makes our programs worse: harder to understand and maintain.

That said, it's easy to think of cases where the tradeoffs might play out the other way. What if we were working with much larger numbers? Try plugging in bigger numbers to the iterative and analytic solutions and watch where the difference in performance starts to get noticeable. My laptop struggles to run the iterative solution above about a hundred million. Even the world's biggest supercomputer, [Summit](https://en.wikipedia.org/wiki/Summit_(supercomputer)) doesn't have enough memory to store a list of all integers up to a quadrillion. But my dinky laptop can calculate `simple_arithmetic_series(3,<PHONE_NUMBER>000000)` with no noticeable delay. With the right algorithm, my laptop can do something that's literally impossible for the world's best supercomputer.

Those numbers seem ridiculous but spoiler alert: Project Euler is going to start throwing hefty numbers at us pretty quick. As we dig deeper performance, resources, and [computational complexity](https://en.wikipedia.org/wiki/Computational_complexity_theory) are going to get critically important.

repository: Grae-Drake/academic-kickstart

repo_name: Grae-Drake/academic-kickstart


text:
# AnyFixture

Fixtures are a great way to increase your test suite performance, but for a large project, they are very hard to maintain.

We propose a more general approach to lazy-generate the _global_ state for your test suite – AnyFixture.

With AnyFixture, you can use any block of code for data generation, and it will take care of cleaning it out at the end of the run.

Consider an example:

```ruby
# The best way to use AnyFixture is through RSpec shared contexts
RSpec.shared_context "account", account: true do
  # You should call AnyFixture outside of transaction to re-use the same
  # data between examples
  before(:all) do
    # The provided name ("account") should be unique.
    @account = TestProf::AnyFixture.register(:account) do
      # Do anything here, AnyFixture keeps track of affected DB tables
      # For example, you can use factories here
      FactoryGirl.create(:account)

      # or with Fabrication
      Fabricate(:account)

      # or with plain old AR
      Account.create!(name: "test")
    end
  end

  # Use .register here to track the usage stats (see below)
  let(:account) { TestProf::AnyFixture.register(:account) }

  # Or hard-reload object if there is chance of in-place modification
  let(:account) { Account.find(TestProf::AnyFixture.register(:account).id) }
end

# You can enhance the existing database cleaning. Posts will be deleted before fixtures reset
TestProf::AnyFixture.before_fixtures_reset do
  Post.delete_all
end

# Or after reset
TestProf::AnyFixture.after_fixtures_reset do
  Post.delete_all
end

# Then in your tests

# Active this fixture using a tag
describe UsersController, :account do
  # ...
end

# This test also uses the same account record,
# no double-creation
describe PostsController, :account do
  # ...
end
```

See real life [example](http://bit.ly/any-fixture).

## Instructions

### RSpec

In your `spec_helper.rb` (or `rails_helper.rb` if you have one):

```ruby
require "test_prof/recipes/rspec/any_fixture"
```

Now you can use `TestProf::AnyFixture` in your tests.

### Minitest

When using AnyFixture with Minitest, you should take care of cleaning the database after each test run by yourself. For example:

```ruby
# test_helper.rb

require "test_prof/any_fixture"

at_exit { TestProf::AnyFixture.clean }
```

## DSL

We provide an optional _syntactic sugar_ (through Refinement) to make it easier to define fixtures and use callbacks:

```ruby
require "test_prof/any_fixture/dsl"

# Enable DSL
using TestProf::AnyFixture::DSL

# and then you can use `fixture` method (which is just an alias for `TestProf::AnyFixture.register`)
before(:all) { fixture(:account) }

# You can also use it to fetch the record (instead of storing it in instance variable)
let(:account) { fixture(:account) }

# You can just use `before_fixtures_reset` or `after_fixtures_reset` callbacks
before_fixtures_reset { Post.delete_all }
after_fixtures_reset { Post.delete_all }
```

## `ActiveRecord#refind`

TestProf also provides an extension to _hard-reload_ ActiveRecord objects:

```ruby
# instead of
let(:account) { Account.find(fixture(:account).id) }

# load refinement
require "test_prof/ext/active_record_refind"

using TestProf::Ext::ActiveRecordRefind

let(:account) { fixture(:account).refind }
```

## Temporary disable fixtures

Some of your tests might rely on _clean database_. Thus running them along with AnyFixture-dependent tests, could produce failures.

You can disable (or delete) all created fixture while running a specified example or group using the `:with_clean_fixture` shared context:

```ruby
context "global state", :with_clean_fixture do
  # or include explicitly
  # include_context "any_fixture:clean"

  specify "table is empty or smth like this" do
    # ...
  end
end
```

How does it work? It wraps the example group into a transaction (using [`before_all`](./before_all.md)) and calls `TestProf::AnyFixture.clean` before running the examples.

Thus, this context is a little bit _heavy_. Try to avoid such situations and write specs independent of the global state.

## Usage report

`AnyFixture` collects the usage information during the test run and could report it at the end:

```sh
[TEST PROF INFO] AnyFixture usage stats:

       key    build time  hit count    saved time

      user     00:00.004          4     00:00.017
      post     00:00.002          1     00:00.002

Total time spent: 00:00.006
Total time saved: 00:00.019
Total time wasted: 00:00.000
```

The reporting is off by default, to enable the reporting set `TestProf::AnyFixture.config.reporting_enabled = true` (or you can invoke it manually through `TestProf::AnyFixture.report_stats`).

You can also enable reporting through the `ANYFIXTURE_REPORT=1` env variable.

## Using auto-generated SQL dumps

> @since v1.0, experimental

AnyFixture is designed to generate data once per a test suite run (and cleanup in the end). It still could be time-consuming (e.g., for system or performance tests); thus, we want to optimize further.

We provide another way of speeding up test data called `#register_dump`. It works similarly to `#register` for the first run: it accepts a block of code and tracks SQL queries made within it. Then, it generates a plain SQL dump representing the data creating or modified during the call and uses this dump to restore the database state for the subsequent test runs.

Let's consider an example:

```ruby
RSpec.shared_context "account", account: true do
  # You should call AnyFixture outside of transaction to re-use the same
  # data between examples
  before(:all) do
    # The block is called once per test run (similary to #register)
    TestProf::AnyFixture.register_dump("account") do
      # Do anything here, AnyFixture keeps track of affected DB tables
      # For example, you can use factories here
      account = FactoryGirl.create(:account, name: "test")

      # or with Fabrication
      account = Fabricate(:account, name: "test")

      # or with plain old AR
      account = Account.create!(name: "test")

      # updates are also tracked
      account.update!(tag: "sql-dump")
    end
  end

 # Here, we MUST use a custom way to retrieve a record: since we restore the data
 # from a plain SQL dump, we have no knowledge of Ruby objects
  let(:account) { Account.find_by!(name: "test") }
end
```

And that's what happened when we run tests:

```sh
# first run
$ bundle exec rspec

# AnyFixture.register_dump is called:
# - is SQL dump present? No
# - run block and write all modifying queries to a new SQL dump
# AnyFixture.clean is called:
# - clean all the affected tables

# second run
$ bundle exec rspec

# AnyFixture.register_dump is called:
# - is SQL dump present? Yes
# - restore dump (do not run block)
# AnyFixture.clean is called:
# - clean all the affected tables
```

### Requirements

Currently, only PostgreSQL 12+ and SQLite3 are supported.

### Dump invalidation

The generated dump could become out of date for many reasons: database schema changed, fixture block has been updated, etc.
To deal with invalidation, we use file content digests as _cache keys_ (dump file name suffixes).

By default, AnyFixture _watches_ `db/schema.rb`, `db/structure.sql` and the file that calls `#register_dump`.

The list of default watch files could be updated by modifying the `default_dump_watch_paths` configuration parameter:

```ruby
TestProf::AnyFixture.configure do |config|
  # you can use exact file paths or globs
  config.default_dump_watch_paths << Rails.root.join("spec/factories/**/*")
end
```

Also, you add watch files to a specific `#register_dump` call via the `watch` option:

```ruby
TestProf::AnyFixture.register_dump("account", watch: ["app/models/account.rb", "app/models/account/**/*,rb"]) do
  # ...
end
```

**NOTE:** When you use the `watch` option, the current file is not added to the watch list. You should use `__FILE__` explicitly for that.

Finally, if you want to forcefully re-generate a dump, you can use the `ANYFIXTURE_FORCE_DUMP` environment variable:

- `ANYFIXTURE_FORCE_DUMP=1` will force all dumps regeneration.
- `ANYFIXTURE_FORCE_DUMP=account` will force regeneration only of the matching dumps (i.e., matching `/account/`).

#### Cache keys

It's possible to provide custom cache keys to be used as a part of a digest:

```ruby
# cache_key could be pretty much anything that responds to #to_s
TestProf::AnyFixture.register_dump("account", cache_key: ["str", 1, {key: :val}]) do
  # ...
end
```

### Hooks

#### `before` / `after`

Before hooks are called either before calling a fixture block or before restoring a dump.
One particular use case is to re-create a tenant in a multi-tenant app:

```ruby
TestProf::AnyFixture.register_dump(
  "account",
  before: proc do
    begin
      Apartment::Tenant.create("test")
    rescue
      nil
    end
    Apartment::Tenant.create("test")
  end
) do
  # ...
end
```

Similarly, after hooks are called either after calling a fixture block or after restoring a dump.

You can also specify global before and after hooks:

```ruby
TestProf::AnyFixture.configure do |config|
  config.before_dump do |dump:, import:|
    # dump is an object containing information about the dump (e.g., dump.digest)
    # import is true if we're restoring a dump and false otherwise
    # do something
  end

  config.after_dump do |dump:, import:|
    # ...
  end
end
```

**NOTE**: after callbacks are always executed, even if dump creation failed. You can use the `dump.success?` method to determine whether data generation succeeds or not.

#### `skip_if`

This callback is available only as of the `#register_dump` option and could be used to ignore the fixture completely. This is useful when you want to preserve the database state between test runs (i.e., do not clean the DB).

Here is a complete example:

```ruby
TestProf::AnyFixture.register_dump(
  "account",
  # do not track tables for AnyFixture.clean (though other fixtures could affect this)
  clean: false,
  skip_if: proc do |dump:|
    Apartment::Tenant.switch!("test")
    # if the current account has matching meta — the database is in actual state
    Account.find_by!(name: "test").meta["dump-version"] == dump.digest
  end,
  before: proc do
    begin
      Apartment::Tenant.create("test")
    rescue
      nil
    end
    Apartment::Tenant.create("test")
  end,
  after: proc do |dump:, import:|
    # do not persist dump version if dump failed or we're restoring data
    next if import || !dump.success?

    Account.find_by!(name: "test").then do |account|
      account.meta["dump-version"] = dump.digest
      account.save!
    end
  end
) do
  # ...
end
```

### Configuration

There a few more configuration options available:

```ruby
TestProf::AnyFixture.configure do |config|
  # Where to store dumps (by default, TestProf.artifact_path + '/any_dumps')
  config.dumps_dir = "any_dumps"
  # Include mathing queries into a dump (in addition to INSERT/UPDATE/DELETE queries)
  config.dump_matching_queries = /^$/
  # Whether to try using CLI tools such as psql or sqlite3 to restore dumps or not (and use ActiveRecord instead)
  config.import_dump_via_cli = false
end
```

**NOTE:** When using CLI tools to restore dumps, it's not possible to track affected tables and thus clean them via `AnyFixture.clean`.

repository: test-prof/test-prof

gha_language: Ruby

repo_name: test-prof/test-prof