text:
# Cascadia JS Day 2
## DNS and Cats
- Decent DNS tutorial

## Accessability
- Marcy Sutton from Substantial
- Are your views accessible? It depends on the framework, the screen reader, the browser, your (shitty?) code?
- Perceivable, Operable, Understandable, Robust - WCAG 2.0 Principles
- Interactivity is a challenge, add focussed states to things
- Notify of updates
- Hamburger button example is not understandable or operable, only has a css class, basically placeholder markup
- could add "role" attr, "tabindex" attr for keyboard accessibility, "aria-label" attr
- in angular, add "ng-keypress" to divs to get keyboard accessability, or just use a <button>
- add a :focus selector along with :hover for better visual appearence when using a keyboard
- graceful degradation: we can use js for accessible apps
- display:none hides things from screen readers
- update accessability related attributes as you update your views
- aria wants you to specify roles, states and properties
- there are a ton of roles, some are abstract and not to be used directly, they are element type, landmarks
- start with native html tags
- read the docs
- don't overdo it
- application mode disables a screen reader's virtual cursor
- screen readers are modal to properly route keystrokes, some to the reader, some to the browser
- role="application" disables the reader's own kbd shortcuts
- ARIA live regions allow updates about state without taking focus
- aria-live="assertive" will be read immediately
- explicitly manage focus if you are tearing out and restoring big bits of the DOM (I'm looking at you continuously rerendering backbone apps)

## Constantly Losing Stuff
- lessons learned and used doing continuation local storage in node
- @othiym23
- need variables scoped accross concurrent requests
- like thread local storage
- with threads these are generally just the thread's stack, in node we use potentially async callbacks, so the stack will often be gone
- node uses continuation passing style
- in express you often just bolt stuff onto the side of the response, but this might not always play nice when your data is cyclical and the response gets traversed by a naive logger
- process-global namespaces
- cls is kind of like domains
- Uses asyncListener, How does asyncListener work? it monkey patches every async function in node-core
- "stackup" uses asyncListener and produces long stack traces, across async boundaries
- asyncListener is currently being bikeshedded, watch out if you're using it.
- What is CLS? provides storage that looks global, but is actually scoped to an async call chain
- the api looks like node domains, because it's based on them
- what is cls useful for: transaction tracing, passing data through complicated web apps, logging, third party-async code
- Sometimes you can use shims, cls-q, cls-redis, to deal with edge cases around connection pools and pipelines
- Sometimes you have to bind callbacks to namespaces explicitly
- EventEmitters are another special case, you need to explicitly bind emitters (like streams) to namespaces
- Let's get real
- Is it safe: some sginificant cpu overhead, more gc pressure and memory overhead, doesn't change behaviour of your program or node
- every new relic user for node is using it
- small but mostly satisfied community of users
- if you want a whole paradigm, try strongloop zones

## All_night_rave.js
- @flohdot
- there will be strobes
- party jobs: djs, vjs, promoters, burly door person, bartenders, performers, dancers, logistics managers
- #1 interactivity, let people participate
- processing & processing.js
- Leverage the internets for interactivity, socket.io is a nice toolkit for collecting all the datas
- <x-gif> + transparent canvas driven by processing over top = funzies

## Making Javascript Tests fast modern and friendly
- @ryanroehmer
- developers will avoid tests that are difficult to write, run or daunting, but when they are easy fast and friendly things will go well
- wrote a backbone.js testing book
- set a foundation, bolting on tests well into a project can be a pain in the butt
- test frameworks provide: reporting, async support, assertions
- lower barriers to entry: make no assumptions, provide test skeletons and be ready to "get out and push"
- write stuff down, the test stack, conventions, guides, and keep it up to date
- what is "fast" for tests: <30 seconds, maybe < 5
- Why is testing slow? network, timers, waits and UI effects
- Know what to look for when trying to speed up tests: ignore pure js code execution, instead look at network/communication outside of JS and explicit waits in code
- The solution: fake out backend server communication and timers
- sinon is an option for this
- Making tests friendly: the culture should support testing and training for the tests
- find test champions who will advocate for the tests, and provide support people writing tests
- educate bosses: create good stories for the cost of bugs
- Track bugs avoided and regressions
- as a higher up, don't make developers rejustify tests

## Barriers to Entry: Learning to Program is the easy part
- Experiential diversity
- Successful careers in the past !== seamless entry into life as a programmer
- llkats gather-the-singletons
- Unrealistic Expectations: knowing terminology, code -> production is complicated, nothing is transparent
- new devs are self conscious and easily embarrassed, are less likely to ask questions and are thus more likely to make mistakes
- offer to answer questions, share stories, be careful ridiculing popular resources, model good behaviour

# Hashing
- @classam
- This is a pretty good introductory talk on hashes, and data structures that use them, both cryptographic and not
- don't use md5

# Distillation.js
- distillation comes in stages, heads (methanol, bad), hearts (ethanol, good), tails (falvour, you may or may not want this)
- traditional distillation is a synchronous process
- Heising 330: continuous distillation
- constantly pump in beer/wine, and maintian a precisely controlled temperature gradient up a column
- they built a continuous still using open source and "maker technology" and a bit of naivety
- must run continuously and is potentially very dangerous
- control system is a "pcduino"
- connects to termperature and barometric sensors and pump and power controllers
- they communicate through a fuse filesystem fromt he devices to a node cor-ordination process
- why node? npm just works, it runs anywhere, it's web forward
- node.js and fuse is not fast enough for some embedded protocols
- can't just press the restart buttonw hen there si a problem
- shit breaks, and when it doesn't it's really bad
- solved witha  mixture of native node modules and external ICs
- lots of code to resolve things without restarts
- watchdog programs and lots fo safety checks
- girhub.com/heising/node330
- makes it easy to interact with sensors and controllers, simple run loop for long running processes, built in common things like unit conversion, pid loops
- dweet.io
- freeboard
- node.js is surprisingly good for industrial processes
-

# Hacking Mentor.js
- Marlena Compton and Ryan Dy
- they worked at pivotal labs on pivotal tracker
- What is mentoring?
- Mentoring and Pairing
- Why take the time to help someone?
- beyond learning and technical skill, also about confidence
- How do I recognize a good mentor? someone who lets me ask my questions without judgement
- Lessons from Pixar's John Lasseter
- Learning in the awkward phase, Side-projects are a great help here
- reddism
- Relax Ipsum
- Learning to build software in the real world
- Mentoring teaches lessons deeper than what can be understood ina  tutorial
- want to teach people to be good software engineers, a commitment to good code
- failure has a great part to play in building great software
- Learning that you belong
- Learning inclusivity: coworkers, professionals, n00bs, makers
- What kind of javascript community should we build?

## Databases and IoT
- @brycebaril
- Put a bird on it!
- Put databases everywhere: intelligent sync, push/pull replication, aggregating relays, peer networks, and more!
- With local databases, IoT becomes a private cloud
- Intr-*a*-net of things
- Let's make a database that crosses space and time: leveldb, timestreamdb, beaglebone black, private network
- do for databases what npm did for package management
- the unix philosophy applied to databases
- timestreamdb, streaming time series database on top of level db
- What's in the box?
- beaglebone!
- leveldb lets us treat the data the same way in the browser and in node

## Meetups
- @rhodesjason
- building baltimore nodeschool
- Lecture format leaves things to be desired for meetups, there's always the trip to the bar afterwards, but that's a much bigger time commitment
- tutor style meetup on weekends
- ietf86 shirt is awesome
- mentors and learners both love it!
- pair programming model for the event
- we all have different bottoms, we all started somewhere different
- having a white soundign first name si the equivalent of having 8 years of professional experience?
- where your bottom is is a matter of privilege
- edgar allan bro!
- rfc 822 and rfc 2616
- listen more, think more and argue less
- think about providing childcare for your events
-

## No More Unicorns
- @ceejbot
- the pronoun debate was very very sad
- why don't you see women on node-core?
- cs degrees granted to women peaked in the early 80s
- google has 17% female engineering workforce, 27% of cs degrees went to women at the time
- our industry is regressive, and regressing
- CJ doesn't want to be a unicorn
- CJ was a late invite to nodesummit 2014, purely as a result of critique
- suggested that node core should recruit women, there were crickets
- stubborn: screw you, i'm gonna do this
- oblivious: too busy coding to notice systemic problems
- try determiend and empathetic
- how you act is what your values are
- if you hire a bunch of white dudes, you didn't try
- step one: say diversity matters in your job listings
- step two: enlist your team's help, have women on the hiring team
- step three: hire somebody who doesn't look like everybody else
- your hiring process sucks
- terrible cultural secret: men overstate, women understate
- another hot tip, women are undervalued salarywise
- let's do better than not being horrible to women
- talking about diversity in hiring is threatening to those in the status quo group
- the games industry is even worse than this crowd
- the standard you walk past is the standard you accept
- stop bad behaviour when you see it

url: https://raw.githubusercontent.com/noahadams/cascadiajs-2014-presentation/cccaa712b2e5402f547e28033408eebdee6bf3b6/Cascadia JS 2014 Day 2.md

path: /Cascadia JS 2014 Day 2.md

filename: Cascadia JS 2014 Day 2.md


text:
# Easy Backtracking Approach: Deduplicating and Pruning

https://leetcode.com/problems/combination-sum/solutions/1881839/easy-backtracking-approach-deduplicating-and-pruning/

[Leetcode](https://leetcode.com/) [39. Combination Sum](https://leetcode.com/problems/combination-sum).

***By Frank Luo***

# Backtracking

It's a typical **Backtracking** algorithm.

We can easily draw the tree below.

![Tree Path](https://assets.leetcode.com/users/images/6ebad867-9940-4817-90e0-1af0c04992bd_1648191321.1437306.png)

Take $\textit{target} = 7$ as the root node and subtract the value of the edge while creating a  child node.

Stop it when the value of the node is $0$ or a negative number.

All paths from the root node to leaf node $0$ are the results of the question.

Let's coding.

```java
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        if (candidates == null || target == 0) {
            return ans;
        }

        backtrack(ans, new ArrayList<>(), candidates, target);
        return ans;
    }

    public static void backtrack(List<List<Integer>> res, List<Integer> list, int[] candidates, int remain) {
        if (remain < 0) {
            return;
        }

        if (remain == 0) {
            res.add(new ArrayList<>(list));
            return;
        }

        int len = candidates.length;
        for (int i = 0; i < len; i++) {
            int num = candidates[i];
            list.add(num);
            backtrack(res, list, candidates, remain - num);
            list.remove(list.size() - 1);
        }
    }
}
```

Take $\textit{target} = 7$ for example, $[[2, 2, 3], [2, 3, 2], [3, 2, 2], [7]]$ are the answer.

However, the correct answer is $[[7], [2, 2, 3]]$.

Since it requires that each solution is not **in order**, so the $[2, 2, 3]$ and $[2, 3, 2]$ are the same answer.

What's problem?

When and how did we **duplicate** the path?

#  Why Duplicated?

At each node of the tree, **all the candidates** were searched and used, so there is a duplicate list.

Is it possible to **deduplicate** while searching?

Of course we can.

We have to **search the elements in order** while searching, since the output is not by order. We search from the certain position in the next round.

```java
    public static void backtrack(List<List<Integer>> res, List<Integer> list, int[] candidates, int start, int remain) {
        if (remain < 0) {
            return;
        }

        if (remain == 0) {
            res.add(new ArrayList<>(list));
            return;
        }

        int len = candidates.length;
        for (int i = start; i < len; i++) {
            int num = candidates[i];
            list.add(num);
            backtrack(res, list, candidates, i, remain - num);
            list.remove(list.size() - 1);
        }
    }
```

By now we **deduplicating** it and complete the problem.

# Pruning

We can prune the tree to make it work more efficiency.

```java
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        if (candidates == null || target == 0) {
            return ans;
        }

        Arrays.sort(candidates);
        backtrack(ans, new ArrayList<>(), candidates, 0, target);
        return ans;
    }

    public static void backtrack(List<List<Integer>> res, List<Integer> list, int[] candidates, int begin, int remain) {
        if (remain < 0) {
            return;
        }

        if (remain == 0) {
            res.add(new ArrayList<>(list));
            return;
        }

        int len = candidates.length;
        for (int i = begin; i < len; i++) {
            int num = candidates[i];
            if (remain - num < 0) {
                break;
            }
            list.add(num);
            backtrack(res, list, candidates, i, remain - num);
            list.remove(list.size() - 1);
        }
    }
}
```

## Analysis

- **Time Complexity**: $O(Sum)$, $Sum$ is all the path.
- **Space Complexity**: $O(\textit{target})$.

----------

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More [Leetcode Solutions](https://leetcode.com/discuss/general-discussion/1868912/My-Leetcode-Solutions-All-In-One). 😉😃💗

license: MIT

repository: longluo/leetcode

branch_name: refs/heads/master

extension: md

filename: 39. Combination Sum(Medium).md

gha_language: Java

gha_license_id: MIT

license_type: permissive

repo_name: longluo/leetcode


text:
# nextjs-redux

Base Next JS config with Redux

## Setup

1. Clone this repo using `git clone https://github.com/whitedwarf2000/nextjs-redux.git <YOUR_PROJECT_NAME>`
2. Move to the appropriate directory: `cd <YOUR_PROJECT_NAME>`.
3. Run `yarn` or `npm install` to install dependencies.

These scripts refer to the different stages of developing an application:

- `dev:desktop` - Runs `next` which starts Next.js in development desktop mode
- `dev:mobile` - Runs `next` which starts Next.js in development mobile mode
- `build:desktop` - Runs `next` build which builds the application desktop mode for production usage
- `build:mobile` - Runs `next` build which builds the application mobile for production usage
- `start` - Runs `next` start which starts a Next.js production server
- `test` - Runs all testing script
- `lint:fix` - Runs lint fix script

### Useful Libraries

- [x] **underscore**: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore
- [x] **redux-thunk**:  https://github.com/reduxjs/redux-thunk
- [x] **redux**: A predictable state container for JavaScript apps.
- [x] **reselect**: Simple selector library for Redux (and others) inspired by getters in [NuclearJS](https://optimizely.github.io/nuclear-js/), subscriptions in re-frame and this proposal from speedskater.
- [x] **immer**: https://immerjs.github.io/immer/docs/introduction
- [x] **@testing-library/react**: Simple and complete React DOM testing utilities that encourage good testing practices.
- [x] **styled-component**: https://styled-components.com/

branch_name: refs/heads/main

gha_language: JavaScript


text:
# Data::Dump::Tree

[![Build Status](https://travis-ci.org/nkh/P6-Data-Dump-Tree.svg?branch=release)](https://travis-ci.org/nkh/P6-Data-Dump-Tree)

## For perl6

Data::Dump::Tree - Renders data structures in a tree fashion with colors

Some blog entries you may want to look at:

http://blogs.perl.org/users/nadim_khemir/2017/08/perl-6-datadumptree-version-15.html

http://blogs.perl.org/users/nadim_khemir/2017/08/take-a-walk-on-the-c-side.html

https://perl6advent.wordpress.com/2016/12/21/show-me-the-data/

![Imgur](http://i.imgur.com/P7eRSwl.png?1)

*Warning*: This module is developed and tested with the latest rakudo. It may not work or install properly with your version of rakudo, there is a test suite run to check its fitness.

NAME
====

Data::Dump::Tree - Renders data structures as a tree

SYNOPSIS
========

    use Data::Dump::Tree ;

    ddt @your_data ;

    my $d = Data::Dump::Tree.new(...) ;
    $d.ddt: @your_data ;

    $d does role { ... } ;
    $d.ddt: @your_data ;

DESCRIPTION
===========

Data::Dump::Tree renders your data structures as a tree for legibility.

It also can:

  * colors the output if you install Term::ANSIColor (highly recommended)

  * filter the data before rendering it

  * display two data structures side by side (DDTR::MultiColumns)

  * display the difference between two data structures (DDTR::Diff)

  * generate DHTML output (DDTR::DHTML)

  * display an interactive folding data structure (DDTR::Folding)

  * display parts of the data structure Horizontally (see :flat)

  * show NativeCall data types and representations (see int32 in examples/)

  * be used to "visit" a data structure and call callbacks you define

INTERFACE
=========

sub ddt $data_to_dump, [$data_to_dump2, ...] :adverb, :named_argument, ...
--------------------------------------------------------------------------

Renders $data_to_dump

This interface accepts the following adverbs:

  * **:print** prints the rendered data, the default befhavior without adverb

  * **:note** 'note's the rendered data

  * **:get** returns the rendered data as a single string

  * **:get_lines** returns the rendering in its native format

  * **:get_lines_integrated** returns a list of rendered lines

  * **:fold** opens a Terminal::Print interface, module must be installed

  * **:remote** sends a rendering the to a listener

See examples/ddt.pl and ddt_receive.pl

  * **:remote_fold** sends a foldable rendering to a listener

See *examples/remote/ddt_fold_send.pl* and *ddt_fold_receive.pl*.

method ddt: $data_to_dump, [$data_to_dump2, ...], :adverb, :named_argument, ...
-------------------------------------------------------------------------------

Renders $data_to_dump, see above for a list of adverbs.

USAGE
=====

    use Data::Dump::Tree ;

    class MyClass { has Int $.size ; has Str $.name }

    my $s = [
	    'text',
	    Rat.new(31, 10),
	    {
		    a => 1,
		    b => 'string',
	    },
	    MyClass.new(:size(6), :name<P6 class>),
	    'aaa' ~~ m:g/(a)/,
	    ] ;

    ddt $s, :title<A complex structure> ;

    ddt $s, :!color ;

Output
------

    A complex structure [5] @0
    ├ 0 = text.Str
    ├ 1 = 3.1 (31/10).Rat
    ├ 2 = {2} @1
    │ ├ a => 1
    │ └ b => string.Str
    ├ 3 = .MyClass @2
    │ ├ $.size = 6
    │ └ $.name = P6 class.Str
    └ 4 = (3) @3
      ├ 0 = a[0]
      ├ 1 = a[1]
      └ 2 = a[2]

**:caller** and **method ddt_backtrace: $backtrace = True**
-----------------------------------------------------------

if **:caller** is given as an argument, the call site is added to the title

if you call **ddt_backtrace**, all the calls to method **ddt**, or sub **ddt**, will display a call stack.

Rendering
=========

Each line of output consists 6 elements.

Data::Dump::Tree (DDT) has a default render mode for all data types but you can greatly influence what and how things are rendered.

Rendering elements
------------------

    tree   binder  type     address
    |      |       |        |
    v      v       v        v

    |- key = value .MyClass @2

### tree (glyphs)

The tree shows the relationship between the data elements. Data is indented under its container.

DDT default tree rendering makes it easy to see relationship between the elements of your data structure but you can influence its rendering.

### key

The key is the name of the element being displayed; in the examples above the container is an array; Data:Dump::Tree uses the index of the element as the key its key. IE: '0', '1', '2', ...

### binder

The string displayed between the key and the value.

### value

The element's value; Data::Dump::Tree renders "terminal" variables, eg: Str, Int, Rat. Container have no value, but a content.

### Type

The element's type with a '.' prepended. IE: '.Str', '.MyClass'

Data::Dump::Tree will render some types specifically:

  * Ints, and Bools, the type is not displayes to reduce noise

  * Hashes as **{n}** where n is the number of element of the hash

  * Arrays as **[n]**

  * Lists as **(n)**

  * Sets as **.Set(n)**

  * Sequences as **.Seq(n)** or **.Seq(*)** when lazy.

You control if sequences are rendered vertically or horizontally, how much of the sequence is rendered and if lazy sequences are rendered (and how many elements for lazy sequences).

Check *examples/sequences.pl* as well as the implementation in *lib/Data/Dump/Tree/DescribeBaseObjects.pm*.

  * Matches as **[x..y]** where x..y is the match range

See *Match objects* in the roles section below for configuration of the Match objects rendering.

### address

The Data::Dump::Tree address is added to every container in the form of a '@' and an index that is incremented for each container. If a container is found multiple times in the output, it will be rendered as *@address* once then as a reference as *§address*

Containers can be named using *set_element_name* prior to rendering.

    my $d = Data::Dump::Tree.new ;

    $d.set_element_name: $s[5], 'some list' ;
    $d.set_element_name: @a, 'some array' ;

    $d.ddt: $s ;

A container's name will be displayed next to his address.

Configuration and Overrides
---------------------------

There are multiple ways to configure the Dumper. You can pass a configuration to the ddt() or create a dumper object with your configuration.

    # subroutine interface
    ddt $s, :titlei<text>, :width(115), :!color  ;

    # basic object
    my $dumper = Data::Dump::Tree.new ;

    # pass you configuration at every call
    $dumper.ddt: $s, :width(115), :!color ;

    # configure object at creation time
    my $dumper = Data::Dump::Tree.new: :width(79) ;

    # use as configured
    $dumper.ddt: $s ;

    # or with a call time configuration override
    $dumper.ddt: $s, :width(115), :max_depth(3) ;

    # see roles for roles configuration

The example directory contain a lot of examples. Read and run the examples to learn how to use DDT.

### colors

#### $color = True

Coloring is on if Term::ANSIColor is installed.

Setting this option to False forces the output to be monochrome.

    ddt $s, :!color ;

#### %colors

You can pass your own colors. The default are:

    %.colors =
	    <
	    ddt_address blue     perl_address yellow  link   green
	    header      magenta  key         cyan     binder cyan
	    value       reset

	    gl_0 yellow   gl_1 reset   gl_2 green   gl_3 red
	    > ;

Where colors are ANSI colors. *reset* means the default color.

By default the tree will not be colored and the key and binder use colors 'key' and 'binder'. For renderings with many and very long continuation lines, having colored glyphs and key-binder colored per level helps greatly.

#### $color_glyphs

Will set a default glyph color cycle.

    # colored glyphs, will cycle
    ddt @data, :color_glyphs ; # uses < gl_0 gl_1 gl_2 gl_3 >

#### @glyph_colors

You can also define your own color cycle with **@glyph_colors**:

    # colored glyphs
    ddt @data, :color_glyphs, glyph_colors => < gl_0 gl_1 > ;

#### $color_kbs

Will set a default key and binding color cycle.

    # used color 'kb_0', 'kb_1' ... and cycles
    ddt @data, :color_kbs ; #uses < kb_0 kb_1 ...  kb_10 >

#### @kb_colors

You can also define your own cycle with **@kb_colors**:

    # colored glyphs, will cycle
    ddt @data, :color_kbs, kb_colors => < kb_0 kb_1 > ;

### $width = terminal width

Note that the glyps' width is subtracted from the width you pass,

    ddt $s, :width(40) ;

DDT uses the whole terminal width if no width is given.

### $width_minus = Int

Reduces the width, you can use it to reduce the computed width.

### $indent = Str

The string is prepended to each line of the rendering

### $nl = Bool

Add an empty line after the last line of the rendering

### $max_depth = Int

Limit the depth of a dump. Default is: no limit.

### $max_depth_message = True

Display a message telling that you have reached the $max_depth limit, setting this flag to false disable the message.

### $max_lines = Int

Limit the number of lines in the rendering, an approximation as *ddt* does not end rendering in the middle of a multi line. There is no limit by default.

### $display_info = True

When set to false, neither the type nor the address are displayed.

### $display_type = True

By default this option is set.

### $display_address = DDT_DISPLAY_ALL

By default this option is set, to change it use:

    use Data::Dump::Tree;
    use Data::Dump::Tree::Enums;

    my $ddt = Data::Dump::Tree.new( :display_address(DDT_DISPLAY_NONE) );

### $display_perl_address = False

Display the internal address of the objects. Default is False.

### Str rendering

By default Str is rendered as the string with '.Str'

You can Control quoting and type display directly in the dumper without having to write a role for it.

  * $string_type

The type displayed for a Str.

  * $string_quote

The quote surrounding the string, it will be used on both sides of the string unless $string_quote_end is set.

  * $string_quote_end

Setting it allows you to have 'asymmetrical quotes' like **[ the string ]**.

### Tree rendering

The tree is drawn by default with Unicode characters (glyphs) + one space.

You can influence the rendering of the tree in multiple ways:

  * using glyphs or simple indenting

See role *DDTR::FixedGlyphs*.

  * rendering caracter set and spacing

See role *AsciiGlyphs* and *CompactUnicodeGlyphs*.

You can also create a role that defines the glyphs to use.

  * the color of the tree

See *$color_glyphs* above.

  * "color blob mode"

See <Color Blob mode> for a way to gain control over the tree rendering.

### Horizontal layout

You can use *:flat( conditions ...)* to render parts of your data horizontally. Horizontal layout is documented in the *LayoutHorizontal.pm* module and you can find examples in *examples/flat.pm*.

You can chose which elements, which type of element, even dynamically, to flatten, EG: Arrays with more than 15 elements.

    dd's example output:

    $($[[1, [2, [3, 4]]], ([6, [3]],), [1, [2, [3, 4]]]], [[1, [2, [3, 4]]],
    [1, [2, [3, 4]]]], $[[1, 2], ([1, [2, [3, 4]]], [1, [2, [3, 4]]], [1,
    [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1,
    [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1,
    [2, [3, 4]]]).Seq], [[1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, 2], [1, 2,
    3], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3,
    4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]]], $[[1, 2], ([1, [2, [3, 4]]],
    [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]],
    [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]],
    [1, [2, [3, 4]]], [1, [2, [3, 4]]]).Seq], "12345678")

    Same data rendered with ddt and I<:flat>:

     (6) @0
       0 = [3] @1       1 = [2] @9   2 = [2] @12        3 = [10] @25
       ├ 0 = [2] @2     ├ 0 = [2] §2 ├ 0 = [2] @13      ├ 0 = [2] §2
       │ ├ 0 = 1        └ 1 = [2] §2 │ ├ 0 = 1          ├ 1 = [2] §2
       │ └ 1 = [2] @3                │ └ 1 = 2          ├ 2 = [2] §13
       │   ├ 0 = 2                   └ 1 = .Seq(11) @14 ├ 3 = [3] @29
       │   └ 1 = [2] @4                ├ 0 = [2] §2     │ ├ 0 = 1
       │     ├ 0 = 3                   ├ 1 = [2] §2     │ ├ 1 = 2
       │     └ 1 = 4                   ├ 2 = [2] §2     │ └ 2 = 3
       ├ 1 = (1) @5                    ├ 3 = [2] §2     ├ 4 = [2] §2
       │ └ 0 = [2] @6                  ├ 4 = [2] §2     ├ 5 = [2] §2
       │   ├ 0 = 6                     ├ 5 = [2] §2     ├ 6 = [2] §2
       │   └ 1 = [1] @7                ├ 6 = [2] §2     ├ 7 = [2] §2
       │     └ 0 = 3                   ├ 7 = [2] §2     ├ 8 = [2] §2
       └ 2 = [2] §2                    ├ 8 = [2] §2     └ 9 = [2] §2
                                       ├ 9 = [2] §2
                                       └ ...
       4 = [2] §12 5 = 12345678.Str

Handling specific types
-----------------------

This section explains how to write specific handlers in classes that create a custom rendering

### in your own classes

When Data::Dump::Tree renders an object, it first checks if it has an internal handler for that type; if no handler is found, the object is queried and its handler is used if it is found; finally, DDT uses a generic handler.

The module tests, examples directory, and Data::Dump::Tree::DescribeBaseobjects are a good places to look at for more examples of classes defining a custom rendering.

#### method **ddt_get_header** in your class

    method ddt_get_header
    {
    # return

    # some text                       # class type

    # usually blank for containers    |

    # the value for terminals         |
    |                                 |
    v                                 v

    '',                              '.' ~ self.^name
    }

#### method **ddt_get_elements** in your class

    method ddt_get_elements
    {
    # return a list of elements data for each element of the container

    # key           # binder    # value
    (1,             ' = ',     'has no name'),
    (3,             ' => ',    'abc'),
    ('attribute',   ': ',      '' ~ 1),
    ('sub object',  '--> ',    [1 .. 3]),
    ('from sub',    '',        something()),

    }

The content of the original container is ignored, what you return is used. This lets you remove/add/modify elements.

### someone else's class and base types

You can not add methods to classes that you do not control. Data::Dump::Tree has type handlers, via roles, that it uses to handle specific types contained the structure you want to render.

You can override the default handlers and add new ones.

Create a role following this template (here a hash example):

    role your_hash_handler
    {
    #                        Type you want to handle is Hash
    #                        ||||
    #                        vvvv
    multi method get_header (Hash $h)
	    {
	    # return
	    # optional description    # type (string to display)
	    '',                       '{' ~ $h.elems ~ '}' }

    multi method get_elements (Hash $h)
	    {
	    # return the elements of your object
	    $h.sort(*.key)>>.kv.map: -> ($k, $v) {$k, ' => ', $v}
	    }
    }

To make that handler active, make your dumper **do** the role

    # using 'does'
    my $d = Data::Dump::Tree.new: :width(80) ;
    $d does your_hash_handler ;

    $d.ddt: @your_data ;

    # or by passing roles to the constructor
    my $d = Data::Dump::Tree.new: :does(DDTR::MatchDetails, your_hash_handler) ;

    # or by passing roles to dump() method
    my $d = Data::Dump::Tree.new ;
    $d.ddt: $m, :does(DDTR::MatchDetails, your_hash_handler) ;

    # or by passing roles to ddt sub
    ddt: $m, :does(DDTR::MatchDetails, your_hash_handler) ;

### FINAL elements

So far we have seen how to render containers but sometimes we want to handle a type as if it was a Str or an Int, EG: not display its elements but instead display it on a single line.

You can, in a handler, specify that a type rendered is not a container, by returning DDT_FINAL in the type's _get_header_ handler.

For example, the Rat class type handler does not show a floating number, it displays the Rat on a single line. Here is the handler:

    multi method get_header (Rat $r)
    {
    # the rendering of the Rat
    $r ~ ' (' ~ $r.numerator ~ '/' ~ $r.denominator ~ ')',

    # its type
    '.' ~ $r.^name,

    # hint DDT that this is final
    DDT_FINAL,

    # hint DDT that this is has an address
    DDT_HAS_ADDRESS,
    }

Filtering
---------

![Imgur](https://i.imgur.com/GCTcmdP.png)

Data::Dump::Tree lets you filter the data to dump.

NOTE: filter must be **multi** subs.

NOTE: **$path**, a list passed to filters, is set if you use **:keep_paths** option, otherwise an empty list is passed to the filters.

To pass a filter to the dumper:

    ddt(
	    $s,

	    # all below are optional

	    :removal_filter(&removal_filter, ...),
	    :header_filters(&header_filter, ...),
	    :elements_filters(&elements_filter,),
	    :footer_filters(&footer_filters,),

	    :keep_paths
	    ) ;

Data::Dump::Tree filters are called in this order:

check if the element is to be removed from the rendering

    * removal filters are called

let you change the header rendering returned by the type's handler

    * header filters are called

let you change the elements of a container returned by the type's handler

    * element filters are called

after the element is rendered

    * footer filters are called

### removal filter

This is called before the type's handler **get_header** is called. This allows you to efficiently remove elements from the rendering.

    multi sub remove_filter(
	    $dumper,
	    $s, 		# "read only" object
	    $path		# path in the data structure

    )
    {
    True # return True if you want the element removed
    }

### header filter

This is called just after the type's _get_header_ is called, this allows you, EG, to insert something in the tree rendering

    multi sub header_filter(
	    $dumper,				# the dumper
	    $replacement                            # replacement
	    $s,                                     # "read only" object
	    ($depth, $path, $glyph, @renderings),   # info about tree

	    ($key, $binder, $value, $type, $final, $want_address) # element info
	    )
    {
    # Add something to the tree
    @renderings.push: (|$glyph , ('', "HEADER", '')) ;
    }

or change the default **rendering** of the object

    multi sub header_filter(
	    $dumper,				# the dumper
	    \replacement                            # replacement
	    Int $s,                                 # will only filter Ints
	    ($depth, $path, $glyph, @renderings),   # info about the tree

	    # what the type's handler has returned
	    (\key, \binder, \value, \type, \final, \want_address) # can be changed
	    )
    {
    @renderings.push: (|$glyph, ('', 'Int HEADER ' ~ $depth, '')) ;

    # in this example we need to set limit or we would create lists forever
    if $depth < 2 { replacement = <1 2> } ;

    # key, binder, value, and type are Str

    key = key ~ 'Hash replacement' ;
    #binder = '' ;
    #value = '' ;
    #type = '' ;

    final = DDT_NOT_FINAL ;
    want_address = True ;
    }

Note: You can not filter elements of type _Mu_ with header filters but you can in element filters.

### elements filter

Called after the type's _get_elements_. You can change the elements.

    multi sub elements_filter(
	    $dumper,
	    Hash $s, # type to filter (ie Hash)

    # rendering data you can optionaly use

    ($depth, $glyph, @renderings, ($key, $binder, $value, $path)),

    # elements you can modify
    @sub_elements
    )

    {
    # optionaly add something in the rendering
    @renderings.push: (|$glyph, ('', 'SUB ELEMENTS', '')) ;

    # set/filter  the elements
    @sub_elements = (('key', ' => ', 'value'), ('other_key', ': ', 1)) ;
    }

### footer filter

Called after the element is rendered.

    multi sub footer_filter($dumper, $s, ($depth, $filter_glyph, @renderings))
    {
    # add message to the rendering after the element is rendered
    @renderings.push: (|$filter_glyph, ('', "done with {$s.^name}", '')) ;
    }

Removing elements
------------------

### In removal filters

See removal filters above.

### In header filters

  * remove the element

If you return a Data::Dump::Tree::Type::Nothing replacement in your filter, the element will not be displayed at all.

    multi sub header_filter($dumper, \replacement, Tomatoe $s, $, $)
    {
    replacement = Data::Dump::Tree::Type::Nothing ;
    }

As DDT streams the rendering, it can not go back to fix the glyphs of the previous element, this will probably show as slightly wrong tree lines.

  * or reduce the type's rendering in a type handler

This does not remove the element but can be useful, create a type handler which renders the type with minimal text. This is sometime preferable to removing.

### In elements filters

  * use an elements filter for the **container** of the type you want to remove

If the element you don't want to see only appears in some containers, you can create a type handler, or filter, for that container type and weed out any reference to the element you don't want to see.

  * or reduce the element rendering

Returning a Data::Dump::Tree::Type::Nothing.new as value, that type renders an empty string.

    multi sub elements_filter( ... )
    {
	    # other elements data ...

	    # the element to reduce rendering of

	    # key          # binder   #value
	    ('your key',   '',        Data::Dump::Tree::Type::Nothing.new),
    }

Color Blob Mode (for lack of a better name)
-------------------------------------------

When rendering very large data structures the default coloring helps, a better way to render large data set is to turn off coloring for most of the data and highlight only the data that is of greater interest. This makes it easier to visually skip large amount of data quickly. The best way of highlighting is by using background color not text color.

You can define "glyph filter" that controls the shape and color of the glyphs.

An example can be found in *examples/background_color.pl6*. A few renderings are generated, some look noisy but they are there to show you the different possibilities, the most interesting examples are the ones that highlight as little as possible. Remember to pass :!color to DDT so element coloring is off.

A simpler example is in *examples/html.pl6*, it uses a role defined in <Data::Dump::Tree::ColorBlobLevel> to set blob colors and filters to transform **DOM::Tiny** parsed data into a rendering more *"HTML"* like.

    use Data::Dump::Tree::ColorBlobLevel ;

    my $d = Data::Dump::Tree.new:
                :string_type(''),
                :string_quote('"'),
                :does[DDTR::ColorBlobLevel],
                :color_kbs,
                :header_filters[&header],
                :elements_filters[&elements],
                :nl ;

    # you can also override foreground and background color per level
    # after you have used the ColorBlobLevel role

    # $d.blob_colors = <  on_125 on_61 on_33 on_37 on_64 > ;
    # $d.blob_colors_fg = < 0 37 64 61> ;

This mode also work surprisingly well for very short renderings, in that case try to use role *DDTR::FixedGlyphs*.

Roles provided with Data::Dump::Tree
------------------------------------

Data::Dump::Tree comes with a few extra roles that are not **does**'ed by the object returned by new()

Please feel free to send me roles you think would be useful to other.

You are welcome to make your own distribution for the roles too, I recommend using namespace DDTR::YourRole.

### DDTR::AsciiGlyphs

Uses ASCII codes rather than Unicode to render the tree.

### DDTR::CompactUnicodeGlyphs

This is the tightest rendering as only one character per level is used to display the tree glyphs.

### DDTR::PerlString

Renders string containing control codes (eg: \n, ANSI, ...) with backslashed codes and hex values.

### DDTR::FixedGlyphs

Replace all the glyphs by a single glyph; default is a two spaces glyph.

    my $d = Data::Dump::Tree.new does DDTR::FixedGlyphs(' . ') ;

### DDTR::NumberedLevel

Will add the level of the elements to the tree glyphs, useful with huge trees. If a Superscribe role is on, the level umber will also be superscribed

### DDTR::SuperscribeType

Use this role to display the type in Unicode superscript letters.

### DDTR::SuperscribeAddress

Use this role to display the address in Unicode superscript letters.

You can also use the method it provides in your type handlers and filters.

### DDTR::Superscribe

Use this role to display the type and address in Unicode superscript letters.

### Data::Dump::Tree::ColorBlobLevel

Colors the rendering per level.

### Match objects

_Match_ objects are displayed as the string that it matched as well as the match start and end position (inclusive, unlike .perl).

    # multiline match
    aaaaa
    aaaaa
    aaaaa
    aaaaa
    [0..23]

    # same match with PerlString role
    "'aaaaa\naaaaa\naaaaa\naaaaa\n'[0..23]"

Some Roles are provided to allows you to change how Match object are displayed.

#### DDTR::MatchLimitString

Limits the length of the match string.

    # default max length of 10 characters
    aaaaa\naaaa(+14)[0..23]

You can set the maximum string length either by specifying a length when the role is added to the dumper.

    $dumper does DDTR::MatchLimit(15) ;

    aaaaa\naaaaa\n(+12)'[0..23]

or by setting the _$.match_string_limit_ member variable

    $dumper does DDTR::MatchLimit ;
    $dumper.match_string_limit = 15 ;

    aaaaa\naaaaa\n(+12)[0..23]

The specified length is displayed, the length of the remaining part is displayed within parenthesis.

#### DDTR::MatchDetails

Give complete details about a Match. The match string is displayed as well as the match start and end position.

You can set the maximum string length either by specifying a length when the role is added to the dumper or by setting the _$.match_string_limit_ member variable.

    # from examples/match.pl

    Match    [passwords]\n        jack=password1\n (+74) ⁰··¹¹³
    ├ <section>  ⁰··⁶⁸
    │ ├ <header> [passwords]⁴··¹⁴
    │ ├ <kvpair>
    │ │ ├ <key> jack ²⁴··²⁷
    │ │ └ <value> password1 ²⁹··³⁷
    │ └ <kvpair>
    │   ├ <key> joy ⁴⁷··⁴⁹
    │   └ <value> muchmoresecure123 ⁵¹··⁶⁷
    └ <section>  ⁶⁹··¹¹³
      ├ <header> [quotas]⁷³··⁸⁰
      ├ <kvpair>
      │ ├ <key> jack ⁹⁰··⁹³
      │ └ <value> 123 ⁹⁵··⁹⁷
      └ <kvpair>
        ├ <key> joy ¹⁰⁷··¹⁰⁹
        └ <value> 42 ¹¹¹··¹¹²

Custom Setup Roles
------------------

If you configure DDT in different ways to render different types, and you should, you will en up writing boilerplate setup code everywhere, you can define functions to return a setup object (or call ddt) or you can use a *custom setup role*. Custom Setup roles define a **custom_setup** method which is called by DDT before rendering your data.

A complete example can be found in *examples/CustomSetup/CustomSetup.pm* and *examples/custom_setup.pl*.

BUGS
====

Submit bugs (preferably as executable tests) and feel free to make suggestions.

Dumper Exception
----------------

As this module uses the MOP interface, it happens that it may use interfaces not implemented by some internal classes.

An example is Grammar that I tried to dump and got an exception about a class that I didn't even know existed.

Those exception are caught and displayed by the dumper as "DDT Exception: the_caught_exception"

Please let me know about them so I can add the necessary handlers to the distribution.

AUTHOR
======

Nadim ibn hamouda el Khemir https://github.com/nkh

Do not hesitate to ask for help.

LICENSE
=======

This program is free software; you can redistribute it and/or modify it under the same terms as Perl6 itself.

SEE-ALSO
========

README.md in the example directory

Perl 5:

  * Data::TreeDumper

Perl 6:

  * Data::Dump

  * Pretty::Printer

gha_language: Raku


text:
# MaintenanceConsole

A library for Teensy 3+ that implements a serial port interface that acts as a maintenance console with features:

* A built-in, extremely simple ftp service for SD card file management.
* Assign console to any non-software serial interface
* Pass custom commands to main program for processing
* Optional flag to use for suppressing main program output when in maintenance mode.
* Two initialization function forms:
  * One only requires the name of the serial port to be used for maintenance interface.
    * Main program must initialize SD card and maintenance port.
  * Another also requires serial port baud rate, SD chip select pin, and a boolean flag for output enabling (need not be used)
    * Main program doesn't initialize SD card or maintenance port.

For project status see the [Wiki](https://github.com/lnigra/MaintenanceConsole/wiki)

repository: lnigra/MaintenanceConsole

repo_name: lnigra/MaintenanceConsole


text:
## What Is Ownership?

*Ownership* is a set of rules that governs how a Rust program manages memory.
All programs have to manage the way they use a computer’s memory while running.
Some languages have garbage collection that constantly looks for no-longer used
memory as the program runs; in other languages, the programmer must explicitly
allocate and free the memory. Rust uses a third approach: memory is managed
through a system of ownership with a set of rules that the compiler checks. If
any of the rules are violated, the program won’t compile. None of the features
of ownership will slow down your program while it’s running.

Because ownership is a new concept for many programmers, it does take some time
to get used to. The good news is that the more experienced you become with Rust
and the rules of the ownership system, the easier you’ll find it to naturally
develop code that is safe and efficient. Keep at it!

When you understand ownership, you’ll have a solid foundation for understanding
the features that make Rust unique. In this chapter, you’ll learn ownership by
working through some examples that focus on a very common data structure:
strings.

> ### The Stack and the Heap
>
> Many programming languages don’t require you to think about the stack and the
> heap very often. But in a systems programming language like Rust, whether a
> value is on the stack or the heap affects how the language behaves and why
> you have to make certain decisions. Parts of ownership will be described in
> relation to the stack and the heap later in this chapter, so here is a brief
> explanation in preparation.
>
> Both the stack and the heap are parts of memory available to your code to use
> at runtime, but they are structured in different ways. The stack stores
> values in the order it gets them and removes the values in the opposite
> order. This is referred to as *last in, first out*. Think of a stack of
> plates: when you add more plates, you put them on top of the pile, and when
> you need a plate, you take one off the top. Adding or removing plates from
> the middle or bottom wouldn’t work as well! Adding data is called *pushing
> onto the stack*, and removing data is called *popping off the stack*. All
> data stored on the stack must have a known, fixed size. Data with an unknown
> size at compile time or a size that might change must be stored on the heap
> instead.
>
> The heap is less organized: when you put data on the heap, you request a
> certain amount of space. The memory allocator finds an empty spot in the heap
> that is big enough, marks it as being in use, and returns a *pointer*, which
> is the address of that location. This process is called *allocating on the
> heap* and is sometimes abbreviated as just *allocating*. Pushing values onto
> the stack is not considered allocating. Because the pointer to the heap is a
> known, fixed size, you can store the pointer on the stack, but when you want
> the actual data, you must follow the pointer. Think of being seated at a
> restaurant. When you enter, you state the number of people in your group, and
> the staff finds an empty table that fits everyone and leads you there. If
> someone in your group comes late, they can ask where you’ve been seated to
> find you.
>
> Pushing to the stack is faster than allocating on the heap because the
> allocator never has to search for a place to store new data; that location is
> always at the top of the stack. Comparatively, allocating space on the heap
> requires more work, because the allocator must first find a big enough space
> to hold the data and then perform bookkeeping to prepare for the next
> allocation.
>
> Accessing data in the heap is slower than accessing data on the stack because
> you have to follow a pointer to get there. Contemporary processors are faster
> if they jump around less in memory. Continuing the analogy, consider a server
> at a restaurant taking orders from many tables. It’s most efficient to get
> all the orders at one table before moving on to the next table. Taking an
> order from table A, then an order from table B, then one from A again, and
> then one from B again would be a much slower process. By the same token, a
> processor can do its job better if it works on data that’s close to other
> data (as it is on the stack) rather than farther away (as it can be on the
> heap). Allocating a large amount of space on the heap can also take time.
>
> When your code calls a function, the values passed into the function
> (including, potentially, pointers to data on the heap) and the function’s
> local variables get pushed onto the stack. When the function is over, those
> values get popped off the stack.
>
> Keeping track of what parts of code are using what data on the heap,
> minimizing the amount of duplicate data on the heap, and cleaning up unused
> data on the heap so you don’t run out of space are all problems that ownership
> addresses. Once you understand ownership, you won’t need to think about the
> stack and the heap very often, but knowing that the main purpose of ownership
> is to manage heap data can help explain why it works the way it does.

### Ownership Rules

First, let’s take a look at the ownership rules. Keep these rules in mind as we
work through the examples that illustrate them:

* Each value in Rust has a variable that’s called its *owner*.
* There can only be one owner at a time.
* When the owner goes out of scope, the value will be dropped.

### Variable Scope

Now that we’re past basic Rust syntax, we won’t include all the `fn main() {`
code in examples, so if you’re following along, make sure to put the following
examples inside a `main` function manually. As a result, our examples will be a
bit more concise, letting us focus on the actual details rather than
boilerplate code.

As a first example of ownership, we’ll look at the *scope* of some variables. A
scope is the range within a program for which an item is valid. Take the
following variable:

```rust
let s = "hello";
```

The variable `s` refers to a string literal, where the value of the string is
hardcoded into the text of our program. The variable is valid from the point at
which it’s declared until the end of the current *scope*. Listing 4-1 shows a
program with comments annotating where the variable `s` would be valid.

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-01/src/main.rs:here}}
```

Listing 4-1: A variable and the scope in which it is
valid

In other words, there are two important points in time here:

* When `s` comes *into scope*, it is valid.
* It remains valid until it goes *out of scope*.

At this point, the relationship between scopes and when variables are valid is
similar to that in other programming languages. Now we’ll build on top of this
understanding by introducing the `String` type.

### The `String` Type

To illustrate the rules of ownership, we need a data type that is more complex
than those we covered in the [“Data Types”][data-types] section
of Chapter 3. The types covered previously are all a known size, can be stored
on the stack and popped off the stack when their scope is over, and can be
quickly and trivially copied to make a new, independent instance if another
part of code needs to use the same value in a different scope. But we want to
look at data that is stored on the heap and explore how Rust knows when to
clean up that data, and the `String` type is a great example.

We’ll concentrate on the parts of `String` that relate to ownership. These
aspects also apply to other complex data types, whether they are provided by
the standard library or created by you. We’ll discuss `String` in more depth in
[Chapter 8][ch8].

We’ve already seen string literals, where a string value is hardcoded into our
program. String literals are convenient, but they aren’t suitable for every
situation in which we may want to use text. One reason is that they’re
immutable. Another is that not every string value can be known when we write
our code: for example, what if we want to take user input and store it? For
these situations, Rust has a second string type, `String`. This type manages
data allocated on the heap and as such is able to store an amount of text that
is unknown to us at compile time. You can create a `String` from a string
literal using the `from` function, like so:

```rust
let s = String::from("hello");
```

The double colon `::` operator allows us to namespace this particular `from`
function under the `String` type rather than using some sort of name like
`string_from`. We’ll discuss this syntax more in the [“Method
Syntax”][method-syntax] section of Chapter 5 and when we talk
about namespacing with modules in [“Paths for Referring to an Item in the
Module Tree”][paths-module-tree] in Chapter 7.

This kind of string *can* be mutated:

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-01-can-mutate-string/src/main.rs:here}}
```

So, what’s the difference here? Why can `String` be mutated but literals
cannot? The difference is how these two types deal with memory.

### Memory and Allocation

In the case of a string literal, we know the contents at compile time, so the
text is hardcoded directly into the final executable. This is why string
literals are fast and efficient. But these properties only come from the string
literal’s immutability. Unfortunately, we can’t put a blob of memory into the
binary for each piece of text whose size is unknown at compile time and whose
size might change while running the program.

With the `String` type, in order to support a mutable, growable piece of text,
we need to allocate an amount of memory on the heap, unknown at compile time,
to hold the contents. This means:

* The memory must be requested from the memory allocator at runtime.
* We need a way of returning this memory to the allocator when we’re
  done with our `String`.

That first part is done by us: when we call `String::from`, its implementation
requests the memory it needs. This is pretty much universal in programming
languages.

However, the second part is different. In languages with a *garbage collector
(GC)*, the GC keeps track of and cleans up memory that isn’t being used
anymore, and we don’t need to think about it. In most languages without a GC,
it’s our responsibility to identify when memory is no longer being used and
call code to explicitly return it, just as we did to request it. Doing this
correctly has historically been a difficult programming problem. If we forget,
we’ll waste memory. If we do it too early, we’ll have an invalid variable. If
we do it twice, that’s a bug too. We need to pair exactly one `allocate` with
exactly one `free`.

Rust takes a different path: the memory is automatically returned once the
variable that owns it goes out of scope. Here’s a version of our scope example
from Listing 4-1 using a `String` instead of a string literal:

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-02-string-scope/src/main.rs:here}}
```

There is a natural point at which we can return the memory our `String` needs
to the allocator: when `s` goes out of scope. When a variable goes out of
scope, Rust calls a special function for us. This function is called
[`drop`][drop], and it’s where the author of `String` can put
the code to return the memory. Rust calls `drop` automatically at the closing
curly bracket.

> Note: In C++, this pattern of deallocating resources at the end of an item’s
> lifetime is sometimes called *Resource Acquisition Is Initialization (RAII)*.
> The `drop` function in Rust will be familiar to you if you’ve used RAII
> patterns.

This pattern has a profound impact on the way Rust code is written. It may seem
simple right now, but the behavior of code can be unexpected in more
complicated situations when we want to have multiple variables use the data
we’ve allocated on the heap. Let’s explore some of those situations now.

#### Ways Variables and Data Interact: Move

Multiple variables can interact with the same data in different ways in Rust.
Let’s look at an example using an integer in Listing 4-2.

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-02/src/main.rs:here}}
```

Listing 4-2: Assigning the integer value of variable `x`
to `y`

We can probably guess what this is doing: “bind the value `5` to `x`; then make
a copy of the value in `x` and bind it to `y`.” We now have two variables, `x`
and `y`, and both equal `5`. This is indeed what is happening, because integers
are simple values with a known, fixed size, and these two `5` values are pushed
onto the stack.

Now let’s look at the `String` version:

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-03-string-move/src/main.rs:here}}
```

This looks very similar, so we might assume that the way it works would be the
same: that is, the second line would make a copy of the value in `s1` and bind
it to `s2`. But this isn’t quite what happens.

Take a look at Figure 4-1 to see what is happening to `String` under the
covers. A `String` is made up of three parts, shown on the left: a pointer to
the memory that holds the contents of the string, a length, and a capacity.
This group of data is stored on the stack. On the right is the memory on the
heap that holds the contents.

Figure 4-1: Representation in memory of a `String`
holding the value `"hello"` bound to `s1`

The length is how much memory, in bytes, the contents of the `String` is
currently using. The capacity is the total amount of memory, in bytes, that the
`String` has received from the allocator. The difference between length
and capacity matters, but not in this context, so for now, it’s fine to ignore
the capacity.

When we assign `s1` to `s2`, the `String` data is copied, meaning we copy the
pointer, the length, and the capacity that are on the stack. We do not copy the
data on the heap that the pointer refers to. In other words, the data
representation in memory looks like Figure 4-2.

Figure 4-2: Representation in memory of the variable `s2`
that has a copy of the pointer, length, and capacity of `s1`

The representation does *not* look like Figure 4-3, which is what memory would
look like if Rust instead copied the heap data as well. If Rust did this, the
operation `s2 = s1` could be very expensive in terms of runtime performance if
the data on the heap were large.

Figure 4-3: Another possibility for what `s2 = s1` might
do if Rust copied the heap data as well

Earlier, we said that when a variable goes out of scope, Rust automatically
calls the `drop` function and cleans up the heap memory for that variable. But
Figure 4-2 shows both data pointers pointing to the same location. This is a
problem: when `s2` and `s1` go out of scope, they will both try to free the
same memory. This is known as a *double free* error and is one of the memory
safety bugs we mentioned previously. Freeing memory twice can lead to memory
corruption, which can potentially lead to security vulnerabilities.

To ensure memory safety, after the line `let s2 = s1`, Rust considers `s1` as
no longer valid. Therefore, Rust doesn’t need to free anything when `s1` goes
out of scope. Check out what happens when you try to use `s1` after `s2` is
created; it won’t work:

```rust,ignore,does_not_compile
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/src/main.rs:here}}
```

You’ll get an error like this because Rust prevents you from using the
invalidated reference:

```console
{{#include ../listings/ch04-understanding-ownership/no-listing-04-cant-use-after-move/output.txt}}
```

If you’ve heard the terms *shallow copy* and *deep copy* while working with
other languages, the concept of copying the pointer, length, and capacity
without copying the data probably sounds like making a shallow copy. But
because Rust also invalidates the first variable, instead of calling it a
shallow copy, it’s known as a *move*. In this example, we would say that
`s1` was *moved* into `s2`. So what actually happens is shown in Figure 4-4.

Figure 4-4: Representation in memory after `s1` has been
invalidated

That solves our problem! With only `s2` valid, when it goes out of scope, it
alone will free the memory, and we’re done.

In addition, there’s a design choice that’s implied by this: Rust will never
automatically create “deep” copies of your data. Therefore, any *automatic*
copying can be assumed to be inexpensive in terms of runtime performance.

#### Ways Variables and Data Interact: Clone

If we *do* want to deeply copy the heap data of the `String`, not just the
stack data, we can use a common method called `clone`. We’ll discuss method
syntax in Chapter 5, but because methods are a common feature in many
programming languages, you’ve probably seen them before.

Here’s an example of the `clone` method in action:

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-05-clone/src/main.rs:here}}
```

This works just fine and explicitly produces the behavior shown in Figure 4-3,
where the heap data *does* get copied.

When you see a call to `clone`, you know that some arbitrary code is being
executed and that code may be expensive. It’s a visual indicator that something
different is going on.

#### Stack-Only Data: Copy

There’s another wrinkle we haven’t talked about yet. This code using integers –
part of which was shown in Listing 4-2 – works and is valid:

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-06-copy/src/main.rs:here}}
```

But this code seems to contradict what we just learned: we don’t have a call to
`clone`, but `x` is still valid and wasn’t moved into `y`.

The reason is that types such as integers that have a known size at compile
time are stored entirely on the stack, so copies of the actual values are quick
to make. That means there’s no reason we would want to prevent `x` from being
valid after we create the variable `y`. In other words, there’s no difference
between deep and shallow copying here, so calling `clone` wouldn’t do anything
different from the usual shallow copying and we can leave it out.

Rust has a special annotation called the `Copy` trait that we can place on
types that are stored on the stack like integers are (we’ll talk more about
traits in Chapter 10). If a type implements the `Copy` trait, a variable is
still valid after assignment to another variable. Rust won’t let us annotate a
type with `Copy` if the type, or any of its parts, has implemented the `Drop`
trait. If the type needs something special to happen when the value goes out of
scope and we add the `Copy` annotation to that type, we’ll get a compile-time
error. To learn about how to add the `Copy` annotation to your type to
implement the trait, see [“Derivable Traits”][derivable-traits]
in Appendix C.

So what types implement the `Copy` trait? You can check the documentation for
the given type to be sure, but as a general rule, any group of simple scalar
values can implement `Copy`, and nothing that requires allocation or is some
form of resource can implement `Copy`. Here are some of the types that
implement `Copy`:

* All the integer types, such as `u32`.
* The Boolean type, `bool`, with values `true` and `false`.
* All the floating point types, such as `f64`.
* The character type, `char`.
* Tuples, if they only contain types that also implement `Copy`. For example,
  `(i32, i32)` implements `Copy`, but `(i32, String)` does not.

### Ownership and Functions

The semantics for passing a value to a function are similar to those for
assigning a value to a variable. Passing a variable to a function will move or
copy, just as assignment does. Listing 4-3 has an example with some annotations
showing where variables go into and out of scope.

Filename: src/main.rs

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-03/src/main.rs}}
```

