text:
Programming in K
================

Array programming languages demand a very different approach to problem solving than garden-variety imperative languages. After you've memorized K's small vocabulary of primitive functions and learned about the wrinkles and shorthand of the syntax you may find that you understand the language, but still don't fully grasp how it can be applied. In this guide I will try to gather examples of problem solving techniques that I discover or find in existing programs, in the hopes that these ideas can help other beginners.

Filtering
---------
You've built a list of values and you want to extract a subset of them that have some property based on a predicate monad `P`. Use `where` (`&`) and then index into the original list to gather the subset:

	P: {~~3!x}    / not multiples of 3
	{x@&P'x}@!20  / filter out matches

If your predicate consists of atomic primitives, you can avoid the `each` (`'`). If your input list is a 0-indexed enumeration, you can avoid the need to index the original list. Thus, the above example could be simplified as follows:

	{&P x}@!20    / get rid of unnecessary indexing and each
	{&~~3!x}@!20  / inline predicate
	&~~3!!20      / eliminate lambda

The use of `where` to solve this kind of problem is an extremely important concept.

K5 adds a special overload to `take` (`#`) which simplifies this pattern, performing essentially `x@&y'x`:

	  (2!)#!8
	1 3 5 7

	  {x~|x}#("racecar";"nope";"bob")
	("racecar"
	 "bob")

Case Selection
--------------
K offers an equivalent to "if" statements in the form of the 3 or more argument version of `$`, sometimes called `cond` for its semantic similarity to the Lisp statement:

	{$[2!x; x%2; 1+3*x]}

This statement checks conditions one after another and falls through to the final case if none of the predicates succeeds. This behavior is useful in many situations. However, if you want to avoid using "cond", you can often replace it by constructing a list and indexing into it, provided each case has no side effects:

	{(1+3*x; x%2)2!x}

This is nicely general and if you augment the list by indexing it to replicate elements you can express complex logic based on a lookup table:

	{(`A;`B;`C)[1 0 0 1 2 1 0]x}

Zipping
-------
You have two lists and you want to map a function `D` over pairings of the elements of these lists. Concatenate the lists and then use `flip` (`+`) to create a list of pairings. You can then apply each pair to `D` by using `eval` (`.`). This works equally well for dyads, triads, tetrads, etc. and an appropriate number of input lists:

	V1: ("A  ";"B  ";"C  ")
	V2: 2 1 3
	D:  {x@(#x)!y+!#x}      / rotate the list x by y positions
	D.'+(V1;V2)             / flip and apply

When you only need to pair up two elements, each-dyad is simpler:

	V1 D'V2

Always consider whether `flip` can make it easier to calculate "with the grain" of your data. If `V1` and `V2` are of different lengths we can insert `take` (`#`) to replicate elements or `drop` (`_`) to remove elements from lists.

Alternatively, it might be easy to construct our desired lists in place provided an index:

	V1: {2!x}          / alternating parity
	V2: {65+x}         / ascii alphabet characters
	D:  {`c$y+x*32}    / make an upper- or lowercase character
	{D[V1 x;V2 x]}'!26

Of course, sometimes we can do the whole operation in parallel and combine the construction of the sequences:

	  `c${65+x+32*2!x}@!26
	"AbCdEfGhIjKlMnOpQrStUvWxYz"

Cartesian Product
-----------------
You want to consider all combinations of two lists of elements via a dyad `D`. This is called a _Cartesian Product_ and can be formed by combining `each left` and `each right`, and possibly joining the results:

	V1: "AB"
	V2: "XYZ"
	D:  {x,y}
	,/V1 D/:\:V2

If the order of results matters (such as if you are doing some kind of minimizing search), reversing the order of the adverbs is equivalent to taking the `flip` of the results:

	  ,/V1 D/:\:V2
	("AX"
	 "AY"
	 "AZ"
	 "BX"
	 "BY"
	 "BZ")

	  ,/V1 D\:/:V2
	("AX"
	 "BX"
	 "AY"
	 "BY"
	 "AZ"
	 "BZ")

	  ,/+V1 D/:\:V2
	("AX"
	 "BX"
	 "AY"
	 "BY"
	 "AZ"
	 "BZ")

If `D` consists of atomic primitives, you can often just use one of `eachleft` or `eachright`:

	  (4+!3)+/:!4
	(4 5 6
	 5 6 7
	 6 7 8
	 7 8 9)

	  (4+!3)+\:!4
	(4 5 6 7
	 5 6 7 8
	 6 7 8 9)

Combining a Cartesian Product with a Filter (as described above) is a straightforward way to approach many search or optimization problems. While a naive K interpreter may perform a great deal of unnecessary work while executing such a program, an interpreter which performs the Cartesian Product lazily using an approach similar to that described in [An APL Machine](http://www.slac.stanford.edu/cgi-wrap/getdoc/slac-r-114.pdf)(1970) could avoid this overhead.

Since this type of operation is so common, there's a primitive which which will handle many such cases- monadic `!` applied to a list, sometimes called "odometer":

	  !3 2
	(0 0 1 1 2 2
	 0 1 0 1 0 1)

	  "ABC"@!3 2
	("AABBCC"
	 "ABABAB")

Iterative Algorithms
--------------------
If an algorithm can be completed in a known number of steps, it is well suited to a solution involving array processing as in the above techniques. Some algorithms, however, must execute for a number of steps which is not easily determined ahead of time or yield a variable number of results depending on the input. K includes some verbs which handle very common algorithms of this nature- for example:

- `find` (dyadic `?`) locates the first instance of a value in a list via a linear search.
- `bin` (dyadic `'`) performs a binary search on a list to find the closest index to a key element.
- `except` (dyadic `^`) removes instances of an element from a list.
- `distinct` (monadic `?`) isolates the unique elements of a list.
- `group` (monadic `=`) collates the indices of matching elements of a list.
- `split` (dyadic `\`) breaks a list at each instance of an element.

When these "irregular" problems come up, the above verbs should come to mind. Do any of them offer a solution, or allow you to break the problem into pieces which are each regular?

Otherwise, we consider the special forms of `over` (`/`) and `scan` (`\`):

- `f/ x` (where `f` is a monadic function) iteratively applies `f` to `x` until the value stops changing or the initial value of `x` is revisited. Also known as _Fixed Point_.
- `n f/ x` (where `f` is a monadic function and `n` is a number) iteratively applies `f` to `x`, `n` times. This is essentially a "for" loop, and often instances of this form could be replaced with a use of `'!`.
- `p f/ x` (where `f` and `p` are monadic functions) iteratively applies `f` to `x` until the predicate `p` applied to `x` evaluates to 0. This is essentially a "do...while" loop and the most general-purpose of the above forms.

The `scan` variations are identical except as with normal uses of `scan` they accumulate a list of intermediate results.

When using the "do...while" forms to implement nontrivial algorithms, it is common to write the body of the loop as taking a tuple containing all the loop's state and returning a new tuple for each iteration:

	  {x[0]<x[1]}{(x[0]*x[0];x[1]*2)}\(2;100)
	(2 100
	 4 200
	 16 400
	 256 800
	 65536 1600)

You might find that `eval` (`.`) is useful for unpacking this tuple into separate arguments, making the loop body and predicate both shorter and easier to understand, especially if tuple elements are used in many places:

	{{x<y}.x}{{(x*x;y*2)}.x}\(2;100)

Sequential Processing
---------------------
Sometimes problems which appear to require sequential processing can be performed in parallel if you provide each iteration with the necessary context. `eachprior` (`':`) handles the most straightforward of these cases. It is often combined with `~` or `-` to find the beginnings of identical runs in a list or find the change between successive elements, respectively:

	  ~~':3 3 4 0 1 1 3 0
	1 0 1 1 1 0 1 1

	  -':3 3 4 0 1 1 3 0
	3 0 1 -4 1 0 2 -3

If you need more context, you can split the list appropriately yourself. To provide sliding windows into a list `x` which each have a length `y`:

	  {+x@(-y-1)_'(!#x)+/:!y}[4 8 9 10 22 3;3]
	(4 8 9
	 8 9 10
	 9 10 22
	 10 22 3)

If you don't want these windows to overlap, `reshape` with a "greedy" `0N` is the ticket:

	  0N 3#4 8 9 10 22 3 7 0 9
	(4 8 9
	 10 22 3
	 7 0 9)

	  0N 2#4 8 9 10 22 3 7 0
	(4 8
	 9 10
	 22 3
	 7 0)

If the iterations are truly sequentially dependent, use dyadic `over`. Consider processing a list of typed characters where each "#" represents a backspace. You can't simply remove every character followed by a "#", as several "#"es may appear consecutively, as in "ab#def##". If we treat the left argument to our dyadic reducing function as a stack we can push elements into with `x,y` and pop elements from with `-1_x`, we can arrive at the following solution:

	  (){$[y="#";-1_x;x,y]}/"ab#def##"
	"ad"

(Or a slightly shorter equivalent, if we're golfing:)

	  (){(x,y;-1_x)y=35}/"ab#def##"

The way this works is clearer if we show the intermediate results:

	  {x{x,"|",y}'(){$[y="#";-1_x;x,y]}\x}"ab#def##"
	("a|a"
	 "b|ab"
	 "#|a"
	 "d|ad"
	 "e|ade"
	 "f|adef"
	 "#|ade"
	 "#|ad")

repository: dasmoth/ok

branch_name: refs/heads/gh-pages

repo_name: dasmoth/ok


text:
# Cryptocurrency and AI Society Website

If you want to write an article or publish a post, simply make a pull request and the CryptoSoc team will see it immediately. Get involved and make improvements.

View [the website](https://cryptosoc.github.io/)

We are a society at the University of Cape Town, South Africa.

## Running locally

You need Ruby and gem before starting, then:

```bash
# install bundler
gem install bundler

# clone the project
git clone https://github.com/CryptoSoc/website.git
cd website

# run jekyll with dependencies
bundle exec jekyll serve
```

## License

Released under [the MIT license](LICENSE).

license: MIT

branch_name: refs/heads/master

extension: md

gha_language: CSS

gha_license_id: MIT

license_type: permissive


text:
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
![python](https://img.shields.io/badge/python-3.6%20%7C%203.7-blue.svg?cacheSeconds=2592000)
[![Build Status](https://travis-ci.org/Giuseppe1992/Distrinet.svg?branch=master)](https://travis-ci.org/github/Giuseppe1992/Distrinet)

# Archive Soon

From Giuseppe: "Hi, unfortunately I am not able to maintain Distrinet regularly since I am working on other projects. I will Archive the project soon, so you are free to clone and extend it, but I will not maintain it. Best Regards Giuseppe"

# Distrinet

Distrinet is a Distributed SDN Network Emulation Tool able to run in Cloud (Amazon AWS Platform in this version) or Physical Clusters ( Beta Version ).

You can find the installation and configuration tutorial at: https://distrinet-emu.github.io

Distrinet is based on [Mininet](http://mininet.org) (https://github.com/mininet/mininet)

gha_language: Python


text:
Lunar is a public Discord bot written in NodeJS that allows for easy customisation.

It makes use of the discord.js library to interact with the official Discord API to serve your needs.

Invite Lunar to your Discord

### **Contributing**
People are free to contribute to the project by opening issues and pull requests in accordance with the **[Contribution Guidelines](https://github.com/maikdevries/Lunar/blob/main/.github/CONTRIBUTING.md)**

repository: maikdevries/Lunar

branch_name: refs/heads/main

gha_language: JavaScript

repo_name: maikdevries/Lunar


text:
---

comments: true
date: 2010-12-11 02:19:00+00:00
layout: post
slug: why-choosing-your-own-path-for-packages-is-asking-the-wrong-question
title: Why choosing your own path for packages is asking the wrong question
wordpress_id: 27
tags: [openwrap]
---

I've had a couple of people asking me if we could change where packages get stored from the /wrap folder to their own folder. I'm not the only one with that feature request, the NuGet guys have had that question asked and even partially implemented a feature for it. I think responding to those requests is not the right thing to do, and this post is to explain why.

When the question "can I change where packages go", usually the underlying, real question, is one of two: "I want them in /lib with the rest of my traditional libraries", or "In my corporate environment I don't want to check-in all the dependencies because I don't care about xcopy deployment".

### Managing local packages

The first question usually is due to the desire developers have to keep all their dependencies in the same location. While I can understand the psychological reasons behind such a request, the reality of how a package manager usually work is quite incompatible with this approach.

Take the typical example of a command you could issue in OpenWrap: _o update-wrap nhibernate-core -clean_. This command asks OpenWrap to update a dependency and remove any old dependencies that were present.

To do so, OpenWrap needs a certain level of guarantees that you don't mess with the structure it relies on to locate packages.

At that stage, you now have no way to differentiate between the two, the lib you own and the package that, for all intent and purposes, is owned by the package manager.

Allowing you to keep two different beasts, library dependencies you own and packages you depend on and that are owned by your package manager, would introduce a very large amount of complexity, not only for OpenWrap but also for you: it becomes very difficult for everybody to differentiate between an immutable package and a mutable dependency you pulled yourself.

For that reason, while I certainly understand why it doesn't feel "neat", keeping packages separate from libraries let everybody know what each of the beasts are, without introducing complexity.

There's also a secondary scenario to take into account. While we, as the OpenWrap team, don't see any reason why you would want to run both NuGet and OpenWrap at the same time, we do recognize that it's a probability that some people will end-up with both solutions running side-by-side in the same projects, and we certainly make sure that this scenario is functional.

As NuGet stores stuff in /packages and we store stuff in /wrap, everything is fine, neither package managers will get confused. If however you were to redirect either systems to the other repository, you'd end up with what I can only define as undefined and probably clusterfucky behaviour, and that's not something either team would want you to end up in.

### Keeping the packages out of source control

Now this scenario I can understand a bit more. A lot of corporate environments, due to the heavy tax they make developers pay by having managed desktops, do have very defined and reliable environments, quite a different thing than what open-source projects and smaller companies can afford to have.

If you do have such an environment, systematically copying new versions of updated packages in your source control increases the size of the repository, while you could potentially live happily without all those binaries.

There is a fundamental issue with this scenario, and one that neither NuGet nor OpenWrap have a solution for at this time: Whenever you don't include the exact version of a dependency you expect, and rely on a central repository to pull those as needed, you may end up with a different version from the developer sitting next to you.

Let's say I originally added a dependency by doing _o add-wrap nhibernate.core_. I shall get whatever version was the latest one at the time I started coding.

A week pass, and nhibernate 3.0 gets released, and breaks your application. The reason is simple, while I still happily run on 2.0, you have the 3.0 package.

Now there are a couple of ways we can enable this. The first one is to restrict you to absolute version definitions in the packages you take dependencies on. While this is the quickest way to get to that point (and the one the NuGet package repository very much has implemented so far), it restricts not only your dependencies at development time when you pull a package you want work on, it also restricts the runtime binding that a system like OpenWrap also takes care of.

The other solution, and the one we'll implement in OpenWrap (depending on feedback, the more users want it, the higher the priority), is in the case where you use the _use-project-repository: false_ instruction in a project (a hidden feature in OpenWrap that won't be part of the documentation until we've covered cases such as those). When you do that, as well as storing the packages in your development package folder (the _wraps/_cache_ folder), we'll also keep a list of absolute versions that you were using. Whenever a resolve or update happens, we'll only rely on that exact list to update your repository.

With this system, you'll be able to only check-in the openwrap dlls, and let the system auto-download and install all the missing dependencies based on the versions that other developers are also using.

There are a couple of issues with this system to ensure that all packages openwrap depends on are also checked-in in your source control, but those are not a big deal, just one of many features we have planned.

### Getting those features in

The OpenWrap team is very committed to features that make life easier for developers that wish to be productive with their dependency management needs.

If you want to see those things happen sooner, why not [join us on the mailing list](http://groups.google.com/group/openwrap-devel) to talk about those features, fork [our repository on github](http://github.com/openrasta/openwrap) and contribute those features? We're a cool bunch and we'll provide you with as much help as you need to implement those. And if you don't have the time, a little message on the mailing list would go a long way to make sure we cover the scenarios you need when we plan for those features.

extension: markdown

gha_language: HTML


text:
# οἰκονόμος, ου, ὁ.

<!-- Status: S2=NeedsReview -->
<!-- Lexica used for edits: BDAG, FFM, LN, A-S -->

## Word data

* Strongs: G36230.

* Alternate spellings:

* Principle Parts:

* Part of speech:

[Noun](http://ugg.readthedocs.io/en/latest/noun.html).

* Instances in the New Testament: 10.

* All Scriptures cited: Yes

## Etymology:

[οἶκος]() + [νέμω](), to manage),

* LXX/Hebrew glosses:

* Time Period/Ancient Authors:

* Related words:

* Antonyms for all senses

* Synonyms for all senses:

## Senses:

### Sense  1.0:

#### Definition:

literally, one put in charge of a household, the manager of a household, estate-steward, land-steward (as in Luke 12:42)

#### Glosses:

manager of a household, steward

#### Explanation:

literally, one put in charge of a household, the manager of a household, estate-steward, land-steward (as in Luke 12:42)

#### Citations:

prop., the manager of a household or estate, a house- or land-steward (usually a slave or freedman): [Lk 12:42](Luk 12:42) [16:1](Luk 16:1), [3](Luk 16:3), [8](Luk 16:8), [I Co 4:2](1Co 4:2), [Ga 4:2](Gal 4:2); [ὀ οἰ. τ. πόλεως]() (RV, treasurer; cf. [I Es 4:49](1Esd.4.49)), [Ro 16:23](Rom 16:23).

### Sense  1.1:

#### Definition:

city treasurer, manager of a city

#### Glosses:

city treasurer

#### Explanation:

idiomatically, manager of a city (as in Rom. 16:23)

#### Citations:

[ὀ οἰ. τ. πόλεως]() (RV, treasurer; cf. [I Es 4:49](1Esd.4.49)), [Ro 16:23](Rom 16:23).

### Sense  2.0:

#### Definition:

one who is responsible for, an administrator, manager

#### Glosses:

administrator

#### Explanation:

figuratively, one who is responsible for, an administrator, manager (as in 1 Cor. 4:1)

#### Citations:

Metaph. (in wider sense; cf. [οἰκονομία]()), an administrator, a steward: of Christian ministers, [I Co 4:1](1Co 4:1), [Tit 1:7](Tit 1:7); of Christians generally, [I Pe 4:10](1Pe 4:10).†

repository: mandolyte/uw-obsidian

repo_name: mandolyte/uw-obsidian


text:
# CodeMirror website

This repository holds the sources for the [website for
CodeMirror](https://codemirror.net/).

This expects to be checked out inside a (installed)
[`codemirror/dev`](https://github.com/codemirror/dev)
repository (it needs access to the sources to build the reference
docs).

```
npm i
npm run build
ls output # ← the website is in there
```

repository: codemirror/website

gha_license_id: NOASSERTION

repo_name: codemirror/website


text:
Go-ansible upgrade guide
====

<!-- @import "[TOC]" {cmd="toc" depthFrom=1 depthTo=6 orderedList=false} -->

<!-- code_chunk_output -->

- [Go-ansible upgrade guide](#go-ansible-upgrade-guide)
- [Upgrade from 0.x to 1.x](#upgrade-from-0x-to-1x)
	- [Package stdoutcallback and results](#package-stdoutcallback-and-results)
	- [Package execute](#package-execute)
		- [Update DefaultExecute](#update-defaultexecute)
			- [Prefixing output lines](#prefixing-output-lines)
			- [ResultsFunc](#resultsfunc)
		- [Update custom executors](#update-custom-executors)
	- [Options](#options)
		- [AnsiblePlaybookPrivilegeEscalationOptions type](#ansibleplaybookprivilegeescalationoptions-type)
		- [AnsiblePlaybookConnectionOptions type](#ansibleplaybookconnectionoptions-type)
		- [AnsiblePlaybookOptions type](#ansibleplaybookoptions-type)
	- [Package ansibler](#package-ansibler)
		- [Playbook attribute](#playbook-attribute)
		- [ExecPrefix attribute](#execprefix-attribute)
		- [CmdRunDir attribute](#cmdrundir-attribute)
		- [Writer attribute](#writer-attribute)

<!-- /code_chunk_output -->

# Upgrade from 0.x to 1.x

## Package stdoutcallback and results

Package **stdoutcallback** has been moved from `github.com/apenella/go-ansible/stdoutcallback` to `github.com/apenella/go-ansible/pkg/stdoutcallback` and package **results** from `github.com/apenella/go-ansible/stdoutcallback/results` to `github.com/apenella/go-ansible/pkg/stdoutcallback/results`

`StdoutCallbackResultsFunc` signature has been updated to `func(context.Context, io.Reader, io.Writer, ...results.TransformerFunc) error`. As first argument it requires a context and a list of transformers has been included instead of the string used as output prefix.

Transformers gives the chance to anyone to customize the executor output. `go-ansible` is provided by four transformers but you could write your own transformers.
- [**Prepend**](https://github.com/apenella/go-ansible/blob/master/pkg/stdoutcallback/results/transformer.go#L21): Sets a prefix string to the output line
- [**Append**:](https://github.com/apenella/go-ansible/blob/master/pkg/stdoutcallback/results/transformer.go#L28) Sets a suffix string to the output line
- [**LogFormat**:](https://github.com/apenella/go-ansible/blob/master/pkg/stdoutcallback/results/transformer.go#L35) Include date time prefix to the output line
- [**IgnoreMessage**:](https://github.com/apenella/go-ansible/blob/master/pkg/stdoutcallback/results/transformer.go#L44) Ignores the output line based on the patterns it recieves as input parameters

The example [**custom-transformer-ansibleplaybook**](https://github.com/apenella/go-ansible/blob/master/examples/custom-transformer-ansibleplaybook/custom-trasnformer-ansible-playbook.go) show how to write your own transformer.

## Package execute
To make the **execute** package more flexible and customizable it has suffered many changes.
First of all, it has been moved from `github.com/apenella/go-ansible/execute` to `github.com/apenella/go-ansible/pkg/execute`.

One the most important changes is that executors' `Execute` method has changed its signature to:
`Execute(ctx context.Context, command []string, resultsFunc stdoutcallback.StdoutCallbackResultsFunc, options ...ExecuteOptions) error`

Since that change, `Executor` interface definition looks like as shown below:
```go
// Executor interface is satisfied by those types which has a Execute(context.Context,[]string,stdoutcallback.StdoutCallbackResultsFunc,...ExecuteOptions)error method
type Executor interface {
	Execute(ctx context.Context, command []string, resultsFunc stdoutcallback.StdoutCallbackResultsFunc, options ...ExecuteOptions) error
}
```

Finally, `Executor` interface has been moved to package `github.com/apenella/go-ansible/pkg/execute` and will not be found on `github.com/apenella/go-ansible/ansible`.

### Update DefaultExecute

`DefaultExecute` has been also updated. Its `ResultsFunc` and `Prefix` attributes has been removed.

The current `DefaultExecute` definition is:
```go
// DefaultExecute is a simple definition of an executor
type DefaultExecute struct {
	// Writer is where is written the command stdout
	Write io.Writer
	// WriterError is where is written the command stderr
	WriterError io.Writer
	// ShowDuration enables to show the execution duration time after the command finishes
	ShowDuration bool
	// CmdRunDir specifies the working directory of the command.
	CmdRunDir string
	// OutputFormat
	Transformers []results.TransformerFunc
}
```

#### Prefixing output lines
Since prefix is not present anymore, in case you need to prefix the executor output is required to define a new `DefaultExecute` instance and passing a prepend transformer as shown below:
```go
playbook := &playbook.AnsiblePlaybookCmd{
    Playbooks:         []string{"site.yml"},
    ConnectionOptions: ansiblePlaybookConnectionOptions,
    Options:           ansiblePlaybookOptions,
    Exec: execute.NewDefaultExecute(
        execute.WithTransformers(
            // That is the prefix
            results.Prepend("Go-ansible example"),
        ),
    ),
}
```

#### ResultsFunc
Regarding `ResultsFunc` it will not be customizable.

### Update custom executors

As is said before, `Executor` interface has changed its signature and to adapt any custom executor `Execute` method must follow the signature:
```go
Execute(ctx context.Context, command []string, resultsFunc stdoutcallback.StdoutCallbackResultsFunc, options ...ExecuteOptions) error
```
- **ctx**: It is a new parameters to specify a `context.Context` to manage the execution flow.
- **command**:  It is an `[]string` that contains either the binary to be executed and its parameters.
- **resultsFunc**: It is a `stdoutcallback.StdoutCallbackResultsFunc` function used to write the execution output.
- **options**:  List of `ExecuteOptions` functions which can be used to configure the executor.
An example of `ExecuteOptions` could be any `WithAttribute` function defined on `DefaultExecute`. Here there is a function to set the writer to `DefaultExecutor`:
```go
// WithWrite set the writer to be used by DefaultExecutor
func WithWrite(w io.Writer) ExecuteOptions {
	return func(e Executor) {
		e.(*DefaultExecute).Write = w
	}
}
```

## Options
### AnsiblePlaybookPrivilegeEscalationOptions type
`AnsiblePlaybookPrivilegeEscalationOptions` type has been moved to `github.com/apenella/go-ansible/pkg/options` and renamed to `AnsiblePrivilegeEscalationOptions`.

In case you are using `AnsiblePlaybookPrivilegeEscalationOptions`, is needed to import `github.com/apenella/go-ansible/pkg/options` and rename the instance type to `options.AnsiblePrivilegeEscalationOptions`.
```go
import (
    ...
    "github.com/apenella/go-ansible/pkg/options"
    ...
)

...
    ansiblePlaybookPrivilegeEscalationOptions := &options.AnsiblePrivilegeEscalationOptions{
		Become:        true,
		AskBecomePass: true,
	}
...

```

### AnsiblePlaybookConnectionOptions type
`AnsiblePlaybookConnectionOptions` type has been moved to `github.com/apenella/go-ansible/pkg/options` and renamed to `AnsibleConnectionOptions`.

In case you are using `AnsiblePlaybookConnectionOptions`, is needed to import `github.com/apenella/go-ansible/pkg/options` and rename the instance type to `options.AnsibleConnectionOptions`.
```go
import (
    ...
    "github.com/apenella/go-ansible/pkg/options"
    ...
)

...
    ansiblePlaybookConnectionOptions := &options.AnsibleConnectionOptions{
		Connection: "local",
	}
...

```

### AnsiblePlaybookOptions type
`AnsiblePlaybookOptions` type has been moved to `github.com/apenella/go-ansible/pkg/playbook`

## Package ansibler
Package ansibler will not longer exist anymore and its components has been moved from `github.com/apenella/go-ansible` to `github.com/apenella/go-ansible/pkg/playbook`.

In case you are using a prior version and you want to upgrade to 1.0.0, `AnsiblePlaybookCmd` requires some updates. Below there is a list with the updates:

### Playbook attribute
`ansible-playbook` accepts a list of playbook files to be run. To make `go-ansible` fully compatible to `ansible-playbook`, `Playbook` (*string type*) attribute has been supersed by `Playbooks` (*[]string type*).

```go
playbook := &playbook.AnsiblePlaybookCmd{
	Playbooks:         []string{"site.yml"},
	Exec:              execute,
	ConnectionOptions: ansiblePlaybookConnectionOptions,
	Options:           ansiblePlaybookOptions,
}
```

### ExecPrefix attribute
Attribute has been removed an it is configured on the executor.
`execute.NewDefaultExecute` can be used to create a new `DefaultExecute`executor with a list of configurations.

```go
ansiblePlaybookConnectionOptions := &options.AnsibleConnectionOptions{
	Connection: "local",
}

ansiblePlaybookOptions := &playbook.AnsiblePlaybookOptions{
	Inventory: "<IP_ADDRESS>,",
}

execute := execute.NewDefaultExecute(
  execute.WithTransformers(
    results.Prepend("Go-ansible example"),
  ),
)

playbook := &playbook.AnsiblePlaybookCmd{
	Playbooks:         []string{"site.yml"},
	Exec:              execute,
	ConnectionOptions: ansiblePlaybookConnectionOptions,
	Options:           ansiblePlaybookOptions,
}
```

### CmdRunDir attribute
Attribute has been removed an it is configured on the executor.
`execute.NewDefaultExecute` can be used to create a new `DefaultExecute`executor with a list of configurations.

```go
ansiblePlaybookConnectionOptions := &options.AnsibleConnectionOptions{
	Connection: "local",
}

ansiblePlaybookOptions := &playbook.AnsiblePlaybookOptions{
	Inventory: "<IP_ADDRESS>,",
}

execute := execute.NewDefaultExecute(
  execute.WithCmdRunDir(dir)
)

playbook := &playbook.AnsiblePlaybookCmd{
	Playbooks:         []string{"site.yml"},
	Exec:              execute,
	ConnectionOptions: ansiblePlaybookConnectionOptions,
	Options:           ansiblePlaybookOptions,
}
```

### Writer attribute
Attribute has been removed an it is configured on the executor.
`execute.NewDefaultExecute` can be used to create a new `DefaultExecute`executor with a list of configurations.

```go
buff := new(bytes.Buffer)

ansiblePlaybookConnectionOptions := &options.AnsibleConnectionOptions{
	Connection: "local",
}

ansiblePlaybookOptions := &playbook.AnsiblePlaybookOptions{
	Inventory: "<IP_ADDRESS>,",
}

execute := execute.NewDefaultExecute(
	execute.WithWrite(io.Writer(buff)),
)

playbook := &playbook.AnsiblePlaybookCmd{
	Playbooks:         []string{"site.yml"},
	Exec:              execute,
	ConnectionOptions: ansiblePlaybookConnectionOptions,
	Options:           ansiblePlaybookOptions,
	StdoutCallback:    "json",
}
```

repository: apenella/go-ansible

gha_language: Go

repo_name: apenella/go-ansible


text:
# Architecture

## Protocol

The Buttplug Standard defines a message based protocol between a
client and a server. Note that the use of client and server here does
not explicitly denote network connection. These terms are used as a
generic way to denote different communication endpoints.

Client are expected to request information from the server about
devices that are connected, and to send information to those devices
via the server. Servers will handle device enumeration, connection
management to hardware, and failure recoveries (for instance, stopping
all connected devices on client disconnect).

While serialization formats are not yet standardized, current
references implementations of the Standard use JSON for serialization.
More information on this is available in the Messages section.

## Stages

Buttplug sessions consist of 3 stages. While these stages need not be
discrete, due to the way Buttplug will likely be used, they will
usually end up being so. Applications may hide or combine some of the
stages depending on requirements.

### Identification

During the identification stage, a client will establish connection
with the server, and send over its identifying information. The server
may trigger some sort of UI event at this point to ask if the user
will allow the client to connect and interact.

### Enumeration

After the client/server connection is set up, device enumeration can
begin. The client can ask the server to scan for devices on various
busses or media (serial, usb, bluetooth, network, etc), and return a
list of devices it can communicate with.

### Consummation

Once devices are found and selected, we can assume the user will begin
interacting with connected devices. At this point, the client will
mostly be sending and receiving device commands. It can usually (but
not always) be assumed that continued enumeration may not be possible
due to the context of situations that Buttplug software will be used
in.

### Example lifecycle

The following lifecycle covers the general message flow expected
between a Buttplug client and a Buttplug server.

<mermaid>
sequenceDiagram
  Participant Client
  Participant Server

  Note over Client,Server: Once a connection is established,
perform the protocol handshake,
which exchanges information
about identification, versions,
ping times, etc...
  Client->>+Server: RequestServerInfo Id=1
  Server->>-Client: ServerInfo Id=1

  Note over Client,Server: If the server has a non-zero
PingTimeout, the client must send
a ping message to theserver
before the specified timeout.
A common strategy is to set
the client Ping time to 1/2 the
requested server ping time.
  loop [PingTime/2]
    Client->>+Server: Ping ID=N++
    Server->>-Client: Ok ID=N++
  end

  Note over Client,Server: The client calls RequestDeviceList
to get a list of already connected
devices.
  Client->>+Server: RequestDeviceList Id=2
  Server->>-Client: DeviceList Id=2

  Note over Client,Server: To discover new devices, the client
instructs the server to start
scanning.
  Client->>+Server: StartScanning Id=3
  Server->>-Client: Ok Id=3

  Note over Client,Server: While the server is scanning, the
server will notify the client of new
devices.
  Server->>Client: DeviceAdded Id=0
  Server->>Client: DeviceAdded Id=0

  Note over Client,Server: Once devices have been discovered,
 the client instruct the server to
 stop scanning. Once all device
managers have stopped scanning,
the server will notify the client.
  Client->>+Server: StopScanning Id=4
  Server->>-Client: Ok Id=4
  Server->>Client: ScanningFinished Id=0

  Note over Client,Server: Devices may disconnect at any time.
The server will notify the client
when this happens.
  Server->>Client: DeviceRemoved Id=0

  Note over Client,Server: The client may instruct devices to
perform actions. Actions vary per
device. Device capabilities are
relayed as part of DeviceAdded and
DeviceList messages.
  Client->>+Server: VibrateCmd Id=5
  Server->>-Client: Ok Id=5

  Note over Client,Server: The client may instruct the server to
stop a device from whatever it
may be doing.
  Client->>+Server: StopDeviceCmd Id=6
  Server->>-Client: Ok Id=6

  Note over Client,Server: The client may instruct the server to
stop all devices. This is considered
 good form for a client that is
shutting down.
  Client->>+Server: StopAllDevices Id=7
  Server->>-Client: Ok Id=7
</mermaid>

repository: buttplugio/buttplug-spec

repo_name: buttplugio/buttplug-spec


text:
# GBDX notebooks in the cloud

GBDX notebooks with examples that we developed on the GBDX platform, not tested
on local machines.

![GCW_logo](https://github.com/krakchris/GCW_toolkit/blob/master/images/GCW--PNG_small.png)

gha_language: Jupyter Notebook


text:
---
title: Teaching Readiness to Teens
image: /images/driving-readiness-teens_1688_1125.jpg
author: Missy
published: true
comments: true
categories:
    - Readiness
    - Teens
    - Driving
layout: post
---

Community mobility is a necessary part of human independence and socialization. While most individuals can use public or private transportation, not everyone can or should drive. As a pediatric occupational therapist, one of the most important and unique roles that I have taken on is facilitating driving readiness <small>[Read more...](/docs/teaching-driving-readiness-to-young-teens-alt-ed-austin.pdf)</small>

### Published Source
[AltEdAusin.com - Teaching driving readiness to young teens](https://www.altedaustin.com/blog/teaching-driving-readiness-to-young-teens)

<!--### Screenshot Link to Published Page-->

![Teaching Readiness to Teens](/images/driving-readiness-teens-screenshot.png)


text:
###Simple Automated Web Crawler and Reporter
==========================================

Crawl a website and email report with relevant information.

Start the periodic crawl by:-
```
$ cd simple-periodic
$ ./run_simple-periodic.sh
```

To stop the periodic crawl:-
```
$ cd simple-periodic
$ ./stop_simple-periodic.sh
```

To just run a crawl once:-
```
$ cd estate
$ ./crawl_stproperty.sh
```

repository: jolks/simple-auto-crawler-reporter

repo_name: jolks/simple-auto-crawler-reporter


text:
---
template: post
title: Learn Functional Python in 10 Minutes
slug: functional
socialImage: /media/mariusz-slonski-lycnz2hkv0q-unsplash.jpg
draft: false
date: 2020-11-30T21:21:14.480Z
description: >+
  You’ll learn what the functional paradigm is as well as how to use functional
  programming in Python. You’ll also learn about list comprehensions and other
  forms of comprehensions.

category: Datastructures & Algorithms
tags:
  - python
  - Datastructures and Algorithms
---
In this short 10 minute article, you’ll learn what the functional paradigm is in Python. You’ll also learn about list comprehensions.

## 📌 Functional Paradigm

In an imperative paradigm, we do things by giving the computer a sequence of tasks and then it executes them. While executing them, it can change states. For example, let’s say we set `A = 5`, then we change the value of A. We have variables in the sense that the value inside the variable varies.

In a functional paradigm, we don’t tell the computer what to do but we tell it what stuff is. What the greatest common divisor of a number is, and so on.

Variables cannot vary. Once we set a variable, it stays that way forever. Because of this, functions have no side effects in the functional paradigm. A side effect is where the function changes something outside of it. Let’s look at an example:

```python
a = 3
def some_func():
    global a
    a = 5

some_func()
print(a)
```

The output  is 5. In the functional paradigm, changing variables is a big no-no and having functions affect things outside of their scope is also a big no-no. The only thing a function can do is calculate something and return it.

Now you might think "no variables, no side effects? Why is this good?". Good question, gnarly stranger reading this.

If a function is called twice with the same parameters, it’s guaranteed to return the same result. If you’ve learnt about mathematical functions, you’ll appreciate this benefit. We call this *referential transparency*. Because functions have no side effects, if we are building a program which computes things, we can speed up the program. If the program knows that `func(2)` equates to 3, we can store this in a table. This prevents the program from running the same function when we already know the answer.

Typically, in functional programming, we do not use loops. We use recursion. Recursion is a mathematical concept, it means “feeding into itself”. With a recursive function, the function calls itself as a sub-function. Here’s a nice example of a recursive function in Python:

```python
def factorial_recursive(n):
    # Base case: 1! = 1
    if n == 1:
    	return 1
    # Recursive case: n! = n * (n-1)!
    else:
    	return n * factorial_recursive(n-1)
```

Some programming languages are also **lazy**. This means they don’t compute or do anything until the very last second. If we write some code to perform `2 + 2`, a functional program will only calculate that when we need to use the resultant. We’ll explore laziness in Python soon.

## 🌍 How Does Python's Map Work?

To understand map, let’s first look at what iterables are. An iterable is anything we can iterate over. These are lists or arrays, but Python has many different iterables. We can even create our own iterable objects which by implementing magic methods. A magic method is like an API that helps our objects become more Pythonic. We need to implement 2 magic methods to make an object an iterable:

```python
class Counter:
	def __init__(self, low, high):
    	# set class attributes inside the magic method __init__
    	# for “initialise”
    	self.current = low
    	self.high = high
	def __iter__(self):
    	# first magic method to make this object iterable
    	return self
  	def __next__(self):
    	# second magic method
    	if self.current > self.high:
      		raise StopIteration
    	else:
      		self.current += 1
		return self.current - 1
```

The first magic method, `__iter__` or dunder iter (double underscore iter) returns the iterative object, we often use this at the start of a loop. Dunder next, `__next__`, returns what the next object is.

Let’s check this out:

```python
for c in Counter(3, 8):
	print(c)
```

This will print:

```python
3
4
5
6
7
8
```

In Python, an iterator is an object which only has an `__iter__` magic method. This means that we can access positions in the object, but cannot iterate through the object. Some objects will have the magic method **next** and not the `__iter__` magic method, such as sets (talked about later in this article). For this article, we’ll assume everything we touch is an iterable object.

The map function lets us apply a function to every item in an iterable. We want to apply a function to every item in a list, but know that it’s possible for most iterables. The syntax for map takes 2 inputs, the function to apply and the iterable object.

```python
map(function, iterable)
```

Say we have a list of numbers like:

```python
[1, 2, 3, 4, 5]
```

And we want to square every number, we can write code like this:

```python
x = [1, 2, 3, 4, 5]
def square(num):
	return num*num
print(list(map(square, x)))
```

Functional Python is lazy. If we didn’t include the `list()` the function would store the definition of the iterable, not the list itself. We need to tell Python *“turn this into a list”* for us to use this.

It’s weird to go from non-lazy evaluation to lazy evaluation suddenly in Python. You’ll get used to it if you think more in the functional mindset than an imperative mindset.

Now it’s nice to write a normal function like `square(num)` but it doesn’t look right. Do we have to define a whole function just to use it once in a map? Well, we can define a function in map using a *lambda (anonymous)* function.

## 🔑 Lambda Expressions in Python

Lambda functions are a one-line function, used for a short period of time. We often use them with higher order functions along with filter, map, and reduce. This lambda expression squares a number given to it:

```python
square = lambda x: x * x
```

Now let’s run this:

```python
>>> square(3)
9
```

I hear you. “Bee, where are the arguments? what the heck is this? that looks nothing like a function?”

Well, it’s confusing but can be explained. We’re assigning something to the variable `square`. this part:

```python
lambda x:
```

Tells Python that this is a lambda function, and the input is called x. Anything after the colon is what we do with the input, and it returns whatever the result of that is.

To simplify our square program into one line we can do:

```python
x = [1, 2, 3, 4, 5]
print(list(map(lambda num: num * num, x)))
```

In a lambda expression, all the arguments go on the left and the stuff we want to do with them go on the right. It gets a little messy, no one can deny that. There’s a certain pleasure in writing code that only other functional programmers can read. Also, it’s super cool to take a function and turn it into a one-liner.

## 🔹 Reduce Function in Python
Reduce is a function that applies a given function on an iterable and returns one thing. Normally we’ll perform a computation on a list to reduce it down to one number. Reduce looks like this:

```python
reduce(function, list)
```

We can (and often will) use lambda expressions as the function.

The product of a list is every single number multiplied together. To program this:

```python
product = 1
x = [1, 2, 3, 4]
for num in x:
	product = product * num
```

But with reduce we can write:

```python
from functools import reduce
product = reduce((lambda x, y: x * y),[1, 2, 3, 4])
```

To get the same product. The code is shorter, and with knowledge of functional programming, it is neater.

## 🍳 Filter

The filter function takes an iterable and filters out all the things we don’t want in that iterable.

Filter takes a function and a list. It applies the function to each item in the list and if that function returns True, it does nothing. If it returns False, it removes that item from the list.

The syntax looks like:

```python
filter(function, list)
```

Let’s see a small example, without filter we’ll write:

```python
x = range(-5, 5)
new_list = []
for num in x:
	if num < 0:
		new_list.append(num)
```

With filter, this becomes:

```python
x = range(-5, 5)
all_less_than_zero = list(filter(lambda num: num < 0, x))
```

## ☁ Higher Order Functions in Python
Higher order functions can take functions as parameters and return functions. An example is:

```python
def summation(nums):
	return sum(nums)
def action(func, numbers):
	return func(numbers)
print(action(summation, [1, 2, 3]))
# Output is 6
```

Or an simple example of the second definition, `return functions`, is:

```python
def rtnBrandon():
	return “brandon”
def rtnJohn():
	return “john”
def rtnPerson():
	age = int(input(“What’s your age?”))
	if age == 21:
    	return rtnBrandon()
	else:
    	return rtnJohn()
```

Higher-order functions make non-varying variables easier to work with. We need not store a variable anywhere if all we’re doing is passing data through a long tunnel of functions.

All functions in Python are first-class objects. We define a first-class object as having one or more of these features:
- Created at runtime
- Assigned to a variable or element in a data structure
- Passed as an argument to a function
- Returned as the result of a function
So all functions in Python are first-class and can be used as a higher-order function.

## 🎶 Partial Application with Functions
Partial application (also called closures) is weird but is cool. We can call a function without supplying all the arguments it requires. Let’s see this in an example. We want to create a function which takes 2 arguments, a base and an exponent, and returns base to the power of the exponent, like so:

```python
def power(base, exponent):
	return base ** exponent
```

Now we want to have a dedicated square function, to work out the square of a number using the power function:

```python
def square(base):
	return power(base, 2)
```

This works, but what if we want a cube function? or a function to the power of 4? Can we keep on writing them forever? Well, we could. But programmers are lazy. If we repeatedly do the same thing, it’s a sign that there is a much quicker way to speed things up and that will allow us to not repeat things. We can use partial applications here. Let’s see an example of the square function using a partial application:

```python
from functools import partial
square = partial(power, exponent=2)
print(square(2))
# output is 4
```

Isn’t that cool! We can call functions which require 2 arguments, using only 1 argument by telling Python what the second argument is.

We can also use a loop, to generate a power function that works from cubed up to powers of 1000.

```python
from functools import partial
powers = []
for x in range(2, 1001):
	powers.append(partial(power, exponent = x))
print(powers[0](3))
# output is 9
```

## 🐍 Functional Programming Isn’t Pythonic
You might have noticed, but a lot of the things we want to do in functional programming revolve around lists. Other than the reduce function & partial application, all the functions we have seen generate lists. Guido (the inventor of Python) dislikes functional stuff in Python because Python already has its own way to generate lists.

If we write “import this” into a Python IDLE session, we’ll get:

```
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let’s do more of those!
```

This is the Zen of Python. It’s a poem about what something being Pythonic means. The part we want to relate to here is:

There should be one — and preferably only one — obvious way to do it.

In Python, map & filter can do the same things as a list comprehension (discussed next). This breaks one rule of the Zen of Python, so these parts of functional programming ‘pythonic’.

Another talking point is Lambda. In Python, a lambda function is a normal function. Lambda is syntactic sugar. Both are equivalent:

```python
foo = lambda a: 2
def foo(a):
	return 2
```

A regular function can do everything a lambda function can, but it doesn’t work the other way around. A lambda function cannot do everything that a regular function can do.

This was a short argument about why functional programming doesn’t fit into the whole Python ecosystem very well. You may have noticed I mentioned list comprehensions earlier, we’ll discuss them now.

## 🎓 List Comprehensions
Earlier, I mentioned that anything we could do with map or filter, we could do with a list comprehension. This is the part where we’ll learn about them.

A list comprehension is a way to generate lists in Python. The syntax is:

```python
[function for item in iterable]
```

So let’s square every number in a list, as an example:

```python
print([x * x for x in [1, 2, 3, 4]])
```

Okay, so we can see how we can apply a function to every item in a list. How do we go around applying a filter? Well, look at this code from earlier:

```python
x = range(-5, 5)
all_less_than_zero = list(filter(lambda num: num < 0, x))
print(all_less_than_zero)
```

We can convert this into a list comprehension like so:

```python
x = range(-5, 5)
all_less_than_zero = [num for num in x if num < 0]
```

List comprehensions support if statements like this. We no longer need to apply a million functions to something to get what you want. If we’re trying to make some kind of list chances are that it’ll look cleaner and easier using a list comprehension.

What if we want to square every number below 0 in a list? Well, with lambda, map and filter we’ll write:

```python
x = range(-5, 5)
all_less_than_zero = list(map(lambda num: num * num, list(filter(lambda num: num < 0, x))))
```

This is long and complicated. With a list comprehension it is:

```python
x = range(-5, 5)
all_less_than_zero = [num * num for num in x if num < 0]
```

A list comprehension is only good for, well, lists. Map and filter work on any iterable, so what’s up with that? We can use any comprehension for any iterable object we encounter.

## 🤔 Comprehensions of Any Iterable
We can generate any iterable using a comprehension. Since Python 2.7, we can even generate a dictionary (hashmap).

```python
# Taken from page 70 chapter 3 of Fluent Python by Luciano Ramalho
DIAL_CODES = [
  (86, ‘China’),
  (91, ‘India’),
  (1, ‘United States’),
  (62, ‘Indonesia’),
  (55, ‘Brazil’),
  (92, ‘Pakistan’),
  (880, ‘Bangladesh’),
  (234, ‘Nigeria’),
  (7, ‘Russia’),
  (81, ‘Japan’),
  ]
>>> country_code = {country: code for code, country in DIAL_CODES}
>>> country_code
{’Brazil’: 55, ‘Indonesia’: 62, ‘Pakistan’: 92, ‘Russia’: 7, ‘China’: 86, ‘United States’: 1, ‘Japan’: 81, ‘India’: 91, ‘Nigeria’: 234, ‘Bangladesh’: 880}
>>> {code: country.upper() for country, code in country_code.items() if code < 66}
{1: ‘UNITED STATES’, 7: ‘RUSSIA’, 62: ‘INDONESIA’, 55: ‘BRAZIL’}# Taken from page 70 chapter 3 of Fluent Python by Luciano Ramalho
DIAL_CODES = [
  (86, ‘China’),
  (91, ‘India’),
  (1, ‘United States’),
  (62, ‘Indonesia’),
  (55, ‘Brazil’),
  (92, ‘Pakistan’),
  (880, ‘Bangladesh’),
  (234, ‘Nigeria’),
  (7, ‘Russia’),
  (81, ‘Japan’),
  ]
>>> country_code = {country: code for code, country in DIAL_CODES}
>>> country_code
{’Brazil’: 55, ‘Indonesia’: 62, ‘Pakistan’: 92, ‘Russia’: 7, ‘China’: 86, ‘United States’: 1, ‘Japan’: 81, ‘India’: 91, ‘Nigeria’: 234, ‘Bangladesh’: 880}
>>> {code: country.upper() for country, code in country_code.items() if code < 66}
{1: ‘UNITED STATES’, 7: ‘RUSSIA’, 62: ‘INDONESIA’, 55: ‘BRAZIL’}
```

If it’s an iterable, we can generate it. Let’s look at one last example of sets. If you don’t know what a set is, check out this [other article I wrote](https://skerritt.blog/a-primer-on-set-theory/). The TL;DR is:

- Sets are lists of elements, no element is repeated twice in that list
- The order in sets do not matter.

```python
# taken from page 87, chapter 3 of Fluent Python by Luciano Ramalho

>>> from unicodedata import name
>>> {chr(i) for i in range(32, 256) if 'SIGN' in name(chr(i), '')}
{'×', '¥', '°', '£', '©', '#', '¬', '%', 'µ', '>', '¤', '±', '¶', '§', '<', '=', '®', '$', '÷', '¢', '+'}
```

You may notice that sets have the same curly braces as dictionaries. Python is smart. It’ll know whether we're writing a dictionary comprehension or a set comprehension based on whether we provide the extra value for the dictionary or not. If you want to learn more about comprehensions, check out this [visual guide](https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/).


text:
# four-heaps

[![codecov](https://codecov.io/gh/maarila/four-heaps/branch/master/graph/badge.svg)](https://codecov.io/gh/maarila/four-heaps)

A project for comparing the efficiency of four different maximum heap implementations: binary heap, binomial heap, pairing heap and Fibonacci heap.

__Documentation:__

* [Project Definition](https://github.com/maarila/four-heaps/blob/master/documentation/ProjectDefinition.md)
* [Project Report](https://github.com/maarila/four-heaps/blob/master/documentation/ProjectReport.md)
* [Testing Report](https://github.com/maarila/four-heaps/blob/master/documentation/TestingReport.md)
* [User Guide](https://github.com/maarila/four-heaps/blob/master/documentation/UserGuide.md)

__Weekly reports:__

* [Week 1](https://github.com/maarila/four-heaps/blob/master/documentation/WeekReport1.md)
* [Week 2](https://github.com/maarila/four-heaps/blob/master/documentation/WeekReport2.md)
* [Week 3](https://github.com/maarila/four-heaps/blob/master/documentation/WeekReport3.md)
* [Week 4](https://github.com/maarila/four-heaps/blob/master/documentation/WeekReport4.md)
* [Week 5](https://github.com/maarila/four-heaps/blob/master/documentation/WeekReport5.md)
* [Week 6](https://github.com/maarila/four-heaps/blob/master/documentation/WeekReport6.md)
* [Week 7](https://github.com/maarila/four-heaps/blob/master/documentation/WeekReport7.md)

repository: maarila/four-heaps

repo_name: maarila/four-heaps


text:
# dictman
> English dictionary man help you correct words and the paraphrasing.
> a word you don't know, you can easy use `dictman xxx`,if you don't save it in database,
> it will search Internet,if you once save you can easy correct them from your database.

#### build by TTD

## Setup

    pip install dictman

## Use
    $dictman xxx
    英音[ ]  美音[]
    意思: ----
    例句: 1.----
         2.----

ps:
if you meet when install
                "'package' must be a string (dot-separated), list, or tuple")
            TypeError: 'package' must be a string (dot-separated), list, or tuple
please update you setuptools by use `pip install setuptools`

### use Apache 2.0 LICENSE

## version diff

v0.1.2 rename `dictman`
v0.1.1 add warning and make it work well in python2.7
v0.1.0 finish word search in python3

repository: mrzhangboss/doctor

repo_name: mrzhangboss/doctor


text:
---
layout: post
title: "Go Refresher: Slices, Arrays"
description: ""
category:
tags: []
---
{% include JB/setup %}

There is nothing quite like a bout of imposter syndrome to bring enough pain to write a post about language primitives.

I was assisting some coworkers on a Go project this week, I haven't worked in Go for a lil bit. I damn near forgot everything concerning arrays and slices. So, what better way to re-inforce the knowledge in the noodle than to write a blog post.

### Arrays ###

Go's arrays are true to the memory/low-level game. An array uses an allocated block of contiguous memory.
Assuming a 8-byte integer (64-bit), an array holding 1, 2, 3, 4 and 5 (in order) might look like this:

Memory Address | Value
-------: | :-----:
0x0000 | 1
0x0008| 2
0x0010| 3
0x0018| 4
0x0020| 5

[Go Playground](https://play.golang.org/p/rmXskg-Tln)
{% highlight go %}
// https://play.golang.org/p/rmXskg-Tln
package main

import (
	"fmt"
	"reflect"
)

func main() {
	ary := [5]int{1, 2, 3, 4, 5}

	t := reflect.TypeOf(ary)

	fmt.Printf("type: %s\nvalue: %v\n\n", t, ary)

	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range ary {
		fmt.Printf("%v\t%d\t%d\n", &ary[i], i, j)
	}
}

/*
Output:

type: [5]int
value: [1 2 3 4 5]

Address         Idx     Val
0xc208036180    0       1
0xc208036188    1       2
0xc208036190    2       3
0xc208036198    3       4
0xc2080361a0    4       5

*/
{% endhighlight %}

### Out of bounds ###

There are a few invariants with arrays. One of them is there size. An array can almost never grow. The above array is 5 integers in size, or capacity. It can't grow to be 6, because it is bounded the physical memory it was assigned by the kernel, via lower level calls.

If you were to attempt to access `ary[6]`, from the preceding example, you would receive an error:
`"...invalid array index 6 (out of bounds for 1-element array)"`. More on this gem later.
[Go Playground](https://play.golang.org/p/GvCYiZmc4Y)

### Adding new elements to an array ###

To append elements to this array, we must:

1. Request the allocation of a new block of memory that has enough space to hold the existing elements of the array plus the new elements
2. Copy the existing elements from the existing block of memory to the new block of memory
3. Add new elements to new block of memory

[Go Playground](https://play.golang.org/p/2owFMGzlsa)
{% highlight go %}
// https://play.golang.org/p/2owFMGzlsa

package main

import (
	"fmt"
	"reflect"
)

func main() {
	ary := [5]int{1, 2, 3, 4, 5}
	fmt.Printf("Adding some thangs to %v\n", ary)

	newAry := [len(ary) + 5]int{}
	for i := 0; i < len(ary); i++ {
		newAry[i] = ary[i]
	}
	for i := len(ary); i < len(newAry); i++ {
		newAry[i] = i * 100
	}

	t := reflect.TypeOf(newAry)

	fmt.Printf("type: %s\nvalue: %v\n\n", t, newAry)

	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range newAry {
		fmt.Printf("%v\t%d\t%d\n", &newAry[i], i, j)
	}
}

/*

  OUTPUT:

  Adding some thangs to [1 2 3 4 5]
  type: [10]int
  value: [1 2 3 4 5 500 600 700 800 900]

  Address		Idx	Val
  0xc208020190  	0	1
  0xc208020198  	1	2
  0xc2080201a0  	2	3
  0xc2080201a8  	3	4
  0xc2080201b0  	4	5
  0xc2080201b8  	5	500
  0xc2080201c0  	6	600
  0xc2080201c8  	7	700
  0xc2080201d0  	8	800
  0xc2080201d8  	9	900
*/
{% endhighlight %}

Are we having fun yet?!

Somewhere between the C or Assembly array (keep it trill) and the Ruby or Python Array (more of a linked list with array and queue functionality), there is tha slice!

### Slices ###

A slice is an abstraction of an array. A slice gives us some of the flexible we need, along with the speed and memory efficiency that we crave!

Its important to drill into your dev-mind that the slice is not a memory allocated data structure unto itself. It points to an underlying arary, that is: a contiguous, finite, block of memory. One can create an infinite number of slices that all point to the same underlying array. With great power, comes great responsibility.

Slices are created using a great many methods:

  - from an array
  - from another slice
  - `make`
  - slice literal

#### From an array or existing slice ####

"Slicing" an array or existing slice involves using brackets along with a combination of start and end points. The start point is inclusive, the end point is exclusive. If the start index is omitted it is defaulted to 0, if the end index is omitted it defaults to the max length of that which is sliced.
{% highlight go %}

foo := []{1, 2, 3, 4}

_ = foo[:]     // [1, 2, 3, 4]  everything
_ = foo[0:0]   // [] nothing
_ = foo[1:2]   // [2] 1 element
_ = foo[1:3]   // [2, 3] 2 element elements
_ = foo[1:]    // [2, 3, 4] from here to eternity, same as [1:len(foo)]
_ = foo[:2]    // [1, 2] all to thither, same as [0:2]

{% endhighlight %}

No, on with the show:

{% highlight go %}
// https://play.golang.org/p/tVwY9m90Et
package main

import (
	"fmt"
	"reflect"
)

func main() {
	ary := [3]rune{'c', 'a', 'r'}

	t := reflect.TypeOf(ary)

	fmt.Println("[ary]")
	fmt.Printf("type: %s\nvalue: %c\n\n", t, ary)

	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range ary {
		fmt.Printf("%v\t%d\t%c\n", &ary[i], i, (j))
	}

	fmt.Println("\n\n[s1]")
	// Slice derived from entire array
	s1 := ary[:]
	t = reflect.TypeOf(s1)
	fmt.Printf("type: %s\nvalue: %c\n\n", t, s1)

	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range s1 {
		fmt.Printf("%v\t%d\t%c\n", &s1[i], i, j)
	}

	fmt.Println("\n\n[s2]")
	// Slice derived from entire array
	s2 := ary[0:1]
	t = reflect.TypeOf(s2)
	fmt.Printf("type: %s\nvalue: %c\n\n", t, s2)

	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range s2 {
		fmt.Printf("%v\t%d\t%c\n", &s2[i], i, j)
	}

	fmt.Println("\n\n[s3]")
	// Slice derived from last character of s1
	s3 := ary[len(s1)-1:]
	t = reflect.TypeOf(s3)
	fmt.Printf("type: %s\nvalue: %c\n\n", t, s3)

	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range s3 {
		fmt.Printf("%v\t%d\t%c\n", &s3[i], i, j)
	}

	// Now the fun

	s3[0] = 't'
	fmt.Printf("\n[s3] = %c", s3)
	fmt.Printf("\n[ary] = %c", ary)
	fmt.Printf("\n[s1] = %c", s1)

	s2[0] = '語'
	fmt.Printf("\n[s2] = %c", s2)
	fmt.Printf("\n[ary] = %c", ary)
	fmt.Printf("\n[s1] = %c", s1)

	ary[0] = 'B'
	fmt.Printf("\n[ary] = %c", ary)
	fmt.Printf("\n[s2] = %c", s2)
	fmt.Printf("\n[s1] = %c", s1)
}

/*
  OUTPUT:

[ary]
type: [3]int32
value: [c a r]

Address		Idx	Val
0x10436180	0	c
0x10436184	1	a
0x10436188	2	r

[s1]
type: []int32
value: [c a r]

Address		Idx	Val
0x10436180	0	c
0x10436184	1	a
0x10436188	2	r

[s2]
type: []int32
value: [c]

Address		Idx	Val
0x10436180	0	c

[s3]
type: []int32
value: [r]

Address		Idx	Val
0x10436188	0	r

[s3] = [t]
[ary] = [c a t]
[s1] = [c a t]

[s2] = [語]
[ary] = [語 a t]
[s1] = [語 a t]

[ary] = [B a t]
[s2] = [B]
[s1] = [B a t]

*/
{% endhighlight %}

Things to note:

- Slice syntax is similar to an array, except it misses the length
- New memory is not allocated for elements of a slice, the slice points to a collection of elements of an underlying array
- A change to a slice, modifies the underlying memory, which can modify any/all other slices that share that memory

#### Using `make` ####

A few things:

 - Syntax: `make([]T, length int, capacity int)`
 - requires a slice with a type
 - requires a length
 - optionally accepts a capacity, defaults to length

{% highlight go %}
package main

import "fmt"
import "reflect"

func main() {
	slice := make([]rune, 4, 8)
	t := reflect.TypeOf(slice)
	fmt.Printf("\n\ntype: %s\nvalue: %v", t, slice)
	fmt.Printf("\nlength: %d", len(slice))
	fmt.Printf("\ncapacity: %d", cap(slice))

	fmt.Println("\n\nAddress\t\tIdx\tVal")
	for i, j := range slice {
		fmt.Printf("%v\t%d\t%s\n", &slice[i], i, string(j))
	}

}

/*
type: []int32
value: [0 0 0 0]
length: 4
capacity: 8

Address		Idx	Val
0x104342e0	0
0x104342e4	1
0x104342e8	2
0x104342ec	3
*/
{% endhighlight %}

Things to note:

- Slice elements default to zero-value ("" for rune/string, 0 for int, etc)
- The range iterates from 0 to length-1, not capacity
- Is it starting to click?

#### Slice Literal ####

Use Go's literal pattern to create a slice.
{% highlight go %}
package main

import (
	"fmt"
	"reflect"
)

func main() {
	slice := []rune{'c', 'a', 'r'}

	t := reflect.TypeOf(slice)

	fmt.Println("[slice]")
	fmt.Printf("type: %s\nvalue: %c\n\n", t, slice)
	fmt.Printf("length: %d\ncap: %d\n\n", len(slice), cap(slice))

	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range slice {
		fmt.Printf("%v\t%d\t%c\n", &slice[i], i, (j))
	}
}

/*
  OUTPUT:

[slice]
type: []int32
value: [c a r]

length: 3
cap: 3

Address         Idx     Val
0xc208000150    0       c
0xc208000154    1       a
0xc208000158    2       r

*/
{% endhighlight %}

Things to note:

- The capacity is the length, i.e. the number of elements in the literal
- The underlying array is _anonymized_

### Growing a slice ###

Okay, so now you are cooking with gasoline.

There are two methods to increase the size of a slice:

  - The magical "append"
  - new slice → copy

#### Append ####

Append takes a few forms:

 - `append(target_slice, element)` → new_slice
 - `append(target_slice, el1, [el2, ])` → new_slice
 - `append(target_slice, ...another_slice)` → new_slice

`append` will return a new slice, the size of target slice plus the number of elements being appended. The target slice is not modifed in place, its length remains the same. *The underlying array is modified.*
[Go Playground](https://play.golang.org/p/wOyfOMWTLH)

{% highlight go %}
// https://play.golang.org/p/wOyfOMWTLH
package main

import (
	"fmt"
)

func printSlice(slice []int) {
	fmt.Println("[slice] =>", slice)
	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range slice {
		fmt.Printf("%v\t%d\t%d\n", &slice[i], i, (j))
	}
	fmt.Println()
	return
}

func main() {
	ary := [3]int{0, 0, 0}
	for i, j := range ary {
		fmt.Printf("%v\t%d\t%d\n", &ary[i], i, (j))
	}
	slice := ary[0:1]

	fmt.Println("[ary] =>", ary)
	printSlice(slice)

	for i := 1; i < 4; i++ {
		_ = append(slice, i*5)
		fmt.Println("[ary] =>", ary)
		printSlice(slice)
	}
}

/*
0xc20804c000    0       0
0xc20804c008    1       0
0xc20804c010    2       0
[ary] => [0 0 0]
[slice] => [0]
Address         Idx     Val
0xc20804c000    0       0

[ary] => [0 5 0]
[slice] => [0]
Address         Idx     Val
0xc20804c000    0       0

[ary] => [0 10 0]
[slice] => [0]
Address         Idx     Val
0xc20804c000    0       0

[ary] => [0 15 0]
[slice] => [0]
Address         Idx     Val
0xc20804c000    0       0
*/
{% endhighlight %}

Look at what happens with we reassign the slice after an append:
[Go Playground](https://play.golang.org/p/PgLVRw3jrJ)

{% highlight go %}
// https://play.golang.org/p/PgLVRw3jrJ
package main

import (
	"fmt"
)

func printSlice(slice []int) {
	fmt.Println("[slice] =>", slice)
	fmt.Println("Address\t\tIdx\tVal")
	for i, j := range slice {
		fmt.Printf("%v\t%d\t%d\n", &slice[i], i, (j))
	}
	fmt.Println()
	return
}

func main() {
	ary := [3]int{0, 0, 0}
	for i, j := range ary {
		fmt.Printf("%v\t%d\t%d\n", &ary[i], i, (j))
	}
	slice := ary[0:1]

	fmt.Println("[ary] =>", ary)
	printSlice(slice)

	for i := 1; i < 4; i++ {
		slice = append(slice, i*5)
		fmt.Println("[ary] =>", ary)
		printSlice(slice)
	}

	fmt.Println("[ary]")
	for i, j := range ary {
		fmt.Printf("%v\t%d\t%d\n", &ary[i], i, (j))
	}
}

/*
0xc20804c000	0	0
0xc20804c008	1	0
0xc20804c010	2	0
[ary] => [0 0 0]
[slice] => [0]
Address		Idx	Val
0xc20804c000	0	0

[ary] => [0 5 0]
[slice] => [0 5]
Address		Idx	Val
0xc20804c000	0	0
0xc20804c008	1	5

[ary] => [0 5 10]
[slice] => [0 5 10]
Address		Idx	Val
0xc20804c000	0	0
0xc20804c008	1	5
0xc20804c010	2	10

[ary] => [0 5 10]
[slice] => [0 5 10 15]
Address		Idx	Val
0xc208036180	0	0
0xc208036188	1	5
0xc208036190	2	10
0xc208036198	3	15

[ary]
0xc20804c000	0	0
0xc20804c008	1	5
0xc20804c010	2	10
*/
{% endhighlight %}

**Note that the original array was left behind.** Like a hermit crap, the slice had to find a new home in memory after its elements outgrew the size its original array.

Things to Note:
 - Append adds the element(s) to a new slice, that is a copy of the target slice given as the first argument, and the underlying array.
 - Append returns a new slice. READ: Append will not change the slice, given as the first argument, in-memory.
 - Append will create a new underlying array if capacity runs out in the original array runs out

#### New Slice → Copy ####

So `append` is all fine and dandy when you have to add elements *to the end* of a collection, but what about random inserts?  Turn around!

Lets assume the slice hasn't hit maximum capacity of the underlying array. Inserting is trivial:
{% highlight go %}
  ...
  slice := make([]int, 500, 1000)
  ...
  newSlice := []int{1, 2, .. 50 }
  // need to insert "newSlice" elements at index 100 of original "slice"
  idx = 100

  // grow the slice by the number of new elements
  slice = slice[:len(slice) + len(newSlice)]

  // shift all elements from the insertion index over to the right to make space for the new elements
  copy(slice[idx+len(newSlice):], slice[idx:])

  // insert new elements at insertion index
  copy(slice[idx:], newSlice)
  ...

{% endhighlight %}

Okay thats easy! But what about when you have maxed out the capacity of the underlying data structure, you know... when there is no space in that there array!?
.. Can you just grow the slice like you might expect?

{% highlight go %}
package main

import (
	"fmt"
)

func main() {
	ary := [3]int{0, 1, 4}
	slice := ary[:]

	// Lets insert a 3 into index 2
	// Step 1. Grow the slice
	slice = slice[:len(slice)+1]

	fmt.Println(slice)
}

/*
  OUTPUT:

  panic: runtime error: slice bounds out of range

*/
{% endhighlight %}

The answer: No!

While the slice needs to be just one element bigger, the underlying array isn't big enough, and we don't have the power to extended the block of memory allocated for our array. We need to allocate a bigger chunk of memory. This requires using the `make` command:

{% highlight go %}
package main

import (
	"fmt"
)

func main() {
	ary := [3]int{1, 2, 4}
	slice := ary[:]

	// Lets insert a 3 into index 2
	val := 3
	idx := 2

	// Step 1. Create a new slice, increasing the length by 1 for the new element. Give the new slice a nice sized capacity for future growth!
	newSlice := make([]int, len(slice)+1, len(slice)*2)

	// Step 2. Copy the elements, index 0 up to the insertion point, from the original slice to the new slice
	copy(newSlice[:idx], slice[:idx])

	// Step 3. Copy the elements, start with the index of the insertion point to the end of the slice, from the original slice to the new slice. However, in the new slice, shift the insertion point to the right by 1 to make room for the new element.
	copy(newSlice[idx+1:], slice[idx:])

  // Step 4. Put that value in proper insertion point!
	newSlice[idx] = val

	fmt.Println(newSlice)
}

/*
  OUTPUT:

  [1 2 3 4]

*/
{% endhighlight %}

You are now free to continue randomly inserting values using the method above. that is, until you hit capacity, again. Capacity algorithms are a topic for another day, however they are very import to the speed, efficiency and resource consumption of your application.

### Summary ###

Notes on arrays:

 * A array is a contiguous block of physical memory reserved for a variable.
 * A array's length is fixed, thus its capacity is fixed.

Notes on slices:

 * is an abstraction tied to an underlying array.
 * capacity is equal to the length of the underlying array, and thus indirectly tied to the physical allocation of a block of memory.
 * length is a _logical limit/size_ set during its creation, either by make, literal, or "slicing" an existing slice or array.
 * length, and capacity if need, be can grown _automagically_ using the "append"
 * If a slices has grown to fill the underlying array, its elements -- like a hermit crab -- will need to find a new home in memory,  if the collection wants to continue to grow by any means other than the magic "append" function (i.e. random insert)

*Special note:
 In Go you do not pass arrays, you pass slices. So get comfortable with everything in the blog post before moving forward ;)*

### Further Reading ###
{% highlight go %}
{% endhighlight %}

[Go Slices: usage and internals](http://blog.golang.org/go-slices-usage-and-internals)

[The mechanics of 'append'](http://blog.golang.org/slices)


text:
# Entity Inheritance

This project demonstrates how to use entity inheritance in CUBA applications.

## Objective

Let's assume that we have two types of customers - companies and individuals, which have some common attributes. We would like to store the common attributes in one table, and use separate linked tables to store specific attributes.

So the data model contains the `Customer` entity, which is a base class stored in the `DEMO_CUSTOMER` table. The `Company` and `Person` entities stored in separate tables with foreign keys that reference the base table.

The `Order` entity has a reference to `Customer`. As the customer can be of the different types, when users create orders, they should be able to choose the type of the customer.

## Implementation Details

In the `Customer` entity:

* Inheritance strategy is set to `JOINED`
* Discriminator column name `DTYPE` and type `String` are left default
* Discriminator value is set to `C`

In the `Company` entity:

* Parent class is set to `Customer`
* Discriminator value is set to `M`

In the `Person` entity:

* Parent class is set to `Customer`
* Discriminator value is set to `P`

The `order-edit.xml` screen descriptor and the corresponding `OrderEdit` controller contain the customer selection components and logic.

## How to Run

To see the example in action, do the following:

* Open the project in Studio
* Click *Run > Start application server*
* If you see the warning *Database does not exist ...*, click *Create DB in background*
* Go to `http://localhost:8080/app` and log in as `admin` / `admin`
* Open *Application > Orders* and create a new order.

Based on CUBA Platform 6.8.1


text:
# Drupal dependencies Ansible role

[![Build Status](https://travis-ci.org/javaguirre/ansible-drupal-dependencies-role.svg?branch=master)](https://travis-ci.org/javaguirre/ansible-drupal-dependencies-role)

Ansible role using [Drush](https://github.com/drush-ops/drush) to manage theme and module dependencies in **Drupal**.

## Dependencies

This role doesn't install Drupal nor Drush, there are other roles already doing that, you could use this role with those.

## Variables

List of variables and default values:

```yaml
drush_bin_path: ""
drupal_path: "/var/www/drupal"
drupal_user: apache
drupal_core_modules: []
drupal_themes: []
drupal_modules: []
drupal_other_modules: []
drupal_default_theme: bartik
drupal_clear_cache: no
drupal_cache_option: all
```

## Usage

An example usage could be like:

```yaml
- hosts: all
  remote_user: myuser
  sudo: no

  vars:
    drush_bin_path: "/usr/bin/drush"
    drupal_user: http
    drupal_core_modules:
      - contact

    drupal_themes:
      - bootstrap

    drupal_modules:
      - ctools
      - entity
      - ldap

    drupal_other_modules:
      - simpletest

    drupal_default_theme: bootstrap

    drupal_clear_cache: yes
    drupal_cache_option: theme
```

## Feedback

[Please send me your requests/questions!](https://github.com/javaguirre/ansible-drupal-dependencies-role/issues)


text:
Word Guess Game
==========================================
![got-hangman-demo](assets/images/got-hangman-demo.PNG)

A simple hangman style game that I made, the theme is Game of Thrones. The word will be randomly chosen (think Game of Thrones characters and places!) and you have to guess its letters.

## How to play
To play, simply enter in a letter with your keyboard, and the game will tell you whether the letter you guessed was a part of the word or not and adjust your score accordingly. Letters that area incorrect will be displayed below the blank word. If you run out of guesses, you lose, and the game will pick a new blank word for you to guess.

+ _press the play button on the audio player for an enhanced experience_ ;)

## Technologies Used
I wrote the contents of the page with HTML and some CSS for stylings, and for the game logic I used Javascript.

repository: ThorNolan/Word-Guess-Game

repo_name: ThorNolan/Word-Guess-Game


text:
# CRS: Customer Retention and Segmentation for Banks

## Inspiration

Customer churning in bank happens when customers discontinue services with the bank. While there can be many reasons for this to happen, one of the primary reason is generalized banking and investment policies. This results on banks incurring heavy revenue losses. The need of the hour is for the banks to devise customer-curated policies. With different data analytics and predictive modelling, we developed a tool to predict potential bank churners and provide different insights to help banks come up with customized policies to retain their customers.

## What it does

The CRS tools has two parts
1. Churn Prediction - This uses Random Forests, a supervised machine learning algorithm, to predict the probability of a customer churning the bank.
2. Customer Segmentation - This uses K-means, an unsupervised machine learning algorithm, to cluster customers to different groups.

## How we built it

1. Churn prediction is built with the Random Forest algorithm using scikit-learn API. The model is trained on a financial dataset and predicts the probability of a person churning the bank. The model was first deployed locally on flask and then on heroku.

2. Customer Segmentation is built with Kmeans algorithm using the scikit-learn API. The model is trained on a financial dataset and groups customers into different clusters. First, the algorithm learns the number of optimal clusters from the data and then clusters the data accordingly using distance metrics. The model along with the cluster map is deployed on voila dashboard. By changing the input parameters, the cluster group of a customer can be predicted. Finally, this is deployed on heroku.

## Challenges we ran into

For churn prediction, the major challenge for us was to deal with a highly skewed dataset. Secondly, for the customer segmentation part, the major challenge was to determine the optimal number of clusters. Apart from these challenges, one of the most important was to figure out deployment on heroku.

## Accomplishments that we're proud of

We have successfully deployed our churn model on a highly skewed dataset. We used SMOTE sampling technique to handle the class imbalance and developed a model with a relatively good performance.

## What we learned

Technically, we learned a lot about front end development. Deploying flask and voila on Heroku was new for us and we thoroughly enjoyed learning it. Also, working with the group helped us to identify our strengths and weaknesses, and with focus and collaboration we were able to solve all the challenges faced. We also learned about the problems faced in the banking world and how to tackle some of them.

## What's next for Customer Retention and Segmentation for Banks
The CRS tool can further be modified to include credit risk and loan risk analysis to provide a complete tool to increase revenue. Also, it can further be extended to predict if a customer should be provided with line of credit or loan, based on their credit history.


text:
title=Accessing File System Resources (org.apache.sling.fsresource)
type=page
status=published
tags=resources,resourceproviders
~~~~~~
[TOC]

## Introduction

The Apache Sling File System Resource Provider provides access to the operating system's file system through the Sling `ResourceResolver`. Multiple locations may be mapped into the resource tree by configuring the file system location and the resource tree root path for each location to be mapped. The provider supports mapping folders and files as binaries, and content structures stored in JSON files or FileVault XML format.

To activate this feature, install the `org.apache.sling.fsresource` bundle. You can get it from the Sling downloads page or from [Maven Central][maven-central].

Currently two major versions are maintained - choose the correct version depending on your Sling environment:

* fsresource 2.x ([trunk][src-trunk]): compatible with Apache Sling API 2.11 and Apache Sling Resource Resolver 1.5.18 or above.
* fsresource 1.x ([branch][src-branch]): compatible with Apache Sling API 2.4 and Apache Sling Resource Resolver 1.1.0 or above.

## Resource Types

Files and directories are mapped into the resource tree as regular `Resource` instances whose resource type depends on the actual nature of the mapped file system resource:

   * Regular files are assigned the `nt:file` resource type
   * Directories are assigned the `nt:folder` resource type

Content stored in JSON or FileVault XML files are mapped with the resource type stored in the files. If a resource type is missing `nt:unstructured` is used as fallback.

## Adapters

File system resources extend from Sling's `AbstractResource` class and thus are adaptable to any type for which an `AdapterFactory` is registered supporting file system resources. In addition File system Resources support the following adapters natively:

   * `java.io.File` -- The Java file object providing access to the file system file
   * `java.net.URL` -- A valid `file://` URL to the file. This URL is derived from the `java.io.File` object by calling the `File.toURI().toURL()` sequence.
   * `java.io.InputStream` -- If the `java.io.File` can be read from (as per `File.canRead()` an `InputStream` to read from the file is returned.

## Configuration

The File System Resource Provider is configured with OSGi Configuration Admin factory configurtions whose factory PID is `org.apache.sling.fsprovider.internal.FsResourceProvider`. Configuration can be managed using the OSGi Configuration Admin API, through the Web Console or by any other means supporting Configuration Admin configurations. Each configuration "mounts" a specific file system path into the resource hierarchy.

Which files are mounted depends on the 'File system layout' configuration parameter:

* FILES_FOLDERS (default): Support only files and folders (classic mode).
* INITIAL_CONTENT: Sling-Initial-Content filesystem layout, supports file and folders ant content files in JSON and jcr.xml format.
* FILEVAULT_XML: FileVault XML format (expanded content package).

Configuration parameters for each mapping:

| Parameter | Name | Description |
|---|---|---|
| File System Root | `provider.file` | File system directory mapped to the virtual resource tree. This property must not be an empty string. If the path is relative it is resolved against sling.home or the current working directory. The path may be a file or folder. If the path does not address an existing file or folder, an empty folder is created. |
| Provider Root	| `provider.root` (2.x), `provider.roots` (1.x) | Location in the virtual resource tree where the file system resources are mapped in. This property must not be an empty string. Only one path is supported. |
| File system layout | `provider.fs.mode` | File system layout mode for files, folders and content. |
| Init. Content Options | `provider.initial.content.import.options` | Import options for Sling-Initial-Content file system layout. Supported options: overwrite, ignoreImportProviders. |
| FileVault Filter | `provider.filevault.filterxml.path` | Path to META-INF/vault/filter.xml when using FileVault XML file system layout. |
| Check Interval | `provider.checkinterval` | If the interval has a value higher than 100, the provider will check the file system for changes periodically. This interval defines the period in milliseconds (the default is 1000). If a change is detected, resource events are sent through the event admin. |
| Cache Size | `provider.cache.size` | Max. number of content files cached in memory.  |

### FILES_FOLDERS file system layout

The mode maps only files and folders. This was the only mode supported in fsresource versions before 1.3.

Notes:

* No caching is used for this mode.
* Resource events are sent when file oder folder changes are detected.

### INITIAL_CONTENT file system layout

The mode maps files and folders, and content files stored in JSON or jcr.xml files. The layout has to match the conventions of the [Apache Sling JCR Content Loader][jcr-contentloader]. The bundle header `Sling-Initial-Content` defines where and how the content should be loaded to.

This mode is best use together with the [Maven Sling Plugin][sling-maven-plugin], which automatically creates the appropriate File System Resource Provider configurations for a Maven bundle project containing content structures. For each path an individual configuration is created.

Usage - deploy OSGi bundle from current maven project and register the appropriate OSGi configuration mappings:

    $ mvn -Dsling.mountByFS=true sling:install

Only register the appropriate mappings:

    $ mvn sling:fsmount

Remove the mappings:

    $ mvn sling:fsunmount

Notes:

* The content of JSON or jcr.xml files is cached in-memory until it changes.
* Resource events are sent when file oder folder changes are detected. When a JSON or jcr.xml file is changed resource events are sent for each resource contained in this file.
* When 'overwrite:=true' is not set for a path in the `Sling-Initial-Content` header the resource provider falls back to the parent resource provider (e.g. JCR repository) if a requested resource is not find in the file system (version 2.x, with version 1.x this always happens).

### FILEVAULT_XML file system layout

The mode maps an maven project containing an expanded content package which uses the [Jackrabbit FileVault XML layout][vaultfs] in the running Sling instance. The existing of a filter file `META-INF/vault/filter.xml` is mandatory.

This mode is best use together with the [Maven Sling Plugin][sling-maven-plugin], which automatically creates the appropriate File System Resource Provider configurations. For each path defined in the filter.xml one mapping configuration is created. The include/exclude definitions are respected as well.

Usage - register the appropriate mappings:

    $ mvn sling:fsmount

Remove the mappings:

    $ mvn sling:fsunmount

Notes:

* The content of .content.xml files is cached in-memory until it changes.
* Resource events are sent when file oder folder changes are detected. When a JSON or jcr.xml file is changed resource events are sent for each resource contained in this file.
* Content excluded by the filter definition is not mounted by the resource provider, if a resource of the relevant path is requested the resource provider falls back to the parent resource provider (e.g. JCR repository).

[src-trunk]: https://github.com/apache/sling-org-apache-sling-fsresource
[src-branch]: https://github.com/apache/sling-org-apache-sling-fsresource/tree/release/1.x
[maven-central]: https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.apache.sling%22%20AND%20a%3A%22org.apache.sling.fsresource%22
[jcr-contentloader]: content-loading-jcr-contentloader.html
[sling-maven-plugin]: http://sling.apache.org/components/sling-maven-plugin/
[vaultfs]: http://jackrabbit.apache.org/filevault/vaultfs.html

repository: apache/sling-site

repo_name: apache/sling-site


text:
## Wrapping method calls (meta-class example)
Originally published: 2003-05-04 08:23:52
Last updated: 2003-05-04 15:49:40
Author: Stephan Diehl

A metaclass is used to wrap all (or just some) methods for logging purposes. The underlying mechanism can be used as well to check pre/post conditions, attribute access,...
The basic point is, that the actual class must not be changed in any way to achive the desired effect.


text:
---
title: Swift Insertion Sort
author: Bruce Wade
date: 2020-04-27 9:00:00-0700
categories: [Algorithms and Data Structures, Swift]
tags: [swift, Sorting]
---
```swift
func insertionSort<T>(_ collection: inout T) where T: BidirectionalCollection & MutableCollection, T.Element: Comparable {
    guard collection.count >= 2 else { return }

    for current in collection.indices {
        var shifting = current

        while shifting > collection.startIndex {
            let previous = collection.index(before: shifting)
            if collection[shifting] < collection[previous] {
                collection.swapAt(shifting, previous)
            } else {
                break
            }
            shifting = previous
        }
    }
}
```

```swift
// Usage
array = [15, 9, 8, 1, 4, 11, 7, 12, 13, 6, 5, 3, 16, 2, 10, 14]
print("Original: \(array)")
insertionSort(&array)
print("Sorted: \(array)")
```


text:
# _Oblique Strategies_

#### _This is a cheap homage to ENO & Jarmish 08.15.2016_

#### By _**HK Kahng and Jon Toler**_

## Description

_This is a randomizing JS, which a cheaper homage to Brian Eno's Oblique Strategies. With the use of Ramdonizer, Math function.

## Known Bugs

_N/A_

## Technologies Used

_Atom_
_HTML_
_CSS_
_Javascript_
_jQuery_
_Boot_strap_

### License

_This software is licensed under the MIT license._

Copyright (c) 2016 HK Kahng and Jon Toler All Rights Reserved.

repository: JonToler/orblique-stagedy

repo_name: JonToler/orblique-stagedy


text:
![Original picture David Greenwell](./lair.jpg?raw=true)

> "It is a dark world where all you have are functions, and all you can do is
> apply them to each other." - Anonymous

# Done status

- [x] Can print stuff
- [x] Arguments
- [x] Functions-as-arguments
- [x] If statements ('?')
- [x] Loops (In the form of recursion?)
- [x] Throwable Exceptions
- [ ] Catchable Exceptions
- [ ] Arrays/Dictionaries
- [ ] Nested Functions

This is an experimental [Den](https://github.com/MuteLang/DenLang) implementation. It
intends to support all of the same syntax with some extra goodies.

### Goals

This is the first language I've ever written an interpreter for, so it is as
much a learning process as anything else.

* Strong, Dynamic types (Erlang style)
* String internment
* Persistent data structures
* Immutability
* Functions as first-class citizens
* Low-memory footprint

### Installation

1. `make`
2. Thats it. You should now have a `lair` binary.

#### Debugging

Edit the `Makefile` to turn on the `DEBUG` flag, then rebuild:

```Makefile
    CFLAGS=-Werror -Wextra -Wall -g3 -Wno-missing-field-initializers -DDEBUG
```

```Bash
    make clean
    make
```

Now you'll get extra fancy, obtuse output:

```Bash
$ ./lair t/functions_all_the_way_down.den
FUNCTION a FUNCTION_ARG {
    RETURN CALL ATOM ATOM
}
FUNCTION b FUNCTION_ARG
    RETURN CALL ATOM ATOM
}
FUNCTION c FUNCTION_ARG
    RETURN CALL ATOM
}
FUNCTION d
    RETURN STRING
}
CALL ATOM CALL ATOM ATOM EOF
---
This is the real test.
```

### Usage

Currently there is no REPL for testing, so for now usage is limited to loading
a file, parsing it, executing it and then doing whatever the program wanted via
STDOUT/STDIN.

    ./lair t/basic.den

### Documentation

Documentation is done with [Doxygen](http://www.stack.nl/~dimitri/doxygen/).
Note that this is for Lair itself, not for Den.

To build docs:

    doxygen lair.conf

repository: qpfiffer/lair

gha_language: C

repo_name: qpfiffer/lair


text:
# Overview

Chatclouds is a wordcloud library which allows you to create and save a wordcloud of your whatsapp chats. The library uses wordcloud library to generate images. The preprocessing of the text from the txt files are already taken care of. The only thing you need to do is to extract your chat from WhatsApp and then using that file in your python code.

Take a look at the library [here](https://pypi.org/project/chatclouds/)

# Installing chatclouds

```
pip install chatclouds
```

# Importing chatclouds

import chatclouds

# Functions

1. show()
    Code:

    from chatclouds import show
    show(filename)
    (filename needs to be the name/ path of txt file containing your WhatsApp Chat)

    What it does:
    show() function returns an image of the WordCloud that has been formed from the chat after preprocessing the text and removing all the stopwords.

2. save()
    Code:

    from chatclouds import save
    save(filename)
    (filename needs to be the name/ path of txt file containing your WhatsApp Chat)

    What it does:
    show() function saves a .png image of the WordCloud that has been formed from the chat after preprocessing the text and removing all the stopwords.

3. plot_time()
    Code:

    from chatclouds import common
    plot_time(filename)
    (filename needs to be the name/ path of txt file containing your WhatsApp Chat)

    What it does:
    plot_time() function shows a bar plot of number of messages with respect to 1 hour time slots.

4. common()
    Code:

    from chatclouds import common
    common(filename)
    (filename needs to be the name/ path of txt file containing your WhatsApp Chat)

    What it does:
    common() function prints the 20 most frequently used word in the chat between two people.

# Example

A sample notebook showing how to use the library could be found [here](https://github.com/ishantjuyal/chatcloud/blob/master/Example/Using%20chatclouds%20library.ipynb)

# Sample output

Sample output of the WordCloud:

![sample](https://github.com/ishantjuyal/chatcloud/blob/master/Example/sample.png)

Sample output of the time analysis plot:

![plot sample](https://github.com/ishantjuyal/chatcloud/blob/master/Example/plot_sample.png)

repository: ishantjuyal/chatcloud

repo_name: ishantjuyal/chatcloud


text:
---
id: 50
title: Enterprise Library 5!!
date: 2010-05-18T02:02:56+00:00
author: Emanuele
layout: post
permalink: /2010/05/18/enterprise-library-5/
categories:
  - announcement
tags:
  - .net
  - enterprise library
language: en
---
Available to this address the newest version of the Enterprise Library. Among the updates, the most interesting (imm&ho):

  * Asynchronous data access support
  * Optimized cache scavenging
  * Support for the .NET 4.0 Framework and integration with Microsoft Visual Studio 2010
  * Integration with Windows Presentation Foundation (WPF) validation mechanisms
  * Major architectural refactoring that provides improved testability and maintainability through full support of the dependency injection style of development

while other features are:

  * Dependency injection container independence (Unity ships with Enterprise Library, but you can replace it with a container of your choice)
  * Programmatic configuration support, including a fluent configuration interface and an XSD schema to enable IntelliSense
  * Redesign of the configuration tool to provide:
      * A more usable and intuitive look and feel
      * Extensibility improvements through meta-data driven configuration visualizations that replace the requirement to write design time code
      * A wizard framework that can help to simplify complex configuration tasks
  * Data accessors for more intuitive processing of data query results
  * Honoring validation attributes between Validation Application Block and DataAnnotations
  * Support for complex configuration scenarios, including additive merge from multiple configuration sources and hierarchical merge
  * Better performance when logging
  * A reduction of the number of assemblies
  * Support for the .NET 4.0 Framework and integration with Microsoft Visual Studio 2010
  * Improvements to Unity

If you don’t know about the Enterprise Library: we are talking about a group of libraries that abstract operations performed daily by almost developers in the world, for example DataAccess, Logging, Validation, Dependency Injection, Unit Test


text:
# knodeo_logger

Simple console logger used in Assign It To Us's knodeo products.

Color coding using `chalk`

## Important Note

This library has been deprecated in favor of aitutils (https://github.com/assignittous/aitutils)

# Install

Add it to your project:

`npm install knodeo-logger --save`

# Sample Code

```coffeescript

logger = require('./index').Logger

logger.debug "This is a debug message"

logger.info "This is an info message"

logger.error "This is an error message"

logger.warn "This is a warn message"

logger.bot "This is a bot message"

logger.shell "This is a shell message"

logger.exec "This is an exec message"

logger.stub "This is a stub message"

logger.todo "This is a todo message"

logger.sql "This is an sql message"

```