text:
This proposal builds on the ''AtInject'' proposal for JMS 2.0 and adds an abstraction layer on-top, that allows clients to easily send and receive messages in a type-safe way.

# Message Body & Properties
## Default: XML message

Simply by annotating it as ''MessageApi'', an interface can be used as the business contract for an asynchronous service.

```java
@MessageApi
public interface TradeService {
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp);
}
```

Note that all methods in such an interface must return ''void'' and not declare any exceptions, as the execution will be done asynchronously.

The sender can simply inject a stub that forwards all calls to the service using JMS.

```java
    ...
    @Inject TradeService tradeService;
    ...
    {
        tradeService.priceUpdate("ORCL", 26.5, now);
    }
```

The receiver just implements the annotated business interface.

```java
public class TradeServiceImpl implements TradeService {
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp) {
        ...
    }
}
```

The default message format is xml, e.g.:

```xml
<?xml version='1.0' encoding='UTF-8'?>
<priceUpdate>
    <symbol>ORCL</symbol>
    <price>26.5</price>
    <timeStamp>2011-09-10-15-34-00</timeStamp>
</priceUpdate>
```

The message payload is generated with JAXB, so objects passed in may have to be annotated accordingly. Note that the root element is the name of the method.

::TODO: Add sample code for the Timestamp class annotated to be formatted as seen above.

## Message Property & Message Selector

By default, all parameters are placed into the body. You can annotate parameters as ''JmsProperty'', so they will additionally be put into a property of the message.

```java
@MessageApi
public interface TradeService {
    public void priceUpdate(@JmsProperty String symbol, BigInteger price, Timestamp timeStamp);
}
```

The receiver can then use a message selector to only receive message with that property:

```java
@JmsMessageSelector("symbol = 'ORCL'")
public class TradeServiceImpl implements TradeService {
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp) {
        ...
    }
}
```

A ''JmsProperty'' annotation can not only appear directly on the parameter, but just as well on any direct or indirect property of a parameter object.

## Message Property only in the header

By using the ''onlyHeader'' attribute of the ''JmsProperty'' annotation, the field will be removed from the payload.

```java
@MessageApi
public interface TradeService {
    public void priceUpdate(@JmsProperty(onlyHeader=true) String symbol, BigInteger price, Timestamp timeStamp);
}
```

While the ''symbol'' parameter is a message property, the message body looks like this:

```xml
<?xml version='1.0' encoding='UTF-8'?>
<priceUpdate>
    <price>26.5</price>
    <timeStamp>2011-09-10-15-34-00</timeStamp>
</priceUpdate>
```

## Object Message

If you want the message payload to be serialized objects instead of an xml string, you can annotate the interface:

```java
@MessageApi
@JmsPayload(format = SERIALIZED)
public interface TradeService {
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp);
}
```

You can place the same annotation at the methods as well.

```java
@MessageApi
public interface TradeService {
    @JmsPayload(format = SERIALIZED)
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp);
}
```

## Map Message

If you want the message payload to be a map instead of an xml string, you can annotate the interface:

```java
@MessageApi
@JmsPayload(format = MAPPED)
public interface TradeService {
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp);
}
```

You can place the same annotation at the methods as well.

```java
@MessageApi
public interface TradeService {
@JmsPayload(format = MAPPED)
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp);
}
```

The mapped message then looks like this:

{|- border="1"
|SYMBOL
|ORCL
|-
|PRICE
|26.5
|-
|TIME_STAMP
|2011-09-10-15-34-00
|}

Note that the default naming scheme for the field names is to make them upper case with underscores.

::TODO: Custom map field name schema and/or custom map field names

::TODO: Custom message marshaller/unmarshaller

# Delivery
## Static Destination Name

The default destination name is the fully qualified name of the interface. You can change that on the ''MessageApi'' annotation.

```java
@MessageApi(destinationName = "Trades")
public interface TradeService {
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp);
}
```

## Dynamic Destination Name

By annotating a parameter as ''JmsDestination'', it is used for the destination name at run time.

```java
@MessageApi
public interface TradeService {
    public void priceUpdate(@JmsDestination String symbol, BigInteger price, Timestamp timeStamp);
}
```

As with static destination names, if a destination does not exist, normally an exception is thrown. By qualifying the ''JmsDestination'' annotation with ''createMissing = true'', missing destinations are created.

::TODO: As a queue or as a topic?!?

```java
@MessageApi
public interface TradeService {
    public void priceUpdate(@JmsDestination(createMissing = true) String symbol, BigInteger price, Timestamp timeStamp);
}
```

On the receivers side, the symbol argument is the name of the destination that was used to deliver the message. This can be different from the destination that the sender used, if the message was routed to a different destination for some reason.

::TODO: maybe this contradicts 3.4.1?

## Delivery Mode NON_PERSISTENT

The sender can statically set the delivery mode with a ''JmsNonPersistent'' annotation:

```java
    @Inject @JmsNonPersistent TradeService tradeService;
```

## Bean Managed Acknowledgement

By default the acknowledgement of messages is done automatically with the transaction.

::TODO

# Special Message Header Fields
## Message-ID & Timestamp

The sender can read the id of a message directly after it was sent from a ''JmsMessageId'' helper:

```java
    ...
    @Inject JmsMessageId messageId;
    @Inject TradeService tradeService;
    ...
    {
        tradeService.priceUpdate("ORCL", 26.5, now);
        String id = messageId.get();
    }
```

If the ''JmsMessageId'' is not injected into the sender, then a message id may not be generated by the JMS provider for performance reasons (see 3.4.3)

The receiver can, too, read the id of the message just received via ''JmsMessageId'':

```java
public class TradeServiceImpl implements TradeService {
    @Inject JmsMessageId messageId;

    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp) {
        String id = messageId.get();
        ...
    }
}
```

''JmsTimestamp'' is analogous.

## Correlation-Id, Reply-To & Message-Type

The interface can include a ''JmsCorrelationId'', which then is added as a header field. To remove it from the payload, add a ''onlyHeader'' attribute to the annotation.

```java
@MessageApi
public interface TradeService {
    public void priceUpdate(@JmsCorrelationId(onlyHeader = true) String correlationId, String symbol, BigInteger price, Timestamp timeStamp);
}
```