Listing 4-3: Functions with ownership and scope
annotated

If we tried to use `s` after the call to `takes_ownership`, Rust would throw a
compile-time error. These static checks protect us from mistakes. Try adding
code to `main` that uses `s` and `x` to see where you can use them and where
the ownership rules prevent you from doing so.

### Return Values and Scope

Returning values can also transfer ownership. Listing 4-4 shows an example
of a function that returns some value, with similar annotations as those in
Listing 4-3.

Filename: src/main.rs

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-04/src/main.rs}}
```

Listing 4-4: Transferring ownership of return
values

The ownership of a variable follows the same pattern every time: assigning a
value to another variable moves it. When a variable that includes data on the
heap goes out of scope, the value will be cleaned up by `drop` unless ownership
of the data has been moved to another variable.

While this works, taking ownership and then returning ownership with every
function is a bit tedious. What if we want to let a function use a value but
not take ownership? It’s quite annoying that anything we pass in also needs to
be passed back if we want to use it again, in addition to any data resulting
from the body of the function that we might want to return as well.

Rust does let us return multiple values using a tuple, as shown in Listing 4-5.

Filename: src/main.rs

```rust
{{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-05/src/main.rs}}
```

Listing 4-5: Returning ownership of parameters

But this is too much ceremony and a lot of work for a concept that should be
common. Luckily for us, Rust has a feature for using a value without
transferring ownership, called *references*.

[data-types]: ch03-02-data-types.html#data-types
[ch8]: ch08-02-strings.html
[derivable-traits]: appendix-03-derivable-traits.html
[method-syntax]: ch05-03-method-syntax.html#method-syntax
[paths-module-tree]: ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html
[drop]: ../std/ops/trait.Drop.html#tymethod.drop

repository: rust-lang-cn/book-cn

gha_language: Rust

repo_name: rust-lang-cn/book-cn


text:
# OCI Terrafrom provider tips and tricks

## Extract compartment resources

```bash
terraform-provider-oci -command=export -compartment_name=<compartment_name> -output_path=./
```

repository: streamnsight/cheat-sheet

repo_name: streamnsight/cheat-sheet


text:
# Sentinel: The Watchtower of Global Issues

![Optional Text](../main/sentinel.png)
# [Demo Video](https://www.youtube.com/watch?v=kjyfBYvqjAc&t=100s&ab_channel=%24and)
## Available at [My Website](http://sentinel.andrewsandell.com)

Sentinel is a website that has compiled data from a number of academic sources to visualize an interactive heatmap of the globe. This allows the user to interact with global issues in a way they never have before.

The site was created with the goal of creating a call to action in users, while providing them the resources and tools they need to incite positive change on a international scale.

The site uses HTML5, CSS, Javascript, and DataMaps.io (http://datamaps.github.io/) an extension on D3.js.

This project was created as a part of SwampHacks 2021.
Available at: http://sentinel.andrewsandell.com/

repository: absandell/Sentinel

repo_name: absandell/Sentinel


text:
> [Go to French version](/fr/Règlements/Décrets,%20ordonnances%20et%20règlements%20statutaires/2002/4.md)

# Designer Remission Order, 2001

**SOR/2002-4**

Enabling authorities:
- [CUSTOMS TARIFF](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md)

Date registered: 13 December 2001

----------

Her Excellency the Governor General in Council, on the recommendation of the Minister of Finance, pursuant to section 115 of the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md)[a], hereby makes the annexed Designer Remission Order, 2001.

a: S.C. 1997, c. 36

## Interpretation

**1** In this Order,

***apparel*** means
- **(a)** any article of heading Nos. 61.01, 61.02, 61.03, 61.04, 61.05, 61.06, 61.07, 61.08, 61.09, 61.10, 61.11, 61.12, 61.13, 61.14, 61.15, 61.16, 61.17, 62.01, 62.02, 62.03, 62.04, 62.05, 62.06, 62.07, 62.08, 62.09, 62.10, 62.11, 62.12, 62.13, 62.14, 62.15, 62.16, 62.17, 65.03, 65.04, 65.05 and 65.06, subheading Nos. 4203.10, 4203.29, 4203.30, 4203.40, 4303.10, 4818.50 and tariff item Nos. 3926.20.92, 3926.20.93, 3926.20.94, 3926.20.95, 3926.20.99, 4015.19.90 and 4015.90.90 in the List of Tariff Provisions set out in the schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md); and
- **(b)** any article of clothing or clothing accessories of subheading No. 4304.00 in that List. (*vêtement*)

***apparel designer*** means an individual who
- **(a)** possesses a degree or diploma in fashion design or apparel design from a recognized educational institution or has an equivalent proficiency in the creation of innovative apparel; and
- **(b)** carries out the creation of innovative apparel, including the conception of styles, the drafting and development of collections, the preparation of sketches, collection boards or story boards, the selection, sampling and testing of fabrics, the preparation of samples of innovative apparel and the retention of any records respecting the creation of innovative apparel, or is directly responsible for those activities being undertaken by other individuals employed by the same employer. (*couturier*)

***collection*** means a product line of original designer apparel to be presented to customers for a specific fashion season. (*collection*)

***fabric*** means all fabric of heading Nos. 51.11, 51.12, 51.13, 52.08, 52.09, 52.10, 52.11, 52.12, 53.09, 53.10, 53.11, 54.07, 54.08, 55.12, 55.13, 55.14, 55.15, 55.16, 56.02, 56.03, 58.01, 58.02, 58.03, 58.04, 58.05, 58.06, 58.07, 58.08, 58.09, 58.10, 58.11, 59.03, 59.06 and 59.07 in the List of Tariff Provisions set out in the schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md) and all fabric of chapter 60 in that List, excluding any fabric that contains aramid fibres. (*tissu*)

***innovative*** means apparel resulting from an on-going creative process that primarily entails the establishment of new relationships among the following principal elements: fabric, colour, assembly, shape and function. (*innovateur*)

***innovative apparel*** means apparel that results from an ongoing creative process that primarily entails the establishment of new relationships among the following principal elements, namely fabric, colour, assembly, shape and function. (*vêtement innovateur*)

***limited quantities***[Repealed, SOR/2004-94, s. 1]

***name***[Repealed, SOR/2003-128, s. 1]

***original designer apparel*** means innovative apparel that is available only in limited quantities, that is created by a recognized apparel designer or a recognized apparel design house and that bears the trademark of that designer or design house, permanently affixed, as its principal commercial identification. (*vêtement de couturier original*)

***recognized apparel designer*** means an individual who
- **(a)** possesses a degree or diploma in fashion design or apparel design from a recognized educational institution or has an equivalent proficiency in the creation of innovative apparel;
- **(b)** carries out the creation of innovative apparel, including the conception of styles, the drafting and development of collections, the preparation of sketches, collection boards or story boards, the selection, sampling and testing of fabrics, the preparation of samples of innovative apparel, and the retention of any records respecting the creation of innovative apparel, or is directly responsible for those activities being undertaken by other individuals employed by the same employer; and
- **(c)** has control, whether in their own right or indirectly through a partnership, corporation, trust or any other entity, over the use of their trademark. (*couturier reconnu*)

***recognized apparel design house*** means a company or partnership that
- **(a)** employs at least one apparel designer; and
- **(b)** has control, whether in its own right or indirectly through a partnership, corporation, trust or any other entity, over the use of its trademark. (*maison de couture reconnue*)

***trademark*** means a word, symbol or design, or any combination of these, used to distinguish the wares of one person or organization from those of others in the marketplace. (*marque de commerce*)

***winter outerwear*** means lined and insulated apparel that is worn over other clothing for protection against the cold. (*vêtement de dessus*)
> SOR/2002-169, s. 1; SOR/2003-128, s. 1; SOR/2003-268, s. 1; SOR/2004-94, s. 1; SOR/2005-351, s. 1; 2014, c. 20, s. 366(E).

## Application

**2** This Order applies to producers of original designer apparel who meet the following criteria:
- **(a)** they are engaged in the creation, the manufacture, or the contracting of the manufacture, and the sale of original designer apparel;
- **(b)** they are a sole proprietorship, corporation or partnership that employs at least one apparel designer or recognized apparel designer or are themselves recognized apparel designers; and
- **(c)** a minimum of 85 per cent of their total net sales revenue is generated from the sale of their original designer apparel for each calendar year for which they claim a remission.
> SOR/2003-128, s. 2; SOR/2003-268, s. 2; SOR/2004-94, s. 2.

## Remission

**3**

- **(1)** Subject to subsection (2) and if the conditions set out in section 4 are met, remission is granted to any producer of original designer apparel of the customs duties paid or payable under the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md) in respect of fabrics imported into Canada during the period beginning on December 13, 2001 and ending on December 31, 2014.

- **(2)** In the case of fabrics used for the manufacture of swimwear of subheading Nos. 6112.31, 6112.39, 6112.41, 6112.49, 6211.11 and 6211.12 in the List of Tariff Provisions set out in the schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md), remission is granted for the period beginning on November 1, 2002 and ending on December 31, 2014.
> SOR/2004-94, s. 3; SOR/2005-351, s. 2; SOR/2010-263, s. 1.

## Conditions

**4** Remission is granted on the following conditions:
- **(a)** the fabric in respect of which the claim is made is to be used by the producer of original designer apparel solely for the manufacture of its own men's or women's original designer apparel of chapters 61, 62 and 65 in the List of Tariff Provisions set out in the Schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md), except for the following items:
	- **(i)** hosiery of heading No. 61.15 in the List of Tariff Provisions set out in the Schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md),
	- **(ii)** [Repealed, SOR/2004-94, s. 4]
	- **(iii)** men's underpants and briefs of subheadings Nos. 6107.11, 6107.12, 6107.19, 6207.11 and 6207.19 in the List of Tariff Provisions set out in the Schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md);
	- **(iv)** women's briefs and panties of subheadings Nos. 6108.21, 6108.22, 6108.29, 6208.91, 6208.92 and 6208.99 in the List of Tariff Provisions set out in the Schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md),
	- **(v)** women's foundation undergarments of heading No. 62.12 in the List of Tariff Provisions set out in the Schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md),
	- **(vi)** winter outerwear with an outershell of fabrics of chapters 54, 55 or 59, or heading Nos. 52.10, 52.11 or 52.12 in the List of Tariff Provisions set out in the Schedule to the [Customs Tariff](/en/Acts/Statutes%20of%20Canada/1997/c.%2036.md),
	- **(vii)** apparel that must be worn to protect the wearer from physical harm while performing particular tasks in a work environment, and
	- **(viii)** apparel chosen by an employer to be worn exclusively by its employees during working hours;
- **(b)** in respect of the four year period commencing on December 13, 2001, the fabric has a value for duty of $14.00 or more per square metre, indexed annually, in accordance with the administrative guidelines issued by the Canada Border Services Agency, to compensate for inflation;
- **(c)** a claim for remission is made to the Minister of Public Safety and Emergency Preparedness within four years of the date of importation;
- **(d)** if the producer of original designer apparel is not the importer of record of the fabric, the claim is accompanied by a waiver from that importer waiving that importer's right to claim a drawback, refund or remission of the customs duties paid or payable in respect of the fabric;
- **(e)** the producer of original designer apparel submits to the Minister of Public Safety and Emergency Preparedness semi-annual reports that contain information relating to the volume, value and use of fabrics in respect of which a claim for remission was made in that period and any other relevant information necessary to the administration of this Order;
- **(f)** the producer of original designer apparel agrees that it shall be subject to audit by the Canada Border Services Agency for the purpose of verifying the accuracy of the amount of remission and whether the information supplied to determine eligibility for remission is accurate and complete and whether the facts upon which the Agency relied to determine eligibility for remission remain unchanged in all material respects; and
- **(g)** if the Canada Border Services Agency elects to conduct the audit referred to in paragraph (f), the information supplied shall be found to be accurate and complete and the facts relied on shall be found to have remained unchanged in all material respects.
> SOR/2004-94, s. 4; SOR/2005-351, s. 4; SOR/2010-263, s. 2.

## Coming into Force

**5** This Order comes into force on the day on which it is registered.

repository: TravisMadill/CanadianLaws

path: /en/Regulations/Statutory Orders and Regulations/2002/4.md

repo_name: TravisMadill/CanadianLaws


text:
---
title: "Trace.axd Information Leak"
alertid: 40029
alerttype: "Active Scan Rule"
status: beta
type: alert
date: 2020-07-20 08:53:37.296Z
lastmod: 2020-07-20 08:53:37.296Z
---
### Type: Active Scan

### Risk: Medium

### Description

The ASP.NET Trace Viewer (trace.axd) was found to be available. This component can leak a significant amount of valuable information.

### Solution

Consider whether or not Trace Viewer is actually required in production, if it isn't then disable it. If it is then ensure access to it requires authentication and authorization.

### References

* https://msdn.microsoft.com/en-us/library/bb386420.aspx
* https://msdn.microsoft.com/en-us/library/wwh16c6c.aspx
* https://www.dotnetperls.com/trace

### CWE: [215](https://cwe.mitre.org/data/definitions/215.html)

### WASC:  13

### Code

 * [org/zaproxy/zap/extension/ascanrulesBeta/TraceAxdScanRule.java](https://github.com/zaproxy/zap-extensions/blob/master/addOns/ascanrulesBeta/src/main/java/org/zaproxy/zap/extension/ascanrulesBeta/TraceAxdScanRule.java)

###### Last updated: 2020-07-20 08:53:37.296Z

repository: zakrush/zaproxy-website

repo_name: zakrush/zaproxy-website


text:
# RailsEngine

RailsEngine is a Rails api application that provides data from a number of resources, and produces business logic for a number of different metrics.  It's built on Rails 5.1.6 and Postgresql 10.4, and returns JSON data at each endpoint.  This project was created by Colin Armstrong (github: colinwarmstrong) and Andrew Mockett(github: MacInnes) for Turing's Backend Engineering program.

# Setup:

First, clone this repository onto your computer:
```
git clone git@github.com:MacInnes/rails_engine.git
```
Then be sure to run `bundle install` from inside the project directory.  Once that is complete, run the following command to create the database:
```
rake db:{drop,create,migrate}
```
In order to seed the database with the included CSV data, simply run the following command:
```
rake import_data
```
If everything is setup correctly, you should be able to run `rspec` from the command line to run our local test suite.

# Gems used:
* Active_Model_Serializers
* Byebug
* Factory-Bot
* Faker
* Pry
* Rspec-Rails
* SimpleCov
* Shoulda-Matchers
* Spring

# API Endpoints:

There are 6 main resources used in this application:
* Merchants
* Customers
* Items
* Invoices
* Invoice_items
* Transactions

For each of these 6 resources, there are endpoints for showing all records or a single record:
* GET `/api/v1/(resource_name)`
* GET `/api/v1/(resource_name)/:id`

In addition, there are a few related endpoints as well:
* GET `/api/v1/(resource_name)/:id/(related_resource_name)`

The related resources are:
* Merchants: Items, Invoices
* Invoices: Transactions, Invoice_items, Items, Customer, Merchant
* Invoice_items: Invoices, Items
* Items: Invoice_items, Merchants
* Transactions: Invoices
* Customers: Invoices, Transactions

There are also a number of Business Intelligence endpoints:
* GET `/api/v1/merchants/most_revenue?quantity=x`
* GET `/api/v1/merchants/most_items?quantity=x`
* GET `/api/v1/merchants/revenue?date=x`
* GET `/api/v1/merchants/:id/revenue`
* GET `/api/v1/merchants/:id/revenue?date=x`
* GET `/api/v1/merchants/:id/favorite_customer`
* GET `/api/v1/merchants/:id/customers_with_pending_invoices`
* GET `/api/v1/items/most_revenue?quantity=x`
* GET `/api/v1/items/most_items?quantity=x`
* GET `/api/v1/items/:id/best_day`
* GET `/api/v1/customers/:id/favorite_merchant`

## Contributing

1. Fork the repo
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Create your new feature (make sure to test it and run RSpec)
4.  Push up your branch (`git push origin my-new-feature`)
6. Create a new pull request

Or email the author at<EMAIL_ADDRESS>with any questions, comments, or concerns.

gha_language: Ruby


text:
## Aroma

Command line utility to compile [CoffeeScript](http://coffeescript.org/) objects into [property list](http://en.wikipedia.org/wiki/Property_list) files.

---

### Rationale

A plist file is very verbose and cumbersome to edit. Aroma lets you define your property lists in CoffeeScript with a much more terse syntax with the added benefit of using logic and variables.

Just create an .aroma.coffee file that exports the object you wish to use:

```coffeescript
foo = "Dynamic!"

