text:
# NeRF: Neural Radiance Fields
### [Project](http://tancik.com/nerf) | [Video](https://youtu.be/JuH79E8rdKc) | [Paper](https://arxiv.org/abs/2003.08934)

Tensorflow implementation of optimizing a neural representation for a single scene and rendering new views.

[NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis](http://tancik.com/nerf)
 [Ben Mildenhall](https://people.eecs.berkeley.edu/~bmild/)\*1,
 [Pratul P. Srinivasan](https://people.eecs.berkeley.edu/~pratul/)\*1,
 [Matthew Tancik](http://tancik.com/)\*1,
 [Jonathan T. Barron](http://jonbarron.info/)2,
 [Ravi Ramamoorthi](http://cseweb.ucsd.edu/~ravir/)3,
 [Ren Ng](https://www2.eecs.berkeley.edu/Faculty/Homepages/yirenng.html)1

 1UC Berkeley, 2Google Research, 3UC San Diego
  \*denotes equal contribution

## Setup

Python 3 dependencies:

* Tensorflow 1.15
* matplotlib
* numpy
* imageio
*  configargparse

The LLFF data loader requires ImageMagick.

You will also need the [LLFF code](http://github.com/fyusion/llff) (and COLMAP) set up to compute poses if you want to run on your own real data.

## What is a NeRF?

A neural radiance field is a simple fully connected network (weights are ~5MB) trained to reproduce input views of a single scene using a rendering loss. The network directly maps from spatial location and viewing direction (5D input) to color and opacity (4D output), acting as the "volume" so we can use volume rendering to differentiably render new views.

Optimizing a NeRF takes between a few hours and a day or two (depending on resolution) and only requires a single GPU. Rendering an image from an optimized NeRF takes somewhere between less than a second and ~30 seconds, again depending on resolution.

## Running code

### Optimizing a NeRF

Run
```
bash download_example_data.sh
```
to get the our synthetic Lego dataset and the LLFF Fern dataset.
To optimize a low-res Fern NeRF:
```
python run_nerf.py --config config_fern.txt
```
To optimize a low-res Lego NeRF:
```
python run_nerf.py --config config_lego.txt
```

### Rendering a NeRF

Run
```
bash download_example_weights.sh
```
to get a pretrained high-res NeRF for the Fern dataset. Now you can use the `render_demo.ipynb` to render new views.

## Generating poses for your own scenes

We recommend using the `imgs2poses.py` script from the [LLFF code](https://github.com/fyusion/llff). Then you can pass the base scene directory into our code using `--datadir <myscene>` along with `-dataset_type llff`. You can take a look at the `config_fern.txt` config file for example settings to use for a forward facing scene.

repository: supanat/nerf

repo_name: supanat/nerf


text:
# uptime

[<-Back-to:Auth](database-auth.md)

**The \`uptime\` table**

This table holds the server's uptime. The core will automatically update the latest entry's value until it crashes and a new record is added.

**Structure**

| Field           | Type         | Attributes | Key | Null | Default     | Extra | Comment |
| --------------- | ------------ | ---------- | --- | ---- | ----------- | ----- | ------- |
| [realmid][1]    | INT          | UNSIGNED   | PRI | NO   |             |       |         |
| [starttime][2]  | INT          | UNSIGNED   | PRI | NO   | 0           |       |         |
| [uptime][3]     | INT          | UNSIGNED   |     | NO   | 0           |       |         |
| [maxplayers][4] | SMALLINT     | UNSIGNED   |     | NO   | 0           |       |         |
| [revision][5]   | VARCHAR(255) | SIGNED     |     | NO   | AzerothCore |       |         |

[1]: #realmid
[2]: #starttime
[3]: #uptime
[4]: #maxplayers
[5]: #revision

**Description of the fields**

### realmid

The ID of the realm. See [realmlist.id](realmlist#id).

### starttime

The time when the server was started, in Unix time.

### uptime

The uptime of the server, in seconds.

### maxplayers

The maximum number of players connected.

### revision

The detailed revision of the worldserver.

license: MIT

repository: azerothcore/wiki

branch_name: refs/heads/master

extension: md

gha_language: CSS

gha_license_id: MIT

license_type: permissive

repo_name: azerothcore/wiki


text:
# Monthly active subscriptions report

Compute (at the end of each month) the total number of active subscriptions per product and billing period.

The snapshot view is: `v_report_active_by_product_term_monthly`

## Timeline configuration

```
curl -v \
     -X POST \
     -u admin:password \
     -H "X-Killbill-ApiKey:bob" \
     -H "X-Killbill-ApiSecret:lazar" \
     -H 'Content-Type: application/json' \
     -d '{"reportName": "report_active_by_product_term_monthly",
          "reportType": "TIMELINE",
          "reportPrettyName": "Monthly active subscriptions",
          "sourceTableName": "report_active_by_product_term_monthly",
          "refreshProcedureName": "refresh_active_by_product_term_monthly",
          "refreshFrequency": "DAILY"}' \
     "http://<IP_ADDRESS>:8080/plugins/killbill-analytics/reports"
```

repository: killbill/killbill-analytics-plugin

gha_language: Java

repo_name: killbill/killbill-analytics-plugin


text:
Getting Started [![Build Status](https://travis-ci.org/twitterdev/twitter-ruby-ads-sdk.svg?branch=master)](https://travis-ci.org/twitterdev/twitter-ruby-ads-sdk)[![Gem Version](https://badge.fury.io/rb/twitter-ads.svg)](http://badge.fury.io/rb/twitter-ads)
------

##### Installation
```bash
# installing the latest signed release
gem install twitter-ads
```

##### Quick Start
```ruby
require 'twitter-ads'

# initialize the client
client = TwitterAds::Client.new(
  CONSUMER_KEY,
  CONSUMER_SECRET,
  ACCESS_TOKEN,
  ACCESS_TOKEN_SECRET
)

# load the advertiser account instance
account = client.accounts('c3won9gy')

# load and update a specific campaign
campaign = account.campaigns('4m0gjms')
campaign.entity_status = EntityStatus::PAUSED
campaign.save

# iterate through campaigns
account.campaigns.each do |camp|
  # do stuff
end
```

##### Command Line Helper
```bash
# The twitter-ads command launches an interactive session for testing purposes
# with a client instance automatically loaded from your .twurlrc file.

~ ❯ twitter-ads
twitter-ads vX.X.X >> CLIENT
=> #<TwitterAds::Client:0x70101526238580 consumer_key="Fy90KQy57152sn5Mv7axji9409">
twitter-ads vX.X.X >> CLIENT.accounts.first
=> #<TwitterAds::Account:0x70101527905720 id="4lvtcum">
```
For more help please see our [Examples and Guides](https://github.com/twitterdev/twitter-ruby-ads-sdk/tree/master/examples) or check the online [Reference Documentation](http://twitterdev.github.io/twitter-ruby-ads-sdk/reference/index.html).

## Compatibility & Versioning

This project is designed to work with Ruby 2.4.0 or greater. While it may work on other version of Ruby, below are the platform and runtime versions we officially support and regularly test against.

Platform | Versions
-------- | --------
MRI | 2.4.x, 2.5.x, 2.6.x, 2.7, 3.0
Rubinius | 2.4.x, 2.5.x

All releases adhere to strict [semantic versioning](http://semver.org). For Example, major.minor.patch-pre (aka. stick.carrot.oops-peek).

## Development
If you'd like to contribute to the project or try an unreleased development version of this project locally, you can do so quite easily by following the examples below.
```bash
# clone the repository
git clone git@github.com:twitterdev/twitter-ruby-ads-sdk.git
cd twitter-ruby-ads-sdk

# install dependencies
bundle install

rake docs # building documentation
rake spec # run all tests

# installing a local unsigned release
gem build twitter-ads.gemspec & gem install twitter-ads-X.X.X.gem
```
We love community contributions! If you're planning to send us a pull request, please make sure read our [Contributing Guidelines](https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/master/CONTRIBUTING.md) first.

## Feedback and Bug Reports
Found an issue? Please open up a [GitHub issue](https://github.com/twitterdev/twitter-ruby-ads-sdk/issues) or even better yet [send us](https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/master/CONTRIBUTING.md) a pull request.

Have a question? Want to discuss a new feature? Come chat with us in the [Twitter Community Forums](https://twittercommunity.com/c/advertiser-api).

## Error Handling

Like the [Response](https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/master/lib/twitter-ads/http/response.rb) and [Request](https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/master/lib/twitter-ads/http/request.rb) classes, the Ads API SDK fully models all [error objects](https://github.com/twitterdev/twitter-ruby-ads-sdk/blob/master/lib/twitter-ads/error.rb) for easy error handling.

## License

The MIT License (MIT)

Copyright (C) 2021 Twitter, Inc.

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.

repository: twitterdev/twitter-ruby-ads-sdk

gha_language: Ruby

repo_name: twitterdev/twitter-ruby-ads-sdk


text:
# Pose-estimation
### Position numbers for different positions.
![positions_numbers](pose_tracking_full_body_landmarks.png)

### sample photos of results.
![first](tests/1.png)
![second](tests/2.png)
![third](tests/3.png)
![fourth](tests/4.png)
![fifth](tests/5.png)
![sixth](tests/6.png)

Reference for the project:\
[Murtaza's Workshop - Robotics and AI](https://www.youtube.com/watch?v=brwgBf6VB0I&t=1788s&ab_channel=Murtaza%27sWorkshop-RoboticsandAI)

gha_language: Python


text:
### The Power of Exploits

If you work for a company that doesn’t have a strong AppSec team, or a company that has not seen powerful (or public) exploitation of their assets, you need to write some exploits.

***Never underestimate the power of a good exploit.***

A good exploit will dramatically change the business' and developer's perception of what security actually means to their company.

But, when you do write them, they have to be very professional, and look the part. Ideally, they should show a criminal business model that makes sense in the industry you are in. For example you could show data being extracted, sold, and manipulated by remote attackers.

It is important that you show those exploits to all parts of the company. From legal, to business-owners, to architects, to developers. You know you've one it right, when your've answered the question _"Why should we do security/appsec?"_

So, if you should find yourself having to justify security, then you’re at a stage where you need some really good professional exploits that will allow people in management to ask the right questions.

And those questions are, _"Can you fix it? Can you solve 'that' security issue from hitting my company? Because I don’t want 'that' (the demo you’ve just done) to happen here.”_


text:
Credits
=======

"robotonotebook" is written and maintained by Simon Griffee.

Contributors
------------

The following kind people contributed directly or indirectly to this project:

- Hynek Schlawack <https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/>
- Peter Downs <http://peterdowns.com/posts/first-time-with-pypi.html>
- Stephen McDonald <https://groups.google.com/d/msg/mezzanine-users/bdqjepkhtzc/dG0xl9qx4kEJ>

Please add yourself here alphabetically when you submit your first pull request.

repository: hypertexthero/mezzanine-robotonotebook

repo_name: hypertexthero/mezzanine-robotonotebook


text:
---
title: /mobile/register
position: 26
type: put
description: Update the status of token mobile device to send push notifications
---
user_id
: The id of the object previously stored

token
: The token of the mobile device

status
: The status of the token, active or inactive

Update the status of token mobile device to send push notifications
{: .success }

~~~ shell
curl -i -XPUT -H "Ckey: YOUR_APP_CKEY" -d '{"user_id": "ID", "token": "TOKEN", "status": "active"}' http://api.hurakann/v1/mobile/register
~~~
{: title="cURL" }

repository: zgbjgg/aviator-jekyll-template

repo_name: zgbjgg/aviator-jekyll-template


text:
## robotron1715-font

This utility takes [Robotron 1715](https://en.wikipedia.org/wiki/PC_1715) ([ru](https://ru.wikipedia.org/wiki/Robotron_1715)) character ROM and saves font to [BDF format](https://en.wikipedia.org/wiki/Glyph_Bitmap_Distribution_Format), which can be used in Unix or converted to other format (for example, [PSF](https://en.wikipedia.org/wiki/PC_Screen_Font)). It serves no purpose except historical interest.

Currently, only Latin ROM (see `s619.bin` below) is included in bdf.

### Preview

| Latin character ROM (s619.bin) | Cyrillic character ROM (s605.bin) | Latin+Cyrillic character ROM (s643.bin) |
| ---- | --- | --- |
| ![Latin](https://github.com/kolontsov/robotron1715-font/blob/master/s619.png)  | ![Cyrillic Only](https://github.com/kolontsov/robotron1715-font/blob/master/s605.png) | ![Latin+Cyrillic](https://github.com/kolontsov/robotron1715-font/blob/master/s643.png) |

### Install

~~~ bash
cp robotron1715.bdf ~/.fonts
fc-cache -f -v
~~~

In Ubuntu, you may need to [enable bitmap fonts first](https://wiki.ubuntu.com/Fonts#Enabling_Bitmapped_Fonts). Also, when using font choose it's native size 16 (it doesn't scale well).

### Rebuild

~~~ bash
pip3 install pypng
./rb1715font.py
~~~

By default, it loads `s619.bin` and generates `robotron1715.bdf` (font) and `robotron1715.png` (preview).

### License

MIT


text:
GIT HOOKS
=========================================================================================================

Generic hooks checking the coding style, specifying the type of commit and syntax checking the commit.

HOW TO USE THIS PROJECT?
=========================================================================================================

- Clone this repo inside at the root of your project : $ git clone https://github.com/NIRALUser/SetupHooks.git
- You need to have KWStyle installed. Please refer to this page http://www.itk.org/Wiki/ITK/Release_4/Coding_Style/KWStyle if you do not have it. Once built, add the path of the executable KWStyle to your PATH variable : export PATH=$PATH:{path_to_KWStyle} in bash, or setenv PATH=$PATH:{path_to_KWStyle} in tcsh. If you want a permanent setup, you can add the path of KWStyle to your PATH environment variable directly in .bashrc or .tcshrc (depending on the shell you use).
- Run the script which will set up the hooks (and add this cloned repo to the ignore list, so it does not pollute your own commits):
  - $ cd SetupHooks
  - $ git checkout Utilities
  - At this point, you might want to check KWStyle.xml.in and modify it to suit your coding preferences.
  - $ ./SetupGitHooks
- You can commit as you used to do and continue your project with these new hooks.

NOTE: If needed, git commit --no-verify will enable you to bypass the hooks.

FEATURES
=========================================================================================================

Pre-commit hook:
- Auto removes trailing whitespaces.
- Uses KWStyle in order to check your coding style (according to the style sheet KWStyle.xml.in that you can edit), prompt errors (which files and which lines do not respect the style).

Prepare-commit-msg hook:
- Modifies the instructions in the commit message: the user has to write a flag in the beginning of his commit message.
Available flags are as follow:
- BUG: - fix for runtime crash or incorrect result
- COMP: - compiler error or warning fix
- DOC: - documentation change
- ENH: - new functionality
- PERF: - performance improvement
- STYLE: - no logic impact (indentation, comments)
- WIP: - Work In Progress not ready for merge

Commit-msg hook:
- Checks the flag of the commit message (it has to respect the instructions given in the prepare-commit-msg).
- Checks the number of characters (default is 78).

IN PROGRESS
=========================================================================================================

- Write a script which automatically corrects the style if run (independant of the hooks, so you can still commit if you dont want to follow the style, for instance if the previous commit didnt follow the style either).

repository: NIRALUser/SetupHooks

repo_name: NIRALUser/SetupHooks


text:
# Lab 5: Dashboards

## Requirements

* Previous labs completed
* APM Application reporting to New Relic

## Setup

1. Uncomment the lab5 section in `main.tf` as follows:

   ```
   #
   # Dashboards
   #
   module "lab5" {
     source = "./lab5"

     application_id = module.lab1.application_id
   }
   ```

1. Save the file

## Edits

1. Edit `lab5.tf` with a text editor of your choice.
1. (optional) Change the name of the dashboard, or explore some of the NRQL
   queries.
1. Save the file

## Apply

1. Run `terraform init`
1. Run `terraform plan`, you should get output similar to the following:

   ```
   ```

1. Run `terraform apply` to create the alert policy, ensuring there are no errors.

gha_language: HCL


text:
# LogitechLed

Unreal Engine 4 plug-in for Logitech LED illumination keyboards.

![Logo](Docs/logo.png)

## About

This plug-in implements Blueprint functions for controlling the LED lights
in supported Logitech keyboards and mice.

Make sure to pull the Tag that matches your Unreal Engine version. If you sync
to Master the code may not compile, because it may depend on Engine changes that
are not yet available in the UE4 Master branch.

## Supported Platforms

This plug-in was last built against **Unreal Engine 4.19** with
*Logitech LED SDK 8.87* and tested on the following platforms:

- Windows

## Dependencies

This plug-in requires Visual Studio and either a C++ code project or the full
Unreal Engine 4 source code from GitHub. If you are new to programming in UE4,
please see the official [Programming Guide](https://docs.unrealengine.com/latest/INT/Programming/index.html)!

## Usage

You can use this plug-in as a project plug-in, or an Engine plug-in.

If you use it as a project plug-in, clone this repository into your project's
*/Plugins* directory and compile your game in Visual Studio. A C++ code project
is required for this to work.

If you use it as an Engine plug-in, clone this repository into the
*/Engine/Plugins* directory and compile your game. Full Unreal Engine 4
source code from GitHub is required for this.

## Support

Please [file an issue](https://github.com/ue4plugins/LogiLed/issues), submit a
[pull request](https://github.com/ue4plugins/LogiLed/pulls?q=is%3Aopen+is%3Apr)
or email us at<EMAIL_ADDRESS>

## References

* [Logitech G Developer Lab](http://gaming.logitech.com/en-us/developers)
* [Logitech Gaming Keyboards](http://gaming.logitech.com/en-us/gaming-keyboards)
* [Introduction to UE4 Plugins](https://wiki.unrealengine.com/An_Introduction_to_UE4_Plugins)

repository: Skjolnir/LogiLed

repo_name: Skjolnir/LogiLed


text:
# Revolver

Given a number of tests, Revolver uses genetic algorithms to write, or rather try to write, a Ruby program that satisfies those tests.

## Why on earth

FUN!

## Installation

Add this line to your application's Gemfile:

    gem 'revolver'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install revolver

## Usage

```ruby
require 'revolver'

# Write a program that returns a number between -500 and 500.
Revolver.new
  .return_value_should(-> retval { retval > -500 })
  .return_value_should(-> retval { retval < 500 })
  .go!
```

If `ENV['VERBOSE']` is set, it will spit out all the programs of all the
generations as they are being written.

## Who's this

This was made by [Josep M. Bach (Txus)](http://blog.txus.io) under the MIT
license. I'm [@txustice][twitter] on twitter (where you should probably follow
me!).

[twitter]: https://twitter.com/txustice

repository: txus/revolver

repo_name: txus/revolver


text:
## Wow, look!

[![Build Status](https://travis-ci.org/tomverran/wowlook.svg?branch=master)](https://travis-ci.org/tomverran/wowlook) [![Download](https://api.bintray.com/packages/tomverran/maven/wowlook/images/download.svg) ](https://bintray.com/tomverran/maven/wowlook/_latestVersion)

A charting library for Scala and Scala JS.
This is currently in the **very early** stages of development

### Installation

This library is available on Bintray, so in your `build.sbt`:

```scala
resolvers += Resolver.bintrayRepo("tomverran", "maven")
libraryDependencies += "io.tvc" %% "wowlook" % "0.3.0" // replace %% with %%% for ScalaJS
```

### Motiviation

I wanted to generate some charts based on some data I have in both the backend
(for static HTML files) and the frontend (for an admin tool) and I didn't have much fun
trying to either use existing Java libraries or Google Charts with ScalaJS.

As such this library generates simple (maybe _too_ simple) SVG charts.
An example of use can be found in `examples/shared/.../Examples.scala`

### Screenshots

These are screenshots of the examples:

#### Bar Chart

![image](https://user-images.githubusercontent.com/1388226/50562948-a9bec380-0d10-11e9-9654-fb1124a430d0.png)

#### Line Chart

![image](https://user-images.githubusercontent.com/1388226/50562946-a0cdf200-0d10-11e9-86d5-09ba94d4a9c6.png)

repository: tomverran/wowlook

repo_name: tomverran/wowlook


text:
pleonasm
========

Create English phrases from hex strings that are easier to recognize and remember

Try it out: http://w-m.github.io/pleonasm/

### Javascript API

```Javascript
.onload(fn)
```

Register a function to be called when the when the dictionaries are loaded and pleonasm is ready to use.

------------------------------------

```Javascript
.encode('601a9f')
```

Encode a hex string into an English phrase. Returns an object, with the key 'code' as the result:

```Javascript
{ translation: 'vulngf',
  codeWords: [ 'visualizing', 'free' ],
  code: 'visualizing free',
  spaced: 'v  u l   ng f   ' }
```

Can take wordDelimiter and groupDelimiter as additional arguments (see .format).

```Javascript
.encode('0167aa36cf832', '_', '/')
{ translation: 'ulvtnnmvcfwmk',
  codeWords:
   [ 'rule',  'veterinarian',
     'move',  'care',
     'fewer', 'mark' ],
  code: 'rule_veterinarian_move/care_fewer_mark',
  spaced: ' ul  v t   n    n m v  c    f w   m  k' }
```
------------------------------------

```Javascript
.decode('visualizing free')
```

Decode an English phrase to get a hex number.

```Javascript
{ hex: '601a9f',
  spaced: 'v  u l   ng f   ',
  translation: 'vulngf' }
```

------------------------------------

```Javascript
.format(codeWords, wordDelimiter, groupDelimiter)
```

Format an array of code words into a string. Words are connected with wordDelimiter (usually ' '), phrases of three words each are connected with groupDelimiter (usually ', ')).

### Javascript (Browser)

Files needed:
```
dictionaries/
-- adj.txt
-- noun.txt
-- verb.txt
js/
-- pleonasm.js
```

```HTML
<script src="js/pleonasm.js"></script>
<script>
  pleonasm.onload(function() {
    var encoded = pleonasm.encode('ad3a507').code;
  });
</script>
```

### node.js

Install via npm:

```
npm install pleonasm

npm test pleonasm
```

Usage:

```Javascript
var pleonasm = require('pleonasm');

pleonasm.onload(function() {
  var encoded = pleonasm.encode('ad3a507').code;
});
```

### Python

```Python
from pleonasm import Encoder, decode

enc = Encoder('../dictionaries')
encoded = enc.encode('601a9f')
print encoded # 'visualizing free'

decoded = decode('rule_veterinarian_move')
print decoded # '0167aa36'
```

### Acknowledgements and other projects

The dictionaries are created from the 1-grams of the [Google Ngram](http://books.google.com/ngrams) data.

The idea of the grammatical template stems from [tripphrase](http://worrydream.com/tripphrase/).

[humanhash](https://github.com/zacharyvoase/humanhash) creates hashes (compressed) from a 256-word dictionary.

repository: w-m/pleonasm

gha_language: JavaScript

repo_name: w-m/pleonasm


text:
---
layout: post
title: "Espressif officially supports LittlevGL on ESP32!  Let's try it!"
author: "kisvegabor"
cover: /assets/esp32/cover.png
image:
  path: /assets/esp32/cover.png
  height: 300
  width: 300

---

**Espressif [has announced](https://www.espressif.com/en/news/ESP32_Modules_Now_Support_LittlevGL_and_%CE%BCGFX) that they support LittlevGL on their ESP32 chips.
Adding GUI to your ESP32 based IoT device is easier than ever.  I made it work in 15 minutes, so it's really worth a try! I will show an other project too where I achieved 30 FPS with ESP32 on 320 x 240 display.**

These are some examples created by the Espressif:

![Audio player example on ESP32 with LittlevGL](/assets/esp32/esp_example1.jpg)
_Audio player example on ESP32 with LittlevGL_

<br>

![Coffee maker and thermostat example on ESP32 with LittlevGL](/assets/esp32/esp_example2.jpg)
_Coffee maker and thermostat example on ESP32 with LittlevGL_

# Still don't know ESP32?

[ESP32](https://www.espressif.com/en/products/hardware/esp32/overview) is powerful SoC (System on Chip) develped by [Espressif](https://www.espressif.com/en).
The modules built with the chip are extremely popular in IoT applications where **connectivity** and **low-power operation** are a must. In addition, ESP32 provides high performance with a **dual-core 200 MHz MCU**.
The modules are usually equipped with **external flash (typically 4 MB)** which can be mapped as program memory.

Regarding the connectivity, the modules come with **fully certified Wi-Fi, BT, and BLE** interfaces.

One of the most **popular modules** is [ESP32 WROOM](https://hu.mouser.com/ProductDetail/Espressif-Systems/ESP32-WROOM-32?qs=chTDxNqvsyltcwz%2FUUJDtQ%3D%3D) for **only $4**.

To get started you should buy a **development board** with an ESP32 module. For example [ESP32-DevkitC](https://hu.mouser.com/ProductDetail/Espressif-Systems/ESP32-DevKitC?qs=sGAEpiMZZMurtJ7VwBTl0Rm64lZhrtuCiot%2fLDk%252bF2ilRoHMowv5Wg%3d%3d)

![ESP32-DevKitC](/assets/esp32/esp_devkitc.jpg).

You **don't need any extra hardware** like a programmer because the ESP32 can be **programmed via a Serial Port** using a simple Micro USB cable.

# GUI with ESP32

Although the ESP32 chip doesn't have an RGB LCD interface or a parallel port to drive a display it has **fast SPI ports**.

[ILI9341](https://cdn-shop.adafruit.com/datasheets/ILI9341.pdf),
[ST7789](https://www.numworks.com/shared/binary/datasheets/st7789v-lcd-controller-73f8bc3e.pdf)
[SSD1306](https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf) are three display controllers which actually have SPI interface and you will find a lot of displays modules equipped with them.

## What graphical performance can you expect from ESP32?

There are two main things which determine the graphical performance:
1. **Rendering time** the time to draw a frame (or a part of it).
2. **Flushing time** the time to transfer the rendered image to the display.

The **rendering time** depends on the speed of the MCU. A GPU can speed it up but unfortunately, ESP32 doesn't have any. Anyway, a 200 MHz core speed should be fine the render nice GUIs fast enough!

The **flushing time** depends on the system's architecture and the peripheries of the MCU. In the case of ESP32, you need to use SPI to send the rendered frame to the display controller.

## Some calculations
By default the **maximum SPI clock speed** of ESP32 is **40 MHz**. What does it mean? On a 320x240 disply with 16 bit color depth you need to transfer  *320 x 240 x 16 = 1,228,000 bits*. On 40 MHz it means *1,228,000 / 40,000,000 = 30 ms*.

So to **transfer a full frame 30 ms** is required.

If you have e.g. 40 ms rendering time the whole process takes 70 ms which means only 14 FPS.

## How to speed ESP32 for GUI applications?

There are two options:
1. **Speed up SPI**
2. **Make the flushing and rendering parallel**

Let's discuss the **SPI speed** first. This table is from ILI9341's datasheet (page 230):

![ILI9341 SPI timing](/assets/esp32/ili9341_spi_timing.png)
_ILI9341 SPI timing_

The first line says the one clock period can be minimum 100 ns which means only 10 MHz. It would be extremely slow.

It turned out that ILI9341 actually [works at higher clock rates](http://www.eevblog.com/forum/microcontrollers/ili9341-lcd-driver-max-spi-clock-speed/) too.
They say 48MHz is even possible but it's still not a big gain compared to the 40 MHz in the previous calculation.

Anyway, in ESP32 you can **increase the SPI speed to 80 MHz** if you use dedicated pins.

According to the [ESP32 SPI documentation](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/spi_master.html#gpio-matrix-and-iomux):
> When the GPIO matrix is used, signals faster than 40MHz cannot propagate and the setup time of MISO is more easily violated, since the input delay of MISO signal is increased. The maximum clock frequency with GPIO Matrix is 40MHz or less, whereas using all IOMUX pins allows 80MHz.

So just choose the following SPI pins to have an 80 MHz clock speed:

![ESP32 SPI: 80 MHz pin configuration](/assets/esp32/esp_spi_80mhz.png)
_ESP32 SPI: 80 MHz pin configuration_

To drive a display only *MOSI* and *SCLK* is required from the table.

So let's use the faster pins. The maximum clock rate is still 40 MHz because of ILI9341 but hopefully, it will give better signals.

To **make the rendering and flushing parallel** you should use **SPI with DMA**. The DMA makes possible to send the rendered image via SPI in the background and let the CPU to do other things.
ESP32 supports using DMA with SPI so it's just the question of the driver and some LittlevGL configuration. (Enable `LV_VDB_DOUBLE` in `lv_conf.h`)

# Build and flush and official example

## Install ESP32 toolchain
To get started you need to **install ESP32 development toolchain**.  Refer to this [Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) and follow the steps.

## Get ESP IoT Solution
[ESP IoT Solution](https://github.com/espressif/esp-iot-solution) is a huge collection of
- drivers
- libraries
- and examples

Clone it somewhere (preferably in the `esp` folder where the toolchain was installed):
1. `cd ~/esp/`
2. `git clone https://github.com/espressif/esp-iot-solution --recurse-submodules`
3. `export IOT_SOLUTION_PATH=~/esp/esp-iot-solution`

## Configure an example
Choose an example and configure it:
1. `cd esp-iot-solution/examples/hmi/lvgl_example`
2. `make defconfig`
3. `make menuconfig`

In the **menuconfig** go to **IoT Solution Settings > IoT Component Management > HMI Components > LVGL Settings**

In **Config Driver**
- Choose your screen driver. In my case it was ILI9341
- Set the Screen pins as shown in the image below
- Set the LCD SPI clock to 40,000,000. It was the maximum value so the previously calculated 80 MHz can't be tried here.

![Configuration of ESP to run a LittlevGL example](/assets/esp32/menuconfig1.jpg)
_Configuration of ESP to run a LittlevGL example_

If you enter into Touch Screen pin configuration you will see only *CS* and *IRQ* pin settings.
Which means that it uses the same SPI as the Screen driver and the *MOSI*, *MISO* and *CLK* pins are shared.
However, my screen has dedicated SPI pins for the touchpad and the screen and I didn't have "Y" cables. So I disabled touchpad for now in "LittlevGL Touchscreen Enable".

In the main menu of *menuconfig* in  *Serial flasher config* be sure the correct Serial port is selected. (ESP32 needs to be connected to your PC to see which Serial port is used.)

After that save the settings and exit menuconfig.

## Build and flash
To build and flash type into the Terminal:
1. `make` to build the project. Or `make -j8` to build on 8 threads.
2. `make flash` to program the ESP

And the result is:
![Running an official LittlevGL example on ESP32](/assets/esp32/esp_official_littlevgl_example.jpg)
 _Running an official LittlevGL example on ESP32_

# LittlevGL with ESP-IDF directly
If you want a **more simple project** with more freedom you should use [ESP-IDF](https://github.com/espressif/esp-idf) which is the core ESP SDK.

There is a LittlevGL project you can use with ESP-IDF: [https://github.com/littlevgl/esp32_ili9431](https://github.com/littlevgl/esp32_ili9431)

This project comes with an **ILI9341** display driver and an **XPT2046** touchpad driver. The display driver uses DMA and **makes rendering and flushing parallel** which result in a decent frame rate.
You can customize these drivers according to your needs.

1. Get this projects: `git clone https://github.com/littlevgl/esp32_ili9431.git --recurse-submodules`
2. Add LittlevGL to the build. Copy `lvgl_component.mk` and `lv_example_component.mk` as `component.mk` to the `lvgl` and `lv_examples` directories respectively.
3. Connect the touch pad (optional):
    - MOSI : 32
    - MISO : 25
    - SCLK : 26
    - CS : 33
    - IRQ : 25

4. `make`
5. `make flash`

![ESP32 is running a LittlevGL example](/assets/esp32/esp32_littlevgl_gui.jpg)
_ESP32 is running a LittlevGL example_

## What FPS can be achieved?

With the GUI on the above image - by making rendering and flushing parallel - I achieved about **30 FPS**!

# Summary

ESP-IoT-Solution is a great an easy-to-use framework. As you can see it takes only a few minutes to get started.

However, you can use ESP-IDF as well to try LittlevGL. This way you will have more control over your project.

If you have a product with ESP32 and LittlevGL you can share it among [LittlevGL References](https://blog.littlevgl.com/2018-12-26/references).

repository: amirgon/blog

repo_name: amirgon/blog


text:
# demo-k8s-kubespray-gcp
Demo code for deployment of Kubespray to GCP

## Getting Started

The following below will guide you to getting started.
### Prerequisites

What things you need to install the software and how to install them
* git
* A service account json key from gcp with Compute Admin privilages, this will also be used to configure gcloud sdk
* terraform
* pip
* ansible
* Jinja2
* python-netaddr
* kubectl
* gcloud

### Prerequisites can be installed on default debian 9.5 or ubuntu 16.04 by running included script. You will need to have sudo on system:
```
sudo apt-get update && sudo apt-get install git -y
git clone https://github.com/cxhercules/demo-k8s-kubespray-gcp.git
cd demo-k8s-kubespray-gcp/
./scripts/ubuntu-install-prereqs.sh
```

### Installing
Create a new k8s deployment.

```
git clone https://github.com/cxhercules/demo-k8s-kubespray-gcp.git
cd demo-k8s-kubespray-gcp/k8s-impl/
cp -a impl-template <myproject>
cd <myproject>
vim terraform.tfvars
```

### Modify terraform.tfvars to fit your needs and we can go ahead with next step.
```
pub_key 		= "cust_id_rsa.pub"  	# path for a key to login to jumpbox, and other systems
api_key 		= "gcp-creds.json"	# GCP credentials file
region 			= "us-west1"
zone 			  = "us-west1-a"
project 		= "myproject"
res_prefix 	= "demo-k8s"
owner       = "cxh"
```

### Kickoff deployment with wrapper script
```
pwd
.../demo-k8s-kubespray-gcp/k8s-impl/<myproject>
./kubespray.sh
```
* While working out some issues ./kubespray.sh can be run multiple times.

Tear down k8s environment

```
cxh@jmp:~/demo-k8s-kubespray-gcp/k8s-impl/cxh-demo$ terraform destroy
random_id.rand: Refreshing state... (ID: HORoM6ngMUM)
data.template_file.nat-startup-script: Refreshing state...
google_compute_health_check.default: Refreshing state... (ID: demo-k8s-hc)
google_compute_health_check.mig-health-check: Refreshing state... (ID: demo-k8s-nat-gateway-us-west1-b)
...
...
  Plan: 0 to add, 0 to change, 30 to destroy.

  Do you really want to destroy?
    Terraform will destroy all your managed infrastructure, as shown above.
    There is no undo. Only 'yes' will be accepted to confirm.

    Enter a value: yes
```

## Troubleshooting

#Connection issues

At times I have run into cannot connect to master issues or other systems. If it is first run, it just might be intermittent. Still investigating if timing issue. I have just run once more, and problem has been resolved.

GCP SDK Setup
```
gcloud auth activate-service-account --key-file gcp-creds.json
Activated service account credentials for<EMAIL_ADDRESS>```

If you don't run above you may see this error when running kubespray.sh script:
```
ERROR: (gcloud.compute.instances.list) Some requests did not succeed:
 - Insufficient Permission
```

## Authors

* **Christian Hercules** - *Initial work* - [github](https://github.com/cxhercules)


text:
# Brute Force

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target−x.

```python
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

        raise ValueError('No two sum solution')
```

## Complexity Analysis

* Time complexity: O(n2).

For each element, we try to find its complement by looping through the rest of array which takes O(n) time. Therefore, the time complexity is O(n2).

* Space complexity: O(1).

[Next](solution2.md)

path: /Leetcode/1. Two Sum/solution1.md


text:
---
title: 'Create Custom AEM Menu Tools with Granite UI Shell'
type: 'blog'
category: 'AEM'
published: true
---

![ ](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/thumbnail.png)

H**[ello Friend!](https://en.wikipedia.org/wiki/Eps1.0_hellofriend.mov)** Have you ever wanted to build your custom menus under **_AEM Tools_** like **ACS AEM [Commons](https://adobe-consulting-services.github.io/acs-aem-commons/)** or **[Tools](https://adobe-consulting-services.github.io/acs-aem-tools/)**, then this story is for you!

Here, I have developed a **[XLS/XLSX to JSON Converter tool](https://github.com/vsr061/aem-excel-to-json)** which converts Excel file to a JSON and stores in JCR.

> _Code will be available **[here](https://github.com/vsr061/aem-excel-to-json)**_

In this tutorial we will learn about two major concepts which get used while _customizing_ AEM

- **Sling Resource Merger**

- **Granite UI**

So, let’s get started.

## **Sling Resource Merger**

The [Sling Resource Merger](https://helpx.adobe.com/in/experience-manager/6-4/sites/developing/using/sling-resource-merger.html) provides services to access and merge resources. It provides diff (differencing) mechanisms for both:

1.  **_Overlays:_** For overlays the resource delivered is an aggregate of the resources and properties retrieved, depending on search paths that can be defined.In a standard installation the primary defaults are **_/apps_**, **_/libs_** — so the content of **_/apps_** has a higher priority than that of **_/libs_** (i.e. it _overlays_ it). Means if you have a same node under **_/apps_** as that of under **_/libs_**, then AEM will read the results from **_/apps_**

2.  **_Overrides:_** It overrides of component dialogs for the touch-enabled UI (**cq:dialog**), using the resource type hierarchy (by means of the property **sling:resourceSuperType**).

> **The goal for using the Sling Resource Merger in AEM is to:**
>
> ensure that customization changes are not made in **/libs**.
>
> This is because the content of **/libs** is overwritten the next time you upgrade your instance (and may well be overwritten when you apply either a hotfix or feature pack).

for our tutorial we will use **_Overlays_** to overlay the AEM Tools node under **_/libs_** and create a similar node structure under **_/apps_**

It’s easy and can be done with one **right-click** on the following path and then select **Overlay Node …**

![Path: /libs/cq/core/content/nav/tools*](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p1.png)

![Then, select Match Node Types(Optional)](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p2.png)

So, it will create similar node structure as shown below:

![New Path: /apps/cq/core/content/nav/tools](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p3.png)

Now, we can add custom nodes here to add our Menu under Tools. So, to add new item to the Menu List, we can add a node of type **nt:unstructured** or a folder. I have added a folder of type **sling:OrderedFolder.** The next part is to add **_id_** and **_jcr:title,_**

1.  **id:** Here, id should be **unique**( The recommended value is hierarchical separated by “-“. e.g. “**cq-commerce-report**”)

2.  **jcr:title:** Renders the Title of the Menu Item.

![New node of custom-tools under tools](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p4.png)

![custom-tools node gets render as Custom Tools menu item with title coming from jcr:title property on the node](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p5.png)

Now, to create an actual tool option, we will add one more **nt:unstructured** node with following properties:

1.  **href:** Location of the **Tool’s landing page** (generally **cq:Page** under **/apps** or **/content**)

2.  **target: href** target attribute

3.  **icon:** You can give a name of a available icon in the [Coral UI](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/coral-ui/coralui3/Coral.Icon.html#availableIcons)

4.  **id:** Here, id should be **unique**( The recommended value is hierarchical separated by “-“. e.g. **"cq-commerce-report"**)

5.  **jcr:description:** Description for your tool

6.  **jcr:title:** Title for your tool

![Actual tool node: xls-to-json](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p6.png)

![Rendered Menu Option](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p7.png)

## **Granite UI**

> Granite Documentation will be available [here](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/index.html)

It’s a time to develop the Landing Page for our tool and this can be done in many ways, but still I have used Granite UI for the following reasons:

1.  It’s easy; just like creating your Touch UI Dialog with LEGO® Architecture.

2.  Easy to maintain.

3.  Less or no code required.

To create Landing Page, I have created a AEM multi-module maven project and added a page under **_/apps/excel-to-json/components/content_** developed using **[Granite UI Shell Page](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/shell/page/index.html)** component.

I have added the **Granite Server Side components** like **[FileUpload](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/form/fileupload/index.html)** and **[PathField](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/form/pathfield/index.html)** to upload the Excel file and to select the path to store converted JSON.

Excel file gets uploaded to a **[Servlet](https://github.com/vsr061/aem-excel-to-json/blob/master/core/src/main/java/com/excel/json/core/servlets/ExcelToJSONServlet.java)** and then it converts the table to JSON format, where each _row_ gets converted to a _JSON object_ with _column name_ as _property_ and cell value as the _property value_.

### **Granite UI Shell Page**

Granite Shell Page is the generic page to render Shell. So, it will get rendered as shown below:

![Blank Shell Page](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p8.png)

![cq:Page Node Structure for the Shell Page](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p9.png)

To know all the Shell page properties, you can refer **[this](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/shell/page/index.html)** page. I will focus on some main properties required to render the page:

**head:** A folder to specify the content of `<head>` of the page. Its child resources are iterated and included as is. You need to use **[IncludeClientlibs](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/includeclientlibs/index.html)** component to add your js and css libraries. Don’t forget to add **“granite.ui.coral.foundation”** category.

![IncludeClientlibs under head](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p10.png)

**title:** The component to render the title.

![title node](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p11.png)

**title** gets rendered to as shown below

![Rendered Title from title node](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p12.png)

**content:** The actual content of the page. Here, you can add _sling:resourceType_ for rendering script or use Granite UI Components as shown below:

![Granite UI Server Side components](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p13.png)

> **Final Page:**

![Final Landing Page](../media/2019-08-10-Create_Custom_AEM_Menu_Tools_with_Granite_UI_Shell/p14.png)

## **Code:**

[Github](https://github.com/vsr061/aem-excel-to-json)

> Check my other stories **_[here](/blogs)_**

## **References:**

1.  [Granite UI Documentation](https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/index.html)

2.  [Sling Resource Merger](https://helpx.adobe.com/in/experience-manager/6-4/sites/developing/using/sling-resource-merger.html)


text:
---
layout: book_page
title: Follow up with a thank you email after your job interview
subhead: Sample thank you emails you can send after a job interview
description: Even after you finish your job interviews, you can continue to impress and stay in touch by sending thanks you emails.
has_basic_bundle_pitch: true
context: interview
last_modified_at: 2016-06-29
book_section: 7
chapter: interview
section: 8
---
Now you’ve aced the Interview, but your work isn’t done yet—you still have a few more opportunities to stand out in the post-interview.

First, if you happen to have your interviewer's email address (we're calling him Andy), shoot him a very, very short email thanking him for his time. You’ll also want to discretely share your contact information just in case he needs it later. Unless there’s something specific he expects you to follow up on, don’t ask any new questions or give Andy any action items in this email. This is just a short email to say "Thanks!" and demonstrate professionalism; it shouldn’t require a response.

## A sample thank you email to send to your interviewer

	To: Andy Smith<EMAIL_ADDRESS>	Subject: Josh Doody interview—Thanks for your time!

Hi Andy

I just wanted to say thanks for your time today. It was great to learn more about ACME Corp, and about the Associate Accountant role in particular. ACME Corp sounds like a great company to work for!

Feel free to email or call anytime if you have any follow-up questions.

Thanks again for your time and have a great day!

All the best

Josh Doody

<EMAIL_ADDRESS>555-555-1234

You’ll also want to send an email to the recruiter if that person and Andy are different people. There’s one wrinkle here: If you *don’t* have Andy’s contact information, you’ll want to ask the recruiter thank him for you and let him know that you appreciated his time.

## A sample thank you email to send to the recruiter you're working with

	To: Shawn Jones<EMAIL_ADDRESS>	Subject: Josh Doody interview—Thanks for your time!

Hi Shawn

I hope you had a great weekend!

Thanks so much for arranging my interview with Andy today. It was great to learn more about ACME Corp, and about the Associate Accountant role in particular. ACME Corp sounds like a great company to work for!

If you talk with him, please thank Andy for me and let him know that I appreciated his time today.

If you need anything else from me, please let me know. Otherwise, I look forward to the next steps in our process!

All the best

Josh Doody

<EMAIL_ADDRESS>555-555-1234

repository: tnorthcutt/fsn-stage

branch_name: refs/heads/main

repo_name: tnorthcutt/fsn-stage


text:
# Getting Started

Compositor Iso is an isolated development environment for building pages, prototypes, and demos with React components and pure JSX.
Instead of needing to open a terminal, install dependencies, and configure
an application build setup,
Iso is completely self-contained,
letting you prototype with React components quickly with minimal overhead.

## JSX

JSX is an XML-like syntax to describe what UI should look like.
If you're familiar with HTML, JSX is similar but with a few key differences:

- All tags must be closed, since JSX is based on XML
- Instead of attributes, JSX uses *props*
- Some HTML attributes are different, to avoid JavaScript reserved words, e.g. use `className` instead of `class`, and `htmlFor` instead of `for`.
- Although JSX looks static, it's actually JavaScript under the hood

```jsx
// bad
<input>

// good
<input />
```

```jsx
// bad
<div class='blue' />

// good
<div className='blue' />
```

## Embedded JavaScript Expressions

With JSX, any [JavaScript expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) can be included by using curly braces.

```jsx
<h1>
  Hello {props.name}
</h1>
```

Expressions can also be used to define props on an element.

```jsx
<h1 id={props.title}>
  {props.title}
</h1>
```

### More About JSX

- [React: Introducing JSX](https://reactjs.org/docs/introducing-jsx.html)
- [React: JSX In Depth](https://reactjs.org/docs/jsx-in-depth.html)
- [JSX Specification](https://facebook.github.io/jsx/)

## Components

The really powerful part of JSX is the ability to use components.
JSX distinguishes between HTML elements and React components based on the capitalization of the tag name.

- Lowercase tags are HTML elements, e.g. `<h1 />`
- Capitalized tags are components, e.g. `<Heading />`

Iso comes with a small set of default components to get started with.

- `<Box />` general-purpose box-model layout component
- `<Flex />` flexbox layout component
- `<Text />` general-purpose typographic component
- `<Heading />` typographic component for headings
- `<Link />` general-purpose link (`<a />`)

Each of these components has its own props API for controlling styling,
based on [styled-system](https://github.com/jxnblk/styled-system).

Read more about Iso [components](components.md).

## Configuration

To use a custom component library or theme with Iso, create an `iso.config.js` file in your project directory. This file should be compatible with with Node.js and browser environments and export `components` and `theme` objects.

In your project folder, ensure all npm dependencies are installed.

```
// example iso.config.js
const Rebass = require('rebass')

module.exports = {
  components: Rebass,
  theme: Rebass.theme
}
```

### Troubleshooting Configurations

- Ensure the module is Node.js compatible
- Ensure all dependencies are installed in your project folder
- Ensure the file does not use JSX or other Babel or webpack features

React more about [configuration](configuration.md)

repository: stereoplegic/iso

repo_name: stereoplegic/iso


text:
<!-- DO NOT EDIT THIS FILE! -->
<!-- Instead edit recipe/pimcore.php -->
<!-- Then run bin/docgen -->

# How to Deploy Pimcore

[Source](/recipe/pimcore.php)

## How to deploy a Pimcore project with zero downtime?

- First, [install](/docs/installation.md) the Deployer.
- Second, require `recipe/pimcore.php` recipe into your _deploy.php_ or _deploy.yaml_ file.
- Third, and now you can have a zero downtime deployment!

Did you know that you can deploy **Pimcore** project with a single command? Just execute `dep deploy`.
Something went wrong? Just run `dep rollback` to rollback your changes.
Also, you can take an advantage of the [Deployer's CLI](/docs/cli.md) to deploy your project.

Another feature of the Deployer is [provisioning](/docs/recipe/provision.md). Take any server, and run `dep provision` command.
This command will configure webserver, databases, php, https, and more.
You will get everything you need to run your **Pimcore** project.

Deployer does next steps to [deploy](#deploy) **Pimcore**:
* Displays info about deployment
* Prepares host for deploy
* Locks deploy
* Prepares release
* Updates code
* Creates symlinks for shared files and dirs
* Makes writable dirs
* Installs vendors
* Clears cache
* Creates symlink to release
* Unlocks deploy
* Cleanup old releases

The pimcore recipe is based on the [symfony](/docs/recipe/symfony.md) recipe.

## Tasks

### pimcore:rebuild-classes
[Source](https://github.com/deployphp/deployer/blob/master/recipe/pimcore.php#L15)

Rebuilds Pimcore Classes.

### pimcore:custom-layouts-rebuild
[Source](https://github.com/deployphp/deployer/blob/master/recipe/pimcore.php#L20)

Creates Custom Layouts.

### pimcore:cache_clear
[Source](https://github.com/deployphp/deployer/blob/master/recipe/pimcore.php#L25)

Removes cache.

### pimcore:deploy
[Source](https://github.com/deployphp/deployer/blob/master/recipe/pimcore.php#L29)

This task is group task which contains next tasks:
* [pimcore:rebuild-classes](/docs/recipe/pimcore.md#pimcorerebuild-classes)
* [pimcore:custom-layouts-rebuild](/docs/recipe/pimcore.md#pimcorecustom-layouts-rebuild)

repository: marvinhinz/deployer

gha_language: PHP

repo_name: marvinhinz/deployer


text:
---
layout: post
title: "Your Ex-Lover Is Dead"
date: 2011-07-12 1:35
categories: [music, transcriptions, piano]

artist: "Stars"
---

This is one of my favorite songs. Back in 2005, Canadian Indie band Stars released this song as a single. In 2007, they released another album aptly entitled [_Do You Trust Your Friends?_][trust] full of remixes by, well, their friends. Well-known artist [Owen Pallett][owen pallett], then known as [Final Fantasy][final fantasy], took it upon himself to arrange this song for piano, vocals and strings.

[YouTube video of the song][owen pallett video] (Owen Pallett’s version)

[The original Stars version][stars video]

This is a song I really wanted to learn to play on the piano and sing. Usually I’m great at picking things up by ear, but the orchestra playing along with the piano made it difficult in this case. I decided to see if there was any sheet music that had been printed for the song. Unfortunately, I found only a single, unofficial transcription that pretty much sucked. I got fed up and decided to transcribe it myself. I think I did a really good job, and I’m fairly sure it’s at as accurate as it can be.

So, without further ado, [this is my transcription][sheet music] for Owen Pallet's version of "Your Ex-Lover Is Dead" by Stars for piano and vocals. As far as I can tell, it's extremely accurate. Here's a video so you can hear how it sounds before you play it yourself.

[trust]: http://en.wikipedia.org/wiki/Do_You_Trust_Your_Friends%3F
[owen pallett]: http://en.wikipedia.org/wiki/Owen_Pallett
[final fantasy]: http://www.dominorecordco.com/uk/news/18-12-09/final-fantasy-name-change-to-owen-pallett/
[owen pallett video]: http://www.youtube.com/watch?v=x4cZyF2i5yw
[stars video]: http://www.youtube.com/watch?v=r5Or6-HOveg
[sheet music]: http://dl.dropbox.com/u/94814/Slingshot/Pictures/Your%20Ex-Lover%20Is%20Dead%20(Final%20Fantasy).pdf


text:
# Lab 03: Deploying to Lambda and API Gateway (Serverless)

## Goal

Add another step to your pipeline: deploy the sample application to AWS Lambda and API Gateway, aka. Serverless.

## Instructions

Make sure you are starting from the starting point for Lab 03.

```
cp lab03-serverless/starting-point/pipeline.yml deploy/pipeline.yml
cp lab03-serverless/starting-point/serverless.json infrastructure/serverless.json
```

The template `infrastructure/serverless.yml` contains the following resources and utilizes the [AWS Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md):

* AWS Lambda
* API Gateway
* CloudWatch alarms
* SNS topic

You need to extend the `pipeline.yml` template which already contains:

1. The sample solution from Lab 02.
1. A `Production` stage with two empty actions `CreateChangeSet` and `ApplyChangeSet` (search for `TODO`).

For the first time you need to hand over results between different stages and actions of your pipeline. Doing so is possible with a `TemplateConfiguration`. You need to complete the file `infrastructure/serverless.json`.

Commit and push your changes and watch your pipeline to build and test the application.

```
git add deploy/pipeline.yml
git add infrastructure/serverless.json
git commit -m "lab 03"
git push deploy master
```

## Help

* CloudFormation [AWS::CodePipeline::Pipeline](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html)
* CodePipeline [Pipeline Structure Reference](https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-pipeline-structure.html)
* [AWS CloudFormation Configuration Properties Reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-action-reference.html)
* [AWS CloudFormation Artifacts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-cfn-artifacts.html)


text:
Increases the contrast of the image by blocks, the larger the block, the larger the area that is thresholded at one time. Invert flips the values of the image, making black into white and vice versa. gauss determines whether the image is to be thresholded usinga Gaussian method or simply a plain thresholding. Below you can see the result of using adaptive threshold with two different values.

```cpp
left.adaptiveThreshold(20);
right.adaptiveThreshold(50);
```

![Thresholding an image](ofxCvGrayscaleImage.adaptiveThreshold.example.png)


text:
# ismir-home

Jekyll version of the ISMIR Homepage

[![Build Status](https://travis-ci.com/ismir/ismir-home.svg?branch=master)](https://travis-ci.com/ismir/ismir-home)

## Contributing (the simple version)

In most cases, this website can be updated by the following process:

* fork the website
* make one or more edits
* create a pull request

For minor changes, it may be sufficient to edit the website source (of your fork) *directly in your web browser*. Once your pull request has been approved and merged, the changes will propagate to the live website.

That's it! Simple, right!?

## Contributing Upstream

Not all of the content in this website originates from *this* repository, which is a downstream consumer of three information sources:

- [conference-archive](http://github.com/ismir/conference-archive): Collection of publication metadata
- [mir-datasets](http://github.com/ismir/mir-datasets): Collection of MIR datasets
- Individual conference websites

### Publication Metadata

If you notice that any publication metadata is incorrect, either here or over at [Zenodo](http://zenodo.org), please submit corrections to the [conference-archive](http://github.com/ismir/conference-archive) repository, which maintains the source data for all ISMIR publications.

This is doubly true for missing PDFs. If possible, please provide a URL or upload the PDF in the issue so that we can more easily fix things.

### Datasets

If you would like to add to or update the [list of datasets](http://ismir.net/resources/datasets/) found on this website, please submit corrections to the [mir-datasets](http://github.com/ismir/mir-datasets) repository, which maintains the collection provided here.

### Conference Websites

The websites of past conferences are being migrated to individual repositories in the ISMIR GitHub organization. Each is being served as a separate GitHub pages site, mapped to the corresponding subdomain.

If you find any **major** issues with these websites, please identify the appropriate repository and create an issue (or ideally a pull request!) there. Please note, however, that these websites are provided primarily for historical purposes, and are in a state of critical-issue only maintenance, *e.g.* only significant issues may be addressed (and even then...).

## Developing Locally

This website is written with Jekyll for simplified automatic deployment via GitHub pages. If you are only ever pushing to master, congratulations! this will be rather transparent.

This feedback loop is slow, however, and it is recommended that bigger changes are developed and tested locally. There are a few things to be aware of when doing so:

### Running the Jekyll development server

Make sure you've installed the `jekyll` tools. See the [instructions here](). To serve the website locally, you must be **inside** the `docs` folder, along side the `_config.yaml` file:

```bash
$ cd ./docs
$ bundle install; bundle exec jekyll serve;
```

This will not work from the repository root.

### Local configuration

The first pass at developing this site, @ejhumphrey couldn't figure out how to properly use relative URLs in Jekyll across (a) the config file, (b) layout files, and (c) markdown in a way that worked for both local development and as a project site in GitHub, prior to taking over the http://ismir.net domain. This issue is detailed [more completely here](http://github.com/ismir/ismir-home/issues/??).

Until this is fixed more correctly, a temporary solution has been developed where a single field is specified in the site's `_config.yaml`:

```yaml
base_url: /ismir-home
```

When developing locally, set this to an empty string (`""`) for local development. When pushing to master, this should match the repository name (`/ismir-home`).

### Deploying

Once you've built the website and confirmed that it works, you can `scp` the site's output to a remote server.

```bash
scp -vr docs/_site/* username@your.host.com:~/destination/
```

#### Automated Deployments on Travis-CI

This repository is currently configured to build **pull requests** and **commits to master**, and in the latter case, redeploy the build output (the static site) to web hosting. While this now makes redeployments easy, configuration was not exactly straightforward.

One can recreate this configuration as follows:

0. Create a `.travis.yml` file.
    1. If starting from the one in this repository, delete the `env:globals` and the `before_install` routine. We'll overwrite these below.
    2. Otherwise, start from the Jekyll template here: https://jekyllrb.com/docs/continuous-integration/travis-ci/
1. Create an SSH key-pair locally with `ssh-keygen`. Here they are called `id_rsa` (private key) and `id_rsa.pub` (public key)
    1. The public key must be copied to the host, e.g. `ssh-copy-id -p 22 -i id_rsa.pub<EMAIL_ADDRESS>    2. The private key must be modified to eliminate the passphrase via `ssh-keygen -p -f id_rsa -N ''`
2. We can now encrypt environment variables that will be used by `./deploy_production.sh`, a shell script that has been made executable (`chmod +x`)
    1. We need to specify two env variables, `DEPLOY_HOST` and `DEPLOY_USER`, to access the host. This can be achieved by supplying this call with the right values from the repository root: `travis encrypt SOMEVAR="secretvalue" --add`
    2. See the instructions here for complete details: https://docs.travis-ci.com/user/encryption-keys
    3. Not that these encrypted values provide an extra layer of obfuscation to the location of the server, and are not strictly necessary – future configurations could provide this info as plaintext.
3. We must encrypt the private key file so that the Travis-CI build context can copy the built website to the host.
    1. The private key is encrypted with the following command, issued from the repository root: `travis encrypt-file id_rsa --add`
    2. This will encrypt the file with a `.enc` suffix, and add an additional command to `before_install`. Add the encrypted file to the repository (NOT THE PRIVATE KEY) and commit both changes.
    3. See the instructions here for complete details: https://docs.travis-ci.com/user/encrypting-files/
4. The `./deploy_production` script takes a path to the private key to use for securely copying data to the host server. One can similarly use this script locally with appropriately configured SSH keys.
    1. Note that `.travis.yml` is configured to only deploy on commits to master.
    2. The ssh-agent must be kick-started before attempting to copy the website to the host.

## WTFs

Here's a shortlist of weird things that have happened in the past that may serve as useful breadcrumbs, should they show up in the future:

* Only _some_ pages in a collection aren't available: Check the folder permissions on the server. In the past they've been set to 775, rather than 755, and this won't work; rsync will update files, but won't fix these wonky settings.

* Some links are `html`, other are `mypage/`: this is a permalinks issue, look into `collections`, which provide permalinks for free in exchange for a little upfront work.

* Datasets table goes missing: Check upstream, it depends on the mir-datasets repository to serve this correctly.

repository: ismir/ismir-home

gha_language: Shell

repo_name: ismir/ismir-home


text:
% Macros

By now you’ve learned about many of the tools Rust provides for abstracting and
reusing code. These units of code reuse have a rich semantic structure. For
example, functions have a type signature, type parameters have trait bounds,
and overloaded functions must belong to a particular trait.

This structure means that Rust’s core abstractions have powerful compile-time
correctness checking. But this comes at the price of reduced flexibility. If
you visually identify a pattern of repeated code, you may find it’s difficult
or cumbersome to express that pattern as a generic function, a trait, or
anything else within Rust’s semantics.

Macros allow us to abstract at a syntactic level. A macro invocation is
shorthand for an "expanded" syntactic form. This expansion happens early in
compilation, before any static checking. As a result, macros can capture many
patterns of code reuse that Rust’s core abstractions cannot.

The drawback is that macro-based code can be harder to understand, because
fewer of the built-in rules apply. Like an ordinary function, a well-behaved
macro can be used without understanding its implementation. However, it can be
difficult to design a well-behaved macro!  Additionally, compiler errors in
macro code are harder to interpret, because they describe problems in the
expanded code, not the source-level form that developers use.

These drawbacks make macros something of a "feature of last resort". That’s not
to say that macros are bad; they are part of Rust because sometimes they’re
needed for truly concise, well-abstracted code. Just keep this tradeoff in
mind.

# Defining a macro

You may have seen the `vec!` macro, used to initialize a [vector][vector] with
any number of elements.

[vector]: vectors.html

```rust
let x: Vec<u32> = vec![1, 2, 3];
# assert_eq!(x, [1, 2, 3]);
```

This can’t be an ordinary function, because it takes any number of arguments.
But we can imagine it as syntactic shorthand for

```rust
let x: Vec<u32> = {
    let mut temp_vec = Vec::new();
    temp_vec.push(1);
    temp_vec.push(2);
    temp_vec.push(3);
    temp_vec
};
# assert_eq!(x, [1, 2, 3]);
```

We can implement this shorthand, using a macro: [^actual]

[^actual]: The actual definition of `vec!` in libcollections differs from the
           one presented here, for reasons of efficiency and reusability.

```rust
macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}
# fn main() {
#     assert_eq!(vec![1,2,3], [1, 2, 3]);
# }
```

Whoa, that’s a lot of new syntax! Let’s break it down.

```rust,ignore
macro_rules! vec { ... }
```

This says we’re defining a macro named `vec`, much as `fn vec` would define a
function named `vec`. In prose, we informally write a macro’s name with an
exclamation point, e.g. `vec!`. The exclamation point is part of the invocation
syntax and serves to distinguish a macro from an ordinary function.

## Matching

The macro is defined through a series of rules, which are pattern-matching
cases. Above, we had

```rust,ignore
( $( $x:expr ),* ) => { ... };
```

This is like a `match` expression arm, but the matching happens on Rust syntax
trees, at compile time. The semicolon is optional on the last (here, only)
case. The "pattern" on the left-hand side of `=>` is known as a ‘matcher’.
These have [their own little grammar] within the language.

[their own little grammar]: ../reference.html#macros

The matcher `$x:expr` will match any Rust expression, binding that syntax tree
to the ‘metavariable’ `$x`. The identifier `expr` is a ‘fragment specifier’;
the full possibilities are enumerated later in this chapter.
Surrounding the matcher with `$(...),*` will match zero or more expressions,
separated by commas.

Aside from the special matcher syntax, any Rust tokens that appear in a matcher
must match exactly. For example,

```rust,ignore
macro_rules! foo {
    (x => $e:expr) => (println!("mode X: {}", $e));
    (y => $e:expr) => (println!("mode Y: {}", $e));
}

fn main() {
    foo!(y => 3);
}
```

will print

```text
mode Y: 3
```

With

```rust,ignore
foo!(z => 3);
```

we get the compiler error

```text
error: no rules expected the token `z`
```

## Expansion

The right-hand side of a macro rule is ordinary Rust syntax, for the most part.
But we can splice in bits of syntax captured by the matcher. From the original
example:

```rust,ignore
$(
    temp_vec.push($x);
)*
```

Each matched expression `$x` will produce a single `push` statement in the
macro expansion. The repetition in the expansion proceeds in "lockstep" with
repetition in the matcher (more on this in a moment).

Because `$x` was already declared as matching an expression, we don’t repeat
`:expr` on the right-hand side. Also, we don’t include a separating comma as
part of the repetition operator. Instead, we have a terminating semicolon
within the repeated block.

Another detail: the `vec!` macro has *two* pairs of braces on the right-hand
side. They are often combined like so:

```rust,ignore
macro_rules! foo {
    () => {{
        ...
    }}
}
```

The outer braces are part of the syntax of `macro_rules!`. In fact, you can use
`()` or `[]` instead. They simply delimit the right-hand side as a whole.

The inner braces are part of the expanded syntax. Remember, the `vec!` macro is
used in an expression context. To write an expression with multiple statements,
including `let`-bindings, we use a block. If your macro expands to a single
expression, you don’t need this extra layer of braces.

Note that we never *declared* that the macro produces an expression. In fact,
this is not determined until we use the macro as an expression. With care, you
can write a macro whose expansion works in several contexts. For example,
shorthand for a data type could be valid as either an expression or a pattern.

## Repetition

The repetition operator follows two principal rules:

1. `$(...)*` walks through one "layer" of repetitions, for all of the `$name`s
   it contains, in lockstep, and
2. each `$name` must be under at least as many `$(...)*`s as it was matched
   against. If it is under more, it’ll be duplicated, as appropriate.

This baroque macro illustrates the duplication of variables from outer
repetition levels.

```rust
macro_rules! o_O {
    (
        $(
            $x:expr; [ $( $y:expr ),* ]
        );*
    ) => {
        &[ $($( $x + $y ),*),* ]
    }
}

fn main() {
    let a: &[i32]
        = o_O!(10; [1, 2, 3];
               20; [4, 5, 6]);

    assert_eq!(a, [11, 12, 13, 24, 25, 26]);
}
```

That’s most of the matcher syntax. These examples use `$(...)*`, which is a
"zero or more" match. Alternatively you can write `$(...)+` for a "one or
more" match. Both forms optionally include a separator, which can be any token
except `+` or `*`.

This system is based on
"[Macro-by-Example](https://www.cs.indiana.edu/ftp/techreports/TR206.pdf)"
(PDF link).

# Hygiene

Some languages implement macros using simple text substitution, which leads to
various problems. For example, this C program prints `13` instead of the
expected `25`.

```text
#define FIVE_TIMES(x) 5 * x

int main() {
    printf("%d\n", FIVE_TIMES(2 + 3));
    return 0;
}
```

After expansion we have `5 * 2 + 3`, and multiplication has greater precedence
than addition. If you’ve used C macros a lot, you probably know the standard
idioms for avoiding this problem, as well as five or six others. In Rust, we
don’t have to worry about it.

```rust
macro_rules! five_times {
    ($x:expr) => (5 * $x);
}

fn main() {
    assert_eq!(25, five_times!(2 + 3));
}
```

The metavariable `$x` is parsed as a single expression node, and keeps its
place in the syntax tree even after substitution.

Another common problem in macro systems is ‘variable capture’. Here’s a C
macro, using [a GNU C extension] to emulate Rust’s expression blocks.

[a GNU C extension]: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

```text
#define LOG(msg) ({ \
    int state = get_log_state(); \
    if (state > 0) { \
        printf("log(%d): %s\n", state, msg); \
    } \
})
```

Here’s a simple use case that goes terribly wrong:

```text
const char *state = "reticulating splines";
LOG(state)
```

This expands to

```text
const char *state = "reticulating splines";
{
    int state = get_log_state();
    if (state > 0) {
        printf("log(%d): %s\n", state, state);
    }
}
```

The second variable named `state` shadows the first one.  This is a problem
because the print statement should refer to both of them.

The equivalent Rust macro has the desired behavior.

```rust
# fn get_log_state() -> i32 { 3 }
macro_rules! log {
    ($msg:expr) => {{
        let state: i32 = get_log_state();
        if state > 0 {
            println!("log({}): {}", state, $msg);
        }
    }};
}

fn main() {
    let state: &str = "reticulating splines";
    log!(state);
}
```

This works because Rust has a [hygienic macro system]. Each macro expansion
happens in a distinct ‘syntax context’, and each variable is tagged with the
syntax context where it was introduced. It’s as though the variable `state`
inside `main` is painted a different "color" from the variable `state` inside
the macro, and therefore they don’t conflict.

[hygienic macro system]: https://en.wikipedia.org/wiki/Hygienic_macro

This also restricts the ability of macros to introduce new bindings at the
invocation site. Code such as the following will not work:

```rust,ignore
macro_rules! foo {
    () => (let x = 3;);
}

fn main() {
    foo!();
    println!("{}", x);
}
```

Instead you need to pass the variable name into the invocation, so that it’s
tagged with the right syntax context.

```rust
macro_rules! foo {
    ($v:ident) => (let $v = 3;);
}

fn main() {
    foo!(x);
    println!("{}", x);
}
```

This holds for `let` bindings and loop labels, but not for [items][items].
So the following code does compile:

```rust
macro_rules! foo {
    () => (fn x() { });
}

fn main() {
    foo!();
    x();
}
```

[items]: ../reference.html#items

# Recursive macros

A macro’s expansion can include more macro invocations, including invocations
of the very same macro being expanded.  These recursive macros are useful for
processing tree-structured input, as illustrated by this (simplistic) HTML
shorthand:

```rust
# #![allow(unused_must_use)]
macro_rules! write_html {
    ($w:expr, ) => (());

    ($w:expr, $e:tt) => (write!($w, "{}", $e));

    ($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{
        write!($w, "<{}>", stringify!($tag));
        write_html!($w, $($inner)*);
        write!($w, "</{}>", stringify!($tag));
        write_html!($w, $($rest)*);
    }};
}

fn main() {
#   // FIXME(#21826)
    use std::fmt::Write;
    let mut out = String::new();

    write_html!(&mut out,
        html[
            head[title["Macros guide"]]
            body[h1["Macros are the best!"]]
        ]);

    assert_eq!(out,
        "<html><head><title>Macros guide</title></head>\
         <body><h1>Macros are the best!</h1></body></html>");
}
```

# Debugging macro code

To see the results of expanding macros, run `rustc --pretty expanded`. The
output represents a whole crate, so you can also feed it back in to `rustc`,
which will sometimes produce better error messages than the original
compilation. Note that the `--pretty expanded` output may have a different
meaning if multiple variables of the same name (but different syntax contexts)
are in play in the same scope. In this case `--pretty expanded,hygiene` will
tell you about the syntax contexts.

`rustc` provides two syntax extensions that help with macro debugging. For now,
they are unstable and require feature gates.

* `log_syntax!(...)` will print its arguments to standard output, at compile
  time, and "expand" to nothing.

* `trace_macros!(true)` will enable a compiler message every time a macro is
  expanded. Use `trace_macros!(false)` later in expansion to turn it off.

# Syntactic requirements

Even when Rust code contains un-expanded macros, it can be parsed as a full
[syntax tree][ast]. This property can be very useful for editors and other
tools that process code. It also has a few consequences for the design of
Rust’s macro system.

[ast]: glossary.html#abstract-syntax-tree

One consequence is that Rust must determine, when it parses a macro invocation,
whether the macro stands in for

* zero or more items,
* zero or more methods,
* an expression,
* a statement, or
* a pattern.

A macro invocation within a block could stand for some items, or for an
expression / statement. Rust uses a simple rule to resolve this ambiguity. A
macro invocation that stands for items must be either

* delimited by curly braces, e.g. `foo! { ... }`, or
* terminated by a semicolon, e.g. `foo!(...);`

Another consequence of pre-expansion parsing is that the macro invocation must
consist of valid Rust tokens. Furthermore, parentheses, brackets, and braces
must be balanced within a macro invocation. For example, `foo!([)` is
forbidden. This allows Rust to know where the macro invocation ends.

More formally, the macro invocation body must be a sequence of ‘token trees’.
A token tree is defined recursively as either

* a sequence of token trees surrounded by matching `()`, `[]`, or `{}`, or
* any other single token.

Within a matcher, each metavariable has a ‘fragment specifier’, identifying
which syntactic form it matches.

* `ident`: an identifier. Examples: `x`; `foo`.
* `path`: a qualified name. Example: `T::SpecialA`.
* `expr`: an expression. Examples: `2 + 2`; `if true { 1 } else { 2 }`; `f(42)`.
* `ty`: a type. Examples: `i32`; `Vec<(char, String)>`; `&T`.
* `pat`: a pattern. Examples: `Some(t)`; `(17, 'a')`; `_`.
* `stmt`: a single statement. Example: `let x = 3`.
* `block`: a brace-delimited sequence of statements and optionally an expression. Example:
  `{ log(error, "hi"); return 12; }`.
* `item`: an [item][item]. Examples: `fn foo() { }`; `struct Bar;`.
* `meta`: a "meta item", as found in attributes. Example: `cfg(target_os = "windows")`.
* `tt`: a single token tree.

There are additional rules regarding the next token after a metavariable:

* `expr` and `stmt` variables may only be followed by one of: `=> , ;`
* `ty` and `path` variables may only be followed by one of: `=> , = | ; : > [ { as where`
* `pat` variables may only be followed by one of: `=> , = | if in`
* Other variables may be followed by any token.

These rules provide some flexibility for Rust’s syntax to evolve without
breaking existing macros.

The macro system does not deal with parse ambiguity at all. For example, the
grammar `$($i:ident)* $e:expr` will always fail to parse, because the parser would
be forced to choose between parsing `$i` and parsing `$e`. Changing the
invocation syntax to put a distinctive token in front can solve the problem. In
this case, you can write `$(I $i:ident)* E $e:expr`.

[item]: ../reference.html#items

# Scoping and macro import/export

Macros are expanded at an early stage in compilation, before name resolution.
One downside is that scoping works differently for macros, compared to other
constructs in the language.

Definition and expansion of macros both happen in a single depth-first,
lexical-order traversal of a crate’s source. So a macro defined at module scope
is visible to any subsequent code in the same module, which includes the body
of any subsequent child `mod` items.

A macro defined within the body of a single `fn`, or anywhere else not at
module scope, is visible only within that item.

If a module has the `macro_use` attribute, its macros are also visible in its
parent module after the child’s `mod` item. If the parent also has `macro_use`
then the macros will be visible in the grandparent after the parent’s `mod`
item, and so forth.

The `macro_use` attribute can also appear on `extern crate`. In this context
it controls which macros are loaded from the external crate, e.g.

```rust,ignore
#[macro_use(foo, bar)]
extern crate baz;
```

If the attribute is given simply as `#[macro_use]`, all macros are loaded. If
there is no `#[macro_use]` attribute then no macros are loaded. Only macros
defined with the `#[macro_export]` attribute may be loaded.

To load a crate’s macros without linking it into the output, use `#[no_link]`
as well.

An example:

```rust
macro_rules! m1 { () => (()) }

// visible here: m1

mod foo {
    // visible here: m1

    #[macro_export]
    macro_rules! m2 { () => (()) }

    // visible here: m1, m2
}

// visible here: m1

macro_rules! m3 { () => (()) }

// visible here: m1, m3

#[macro_use]
mod bar {
    // visible here: m1, m3

    macro_rules! m4 { () => (()) }

    // visible here: m1, m3, m4
}

// visible here: m1, m3, m4
# fn main() { }
```

When this library is loaded with `#[macro_use] extern crate`, only `m2` will
be imported.

The Rust Reference has a [listing of macro-related
attributes](../reference.html#macro-related-attributes).

# The variable `$crate`

A further difficulty occurs when a macro is used in multiple crates. Say that
`mylib` defines

```rust
pub fn increment(x: u32) -> u32 {
    x + 1
}

#[macro_export]
macro_rules! inc_a {
    ($x:expr) => ( ::increment($x) )
}

#[macro_export]
macro_rules! inc_b {
    ($x:expr) => ( ::mylib::increment($x) )
}
# fn main() { }
```

`inc_a` only works within `mylib`, while `inc_b` only works outside the
library. Furthermore, `inc_b` will break if the user imports `mylib` under
another name.

Rust does not (yet) have a hygiene system for crate references, but it does
provide a simple workaround for this problem. Within a macro imported from a
crate named `foo`, the special macro variable `$crate` will expand to `::foo`.
By contrast, when a macro is defined and then used in the same crate, `$crate`
will expand to nothing. This means we can write

```rust
#[macro_export]
macro_rules! inc {
    ($x:expr) => ( $crate::increment($x) )
}
# fn main() { }
```

to define a single macro that works both inside and outside our library. The
function name will expand to either `::increment` or `::mylib::increment`.

To keep this system simple and correct, `#[macro_use] extern crate ...` may
only appear at the root of your crate, not inside `mod`.

# The deep end

The introductory chapter mentioned recursive macros, but it did not give the
full story. Recursive macros are useful for another reason: Each recursive
invocation gives you another opportunity to pattern-match the macro’s
arguments.

As an extreme example, it is possible, though hardly advisable, to implement
the [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) automaton
within Rust’s macro system.

```rust
macro_rules! bct {
    // cmd 0:  d ... => ...
    (0, $($ps:tt),* ; $_d:tt)
        => (bct!($($ps),*, 0 ; ));
    (0, $($ps:tt),* ; $_d:tt, $($ds:tt),*)
        => (bct!($($ps),*, 0 ; $($ds),*));

    // cmd 1p:  1 ... => 1 ... p
    (1, $p:tt, $($ps:tt),* ; 1)
        => (bct!($($ps),*, 1, $p ; 1, $p));
    (1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*)
        => (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p));

    // cmd 1p:  0 ... => 0 ...
    (1, $p:tt, $($ps:tt),* ; $($ds:tt),*)
        => (bct!($($ps),*, 1, $p ; $($ds),*));

    // halt on empty data string
    ( $($ps:tt),* ; )
        => (());
}
```

Exercise: use macros to reduce duplication in the above definition of the
`bct!` macro.

# Common macros

Here are some common macros you’ll see in Rust code.

## panic!

This macro causes the current thread to panic. You can give it a message
to panic with:

```rust,no_run
panic!("oh no!");
```

## vec!

The `vec!` macro is used throughout the book, so you’ve probably seen it
already. It creates `Vec<T>`s with ease:

```rust
let v = vec![1, 2, 3, 4, 5];
```

It also lets you make vectors with repeating values. For example, a hundred
zeroes:

```rust
let v = vec![0; 100];
```

## assert! and assert_eq!

These two macros are used in tests. `assert!` takes a boolean. `assert_eq!`
takes two values and checks them for equality. `true` passes, `false` `panic!`s.
Like this:

```rust,no_run
// A-ok!

assert!(true);
assert_eq!(5, 3 + 2);

// nope :(

assert!(5 < 3);
assert_eq!(5, 3);
```

## try!

`try!` is used for error handling. It takes something that can return a
`Result<T, E>`, and gives `T` if it’s a `Ok<T>`, and `return`s with the
`Err(E)` if it’s that. Like this:

```rust,no_run
use std::fs::File;

fn foo() -> std::io::Result<()> {
    let f = try!(File::create("foo.txt"));

    Ok(())
}
```

This is cleaner than doing this:

```rust,no_run
use std::fs::File;

fn foo() -> std::io::Result<()> {
    let f = File::create("foo.txt");

    let f = match f {
        Ok(t) => t,
        Err(e) => return Err(e),
    };

    Ok(())
}
```

## unreachable!

This macro is used when you think some code should never execute:

```rust
if false {
    unreachable!();
}
```

Sometimes, the compiler may make you have a different branch that you know
will never, ever run. In these cases, use this macro, so that if you end
up wrong, you’ll get a `panic!` about it.

```rust
let x: Option<i32> = None;

match x {
    Some(_) => unreachable!(),
    None => println!("I know x is None!"),
}
```

## unimplemented!

The `unimplemented!` macro can be used when you’re trying to get your functions
to typecheck, and don’t want to worry about writing out the body of the
function. One example of this situation is implementing a trait with multiple
required methods, where you want to tackle one at a time. Define the others
as `unimplemented!` until you’re ready to write them.

# Procedural macros

If Rust’s macro system can’t do what you need, you may want to write a
[compiler plugin](compiler-plugins.html) instead. Compared to `macro_rules!`
macros, this is significantly more work, the interfaces are much less stable,
and bugs can be much harder to track down. In exchange you get the
flexibility of running arbitrary Rust code within the compiler. Syntax
extension plugins are sometimes called ‘procedural macros’ for this reason.

repository: pjakma/trpl-ebook

repo_name: pjakma/trpl-ebook


text:
# HiddenListForm
My example to have a multi-value, searchable form that allows a dropdown to appear with filtered
search results based on what is typed.  Each item can be added as a hidden input, visible to the
user as a tag with a cancel button.  Submitting the form submits each related tag to the associated
name - so you can submit a dynamic list of values all with the same input name, and the user can
clearly see what is and isn't being submitted.

### Dependencies:
I am using the following open-source projects in the completion of this project.  The files that
use them expect them to be in the relative `js/ and `css/` files respectively:
* [Bootstrap](http://getbootstrap.com/)
* [jQuery](https://jquery.com/)

repository: aaroncarsonart/HiddenListForm

repo_name: aaroncarsonart/HiddenListForm


text:
# JetEZ - Easy SDK

JetEZ is an easy (EZ) and lightweight alternative to the official JET SDK with some
limitations. JetEZ creates signed JunOS install packages including any kind of
files described in a [yaml file](https://github.com/Juniper/jetez/blob/master/docs/jet-yaml.md).
This allows to install Python and SLAX scripts and cross compiled binaries.

The [example app](https://github.com/Juniper/jetez/tree/master/example-app)
shows how to build a GO application for JunOS using JetEZ.

In order to develop and distribute JetEZ applications, you need a package
[signing certificate](https://www.juniper.net/documentation/us/en/software/junos/jet-developer/topics/topic-map/jet-on-device-applications.html#id-develop-signed-jet-applications__id-jet-certificate-request).

```bash
$ jetez --help
usage: jetez [-h] --source DIR [-v VERSION] -k FILE -c FILE [-j FILE]
             [-b BUILD] [-d]

JetEZ - Easy SDK
----------------

This tool creates a JET install package (.tgz) from source directory using
the parameters from jet.yaml project description file.

optional arguments:
  -h, --help            show this help message and exit
  --source DIR          source directory
  -v VERSION, --version VERSION
                        version string
  -k FILE, --key FILE   path to signing key
  -c FILE, --cert FILE  path to signing cert
  -j FILE, --jet FILE   path to project file (default: <source>/jet.yaml)
  -b BUILD, --build BUILD
                        build directory (default: .build)
  -d, --debug           verbose logging

```

JetEZ generates signed packages for installation on upgraded JunOS only (FreeBSD 10 or later).

repository: Juniper/jetez

repo_name: Juniper/jetez


text:
# Put module startup scripts in this directory.

## **NOTE:** Please make sure to number the file names so that they are executed in the proper order.

## I.e.,

- First Script: 1-InitializeVariables.ps1
- Second Script: 2-ImportRequiredModules.ps1
- Second Script: 2-ImportModels.ps1
- Third Script: 3-InitializeConfiguration.ps1
- Nth Script: N-NthStartupScript.ps1
- ...

gha_language: PowerShell


text:
---
title: Use Redis on Carina
author: Bill Anderson<EMAIL_ADDRESS>date: 2016-01-04
permalink: docs/tutorials/data-stores-redis/
description: Learn how to use Redis on Carina
docker-versions:
  - 1.9.0
topics:
  - docker
  - intermediate
  - data-stores
  - redis
---

This tutorial describes using Redis on Carina so you can store data in a container.

### Prerequisites

[Create and connect to a cluster](/docs/tutorials/create-connect-cluster/)

### A primer on Redis security

Redis is intended and designed to run on a secure intranet. As a result it does
not have certain features you might expect, such as SSL or a User system. Redis
uses a single password or token to provide minimal authenticated access. As
there are no users there are no permissions other than you have access
or you do not. Best practice is to always use a password, which you can
set either in the config file or via the command line.

Running Redis over SSL requires running a proxy service such as Nginx or Stunnel. It
also requires you to use a client library that has added SSL support.
Running a Redis container with an SSL proxy means writing your own
Dockerfile to add an additional service as well as your generated SSL
certificates. How to do that is out of scope for this tutorial.

A final, if somewhat more drastic, step you can take is to rename certain
commands such as `CONFIG`. This is, at its core, "security through obscurity" but
in a plain-text protocol with minimal authentication support it is an option to
consider. Note that tools such as Sentinel and the Jedis client library for
Java do not work well with renaming commands. For more information about
security and Redis read the [Redis Security
](http://redis.io/topics/security) article.

### Run a Redis instance

Run a Redis instance to store your application data.

1. Run a Redis instance in a container from an official image using a
   password via the command line.

    ```bash
    $ docker run --detach --publish-all -m 1G redis \
	  redis-server --requirepass mysecretpassword \
	  --maxmemory 800M
    ```

    The output of the `docker run` command is the Redis container's ID.
    The `-m 1G` option specifies a reserved memory of one gigabyte. With Redis all data
    is in memory, so reserve some memory for the container and
    folow it up with a `maxmemory` setting to limit Redis' data memory
    allocation. In this case 800 MB was specified as the `maxmemory` value for Redis
    to provide 800 MB of data and client buffer space, and 200 MB for Redis persistence
    requirements.

    Note: Although you can change the password via the API, restarting the
    container resets it to the password specified on the command line. If
    you want to manage the password via the API, you can choose to not set a password
    at the command line and then *immediately* set one via the API.

1. View the status of the container by using the `--latest` parameter.

    ```bash
    $ docker ps --latest
    CONTAINER ID        IMAGE               COMMAND CREATED             STATUS              PORTS NAMES
    559d211c4cb1        redis               "/entrypoint.sh redis"   16 seconds ago      Up 6 seconds        <IP_ADDRESS>:32768->6379/tcp 7ffed4c5-fdcb-473d-8740-f133804b39a4-n1/amazing_mayer
    ```

    The output of this `docker ps` command is your running Redis container.

    The status of the container should begin with Up. If it doesn't, see
    the [Troubleshooting](#troubleshooting) section at the end of the
    tutorial.

1. View the ID of the container by using the `--quiet` parameter, store
   it in an environment variable for later use.

    ```bash
    $ REDCON=$(docker ps --quiet --latest)
    $ echo $REDCON
<PHONE_NUMBER>5c
    ```

    The output of the `docker ps` command is the shortened ID of the
	Redis container. This output was stored in the `REDCON` environment
	variable and displayed using the `echo` command.

1. Discover the IP address and port on which Redis is running by combining the `docker port` command, the ID of the container, and the default Redis port of 6379.

    ```bash
    $ docker port $REDCON 6379
    <IP_ADDRESS>:32769
    ```

    For the containerized Redis service you don't need to keep track of
	its name, IP address, or port.  Instead, you discover this information
	dynamically with the preceding command and use it later in the tutorial to
	connect to Redis.

1. To make using `redis-cli` easier, create a few more environment variables. Use `REDIS_HOST` for the IP address and `REDIS_PORT` for the TCP port.

    ```bash
    $ REDIS_HOST=$(docker inspect --format {% raw %}'{{ (index (index .NetworkSettings.Ports "6379/tcp") 0).HostIp }}'{% endraw %} $REDCON)
    $ REDIS_PORT=$(docker inspect --format {% raw %}'{{ (index (index .NetworkSettings.Ports "6379/tcp") 0).HostPort }}'{% endraw %} $REDCON)
    $ echo $REDIS_HOST:$REDIS_PORT
    ```

1. Testing the connection

    ```bash
    $ docker run --rm redis redis-cli -h $REDIS_HOST -p $REDIS_PORT -a mysecretpassword
    <IP_ADDRESS>:32769>
    ```

    Type in `PING`. You should see `PONG` come back. You should
    now have a functional Redis server requiring authentication.

1.  Set and get a key.

    ```bash
    $ docker run --rm redis redis-cli -h <IP_ADDRESS> -p 32769 -a mysecretpassword set redis:on:carina true
    OK
    $ docker run --rm redis-cli -h <IP_ADDRESS> -p 32769 -a mysecretpassword get redis:on:carina
    "true"
    ```

### Troubleshooting

If the status of the container does not begin with `Up`, check Redis' log
output. The Redis official container logs to `stdout` by default. We can see
those logs using the `docker logs` command.

```bash
$ docker logs $REDCON
```

This command will tell you why Redis failed to start as well as other
information such as whether THP support is enabled and any warnings about the
kernel's overcommit_memory settings.

See [Troubleshooting common problems](/docs/tutorials/troubleshooting/).

For additional assistance, ask the [community](https://community.getcarina.com/) for help or join us in IRC at [#carina on Freenode](http://webchat.freenode.net/?channels=carina).

### Resources

* [Redis Quick Start](http://redis.io/topics/quickstart)
* [Redis Security](http://redis.io/topics/security)

### Next steps

If you want Redis to listen only on the internal, multi-tenant network within
Carina, read [Communicate between containers over the ServiceNet internal
network](/docs/tutorials/servicenet/).

If Redis isn't the data store for you, read [Use MongoDB on
Carina](/docs/tutorials/data-stores-mongodb/).