The correlation id can be a ''JmsMessageId'', a custom String, or a provider native byte''''.

''JmsReplyTo'' and ''JmsMessageType'' are analogous.

## Redelivered

The receiver can read the redelivered flag of the message just received via ''JmsRedelivered'':

```java
public class TradeServiceImpl implements TradeService {
    @Inject JmsRedelivered redelivered;

    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp) {
        if (redelivered.get()) {
            ...
        }
    }
}
```

## Static Time-To-Live & Expiration

The sender can specify a constant time-to-live for all messages sent to a service by using the ''JmsTimeToLive'' annotation:

```java
    @Inject @JmsTimeToLive(1000) TradeService tradeService;
```

The default time-to-live is zero, i.e. to never expire.

It can also read the calculated expiration just after the send:

```java
    @Inject JmsExpiration jmsExpiration;
    @Inject TradeService tradeService;
    ...
    {
        tradeService.priceUpdate("ORCL", 26.5, now);
        long expiration = jmsExpiration.get();
    }
```

The receiver can use the same annotation:

```java
public class TradeServiceImpl implements TradeService {
    @Inject JmsExpiration jmsExpiration;
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp) {
        long expiration = jmsExpiration.get();
        ...
    }
}
```

## Dynamic Time-To-Live

The sender can dynamically specify a time-to-live just before it sends a message, with the help of a ''JmsDynamicTimeToLive'' object:

```java
    @Inject TradeService tradeService;
    @Inject JmsDynamicTimeToLive timeToLive;
    ...
    {
        timeToLive.set(1000);
        tradeService.priceUpdate("ORCL", 26.5, now);
    }
```

You can reset the time-to-live back to the default (static) time-to-live by calling ''JmsDynamicTimeToLive#reset()''.

::TODO: Alternative syntax (no reset required):
```java
    @Inject TradeService tradeService;
    ...
    {
        withTimeToLive(1000).on(tradeService).priceUpdate("ORCL", 26.5, now);
    }
```

If both a dynamic and a static time-to-live are specified, the dynamic value is used.

The sender as well as the receiver can read the calculated expiration just as with a static time-to-live.

## Static Priority

The priority of messages can be specified by annotating the methods of the interface as ''JmsPriority'':

```java
@MessageApi
public interface TradeService {
    @JmsPriority(3)
    public void priceUpdate(String symbol, BigInteger price, Timestamp timeStamp);
}
```

The same annotation can be placed at the interface as well. The method annotation overrides the interface annotation.

::TODO: Maybe better just at the injection point... the receiver is not interested, is it?

## Dynamic Priority

The sender can dynamically specify the priority just before it sends a message, with the help of a ''JmsDynamicPriority'' object:

```java
    @Inject TradeService tradeService;
    @Inject JmsDynamicPriority priority;
    ...
    {
        priority.set(7);
        tradeService.priceUpdate("ORCL", 26.5, now);
    }
```

You can reset the priority back to the default (static) priority by calling ''JmsDynamicPriority#reset()''.

::TODO: Alternative syntax (no reset required):
```java
    @Inject TradeService tradeService;
    ...
    {
        withPriority(7).on(tradeService).priceUpdate("ORCL", 26.5, now);
    }
```

If both a dynamic and a static priority are specified, the dynamic value is used.

The sender as well as the receiver can read the priority analogous to the ''JmsExpiration'' above.

gha_language: Java


text:
local-pv-provisioner
====================

`local-pv-provisioner` is a custom controller that creates [local](https://kubernetes.io/docs/concepts/storage/volumes/#local) PersistentVolume(PV) resources from devices that match the specified conditions. It also cleanup the PVs when it's released and with the periodical trigger.

* The PVs will be removed along with the deletion of the node because of using `ownerReferences`.

## How to discover devices

`local-pv-provisioner` searches for devices according to `--device-path` and `--device-name-filter` options.

* `--device-path` option specifies the path to search the devices.
* `--device-name-filter` option filters the device names using a regular expression.

If you specify the following condition, all devices under `/dev/disk/by-path/` will be selected.

```console
$ local-pv-provisioner --device-path="/dev/disk/by-path/" --device-name-filter=".*"
```

## What resources are created

```yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: local-node1-pci-0000-3b-00.0-ata-1
  ownerReferences:
    - apiVersion: v1
      kind: Node
      name: node1
      uid: a958d5a1-2644-4e26-abb3-f810576b2f7f
spec:
  capacity:
    storage: 100Gi
  volumeMode: Block
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /dev/disk/by-path/pci-0000:3b:00.0-ata-1
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - node1
```

* `metadata.name` is decided according to the following rules.
    * The name is a concatenation of `local`, node name, and device name with `-`.
    * If it contains characters other than alphabets, numbers, `-` and `.`, it is replaced with `-`.
* `spec.storageClassName` is automatically set a value `local-storage`.
* `spec.capacity.storage` is decided from the max capacity of the device.
* The device specified `spec.local.path` is cleaned up by filling the first 100MB with zero value.

## Prometheus metrics

`local-pv-provisioner` exposes the following metrics.

### `local_pv_provisioner_available_devices`

`local_pv_provisioner_available_devices` is a gauge that indicates the number of available devices recognized by `local-pv-provisioner`.

| Label  | Description            |
| ------ | ---------------------- |
| `node` | The node resource name |

### `local_pv_provisioner_error_devices`

`local_pv_provisioner_available_devices` is a gauge that indicates the number of error devices recognized by `local-pv-provisioner`.

| Label  | Description            |
| ------ | ---------------------- |
| `node` | The node resource name |

## Usage

### Start `local-pv-provisioner`

1. Create symbolic links to device files that you want to expose for pods in `/dev/crypt-disk/by-path`.

2. Prepare kind environment.
    ```
    $ kind create cluster --config cluster.yaml --image quay.io/cybozu/kind-node:1.16 --wait=300s
    ```

3. Deploy `local-pv-provisioner`.
    ```
    $ kubectl apply -f local-pv-provisioner.yaml
    ```

4. Check that the pods have started and PVs have been created.
    ```
    $ kubectl get pod,pv
    NAME                             READY   STATUS    RESTARTS   AGE
    pod/local-pv-provisioner-5kn9n   1/1     Running   0          49s
    pod/local-pv-provisioner-rq8sm   1/1     Running   0          46s

    NAME                                               CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS    REASON   AGE
    persistentvolume/local-kind-worker-dummy-dev-01    1Ki        RWO            Retain           Available           local-storage            37s
    persistentvolume/local-kind-worker-dummy-dev-02    1Ki        RWO            Retain           Available           local-storage            37s
    persistentvolume/local-kind-worker2-dummy-dev-01   1Ki        RWO            Retain           Available           local-storage            34s
    persistentvolume/local-kind-worker2-dummy-dev-02   1Ki        RWO            Retain           Available           local-storage            34s
    ```

### How to use volumes

1. Create a PVC as follows:
    ```yaml
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      name: sample-pvc
    spec:
      storageClassName: local-storage
      accessModes:
        - ReadWriteOnce
      volumeMode: Block
      resources:
        requests:
          storage: 1Ki
    ```
    Set the values according to PV as follows:
    * `spec.storageClassName`: `local-storage`
    * `spec.accessModes`: `ReadWriteOnce`
    * `spec.volumeMode`: `Block`

2. Create a pod as follows:
    ```yaml
    apiVersion: v1
    kind: Pod
    metadata:
      name: sample-pod
    spec:
      containers:
        - name: ubuntu
          image: quay.io/cybozu/ubuntu:20.04
          command: ["/usr/local/bin/pause"]
          volumeDevices:
            - name: sample-volume
              devicePath: /dev/sample-dev
      volumes:
        - name: sample-volume
          persistentVolumeClaim:
            claimName: sample-pvc
    ```

3. The PVC will be bound to a PV.
    ```
    $ kubectl get pv,pvc
    NAME                                               CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM                STORAGECLASS    REASON   AGE
    persistentvolume/local-kind-worker-dummy-dev-01    1Ki        RWO            Retain           Available                        local-storage            3m29s
    persistentvolume/local-kind-worker-dummy-dev-02    1Ki        RWO            Retain           Available                        local-storage            3m29s
    persistentvolume/local-kind-worker2-dummy-dev-01   1Ki        RWO            Retain           Available                        local-storage            3m26s
    persistentvolume/local-kind-worker2-dummy-dev-02   1Ki        RWO            Retain           Bound       default/sample-pvc   local-storage            3m26s

    NAME                               STATUS   VOLUME                            CAPACITY   ACCESS MODES   STORAGECLASS    AGE
    persistentvolumeclaim/sample-pvc   Bound    local-kind-worker2-dummy-dev-02   1Ki        RWO            local-storage   29s
    ```

## How to cleanup released PVs

The cleanup process is:
1. Watches Update events for Persistent Volume
2. If `spec.storageClassName: local-storage` and `status.phase: Released`, fill the first 100MB of the corresponding device with zero value.
3. Delete the Persistent Volume from Kubernetes API server.
  - Note that, this process is executed even if failed to cleanup the device.

Note that this cleanup process is also executed periodically (interval: 1 hour).

## Command-line flags and environment variables

| Flag               | Env name              | Default              | Description                                                                                |
| ------------------ | --------------------- | -------------------- | --------------------------------------------------------------------------------------------------- |
| metrics-addr       | LP_METRICS_ADDR       | `:8080`              | Bind address for the metrics endpoint.                                                              |
| device-dir         | LP_DEVICE_DIR         | `/dev/disk/by-path/` | Path to the directory that stores the devices for which PersistentVolumes are created.              |
| device-name-filter | LP_DEVICE_NAME_FILTER | `.*`                 | A regular expression that allows selection of devices on device-idr to be created PersistentVolume. |
| node-name          | LP_NODE_NAME          |                      | The name of Node on which this program is running. It is a required flag.                           |
| polling-interval   | LP_POLLING_INTERVAL   | `5m`                 | Polling interval to check devices.                                                                  |
| development        | LP_DEVELOPMENT        | `false`              | Use development logger config.                                                                      |

## Docker images

Docker images are available on [Quay.io](https://quay.io/repository/cybozu/local-pv-provisioner)

repository: cybozu/neco-containers

branch_name: refs/heads/main

extension: md

gha_language: Go

license_type: permissive

repo_name: cybozu/neco-containers


text:
# reactn
React, but with built-in global state management.

## No Boilerplate!

For class components, simply change `import React from 'react';` to `import React from 'reactn';`, and your React class components will have global state built in!

For functional components, `import { useGlobal } from 'reactn';` to harness the power of React Hooks!

If you prefer decorators, you can continue to use the `react` package for your components and instead `import reactn from 'reactn';` and use the `@reactn` decorator!

## Intuitive!

Global state in class components behaves exactly like local state! Instead of `this.state` and `this.setState` to read and write to the local state, you can use `this.global` and `this.setGlobal` to read and write to the global state object.

Global state in functional components behaves almost identically to local state. Instead of `[ value, setValue ] = useState(default)`, you can use `[ value, setValue ] = useGlobal(key)` where the key is the key of the global state to which you want to read and write. You may also use `[ global, setGlobal ] = useGlobal()` to access the entire global object.

## Install

* `npm install reactn --save` or
* `yarn add reactn`

## Example (Class Component)

The below example reads an array of cards from the global state. The cards are deleted from the global state via the `Card` component and added to the global state via the `AddCard` comonent. Despite this, the `Cards` component can still access them and will re-render whenever either other component updates the cards in the global state.

```JavaScript
import React from 'reactn'; // uses reactn for built-in global state on components
import AddCard from '../add-card/add-card';
import Card from '../card/card';

// Render all cards in the global state, plus an additional Add Card button.
export default class Cards extends React.PureComponent {

  // For each card in the global state, render a Card component.
  get cards() {

    // this.global returns the global state,
    //   much the same way this.state returns the local state.
    return this.global.cards.map(card =>
      <Card
        key={card.id}
        {...card}
      />
    );
  }

  render() {
    return (
      <div className="cards">
        {this.cards}
        <AddCard />
      </div>
    );
  }
}
```

## Example (Functional Component)

Using React Hooks in React v16.7, you can harness `useGlobal` to access the global state.

The above component re-written as a functional component would look like this:

```JavaScript
import React from 'react';
import { useGlobal } from 'reactn';
import AddCard from '../add-card/add-card';
import Card from '../card/card';
import './cards.scss';

// Render all cards in the global state, plus an additional Add Card button.
const Cards = () => {

  const [ cards ] = useGlobal('cards');

  // For each card in the global state, render a Card component.
  return (
    <div className="cards">
      {cards.map(card =>
        <Card
          key={card.id}
          {...card}
        />
      )}
      <AddCard />
    </div>
  );
};

export default Cards;
```

license: MIT

repository: BTMPL/reactn

branch_name: refs/heads/master

gha_license_id: MIT

repo_name: BTMPL/reactn


text:
# rb-music

**rb-music** is a Ruby gem for working with musical notes, scales and intervals. It is basically a direct port of the wonderful [music.js](https://github.com/gregjopa/music.js) library by Greg Jopa.

## Installation

In your Gemfile:

```
gem 'rb-music', git: 'https://github.com/mwise/rb-music', branch: 'master'
```

In your Ruby code:

```
require 'rb-music'
```

## Overview

### Note

`Note.from_latin(name)`: Note by latin name and octave

```ruby
n = Note.from_latin('A4');  # single note
n.frequency  # 440
n.latin  # "A"
n.octave # 4
n.midi_note_number # 69

n = Note.from_latin('C4')  # base note for scale
n.scale('major') #  NoteSet built from the given note and scale
```

### Interval

`Interval.from_name(name)`: Interval by name

`Interval.from_semitones(num)`: Interval by semitones

```ruby
Interval.from_name('fifth') # define by name
whole_step = Interval.from_semitones(2) # define by # of semitones

c = Note.from_latin('C3')

# use intervals to transpose notes
d = c.add(whole_step)

# use intervals to define chords
cmaj = c.add(['unison','major third','fifth'])
```

repository: mwise/rb-music

repo_name: mwise/rb-music


text:
# Development

## Prerequisites

Node 16. All packages come with `.nvmrc` file, so you can make use of it using some nvm scripts.

## Install

```
npm i
```

Will install everything in every package and link any dependencies (including in `./examples/`) using Lerna.

## Build

```sh
npm run build -- <package-name> [-w]
# examples:
npm run build -- client -w
npm run build -- server-testing
npm run build
```

- `<package-name>` name of npm package, not its directory (only of `@cardsgame/`)
- `-w` will start `build:watch` scripts instead

# Release

Bumping versions and publishing npm packages happens on CI. To initialize it, developer needs to rebase `main` branch onto `development`. Inspect [`.circleci/config.yml`](../.circleci/config.yml) for more details.

Bot user @greenly-builder is authenticated on CircleCI with read-**write** access, so it'll appear in release commits.

# Maintenance

> Old notes here, ignore for now

Keep generating changelog with these, until we hit 1.0

```
npx conventional-changelog --preset angular --release-count 0 --outfile ./CHANGELOG.md --verbose
npx lerna exec --concurrency 1 --stream -- 'conventional-changelog --preset angular --release-count 0 --commit-path $PWD --pkg $PWD/package.json --outfile $PWD/CHANGELOG.md --verbose'
```

# Server

## Units

All dimensional units are in **centimeters**, to be as close to reality as possible.

The client-side would have to decide how to scale it and present on any devices. Sometimes it would be needed to ignore some units, for example: table size on small mobile devices. Package `@cardsgame/utils` contains 2 useful methods for conversion: `cm2px()` and `px2cm()`

repository: Zielak/cardsGame

gha_language: TypeScript

repo_name: Zielak/cardsGame


text:
# Fusion-physic
A simple 2d physic engine made with python and pygame. can use in games

you need python v 2.3.7 or 3x and pygame to run the Fusion physic engine

-- Creator
Gokul Kris : game dev / Student

# Discontinued
* This program is no longer maintained or supported


text:
# Module 5: Performance
# Demonstration: Testing Index Performance

### Objectives

In this demonstration, you will see how to evaluate the performance impact of indexes.

### Preparation

1.	Ensure that the 10985C-MIA-DC and 10985C-MIA-SQL virtual machines are running and then log on to 10985C-MIA-SQL as **ADVENTUREWORKS\Student** with the password **Pa$$w0rd**.

2.	Run **D:\Demofiles\Mod05\Setup.cmd** as an administrator to revert any changes.

### Demonstration Steps

1.  In the virtual machine, on the taskbar, click **Microsoft SQL Server Management Studio**.

2.  In the **Connect to Server** dialog box, in the **Server name** box, type **MIA-SQL**. In the **Authentication** box, ensure **Windows Authentication** is selected, and then click **Connect**.

3.  On the **File** menu, point to **Open**, click **File**, browse to the **D:\\Demofiles\\Mod05\\Demo1.sql** file, and then click **Open**.

4.  To turn statistics on, highlight the code under **Step 1** and click **Execute**.

5.  To run a query with no indexes, highlight the code under **Step 2** and click **Execute**.

6. Click the **Messages** tab, and note the number of logical reads performed and the execution times.

7.  To create indexes, highlight the code under **Step 3** and click **Execute**.

8.  To run a query with indexes, highlight the code under **Step 4** and click **Execute**.

9. Click the **Messages** tab again, and compared the number of logical reads performed and the execution times against those for the previous query.

10.  To drop the indexes, highlight the code under **Step 5** and click **Execute**.

11.  Close SQL Server Management Studio without saving any changes.

©2016 Microsoft Corporation. All rights reserved.

The text in this document is available under the [Creative Commons Attribution 3.0 License](https://creativecommons.org/licenses/by/3.0/legalcode "Creative Commons Attribution 3.0 License"), additional terms may apply.  All other content contained in this document (including, without limitation, trademarks, logos, images, etc.) are **not** included within the Creative Commons license grant.  This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes.

This document is provided "as-is." Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it. Some examples are for illustration only and are fictitious. No real association is intended or inferred. Microsoft makes no warranties, express or implied, with respect to the information provided here.


text:
# chips-net

[![Pipeline](https://gitlab.com/chipsneutrino/chips-net/badges/master/pipeline.svg)](https://gitlab.com/chipsneutrino/chips-net/pipelines)
[![Docs chipsneutrino.gitlab.io/chips-net](https://img.shields.io/website-up-down-green-red/http/shields.io.svg)](https://chipsneutrino.gitlab.io/chips-net/)
[![Code style:
black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

This repository contains the software to train and evaluate Convolutional Neural
Networks (CNNs) for neutrino event characterisation (cosmic muon rejection, beam
neutrino classification, neutrino energy estimation) within water Cherenkov
detectors, specifically for CHIPS R&D project detectors. For a detailed
description of the implementation see
[link](https://joshtingey.github.io/phd-thesis/thesis.pdf). We use the
[Tensorflow](https://www.tensorflow.org/) framework as the backend and employ
multiple GPUs for training and inference.

## Setup

The "environment.yaml" file contains the required Conda environment definition. Additionally, CUDA version 10.1 is required. To ensure that this version is used and the environment is installed correctly, we provide a bash script that can be used as follows:

```bash
source setup.sh
```

Once this is complete, you can source the same script again in the future to activate the environment.

## Usage

The default configurations for creating data, running training, and performing SHERPA hyperparameter optimisation studies are located in ./chipsnet/config/ these will need to be modified for your setup.

To create the training data (.tfrecords) files from the simulation 'map' files run:

```bash
make create
```

To train a beam neutrino classification model run:

```bash
make train_beam
```

To train a beam neutrino energy estimation regression model run:

```bash
make train_energy
```

To run a SHERPA hyperparameter optimisation study run:

```bash
make study
```

To run any task with a given configuration use the following:

```bash
python chipsnet/run.py [config_path]
```

To run all the tests call:

```bash
make test
```

## Analysis

To use the analysis results notebook in ./analysis/ run the following and navigate to the url given.

You will need to forward the port to your local machine if working remotely.

```bash
jupyter-lab
```

## Tips

- It's important to first copy data to the local GPU machine or the training rate is reduced significantly due to the networking bottleneck.

repository: chipsneutrino/chips-net

repo_name: chipsneutrino/chips-net


text:
iPray booklet generator
=======================

Intallation and getting ready
-----------------------------

This is a Python based app to generate iPray booklets

for development I'm using several python packages to make our life easier:

pip install Jinja2

pip install gspread

pip install --upgrade oauth2client

pip install PyOpenSSL

pip install git+https://github.com/jachinlin/kindle_maker.git

And spreadsheets as a database for all the texts. Here the instructions I have followed to get my ready the system to read that database:

https://gspread.readthedocs.io/en/latest/oauth2.html

In order to access the database you need the credentials, created through:

https://console.developers.google.com/apis

Things to have into account when running it
-------------------------------------------

* The database has to be in a google spreadsheet shared with the right address to access through the API

Running the build
-----------------

python .\src\build_iPray.py D:\dev\booklet-generator\data\ 2023

You will need scribus 1.5.7+ to open the result and generate the final booklet pdf
You need to install the keepcalm font to edit the cover

repository: immagery/booklet-generator

repo_name: immagery/booklet-generator


text:
## Getting started

 There are a few ways to open this project.

 ### Android Studio

 1. Android Studio -> File -> New -> From Version control -> Git
 2. Enter `https://github.com/bikebuka/bikebuka.git` into URL field

 ### Command line + Android Studio

 1. Run `git clone https://github.com/bikebuka/bikebuka.git`
 2. Android Studio -> File -> Open

repository: bikebuka/BikeBuka

gha_language: Kotlin

repo_name: bikebuka/BikeBuka


text:
---
title: Introduction
subtitle: Frontend
---

# Introduction
The Codex Frontend is built on top of some great open-source projects.

### Technologies
- Written in **Typescript**
- Build upon the **React Framework**
- Using the **Antd** UI library
- Styled with **SCSS** (well, most of it anyways...)
- Dependency Injection using **InversifyJS**

### Features
- Plugin-based extensions, quite similar to Laravel Service Providers
- Lazy loaded components/pages.
- GraphQL Api

## Core Concepts

repository: thexdesk/develop

branch_name: refs/heads/develop

gha_license_id: NOASSERTION

repo_name: thexdesk/develop


text:
---
layout: post
title: "I'm A Maker, Dammit"
published: true
categories: []

---

The other day I encountered this [blog post](http://joelrunyon.com/two3/russell-kirsch-encounter-lessons) in which
an entrepreneur accidentally meets Russell Kirsch, computing pioneer and inventor of the first digital photo.

Kirsch, at the wise age of 81, informs the author of two principles he follows.

>Do things that have never been done before

>Nothing is withheld from us what we have conceived to do.

Russell Kirsch's advice to work with determination and courage seems quaintly romantic. It surprises me that his words seem
foreign to *me*, an entrepreneur living in the Silicon Valley.  If anything, the principle of "Making Great Things"
should be my personal religion. But as I read these blog posts, I could feel that I was not living that way.

Day to day, I find myself thinking of users as people I need to monetize. I no longer try to "do things that have never been done."
I do things to get to achieve the mythical goals of Growth and Traction. I judge my work by a yardstick that measures how rich
I make other people. So if "nothing is withheld from us what we have conceived to do," why am I spending all my time conceiving
to do things I don't even care about?

These principles are not why I got into startups. So from today, I've decided to distance myself from this "Silicon Valley way of thinking".
Hacker News and Lean Startup be damned.

I'm a maker, dammit. I'm going to go make great things.


text:
Ethereal Legends - An Indie Action RPG built with Unreal Engine 4 for Steam, PS4, and Xbox One.

Ethereal Legends Module for Unreal Engine 4

Created and Programmed by Scott McCutchen

Soverance Studios

<EMAIL_ADDRESS>
www.soverance.com

www.ethereallegends.com

This module is provided as is, and is not intended to be a complete, working game. Instead, this module is meant to be used as a learning resource for others looking to bring their UE4 games to C++.

While I'd love to completely open-source Ethereal Legends, significant portions of the code used to create the full game is currently within UE4's Blueprint system, and of course I do not have the rights to redistribute any of the assets I've used to create the game. So this repository is the best I can do, providing you with the direct source I've used to build the game's foundation.

If you find something in the game that you'd like to add or change, this is the place to start. Feel free to ask me any questions you have about the code you find here, and be sure to make a pull request if you make any changes or fixes and I'll work to integrate it into the game. I'll be sure to add your name to the in-game credits for successful PRs!

repository: townie/EtherealLegends

repo_name: townie/EtherealLegends


text:
# @ng-easy/builders

[![CI](https://github.com/ng-easy/platform/actions/workflows/ci.yml/badge.svg)](https://github.com/ng-easy/platform/actions/workflows/ci.yml) [![npm latest version](https://img.shields.io/npm/v/@ng-easy/builders/latest.svg)](https://www.npmjs.com/package/@ng-easy/builders) [![README](https://img.shields.io/badge/README--green.svg)](/libs/builders/README.md) [![CHANGELOG](https://img.shields.io/badge/CHANGELOG--orange.svg)](/libs/builders/CHANGELOG.md) ![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)

Builders for [Nx](https://nx.dev) and [Angular](https://angular.io) projects.

## image-optimizer

This builder is a wrapper of [`@ng-easy/image-optimizer`](https://github.com/ng-easy/platform/tree/main/libs/image-optimizer) designed to generate build time optimized images from an assets folder.

A suggested configuration would be to place original images in a separate folder and make the output path the standard assets folder of the project and include them in the repo. This way it will integrate nicely with [Nx](https://nx.dev/)/[Angular](https://angular.io/) build process without need for build orchestration.

### Configuration of the builder

In your `angular.json`/`workspace.json` you can use the builder with:

```json
"optimize-images": {
  "builder": "@ng-easy/builders:image-optimizer",
  "options": {
    "assets": ["src/assets/original-images"],
    "outputPath": "src/assets/optimized-images"
  }
}
```

- `assets`: folders containing source images
- `outputPath`: where optimized images will be saved
- `deviceSizes`: expected device widths from the users of your website used in responsive of fill layouts, defaults to `[640, 750, 828, 1080, 1200, 1920, 2048, 3840]`
- `imageSizes`: image sizes when using fixed or intrinsic layouts, should be smaller and different from device sizes, defaults to `[16, 32, 48, 64, 96, 128, 256, 384]`
- `quality`: Quality of optimized images between `10` and `100`, defaults to `75`
- `formats`: optimized output formats, can be `png`, `jpeg`, `webp`, `avif` or `heif`, defaults to `["jpeg", "webp"]`

## semantic-release

This builder is a wrapper of [**semantic-release**](https://github.com/semantic-release/semantic-release) to automate the release process of Angular projects. It uses internally:

- [`@semantic-release/commit-analyzer`](https://www.npmjs.com/package/@semantic-release/commit-analyzer)
- [`@semantic-release/release-notes-generator`](https://www.npmjs.com/package/@semantic-release/release-notes-generator)
- [`@semantic-release/changelog`](https://www.npmjs.com/package/@semantic-release/changelog)
- [`@semantic-release/npm`](https://www.npmjs.com/package/@semantic-release/npm)
- [`@semantic-release/github`](https://www.npmjs.com/package/@semantic-release/github)

The configuration of the plugins is opinionated and it includes for configured projects:

- Generating the changelog
- NPM release
- GitHub release
- Update the package version in the source code

### Configuration of the builder

In your `angular.json`/`workspace.json` you can use the builder with:

```json
"release": {
  "builder": "@ng-easy/builders:semantic-release",
  "configurations": {
    "local": {
      "force": true
    }
  }
}
```

Additionally, you can use the following options:

- `dryRun`: defaults to `false`, runs the release process without releasing
- `force`: defaults to `false`, forces the release in a non CI environment, can be used to make a release locally
- `mode`: can be either `independent` or `sync`, defaults to `independent`, choose whether you want to make individual versioning or group all under the same version

If using Nx, the `release` target has to be run respecting the order of dependencies. That can be configured in the `nx.json` root config file:

```json
{
  "tasksRunnerOptions": {
    "default": {
      "runner": "@nrwl/nx-cloud",
      "options": {
        "cacheableOperations": ["build"],
        "strictlyOrderedTargets": ["build", "release"]
      }
    }
  },
  "targetDependencies": {
    "build": [{ "target": "build", "projects": "dependencies" }],
    "release": [{ "target": "release", "projects": "dependencies" }]
  }
}
```

If using just the Angular CLI, make sure to perform releases according to the order of dependencies.

### How to use `independent` mode

With this mode each releasable library will have its own version according to [semver](https://semver.org/). This is the preferred approach.

[Conventional commits](https://www.conventionalcommits.org/) follow the pattern `<type>[(optional scope)]: <description>`. When the builder is configured in `independent` mode, only the following commits will considered that apply for the individual project:

- Those without scope or scope equal to `*`
- Those where the scope is equal to the project name

Example of `angular.json`/`workspace.json`:

```json
{
  "projects": {
    "library": {
      // Only commits like "feat: new feature", "feat(*): new feature" or "feat(library): new feature" will be considered
      "targets": {
        "build": {
          /* */
        },
        "release": {
          "builder": "@ng-easy/builders:semantic-release"
        }
      }
    }
  }
}
```

Dependencies will be calculated using Nx project graph. When `projectA` is a dependency of `projectB` and the first gets upgraded to a new version, it will create a new commit that will bump the version of the latter. It will happen only if both projects are a buildable and publishable library, having the `release` target correctly configured.

### How to use `sync` mode

With this mode each all libraries will have the same version.

Just use these options:

```json
"release": {
  "builder": "@ng-easy/builders:semantic-release",
  "options": {
    "mode": "sync"
  }
}
```

All commits will be considered for a potential version bump. Changelog will still be in each project, only containing the changes that apply to the specific library.

### Bump major version

```shell
git commit -m "feat: :sparkles: bump major version" -m "BREAKING CHANGE New version"
```

### Force a specific version

If you want to force a version bump not following semantic release run:

```shell
git tag {packageName}@{newVersion} # Force a new higher base version
git push --tags
git commit -m "fix({project}): :arrow_up: force version bump" --allow-empty # Force the semantic release process
git push
```

And then do a release.

### Tips for GitHub Actions CI

Here you can find an example of a [workflow](https://github.com/ng-easy/platform/blob/main/.github/workflows/release.yml), below some details to consider:

```yml
name: Release
on:
  workflow_dispatch: # manual release
  schedule:
    - cron: '0 0 * * *' # scheduled nightly release

jobs:
  npm:
    name: Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repo
        uses<EMAIL_ADDRESS>        with:
          fetch-depth: 0
          persist-credentials: false # Needed so that semantic release can use the admin token

      - name: Fetch latest base branch
        run: git fetch origin main

      # Setup node, install dependencies

      - name: Release
        run: npm run release # nx run-many --target=release --all / ng run project:release
        env:
          CI: true
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} # Personal access token with repo permissions

      # Alternative using GitHub action
      - name: Release
        uses: mansagroup/nrwl-nx-action@v2
        with:
          targets: release
          nxCloud: 'true'
        env:
          CI: true
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} # Personal access token with repo permissions
```

repository: wSedlacek/platform

repo_name: wSedlacek/platform


text:
# community-management-simulator
An agent-based mode of an online community with management policies

WORK IN PROGRESS!

There are two versions of the model:

* v2 is the fully interactive version recommended for playing around with in NetLogo style
* v3 is intended for running from Behavior Space or in headless mode. The user interface is stripped to the barebones and the code is optimized for performance.

Full model specification are found in the document inside the LATEX folder. There is also a PDF export for easier reading.

Instructions and how-to information are found in the model itself in the Info tab.

To run the model, you will need NetLogo (https://ccl.northwestern.edu/netlogo/download.shtml). Download the model from the NetLogo model folder, open it in NetLogo and run it from the interface tab as normal.


text:
# treetalk
Civic tech app that lets you chat with trees registered in our database about the environment, CO2 emissions, and how your week has been.

Data from: https://data.illinois.gov/api/views/dzge-uybj/rows.json

repository: vingkan/treetalk

gha_language: JavaScript

repo_name: vingkan/treetalk


text:
## Cheat Sheet - [SouJava Online] Let's make a contract: the art of designing a Java API - Mario Fusco

[video](https://www.youtube.com/watch?v=bfJZDetMKEc)

* Costs little to write it, a lot to mantain it.
* Keep minimal exposed front.
* Javadoc for: valid values, errors, exceptions, use common annotations.
* Use semantic naming, use typed args.
* Consistent naming.
* Consistent # arguments ,  use factories:
    - can return different subclasses, good to check preconditions.
    - can use a fluent e.g. stream API.
* Overload for primitives (necessary evil), but keep minimal.
* Use interfaces with broader usage the most, e.g. not ArrayList but Collection or Iterable:
    - List, does the order meaningful?
    - Are element distinct? Else use Set or Collection. Avoid useless copy of objects.
* Use lambda: @FunctionalIterface as arguments of your API, use std. Consumer Interfaces as much as possibile.
* Avoid checked Exceptions, (lambda forbid them).
* Loan pattern, avoid leak of resources:
    - version 1: use finally || try with resources J7+;
    - version 2: functional withFile(name , @FunctionalInterface apply consumer ).
* Break big interfaces into small interfaces, delegate to subinterfaces from the master interface:
    - e.g. group by topic.
* Be defensive on data, immutable problem of list returned:
    - return Collections.unmodifiableList();
    - this is does not cover for content of the collection, try use guava, use vavr.
* Prefer enum to boolean, opens to future multiple value and adds more semantic.
* Avoid string typing, give it a name Map<String, ...>
* Avoid Primitive Obsession.
* Create Classes with Empty instances.
* Return optionals or empty collections. to avoid NullPointer.
* Warning Optional.of throws a NullPointerExc if value null:
    - wrong default, use ofNullable();
    - it help express intent of nullability of return, not the NOT NULL, it's a warning to consumer not a garantee;
    - using of with nullpointer help with a fast fail logic, if you use without check at least it breaks fast.
* Design API is all about tradeoffs and iterative discover.
* Design, minimal guidlines:
    - remove duplicates;
    - avoid leaks;
    - avoid unclear intentions;
    - favor broader usage;
    - use your API, with writing tests;
    - check for quality feedback.

repository: jugtaas/cheat-sheet

repo_name: jugtaas/cheat-sheet


text:
liblastfm
=========
[![Hackage](https://budueba.com/hackage/liblastfm)](https://hackage.haskell.org/package/liblastfm)
[![Build Status](https://secure.travis-ci.org/supki/liblastfm.png?branch=master)](https://travis-ci.org/supki/liblastfm)

Complete API interface to [last.fm][last.fm] service.
Documentation is available in two flavours:

  * original [API reference][last.fm/api]

  * liblastfm [haddocks][liblastfm/haddocks]

Introduction
------------
liblastfm provides Applicative interface for constructing requests. Also, it handles all machinery needed to prepare request for sending:

  * [signing][last.fm/sign]

  * url-encoding

  * miscellaneous stuff like choosing correct HTTP method, etc

Once request is ready, liblastfm can send it and get you back a response.
Response format might be:

  * [aeson][aeson] `Value` for json queries

  * [xml-conduit][xml-conduit] `Document` for xml queries

Installation
------------
To install either use hackage:

    % cabal install liblastfm

Or git:

    % git clone git@github.com:supki/liblastfm
    % cd liblastfm
    % cabal install

Usage
-----
Suppose, you need to use [`tag.search`][last.fm/api-usage] API method.
First find it in liblastfm: `Tag` would be the name of the module and `search` would be the name of function. [Here it is][liblastfm/haddocks-usage].
So import a couple of modules:

    >>> import           Lastfm            -- a bunch of useful utilities
    >>> import qualified Lastfm.Tag as Tag -- for Tag.search

Now you may use applicative `<*>` for required and `<*` or `*>` for optional parameters to construct
desired request:

    Tag.search <*> tag "russian-folk" <* limit 3 <*> apiKey "29effec263316a1f8a97f753caaa83e0" <* json

To send constructed request use `lastfm`:

    >>> con <- newConnection
    >>> lastfm con $ Tag.search <*> tag "russian-folk" <* limit 10 <*> apiKey "29effec263316a1f8a97f753caaa83e0" <* json
    Right (Object (fromList [("results",Object (fromList [("tagmatches", ...

[Wiki][liblastfm/wiki] describes how to parse responses.

FAQ
---

**Q: I'm getting the following error. How do I fix it?**

```
>>> Artist.getInfo <*> artist "Pink Floyd" <*> apiKey "29effec263316a1f8a97f753caaa83e0"

<interactive>:8:27:
    Couldn't match expected type `Data.Text.Lazy.Internal.Text'
                with actual type `[Char]
```

A: This means you haven't OverloadedStrings extension enabled.
To enable it (either one works):

  * type in `:set -XOverloadedStrings` while in ghci session.

  * add `{-# LANGUAGE OverloadedStrings #-}` to the top of the file

  * compile with `-XOverloadedStrings` switch

**Q: I'm getting the following error. How do I fix it?**

```
>>> lastfm (Artist.getInfo <*> artist "Pink Floyd" <*> apiKey "29effec263316a1f8a97f753caaa83e0")

<interactive>:13:1:
    No instance for (Show (IO (Either LastfmError r0)))
      arising from a use of `print'
    Possible fix:
      add an instance declaration for (Show (IO (Either LastfmError r0)))
    In the first argument of `print', namely `it'
    In a stmt of an interactive GHCi command: print it
```

A: This error message indicates that GHC cannot infer response format for the `Request`.
To fix it, add use `json` or `xml` helpers, depending on your needs

A note on testing
-----------------

To test Lastfm API compatibility (`api` test suite)—specifically, authentication requiring
examples—you will need to set `HASKELL_LIBLASTFM_APIKEY`, `HASKELL_LIBLASTFM_SESSIONKEY`,
and `HASKELL_LIBLASTFM_SECRET` environment variables to your api key, session key, and
secret respectively; for example (bash):

```bash
export HASKELL_LIBLASTFM_APIKEY="__API_KEY__"
export HASKELL_LIBLASTFM_SESSIONKEY="__SESSION_KEY__"
export HASKELL_LIBLASTFM_SECRET="__SECRET__"
```

Please, consult Lastfm API documentation and  `example/*-authentication.hs`
examples if you don't know where to get your credentials.

 [last.fm]: http://www.last.fm/
 [last.fm/api]: http://www.last.fm/api/intro
 [last.fm/api-usage]: http://www.last.fm/api/show/tag.search
 [last.fm/sign]: http://www.last.fm/api/authspec#8
 [liblastfm/haddocks]: http://supki.github.io/liblastfm/
 [liblastfm/haddocks-usage]: http://supki.github.com/liblastfm/Network-Lastfm-Tag.html#v:search
 [liblastfm/wiki]: https://github.com/supki/liblastfm/wiki/How-to-parse-JSON-response
 [aeson]: https://hackage.haskell.org/package/aeson
 [xml-conduit]: https://hackage.haskell.org/package/xml-conduit

repository: supki/liblastfm

extension: markdown

gha_language: Haskell

repo_name: supki/liblastfm


text:
# "Learn to Recover Visible Color for Video Surveillance in a Day" (ECCV2020 Oral)

This repository contains the code and dataset for the paper ["Learn to Recover Visible Color for Video Surveillance in a Day"]() by Guangming Wu, Yinqiang Zheng, Zhiling Guo, et al.

## Requirements

The source code have been valified on the following env:

- NVIDIA GPU > 8GB
- Ubuntu 16.04 LTS
- Anaconda Python(3.6)
- [Pytorch](https://pytorch.org/) > 1.0
- OpenCV 3

## VSIAD Dataset

```
Link => https://univtokyo-my.sharepoint.com/:u:/g/personal/9291958590_utac_u-tokyo_ac_jp/EZTYb_6LBWhEv1je1gzT8-wB1Dud678ewydOS_wM1YawdA?e=8Y37Kx
passwd => eccv2020
```

## Pretrained model
```
checkppoint/
--res18ynet-VC24-RGB2LAB_iter_100000.pth                 => (SSN, SSM => 0)
--res18ynetsync-VC24-L2LAB_iter_100000.pth               => (SSN, L2LAB)
--res18ynetsync-VC24-RGB2LAB_iter_100000.pth             => (SSN, full model)
--res18ynetsync-VC24-RGB2LAB-nop_iter_100000.pth.pth     => (SSN, perceptual => 0)
--res18ynetsync-VC24-LAB2LAB_iter_100000.pth             => (SSN, LAB2LAB)
--res18ynetsyncGN-VC24-RGB2LAB_iter_100000.pth           => (SSN, IN2GN)
```

## Usage

```
pending
```

## Publication
G. Wu, Y. Zheng, Z. Guo, et al., "Learn to Recover Visible Color for Video Surveillance in a Day," European Conference on Computer Vision (**ECCV**), to appear, 2020. (oral presentation, acceptance rate: 2%)

## Citation

```
@inproceedings{wu2020learn,
  title={Learn to Recover Visible Color for Video Surveillance in a Day},
  author={Wu, Guangming and Zheng, Yinqiang and Guo, Zhiling and Cai, Zekun and Shi, Xiaodan and Ding, Xin and Huang, Yifei and Guo, Yimin and Shibasaki, Ryosuke},
  booktitle={European Conference on Computer Vision},
  pages={495--511},
  year={2020},
  organization={Springer}
}
```

## Contact
For any question, please contact
```
huster-wgm(.at.)csis.u-tokyo.ac.jp or
guangmingwu2010(.at.)gmail.com
```

repository: huster-wgm/VSIAD

repo_name: huster-wgm/VSIAD


text:
**[299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)**

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.

Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.

Please note that both secret number and friend's guess may contain duplicate digits.

**Example 1:**
```
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
```

**Example 2:**
```
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
```

**Note:** You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

**Solution:**

```java
class Solution {
    public String getHint(String secret, String guess) {
        char[] s = secret.toCharArray();
        char[] g = guess.toCharArray();
        Map<Character, Integer> smap = new HashMap<>();
        Map<Character, Integer> gmap = new HashMap<>();
        int bull = 0, cow = 0;
        for(int i = 0; i < s.length; i++) {
            if(s[i] == g[i])
                bull++;
            else {
                if(smap.containsKey(s[i])) {
                    smap.put(s[i], smap.get(s[i]) + 1);
                } else {
                    smap.put(s[i], 1);
                }
                if(gmap.containsKey(g[i])) {
                    gmap.put(g[i], gmap.get(g[i]) + 1);
                } else {
                    gmap.put(g[i], 1);
                }
            }
        }
        for(char si : smap.keySet()) {
            if(gmap.containsKey(si))
                cow += Math.min(gmap.get(si), smap.get(si));
        }

        return bull + "A"+cow+"B";
    }
}
```

```java
class Solution {
    public String getHint(String secret, String guess) {
        char[] s = secret.toCharArray();
        char[] g = guess.toCharArray();
        int[] flag = new int[10];
        int bull = 0, cow = 0;
        for(int i = 0; i < s.length; i++) {
            if(s[i] == g[i])
                bull++;
            else {
                flag[s[i] - '0']++;
            }
        }
        for(int i = 0; i < g.length; i++) {
            if(flag[g[i] - '0'] != 0 && g[i] != s[i]) {
                cow++;
                flag[g[i] - '0']--;
            }
        }
        return bull + "A"+cow+"B";
    }
}
```

url: https://raw.githubusercontent.com/HughQS/leetcode/a3400a54b05e01ea8c350f4bed98e81b333d3730/easy/299. Bulls and Cows.md

repository: HughQS/leetcode

path: /easy/299. Bulls and Cows.md

filename: 299. Bulls and Cows.md

repo_name: HughQS/leetcode


text:
# Pre-work - *Name of App Here*

**Tip Calculator** is a tip calculator application for iOS.

Submitted by: **Prasanth Ramineni**

Time spent: **7** hours spent in total

## User Stories

The following **required** functionality is complete:

* [x] User can enter a bill amount, choose a tip percentage, and see the tip and total values.
* [x] Settings page to change the default tip percentage.

The following **optional** features are implemented:
* [x] UI animations
* [ ] Remembering the bill amount across app restarts (if <10mins)
* [ ] Using locale-specific currency and currency thousands separators.
* [x] Making sure the keyboard is always visible and the bill amount is always the first responder. This way the user doesn't have to tap anywhere to use this app. Just launch the app and start typing.

The following **additional** features are implemented:
- [x] Toggle Theme button added to Settings View

## Video Walkthrough

Here's a walkthrough of implemented user stories:

<img src='http://i.imgur.com/P4dkX3c.gif' title='Video Walkthrough' width='' alt='Video Walkthrough' />

GIF created with [LiceCap](http://www.cockos.com/licecap/).

## Project Analysis

As part of your pre-work submission, please reflect on the app and answer the following questions below:

**Question 1**: "What are your reactions to the iOS app development platform so far? How would you describe outlets and actions to another developer? Bonus: any idea how they are being implemented under the hood? (It might give you some ideas if you right-click on the Storyboard and click Open As->Source Code")

**Answer:** iOS is a great platform to develop mobile apps. Xcode is the best IDE so far for developing native apps for iOS devices. Outlets are the brigdges that connet the UIView elements to the View Controller and Actions are events that listen when a user plays with the UI elemnent

## License

    Copyright [yyyy] [name of copyright owner]

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

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

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


text:
# README #

This is a project to create a "living document," so to speak, for the [BMLT's semantic capabilities](https://bmlt.app/semantic/).

It will present an interactive "worksheet" that can be used to construct a URL (or shortcode) to present alternative BMLT interfaces.

View a live demo at: https://bmlt.app

This file is part of the Basic Meeting List Toolbox (BMLT).

Find out more at: https://bmlt.app

License
-------

BMLT is free software: you can redistribute it and/or modify
it under the terms of the MIT License.

BMLT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
MIT License for more details.

You should have received a copy of the MIT License along with this code.
If not, see <https://opensource.org/licenses/MIT>.

CHANGELIST
----------
***Version 1.3.4* ** *- December 14, 2018*

- When creating URLs for static content, the HTTP_X_FORWARDED_PROTO header is now inspected for determining protocol.
- Added sorting to service bodies and formats.

***Version 1.3.3* ** *- November 11, 2017*

- Added a change to the reported UA for the cURL call. Some servers' security software might have issues with the original one.

***Version 1.3.2* ** *- September 24, 2017*

- Changed "escape" to "encodeURIComponent" in order to resolve issues with non-Roman character sets.

***Version 1.3.1* ** *- May 18, 2017*

- Added a setting to the cURL caller to allow it to work in SSL on IIS servers.

***Version 1.3.0* ** *- May 9, 2017*

- Added support for the new Coverage Area option, which includes a map display of the coverage area.

***Version 1.2.1* ** *- March 31, 2017*

- The Google Maps API include needed to be SSL.

***Version 1.2.0* ** *- January 5, 2017*

- Added support for the new "Ends Before" time parameter.

***Version 1.1.4* ** *- December 11, 2016*

- Fixed a bug where certain fields were not being properly hidden, and certain menu values were left enabled when they should have been disabled, when the [[BMLT_TABLE]] shortcode was selected.
- Added support for the Google SAPI key in the embedded (in the Root Server) version.

***Version 1.1.3* ** *- May 2, 2016*

- Tweaked the format of this README to match the rest of the projects.
- Added [Doxygen](http://doxygen.nl) documentation.

***Version 1.1.2* ** *- April 6, 2016*

- The weekday boxes were not being re-shown after the table section was displayed.

***Version 1.1.1* ** *- April 4, 2016*

- Fixed an issue where the specific fields list was shown for simple response. It is not actually valid, there.

***Version 1.1.0* ** *- March 29, 2016*

- Added support for the new [[BMLT_TABLE]] shortcode.

***Version 1.0.11* ** *- March 27, 2016 (Happy Easter!)*

- Added the block mode checkbox to the shortcode searches.

***Version 1.0.10* ** *- March 23, 2016*

- Fixed a JavaScript bug, in which Root Servers with reduced complements of additional meeting data could cause the sort stuff to reference null objects.

***Version 1.0.9* ** *- March 20, 2016*

- Fixed a minor bug with the new server langs, where an invalid display could happen (Select "Server Languages" in XML or JSON, then switch to a different output type).

***Version 1.0.8* ** *- March 20, 2016*

- Added the JSON version of GetServerLangs.

***Version 1.0.7* ** *- March 18, 2016*

- Fixed a warning.
- Added a selection for the XML GetLangs response.
- Fixed an issue with the Root Server not having SSL honored.

***Version 1.0.6* ** *- March 13, 2016*

- Adding better capability for SSL, cleaned URIs and integration with the Root Server.

***Version 1.0.5* ** *- March 5, 2016*

- Tweaked the project to allow embedding in the main server.

***Version 1.0.4* ** *- September 18, 2015*

- Fixed the URL/Shortcode display to better form itself around long URIs.

***Version 1.0.3* ** *- July 2, 2015*

- Corrected the text describing the start times.

***Version 1.0.2* ** *- July 1, 2015*

- Added a link to the documentation page.

***Version 1.0* ** *- April 24, 2015*

- First official Release.

***Version 1.0b3* ** *- April 24, 2015*

- Now don't display the Service body sections if only 1 Service body..

***Version 1.0b2* ** *- April 11, 2015*

- This tool won't work on Root Server versions below 2.6.15. I now test for that.

***Version 1.0b1* ** *- April 11, 2015*

- Oops. Forgot to add the start time/duration sections.

***Version 1.0b0* ** *- April 9, 2015*

- First Beta release. No code change from 1.0a6, except that we are no longer running debug mode.

***Version 1.0a6* ** *- April 9, 2015*

- Made the NOT sections XOR with the "NOT-NOT" sections.

***Version 1.0a5* ** *- April 8, 2015*

- Added the "NOT" Service body section.

***Version 1.0a4* ** *- April 8, 2015*

- Added the weekday header code for the [[BMLT_SIMPLE]] shortcode search results.
- Fixed an issue where the Service body and format labels were not being properly associated with their checkboxes.
- Changed the way that Service bodies are recorded in the state, with an eye towards adding "not" Service bodies (it is possible, but not not reflected in the UI).

***Version 1.0a3* ** *- April 4, 2015*

- Fixed an issue with the way the field values checkboxes were set up in the meeting search fieldset. The labels were not properly hooked up to the checkboxes.

***Version 1.0a2* ** *- March 29, 2015*

- Fixed an issue with the sort selection, where unsorting the first item with more than 3 items would not re-flow the sort order.
- Make the selected sort items more prominent with CSS.
- Added a JavaScript noscript declaration.
- Added some styling to the basic URL entry form.
- The URL entry form now allows return-key submit.
- Prevent sort items from doing anything other than unsorting if they already have a value.
- Added a header and a basic instruction blurb.

***Version 1.0a1* ** *- March 28, 2015*

- First official "feature complete" alpha.

repository: bmlt-enabled/bmlt-root-server

gha_language: PHP

repo_name: bmlt-enabled/bmlt-root-server


text:
Back to [main page](../index.md).

#### Solution to challenge #1
```
telomerase = open("telomerase.txt")

seq = telomerase.read()

print seq

for aa in seq:
  print aa
```
Back to the [lesson](RepeatingThings.md)

#### Solution to challenge #2
```
telomerase = open("telomerase.txt")

for line in telomerase:
  print line
```
Back to the [lesson](RepeatingThings.md)

#### Solution to challenge #3
```
telomerase = open("telomerase.txt")

seq = telomerase.read()

for aa in "ACDEFGHKILMNPQRSTVYW":
  aa_count = seq.count(aa)
  aa_freq = aa_count/float(len(seq))
  print aa, round(aa_freq, 3)
```
Back to the [lesson](RepeatingThings.md)

Back to [main page](../index.md).

gha_language: Python


text:
---
layout: post
title: 'Writing Init Script for Apache Tomcat'
date: 2015-11-09 15:01
comments: true
categories: [java, bash, Tomcat, init]
---
![](https://upload.wikimedia.org/wikipedia/commons/8/80/Lechatbotte1.jpg)

Apache Tomcat's binary distribution downloaded from [the vendor site](http://tomcat.apache.org/download-80.cgi) contains no SystemV-compatible init script, so let's create a custom one.

## 1. A quick-and-dirty solution

The **catalina.sh** script living in the **bin** directory of Tomcat's distribution knows what to do when receiving **start** and **stop** command, so the simplest possible script for starting and stopping Tomcat would be as short as that:

```
#!/bin/bash
owner=tomcat
export CATALINA_HOME=/opt/tomcat
su -s /bin/sh -c "$CATALINA_HOME/bin/catalina.sh $1" $owner
```

(here and bellow variables with the lowercase names are local variables of the script, those with uppercase names are global variables visible by a Tomcat process).

The **-s** argument of the **su** command is required only if your **tomcat** user have a pseudo-shell (such as `/sbin/nologin`) for its login shell. You also can use the following **sudo** command-line instead of **su**:

```
sudo -E -u $owner $CATALINA_HOME/bin/catalina.sh $1
```

The _"Capital E"_ argument tells **sudo** to preserve current environment (a thing **sudo** normally doesn't do for some security reasons).

## 2. Adding more feautures

If you run Tomcat on the one of the _Red Hat_ derivatives, you apparently would like to add compatibility with the **chkconfig** utility to your `/etc/init.d/tomcat`. In order to do so add the following "magic" comment line right after the _bang-line_:

```
# chkconfig: 345 97 03
```

(`235` is a list of runlevels you want Tomcat to start on, `97` and `03` determines an order your service would be started after system boot and stopped before shutdown)

It would be conveniently enough, if our script understanded not only **start** and **stop** command, but **restart** too. **catalina.sh** by inself knows nothing about how to do restart, so we should tell it and replace the simple last line of our script by a way more complicated construction:

```
catalina() {
        su -s /bin/sh -c "$CATALINA_HOME/bin/catalina.sh $1" $owner
}

case $1 in
restart)
        catalina stop
        catalina start
        ;;
*)
        catalina $1
        ;;
esac
```

A bad news is that over a half of web applications existing in our imperfect world don't like to stop when Tomcat tells them to do so. Its developers know about that and add a optional **-force** parameter to the **stop** command. So, if an application you deploy on your Tomcat is from those stubborn ones, you could bring it to heel by rewriting our **catalina** function the following way:

```
$timeout=15
catalina() {
        if [ "$1" = "stop" ]
        then
                cmd="stop $timeout -force"
        else
                cmd="$1"
        fi
        su -s /bin/sh -c "$CATALINA_HOME/bin/catalina.sh $cmd" $owner
}
```

Where **$timeout** is a number of seconds to wait between saying `catalina.sh stop` and sending a _SIGKILL_ to Tomcat process.

But in order to work that way our script have to know where Tomcat's PID-file is (surprisingly enough,there's no default location.) We can let him know by setting an environment variable named **CATALINA_PID**:

```
export CATALINA_PID=$CATALINA_HOME/logs/tomcat.pid
```

(PID-file isn't put into a conventional `/var/run` directory, because normally **tomcat** user has no write permissions there)

If you need reaction on the **status** command in your script, it'll be a tricky part, because **catalina.sh** has no subcommand telling something about a current status of Tomcat service. My personal (of course, imperfect) variant of **status** function can be seen bellow:

```
status() {
        if [ -f "$CATALINA_PID" ]
        then
                pid=`cat $CATALINA_PID`
                if [ "`ps ho user -p $pid`" = "$owner" ]
                then
                        echo "Running (PID: $pid)"
                        exit 0
                else
                        echo "PID-file exists, but process isn't found"
                fi
        else
                echo "Stopped"
        fi
        exit 1
}
```

## 3. Changing JVM behaviour

If you've downloaded from [Oracle Java Archive](http://www.oracle.com/technetwork/java/javase/archive-139210.html) (or somewhere else) some historic version of JVM and want to run Tomcat by it, because let's say some old buggy clients works well only against this particular JVM, you can tell Tomcat where the desirible Java lives by setting **JAVA_HOME** variable in the preamble of your script. For example:

```
export JAVA_HOME=/opt/jdk1.7.0_45
```

Also, oftentimes happens that the default values of JVM heap and permanent memory values aren't sufficient for your web applications' needs. You can change them by setting **CATALINA_OPTS** varible:

```
export CATALINA_OPTS="-server -Xms1024m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m"
```

(setting start memory values equal to the maximal ones is highly recomandend for any server JVM processes)

If you set a well-known **JAVA_OPTS** instead of **CATALINA_OPTS**, it'll work too, but variant with **CATALINA_OPTS** is recomended by comments inside **catalina.sh** script, because it affects only the process of Tomcat itself and doesn't affect short-lived processes starting and stopping your Tomcat instance.

## 4. Separation between program and data

By default, Tomcat stores all its files: scripts, libraries, configs, logs, and deployed web applications in one file hierarchy, but I think, it's not such a bad idea to separate our binary installation from changeable files (after all, that's one of the key ideas under the standard Unix file layout.) With a such kind of setup it's possible to run multiple Tomcat instances using the exactly same version of binaries, but operating on the different ports and with the different set of web apllications deloyed upon them, or even more important, to upgrade (or maybe downgrade) your Tomcat installation without affecting its configurations files and webapps' directories.

Before telling Tomcat, where a new home for its moving parts is, we have to create a set of necessary directories (let's name its root `/opt/MyWebApp`), give away them to Tomcat's owner, and copy the serever's configuration:

```
mkdir -p /opt/MyWebApp/{logs,temp,work}
chown tomcat:tomcat /opt/MyWebApp/{logs,temp,work}
rsync -a /opt/tomcat/{conf,webapps} /opt/MyWebApp/
```

Then, in order to let Tomcat know about our new setup, an environment variable named **CATALINA_BASE** should be defined in the preamble of our init script (by default, it set equal to the **CATALINA_HOME**):

```
export CATALINA_BASE=/opt/MyWebApp
```

And the last thing I want to let you know for today. A full-blown init script for Tomcat containing all the aforementioned features can be found at [my page on github](https://github.com/alces/essentia-et-accidentia/blob/master/code-samples/tomcat_init_script.sh).

---

Tested against `apache-tomcat-8.0.28`, `CentOS 6.4`

repository: alces/essentia-et-accidentia

repo_name: alces/essentia-et-accidentia


text:
bounded-intmap
==============

The most current work on this is being done in [haskell/containers#340](https://github.com/haskell/containers/pull/340). This repository is not obsolete because it is still the best description of the algorithm, but it is unmaintained.

`bounded-intmap` is a reimplementation of `Data.IntMap` that uses minimum and maximum bounds on subtrees instread of bit prefixes. The original idea, by Edward Kmett, is described [here](https://www.fpcomplete.com/user/edwardk/revisiting-matrix-multiplication/part-4). As per my current benchmark results, this implemenation seems to range from 33% faster to 33% slower than stock `Data.IntMap`. However, only four types of function in the benchmark, `intersection`, `difference`, `fromAscList`, and `foldlWithKey`, are slower than stock `Data.IntMap`, and not all of these are slower in all cases. In comparison, `lookup`, `member`, `map`, `mapMaybe`, `insert`, `delete`, `update`, 'alter', and `union` are all faster than stock `Data.IntMap`. Additionally, this implementation, on GHC, has an overhead of 3 words per key/value pair, while stock `Data.IntMap` has an overhead of 6 words per key/value pair.

I deviate from Edward Kmett's implementation in a couple of ways:

* I removed the redundant encoding of bounds. Previously, you might have a tree like this:

               0,7
              /    \
           0,3      4,7
          /   \     /  \
        0,1   2,3  4,5  6,7

  Now, you have trees like this:

          0,7
          /  \
         3    4
        / \  / \
       1   2 5  6

  Note that this means that this implementation consumes less memory than the current `Data.IntMap`.

* I factored the datatype into two pieces: `Node` for non-empty trees, and `WordMap` for possibly empty trees.
* I cache some of the computation for locating a key as I traverse the key, making it quicker to decide which way to go.
* The values associated with each key are stored with the key instead of at the leaves.

Why `WordMap`?
--------------

Although the main goal of this project is to replace `Data.IntMap`, I also expose another module, `Data.WordMap`. In fact, my `IntMap` implementation is mostly just a wrapper of the `WordMap` code. The primary reason for this is code readability. Fundamentally, the data structure implemented here is a trie, and wants to work with lexographically ordered strings of bits. `Word`s have the correct ordering and more naturally fit the idea of bitstring than an `Int`, which is used for arithmetic. Given that I, unlike the previous `Data.IntMap`, actually use comparisons, the convenience for using `Word`s is even larger. The decision to expose `Data.WordMap` was then a simple one: I had already written the code, so why not?

Secondarily, I believe that the Haskell community doesn't use `Word`s enough, even when they are most applicable (which is weird, given the love of more accurately showing invariants in the type system), and having some libraries that actually use them would help.

Benchmark Results
-----------------
The criterion report is [here](http://gereeter.github.io/bounded-intmap/report.html).

Current Progress
----------------
Below is a listing of every function in stock `Data.IntMap`, along with the implementation state in `bounded-intmap`. There are three implementation states:

* Raw means that I have implemented the function directly. These functions should be on par with or faster than their corresponding functions in stock `Data.IntMap`.
* Delegated means that I have implemented the function, but in terms of other functions. This usually means that it will be slower than stock `Data.IntMap`, sometimes asymptotically, and I haven't figured out how to implement it (or implement it nicely) yet. Note that some functions marked as such, like `insertWithKey`, are trivial uses of other functions are should have almost no performance hit.
* Unimplemented means that I have yet to implement the function in any form.

### Operators
* `(!)`. Delegated, using `findWithDefault`.
* `(\\)`. Delegated, using `difference`.

### Query
* `null`. Raw.
* `size`. Raw.
* `member`. Raw.
* `notMember`. Raw.
* `lookup`. Raw.
* `findWithDefault`. Raw.
* `lookupLT`. Raw.
* `lookupGT`. Raw.
* `lookupLE`. Raw.
* `lookupGE`. Raw.

### Construction
* `empty`. Raw.
* `singleton`. Raw.

#### Insertion
* `insert`. Raw.
* `insertWith`. Raw.
* `insertWithKey`. Delegated, using `insertWith`.
* `insertLookupWithKey`. Raw.

#### Delete/Update
* `delete`. Raw.
* `adjust`. Raw.
* `adjustWithkey`. Delegated, using `adjust`.
* `update`. Raw.
* `updateWithKey`. Delegated, using `update`.
* `updateLookupWithKey`. Raw.
* `alter`. Delegated, using `lookup` and either `delete` or `insert`.
* `alterF`. Delegated, using `lookup` and either `delete` or `insert`.

### Combine
#### Union
* `union`. Raw.
* `unionWith`. Delegated, using `unionWithKey`.
* `unionWithKey`. Raw.
* `unions`. Delegated, using lots of `union`s.
* `unionsWith`. Delegated, using lots of `unionWith`s.

#### Difference
* `difference`. Raw.
* `differenceWith`. Delegated, using `differenceWithKey`.
* `differenceWithKey`. Raw.

#### Intersection
* `intersection`. Raw. See note on `intersectionWithKey`.
* `intersectionWith`. Delegated, using `intersectionWithKey`.
* `intersectionWithKey`. Raw. Note that it is still slower than stock `Data.IntMap` by up to (though not necessarily) 50%.

#### Universal combining function
* `mergeWithKey`. Delegated, using `merge`. Much slower than stock `mergeWithKey` and always will be - this function is terrible and abstraction-breaking.

### Traversal
#### Map
* `map`. Raw. Actually, this is sort of delegated to `fmap`, but since the delegation is just `map = fmap` and will probably be inlined, I count this as raw.
* `mapWithKey`. Raw.
* `traverseWithKey`. Raw.
* `mapAccum`. Delegated, using `mapAccumWithKey`.
* `mapAccumWithKey`. Raw.
* `mapAccumRWithKey`. Raw.
* `mapKeys`. Delegated, using `foldrWithKey'` and lots of `insert`s.
* `mapKeysWith`. Delegated, using `foldrWithKey'` and lots of `insertWith`s.
* `mapKeysMonotonic`. Delegated, using `mapKeys`.

#### Folds
* `foldr`. Raw.
* `foldl`. Raw.
* `foldrWithKey`. Raw.
* `foldlWithKey`. Raw.
* `foldMapWithKey`. Raw.

#### Strict folds
* `foldr'`. Raw.
* `foldl'`. Raw.
* `foldrWithKey'`. Raw.
* `foldlWithKey'`. Raw.

### Conversion
* `elems`. Delegated, using `foldr`.
* `keys`. Delegated, using `foldrWithKey`.
* `assocs`. Delegated, using `toAscList`.
* `keysSet`. Delegated, using `keys` and `Data.IntSet.fromDistinctAscList`. Note that this is only for `IntMap`, not for `WordMap`, as I'm not sure what to convert to.
* `fromSet`. Delegated, using `Data.IntSet.toList` and `fromDistinctAscList`. Note that this is only for `IntMap`, not for `WordMap`, as I'm not sure what to convert from.

#### Lists
* `toList`. Delegated, using `toAscList`.
* `fromList`. Delegated, using lots of `insert`s.
* `fromListWith`. Delegated, using lots of `insert`s.
* `fromListWithKey`. Delegated, using lots of `insert`s.

#### Ordered lists
* `toAscList`. Delegated, using `foldrWithKey`.
* `toDescList`. Delegated, using `foldlWithKey`.
* `fromAscList`. Delegated, using `fromList`.
* `fromAscListWith`. Delegated, using `fromListWith`.
* `fromAscListWithKey`. Delegated, using `fromListWithKey`.
* `fromDistinctAscList`. Delegated, using `fromList`.

### Filter
* `filter`. Delegated, using `filterWithKey`.
* `filterWithKey`. Raw.
* `restrictKeys`. Delegated, using `filterWithKey` and `Data.IntSet.member`. Note that this is only for `IntMap`, not for `WordMap`, as I'm not sure what set to intersect with.
* `withoutKeys`. Delegated, using `filterWithKey` and `Data.IntSet.notMember`. Note that this is only for `IntMap`, not for `WordMap`, as I'm not sure what set to intersect with.
* `partition`. Delegated, using `partitionWithKey`.
* `partitionWithKey`. Raw.
* `mapMaybe`. Delegated, using `mapMaybeWithKey`.
* `mapMaybeWithKey`. Raw.
* `mapEither`. Delegated, using `mapEitherWithKey`.
* `mapEitherWithKey`. Raw.
* `split`. Delegated, using `splitLookup`.
* `splitLookup`. Raw.
* `splitRoot`. Raw.

### Submap
* `isSubmapOf`. Delegated, using `isSubmapOfBy`.
* `isSubmapOfBy`. Raw.
* `isProperSubmapOf`. Delegated, using `isProperSubmapOfBy`.
* `isProperSubmapOfBy`. Raw.

### Min/Max
* `findMin`. Raw. Note that this is asymptotically faster than stock `Data.IntMap`.
* `findMax`. Raw. Note that this is asymptotically faster than stock `Data.IntMap`.
* `deleteMin`. Delegated, using `findMin` and `delete`.
* `deleteMax`. Delegated, using `findMin` and `delete`.
* `deleteFindMin`. Delegated, using `findMin` and `delete`.
* `deleteFindMax`. Delegated, using `findMin` and `delete`.
* `updateMin`. Delegated, using `findMin` and `update`.
* `updateMax`. Delegated, using `findMin` and `update`.
* `updateMinWithKey`. Delegated, using `findMin` and `updateWithKey`.
* `updateMaxWithKey`. Delegated, using `findMin` and `updateWithKey`.
* `minView`. Delegated, using `findMin` and `delete`.
* `maxView`. Delegated, using `findMin` and `delete`.
* `minViewWithKey`. Delegated, using `findMin` and `delete`.
* `maxViewWithKey`. Delegated, using `findMin` and `delete`.

### Debugging
Note that this section shouldn't matter to the average user.
* `showTree`. Raw.
* `showTreeWith`. _Unimplemented_.

Description of the internals
----------------------------
### The basic integer map: the bitwise trie ###
We are trying to create an efficient, simple mapping from integers to values. The most common approaches for these are hash tables, which are not persistent (though we can come close with HAMTs), and binary search trees, which work well, but don't use any special properties of the integer. To come up with this mapping, we need to think of integers not as numbers, but instead as strings of bits. Once we change our mindset, we can use the standard _trie_ data structure to build our mapping. As bits are particularly simple, so is the resulting structure:

```haskell
data WordMap a = Bin (WordMap a) (WordMap a) | Tip a | Nil
```

The `Bin` constructor represents a bitwise branch, and the `Tip` constructor comes after (on my machine) 64 `Bin` construtors in the tree.  Unfortunately, this approach is horribly slow and space efficient. To see why, let us look at the tree structure for `singleton 5 "hello"`:

```
\0
 \0
  \0
   \0
    \0
     \0
      \0
       \0
        \0
         \0
          \0
           \0
            \0
           1/
            \0
           1/
         "hello"
```

Note that, for brevity, I have shortened the word size to 16 bits - the diagram is 4 times larger for our 64 bit system. In this atrocious tree structure, there is one pointer for every bit - a 64 fold explosion in space. Arguably worse is the fact that every single `lookup` or `insert` or `delete` must traverse 64 pointers, resulting in 64 cache misses and a terrible runtime. So, how do we fix this?

### Path compression: PATRICIA trees and stock `Data.IntMap` ###
The key observation to reducing the space usage is that we can compress nodes that only have one child together - since they form a linear chain, we can simply concatenate the bits within that chain. For example, again temporarily shortening the word size to 16 bits:

```
singleton 5 "hello":

|<PHONE_NUMBER>000101
"hello"

fromList [(1, "1"), (4, "4"), (5, "5")]:

     |<PHONE_NUMBER>000___
001/  \10_
"1"  0/ \1
    "4" "5"
```

This clearly produces a much more space efficient structure, and the basic operations, while more complicated, are still straightforward. In Haskell, the structure is:

```haskell
data WordMap a = Bin Prefix Mask (WordMap a) (WordMap a) | Tip Word a | Nil
```

Note that in the above representation, the `Mask` is used to tell how long the `Prefix` is, and the `Word` in the `Tip` nodes is to avoid the for using `Bin` for singletons. This final representation is known as the big-endian PATRICIA tree, and is what today's `Data.IntMap` uses internally, albeit with some optimizations like strictness and unpacking, which I have omitted for simplicity. However, we can take this structure a few steps farther, which is the goal of this package.

### Implicit prefixes: a simpler representation ###

The central observation for this step comes from Edward Kmett, as mentioned in a previous section. In the PATRICIA tree representation, we explicitly stored the common prefix of all the keys in a subtree. However, this prefix is not needed if we know what the largest and smallest keys stored within a subtree are - the common prefix of all the keys is just the common prefix of the minimum and maximum keys. Using this observation, we get another representation:

```haskell
data WordMap a = Bin Word Word (WordMap a) (WordMap a) | Tip Word a | Nil
```

In tree form:
```
singleton 5 hello:

| 5
"hello"

fromList [(1, "1"), (4, "4"), (5, "5")]:

    | (1, 5)
  1/  \ (4, 5)
"1"  4/ \5
    "4"  "5"
```

Traversing this tree efficiently is a bit more difficult, but still possible. For details, see the section below titled "Figuring out which way to go". This representation, since it gives exact minimums and maximums, can actually be more efficient than the PATRICIA tree, as seaches can terminate earlier. The range of values between the minimum and maximum is generally smaller than the range of values with the correct prefix, and so searches will know earlier if they are going to fail. However, the big gains of this representation come after a few more steps.

### Removing redundancy ###
You may have noticed that the above representation store many keys repeatedly - in the {1,4,5} example, 1 was stored twice, 4 was stored twice, and 5 was stored three times. The reason for this is very simple. In the {1,4,5} example, we knew that the minimum was 1 and the maximum was 5. At the first branch, we split the set into two parts - {1} and {4,5}. However, the minimum of the smaller set was exactly the minimum of the original set. Similarly, the maximum of the larger set was exactly the maximum of the original set. Since we always travers the tree downward, this information is not needed. We can restructure the tree to only store 1 new value at each branch, removing the redundancy. Note that we also have to add an extra value at the root node, where this transformation does not work. In summary:

```haskell
data WordMap a = Empty | NonEmpty Word (Node a)
data Node a = Bin Word (Node a) (Node a) | Tip a
```

In tree form:
```
    | 1
    | 5
   / \
"1" 4/ \
   "4"  "5"
```

With this optimization, the operations get more complicated again, but we have achieved something amazing - this new representation is more memory efficient than stock `Data.IntMap`. We will improve this again, as well as the runtime, with our final optimization.

### Moving the values upward ###
If you look carefully at the tree structure from the previous section, you will notice that we removed the redundancy perfectly - every key is stored exactly once. However, if the keys are stored in a unique location in the tree, why are the values stored far away? We can move the values upward in the tree to pair them with their keys and so get a simpler structure.

In Haskell:
```haskell
data WordMap a = Empty | NonEmpty Word a (Node a)
data Node a = Bin Word a (Node a) (Node a) | Tip
```

In tree form:
```
    | 1 "1"
    | 5 "5"
   / \
     / \ 4 "4"
```

At first, this seems to improve neither runtime nor space usage - after all, all we did was move the values around. However, the `Tip` constructor is now empty, meaning that it can be shared among all the leaves of every tree. The `Tip` constructor essentiall disappears from the space usage profile, and we get a gain in memory. The runtime effect is even larger. Because the values are now high in the tree, functions like `lookup` don't have to go all the way to the leaves. This means following fewer pointers, which means fewer cache misses and just a shorter loop. Admittedly, after all this work, our functions have become much larger than the sizes they started with, but we have won speed gains and significant memory gains from the current state of the art.

### Figuring out which way to go ###
Suppose we are looking up a key `k` in a tree. We know that the minimum key in the tree is `min` and that the maximum key is `max`. Represented in binary:

             shared prefix   bit to split on
               /----------\  /
    min:<PHONE_NUMBER>01 0 ????????
    max:<PHONE_NUMBER>01 1 ????????
    k:<PHONE_NUMBER>01 ? ????????

To figure out in which subtree we need to recursively search for `k`, we need to know whether the bit to split on is zero or one. Now, if it is zero, then

    xor min k:<PHONE_NUMBER>00 0 ????????
    xor k max:<PHONE_NUMBER>00 1 ????????

If it is one:

    xor min k:<PHONE_NUMBER>00 1 ????????
    xor k max:<PHONE_NUMBER>00 0 ????????

Therefore, the splitting bit is set iff `xor min k > xor k max`. Taking the terminology from the original article, `insideR k min max = xor min k > xor k max`.

repository: gereeter/bounded-intmap

gha_language: HTML

repo_name: gereeter/bounded-intmap


text:
## VERGE Price listings

##### Motivation:

_A webservice that fetches the current price levels for verge and serves them via the api to reduce request rates on the original services and raises the privacy and security for our users by not requiring them to access a 3rd-party api._

## Requirements

- latest Mongo DB running to cache price levels
- yarn / NPM (comes with NodeJS)
- NodeJS (>= 8.x.x)
- and an ethernet connection lol ;)

## How to start

1. Run yarn / npm to install all required modules
2. you can either choose to run the prod or dev mode!
   1. Production: `yarn run prod`
   2. Development: `yarn run dev`
3. Then you will be able to access the service via `localhost:3000/api/v1/price/:currency`

## Production hosting

The server isn't optimized for production so we have to get some messaurements to do:

- Missing GZIP when sending responses
- No HTTPS
- Caching is partially suppported
- Multi Request handling isn't supported
- Sharding isn't supported

That's why we have to wrap this services with an **NGINX server** to proxy those request to this backend service. Meanwhile this services is running as sharding service within **PM2**.

repository: vergecurrency/verge-price-ticker

repo_name: vergecurrency/verge-price-ticker


text:
---
topic: "TBD"
desc: "TBD"
lecture_date: 2016-08-24 09:00:00.00-7:00
week: "4"
---

# Morning:

8:45am: APS with Miles

10:15am: Transition to Project Phase of SPIS

# Check in: "I'm (name)",
    * I'm glad, mad, sad, afraid, or I pass.
    * I'm in
    * Welcome

# Strategies

## Strategies to try
* Acknowledge each other's good ideas!
* Empathize- view things from the other person's perspective
* Be patient with your partner
* Confront problems instead of avoiding them
* Share things: time on the keyboard, conversation, food
* Seek outside opinion if you disagree

## Strategies to consider avoiding
* Being passive aggressive a.k.a. sarcasm, non-cooperation
* Resorting to physical violence

# Project related topics
* Schedule for the project phase
* Working with your (possibly new) partner
* Planning your project

* If time: discussion about data survey

# Afternoon

1:15-3pm: Open Lab.   Work with your new partner to prepare a project plan.

3:30pm: Non Academic (fun) activity.


text:
Serveo
=======================================================================

[![GoDoc](https://godoc.org/github.com/Axelen123/serveo?status.svg)](https://godoc.org/github.com/Axelen123/serveo)
[![Build Status](https://travis-ci.org/Axelen123/serveo.svg?branch=master)](https://travis-ci.org/Axelen123/serveo)

- [What is Serveo?](#what-is-serveo)
- [Installation](#installation)
- [Usage](#usage)
- [Docs](#docs)
- [Contributing](#contributing)
- [License](#license)

## What is Serveo?
This is an open source (unofficial) CLI for [serveo.net](https://serveo.net),
a service that allows you to expose local servers without port forwarding.

## Installation

Right now the only way to install serveo is from source.

You need to install [go](https://golang.org) first, I recommend version 1.12 or higher.
You also need openssh installed:
### Debian/Ubuntu Linux

Open a terminal and run:
```sh
sudo apt-get install openssh-client
go get -v -u github.com/Axelen123/serveo/cmd/serveo
```

### MacOS

Open a terminal and run:
```sh
go get -v -u github.com/Axelen123/serveo/cmd/serveo
```

### Windows 10

Open the start menu and search for "*features*".
Click on "*Apps and features*" -> "*Manage optional features*". Scroll down until you find "*OpenSSH Client*" (Not the server!) and click install.

Open a command prompt and run:
```sh
go get -v -u github.com/Axelen123/serveo/cmd/serveo
```

Now the binary should be in your GOPATH/bin folder.
Make sure to add GOPATH/bin to your PATH.

## Usage

### HTTP
Exposing an http server is easy:
```sh
serveo http

#On another port:

# Replace 8080 with the port your server uses
serveo http -p 8080

# You can also specify a custom [sub]domain:
# (if you don't specify a domain, your username will be used)

# These do the same thing
serveo http -d hello
serveo http -d hello.serveo.net

# For info on using a custom domain, see the wiki.
serveo http -d mydomain.com
```

### SSH
You can expose SSH as well!
```sh
serveo ssh

# ssh also works with domains

serveo ssh -d hello
```

Use these commands to ssh into it:
```sh
# For OpenSSH 7.3 or newer:
ssh -J serveo.net username@mydomainoralias

# For OpenSSH 7.2 or older:
ssh -o ProxyCommand="ssh -W mydomainoralias:22 serveo.net" username@mydomainoralias
```

### Config

The cli also supports config files, to initialize one you need to run:
```sh
serveo init
```

It should give you a file that looks like this:
```json
{
  "http": 80,
  "ssh": false,
  "domain": "",
  "tcp": []
}
```

The configuration options are similar to the CLI options:

- http: contains the port that an http server uses. You can disable it by setting to -1.
- ssh: expose ssh server or not
- domain: domain/alias for http and ssh
- tcp: contains paths to expose, example (remove comments if you want to use these):
```js
{
    "http": -1,
    "ssh": false,
    "domain": "",
    "tcp": [
        {
            "local": {
                // Expose http server on
                // raspberry pi
                "host": "raspberrypi",
                "port": 80
            },
            "remote": {
                "host": "pisrv",
                "port": 80
            }
        },
        {
            "local": {
                // expose local redis
                "host": "",
                "port": 6379
            },
            "remote": {
                "host": "redis",
                "port": 6379
            }
        }
    ]
}
```

#### Using the config

You can use the config like this:
```sh
# If you run without arguments it will
# use "serveo.config.json" as config file
serveo

# You can also specify config file:
serveo -c myconf.json
```

## Docs

You can find reference documentation at [godoc](https://godoc.org/github.com/Axelen123).

## Contributing

Note: by contributing code to the Redis project in any form, including sending a pull request via Github, a code fragment or patch via private email or public discussion groups, you agree to release your code under the terms of the MIT license that you can find in the [LICENSE](LICENSE) file included in the source distribution.

See [CONTRIBUTING.md](CONTRIBUTING.md) for more info.

## License

[MIT](LICENSE)

This project is not affiliated with serveo.net or its creator(s)


text:
# Comm Epics

Comm epics, more formally Communication Epics, are epics that support interacting with the
[Jupyter Messaging Protocol](https://jupyter-client.readthedocs.io/en/stable/messaging.html)
via comm messages.

A few years ago, Jupyter added a
[custom messaging](https://jupyter-client.readthedocs.io/en/stable/messaging.html#custom-messages)
system for developers to add their own objects with Front-end and Kernel-side components,
and allow them to communicate with each other. To do this, IPython adds a notion of a `Comm`,
which exists on both sides (Front end and Kernel), and can communicate in either direction.
As such, Comm messages are an arbitrary data exchange format built on top of the
Jupyter Messaging Protocol.

Comm messages are one-way communications to update comm state,
used for synchronizing widget state, or simply requesting actions of a comm's counterpart
(kernel-side request to front end or front-end request to kernel-side).

## commListenEpic

The `commListenEpic` is activated whenever a new kernel is successfully launched.

This epic, `commListenEpic`:

- maps `comm_open` kernel messages to `COMM_OPEN` actions dispatched to the Redux store
- maps `comm_msg` actions to `COMM_MSG` Redux actions.

This epic also includes some custom logic to handle processing comm messages that are
specific to [ipywidgets](https://ipywidgets.readthedocs.io/en/latest/). See more below.

## ipywidgetsModel

This epic listens to comm messages targeting ipywidget's `LinkModel` construct and updates
the nteract Redux state accordingly.

repository: nteract/nteract

repo_name: nteract/nteract