module.exports =
  foo: foo
  baz: "bar"
```

The generated plist will be:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>foo</key>
    <string>Dynamic!</string>
    <key>baz</key>
    <string>bar</string>
  </dict>
</plist>
```

Notice how much more terse the coffee file is? Did you also notice how we used a variable!

---

### Usage

__Compile a single file:__

* `$ aroma -c myfile.aroma.coffee`

__Compile all the aroma coffee files in `./src` to plist files in `./lib`:__

* `$ aroma -o lib -c src`

__Watch the current directory for any changes and automatically compile .aroma.coffee files:__

* `$ aroma -w`

__Specify what extension to save the property list as:__

* `$ aroma -e tmTheme`

---

### Installation

Aroma is a Node.js module so first you must install [Node.js](http://nodejs.org/) then run `npm install -g aroma`

---

### License

MIT

repository: jisaacks/Aroma

gha_language: CoffeeScript

repo_name: jisaacks/Aroma


text:
RFPasswordGenerator
===================

I found this (http://neilang.com/entries/how-to-write-a-password-generator/) great article about writing your own Password Generator so I decided to create one.

![Password Generator](http://i.imgur.com/22nshMQ.png)

How To Get Started
==================

1.  Drag and drop RFPasswordGenerator Class into your project.
2.  `#import "RFPasswordGenerator.h"`
3.  Use 3 different security options:

     `NSString *myHighSecurityPassword = [RFPasswordGenerator generateHighSecurityPassword];`

     `NSString *myMediumSecurityPassword = [RFPasswordGenerator generateMediumSecurityPassword];`

     `NSString *myLowSecurityPassword = [RFPasswordGenerator generateLowSecurityPassword]`

Created By
==========

Ricardo Funk ([@rfunk82](http://www.twitter.com/rfunk82))

License
=======

> This is licensed under an MIT License:

> Copyright (c) 2013 Ricardo Funk

> 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.

> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.


text:
---
title: Activating the "password reset" feature of Apostrophe
layout: tutorial
---

## Password Reset

Apostrophe includes a "password reset" feature for your users. This feature follows the usual pattern: the user must prove they control the email address associated with their account.

For security reasons, and because most sites don't have the [apostrophe-email](/tutorials/devops/email.md) module configured yet, this option must be turned on for your site:

{% code-tabs %}
{% code-tabs-item title="app.js" %}
```javascript
modules: {
  'apostrophe-email': {
    // See the nodemailer documentation, many
    // different transports are available, this one
    // matches how PHP does it on Linux servers
    nodemailer: {
      sendmail: true,
      newline: 'unix',
      path: '/usr/sbin/sendmail'
    }
  },
  'apostrophe-login': {
    passwordReset: true,
    // The default: you have 48 hours to use a password reset link,
    // once it is sent to you
    passwordResetHours: 48,
    email: {
      from<EMAIL_ADDRESS>    }
  }
}
```
{% endcode-tabs-item %}
{% endcode-tabs %}

Once you enable the feature, the user will automatically see a "Reset My Password" link at the bottom of the login form at `/login`. If you don't see that link, make sure you haven't previously overridden your `loginBase.html` template.

## User Redirects on Login

By default, after a user logs in, they are redirected to the homepage.

It is possible to customize this behavior.

You can implement a `loginAfterLogin` method in any module. This method takes `req` and an optional callback.

Setting req.redirect will cause Apostrophe to redirect the user to that location.

{% code-tabs %}
{% code-tabs-item title="lib/modules/my-module/index.js" %}
```javascript
module.exports = {
  construct: function(self, options) {
    self.loginAfterLogin = function(req) {
      if (req.user.isSpecialInSomeWay) {
        req.redirect = '/special';
      } else {
        // Just let them go go the home page
      }
    };
  }
};
```
{% endcode-tabs-item %}
{% endcode-tabs %}

*Don't forget to enable your module in `app.js`.*

If you do not set `req.redirect`, the user is redirected to the home page.

For a complete example, check out the [apostrophe-second-chance-login](https://npmjs.org/package/apostrophe-second-chance-login) module, which turns 404's into an opportunity to log in, if a page exists that the user might have the privilege of seeing after logging in.

## What to do when you are locked out of Apostrophe

Apostrophe is a user-friendly system. But every now and then, you may find a way to "lock yourself out" of Apostrophe. Chicken and egg problems can be frustrating, but don't worry! Here's how to resolve these situations.

### 1. You forgot the password for your account

If your site has the "forgot password" feature enabled, you can go to `/login` and click the "forgot password" link. After completing the form be patient and be sure to check your spam folder.

If this feature is not enabled for your site or does not work for you, reach out to a coworker whose account is still functioning. If they have the `admin` permission, they will be able to edit your user via the "Users" dropdown and set a new password.

> If this option does not work for you, it is possible for you (or your developer) to change your password or add a new admin account via the command line. See #2 below.

### 2. Your only `admin` account is in the trash

Maybe you accidentally moved it to the trash, maybe another admin user did. Oops! Now how do you log in?

If you are the developer of the site, or you are in communication with them, you can create a new admin account at the command line:

``` bash
node app apostrophe-users:add admin admin
```

The first argument is the username, the second argument is the group name.

**If you get a duplicate key error,** an admin user may still exist after all. Running this command will prompt you for a new password for the `admin` user:

``` bash
node app apostrophe-users:change-password admin
```

**If you get an error saying there is no `admin` group,** it is possible that you do not have a group by that name. Maybe the group was moved to the trash too. You can create a new `admin` group:

``` bash
node app apostrophe-groups:add admin admin
```

The first argument is the group name, the second is the permission you wish to give the group. The `admin` permission grants full access to everything.

{% hint style='info' %}
If you're reading this and you do not have access to the command line or recognize it, make sure no one else you work with has access to a working admin account first. Then reach out to the developer responsible for your site.
{% endhint %}

### 3. You pasted a bad embed code into an HTML widget

Apostrophe offers a raw HTML widget. It's handy for embed codes, but also risky because many websites offer poor quality embed codes that don't "play nicely with others." Some of these can break Apostrophe's version of the `jQuery` library, which wrecks the editing experience on that page. That is especially serious if it is the home page.

Fortunately, Apostrophe has a built-in workaround to disable raw HTML widgets on the page.

If you are currently looking at this URL (just an example):

```url
https://www.example.com/
```

And the editing interface does not respond, try this URL:

```url
https://www.example.com/?safemode=1
```

Once you gain editing access, look for the HTML widget on the page. It will be easy to find because it will be temporarily displaying the HTML embed source code. Click the icon to edit the widget, and make sure you pasted the embed code correctly.

If you did paste it correctly, it is most likely incompatible with Apostrophe. Click the icon to delete the widget, or edit it and erase the markup it contains. Then find a better embed code, or work with the provider of the embed code to fix its "antisocial" characteristics.

{% hint style='info' %}
The following are common problems that embed code developers need to be aware of:

1. Do not use `document.write` in an embed code. This will break any website that loads your markup "on the fly" after the page is first rendered.

2. Do not install `jQuery` globally (do not overwrite `window.$`). Similarly, do not overwrite `lodash` (`window._`). It is easy to wrap your JavaScript in a closure in which it can still see a convenient `$` variable without breaking other versions of these libraries.
{% endhint %}

repository: nick-hunter/apostrophe-documentation

repo_name: nick-hunter/apostrophe-documentation


text:
# System configuration

If needed, set these system configs ```BEFORE``` using GL's other modules.

```python
import graphlearn as gl
gl.set_xxx
gl.set_yyy

gl.other_models...
```

* Set default neighbor id. Default is ```0```.

When the neighbor count is less than sampling count, fill with a default id.

```python
gl.set_default_neighbor_id(nbr_id)
```

* Set default int attribute value. Default is ```0```.

Fill with the default attribute value for not found nodes or edges when looking up.

```python
gl.set_default_int_attribute(value)
```

* Set default float attribute value. Default is ```0.0```.

Fill with the default attribute value for not found nodes or edges when looking up.

```python
gl.set_default_float_attribute(value)
```

* Set default string attribute value. Default is ```''```.

Fill with the default attribute value for not found nodes or edges when looking up.

```python
gl.set_default_string_attribute(value)
```

* Set inter thread number. Default is ```32```.

Inter threads are used to handle operators and response system request.

```python
gl.set_inter_threadnum(num)
```

* Set intra thread number. Default is ```32```.

Intra threads are used inside operators to speed up.

```python
gl.set_intra_threadnum(num)
```

* Set RPC max message size. Default is ```16MB```.

Usually no need to reset. In some large-scale cases, enlarge it as requirement.

```python
gl.set_rpc_message_max_size(size)
```

[Home](../README.md)

repository: lorinlee/graph-learn

repo_name: lorinlee/graph-learn