text:
# 611 Knight Shortest Path

**Description**
Given a knight in a chessboard \(a binary matrix with 0 as empty and 1 as barrier\) with a source position, find the shortest path to a destinationposition, return the length of the route.
Return -1 if knight can not reached.

**Notice**
source and destination must be empty.
Knight can not enter the barrier.

**Clarification**
If the knight is at \(x, y\), he can get to the following positions in one step:

\(x + 1, y + 2\)
\(x + 1, y - 2\)
\(x - 1, y + 2\)
\(x - 1, y - 2\)
\(x + 2, y + 1\)
\(x + 2, y - 1\)
\(x - 2, y + 1\)
\(x - 2, y - 1\)

**Example**
\[\[0,0,0\],
 \[0,0,0\],
 \[0,0,0\]\]
source = \[2, 0\] `destination` = \[2, 2\] return 2

\[\[0,1,0\],
 \[0,0,0\],
 \[0,0,0\]\]
source = \[2, 0\] destination = \[2, 2\] return 6

\[\[0,1,0\],
 \[0,0,1\],
 \[0,0,0\]\]
source = \[2, 0\] destination = \[2, 2\] return -1

\[Problem\]

Given a knight in a chessboard \(a binary matrix with `0` as empty and `1` as barrier\) with a `source` position, find the shortest path to a `destination` position, return the length of the route.
Return `-1` if knight can not reached.

 **Notice**

source and destination must be empty.
Knight can not enter the barrier. **Clarification**

If the knight is at \(_x_, _y_\), he can get to the following positions in one step:

```text
(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)
```

**Example**

```text
[[0,0,0],
 [0,0,0],
 [0,0,0]]
source = [2, 0] destination = [2, 2] return 2

[[0,1,0],
 [0,0,0],
 [0,0,0]]
source = [2, 0] destination = [2, 2] return 6

[[0,1,0],
 [0,0,1],
 [0,0,0]]
source = [2, 0] destination = [2, 2] return -1
```

\[Idea\]

Examples:

```text

In above diagram Knight takes 3 step to reach from (4, 5) to (1, 1)
(4, 5) -> (5, 3) -> (3, 2) -> (1, 1)  as shown in diagram
```

This problem can be seen as shortest path in unweighted graph. Therefore we use [BFS](http://www.geeksforgeeks.org/breadth-first-traversal-for-a-graph/) to solve this problem. We try all 8 possible positions where a Knight can reach from its position. If reachable position is not already visited and is inside the board, we push this state into queue with distance 1 more than its parent state. Finally we return distance of target position, when it gets pop out from queue.
Below code implements BFS for searching through cells, where each cell contains its coordinate and distance from starting node. In worst case, below code visits all cells of board, making worst-case time complexity as O\(N^2\)

```cpp
/**
 * Definition for a point.
 * struct Point {
 *     int x, y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    /**
     * @param grid a chessboard included 0 (false) and 1 (true)
     * @param source, destination a point
     * @return the shortest path
     */
    int shortestPath(vector<vector<bool>>& grid, Point& source, Point& destination) {
        // Write your code here
        if(grid.empty() || grid[0].empty()) return -1;

        int m = grid.size();
        int n = grid[0].size();

        vector<vector<int>> directions = {{-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}};

        vector<vector<int>> record(m, vector<int>(n, INT_MAX)); // record current distance, also plays a role to check if visited
        record[source.x][source.y] = 0;

        queue<Point> q;
        q.push(source);
        while (!q.empty()) {
            Point head = q.front();
            q.pop();
            for (int k = 0; k < 8; ++k) {
                int x = head.x + directions[k][0];
                int y = head.y + directions[k][1];
                if (x >=0 && x < m && y >= 0 && y < n && !grid[x][y] &&
                    record[head.x][head.y] + 1 < record[x][y]) {
                    record[x][y] = record[head.x][head.y] + 1;
                    q.push(Point(x, y));
                }
            }
        }
        if (record[destination.x][destination.y] == INT_MAX)
            return -1;
        return record[destination.x][destination.y];
    }
};
```


text:
# Welcome to  ReInA (Reasoning In AI)

For github page visit [Reina](https://github.com/Qyu-ai/Reina).

## About
ReInA (Reasoning In AI) is a causal inference platform aimed at estimating heterogeneous treatment effects in observational data. There are various open-source projects that provide convenient causal inference methods, but the current out-of-box packages are limited to local memory for computation. Hence, this project integrates Apache Spark with various machine learning (ML) powered causal inference frameworks, enabling causal analysis on big-data.

## Installation

	pip install reina

license: MIT

repository: Qyu-ai/Reina

branch_name: refs/heads/main

extension: md

gha_language: Python

gha_license_id: MIT

license_type: permissive

repo_name: Qyu-ai/Reina


text:
# Wolfram Web Engine for Python

Wolfram Web Engine for Python uses the Python AIOHTTP web server to handle requests for a Wolfram Engine.
Web pages are specified on the server with standard Wolfram Language functions such as [APIFunction](https://reference.wolfram.com/language/ref/APIFunction.html), [FormFunction](https://reference.wolfram.com/language/ref/FormFunction.html), [FormPage](https://reference.wolfram.com/language/ref/FormPage.html),
[URLDispatcher](https://reference.wolfram.com/language/ref/URLDispatcher.html), [AskFunction](https://reference.wolfram.com/language/ref/AskFunction.html), [HTTPResponse](https://reference.wolfram.com/language/ref/HTTPResponse.html), [HTTPRedirect](https://reference.wolfram.com/language/ref/HTTPRedirect.html), etc. This allows you to integrate Wolfram Language
functionality seamlessly with existing Python web applications like Django and AIOHTTP.

## Getting Started

### Prerequisites

1. Python 3.5 or higher
2. Wolfram Language 11.3 or higher (Mathematica, Wolfram Desktop, or Wolfram Engine)
3. [WolframClientForPython](!https://github.com/WolframResearch/WolframClientForPython)

### Install Using pip (Recommended)
Recommended for most users. It installs the latest stable version released by Wolfram Research.

Evaluate the following command in a terminal:

```
>>> pip3 install wolframwebengine
```

### Install Using Git

Recommended for developers who want to install the library along with the full source code.
Clone the library’s repository:

```
>>> git clone git://github.com/WolframResearch/WolframWebEngineForPython
```

Install the library in your site-package directory:

```
>>> cd WolframWebEngineForPython
>>> pip3 install .
```

The following method is not installing the library globally, therefore all the example commands needs to run from the cloned directory.

### Start a demo server

Start a demo server by doing:

```
python3 -m wolframwebengine --demo
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop/wolframengineforpython/wolframwebengine/examples/demoapp
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

Now you can open your web browser at the address http://localhost:18000/

![image](https://raw.githubusercontent.com/WolframResearch/WolframWebEngineForPython/master/docs/assets/image1.png)

## Two different ways of structuring an application:

1. Use a single file with URLDispatcher
2. Use multiple files in a directory layout

### Single file with URLDispatcher

One way to run your server is to direct all requests to a single file
that runs a Wolfram Language [URLDispatcher](https://reference.wolfram.com/language/ref/URLDispatcher.html) function.

Write the following content in a file called `dispatcher.m`:

```
URLDispatcher[{
    "/api" -> APIFunction["x" -> "String"],
    "/form" -> FormFunction["x" -> "String"],
    "/" -> "hello world!"
}]
```

From the same location run:

```
>>> python3 -m wolframwebengine dispatcher.m
----------------------------------------------------------------------
Address         http://localhost:18000/
File            /Users/rdv/Desktop/dispatcher.m
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

All incoming requests will now be routed to the `URLDispatcher` function in `dispatcher.m`.
You can now open the following urls in your browser:

```
http://localhost:18000/
http://localhost:18000/form
http://localhost:18000/api
```

For more information about `URLDispatcher` please refer to the [online documentation](https://reference.wolfram.com/language/ref/URLDispatcher.html).

### Multiple files in a directory layout

Another way to write an application is to create a directory structure that is served by the server. The url for each file will match the file's directory path.

The server will serve content with the following rules:

1. All files with extensions '.m', '.mx', '.wxf', '.wl' will be evaluated in the Kernel using [GenerateHTTPResponse](https://reference.wolfram.com/language/ref/GenerateHTTPResponse.html) on the content of the file.
2. Any other file will be served as static content.
3. If the request path corresponds to a directory on disk, the server will search for a file named index.wl in that directory. This convention can be changed with the --index option.

Create an application by running the following code in your current location:

```
mkdir testapp
mkdir testapp/form
mkdir testapp/api
echo 'ExportForm[{"hello", UnixTime[]}, "JSON"]' >  testapp/index.wl
echo 'FormFunction["x" -> "String"]'             >  testapp/form/index.wl
echo 'APIFunction["x" -> "Number", #x! &]'       >  testapp/api/index.wl
echo 'HTTPResponse["hello world"]'               >  testapp/response.wl
echo '["some", "static", "JSON"]'                >  testapp/static.json
```

Start the application by running:

```
>>> python3 -m wolframwebengine testapp
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop/testapp
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

Then open the browser at the following locations:

```
http://localhost:18000/
http://localhost:18000/form
http://localhost:18000/api?x=4
http://localhost:18000/response.wl
http://localhost:18000/static.json
```

One advantage of a multi-file application structure is that is very easy to extend the application. You can simply place new files into the appropriate location in your application directory and they will automatically be served.

## Using Docker

Wolfram Web Engine for Python is available as [a container image from Docker Hub](https://hub.docker.com/r/wolframresearch/wolframwebengineforpython) for use in containerized environments.

This image is based on the [official Wolfram Engine Docker image](https://hub.docker.com/r/wolframresearch/wolframengine); information on product activation and license terms
is available on the [Docker Hub page](https://hub.docker.com/r/wolframresearch/wolframengine) for the latter image.

```
# exposes the server on port 8080 of the host machine
>>> docker run -ti -p 8080:18000 wolframresearch/wolframwebengineforpython --demo

# serve files from the /srv directory
>>> docker run -ti -p 8080:18000 wolframresearch/wolframwebengineforpython /srv
```

The commands above do not include activation/licensing configuration; see the [official Wolfram Engine Docker image](https://hub.docker.com/r/wolframresearch/wolframengine) for information on activating the Wolfram Engine kernel.

Note regarding on-demand licensing: As Wolfram Web Engine for Python does not use WolframScript, the `-entitlement` command-line option and the `WOLFRAMSCRIPT_ENTITLEMENTID`
environment variable cannot be used to pass an on-demand license entitlement ID to the Wolfram Engine kernel inside this image.
As a workaround, the `WOLFRAMINIT` environment variable can be set to pass both the entitlement ID and the license server address to the kernel:

```
>>> docker run -ti -p 8080:18000 --env WOLFRAMINIT='-pwfile !cloudlm.wolfram.com -entitlement O-WSTD-DA42-GKX4Z6NR2DSZR' wolframresearch/wolframwebengineforpython --demo
```

## Options

```
>>> python3 -m wolframwebengine --help
usage: __main__.py [-h] [--port PORT] [--domain DOMAIN] [--kernel KERNEL]
                   [--poolsize POOLSIZE] [--cached] [--lazy] [--index INDEX]
                   [--demo [{None,ask,trip,ca,form}]]
                   [path]

positional arguments:
  path

optional arguments:
  -h, --help            show this help message and exit
  --port PORT           Insert the port.
  --domain DOMAIN       Insert the domain.
  --kernel KERNEL       Insert the kernel path.
  --poolsize POOLSIZE   Insert the kernel pool size.
  --startuptimeout SECONDS
                        Startup timeout (in seconds) for kernels in the pool.
  --cached              The server will cache the WL input expression.
  --lazy                The server will start the kernels on the first
                        request.
  --index INDEX         The file name to search for folder index.
  --demo [{None,ask,trip,ca,form}]
                        Run a demo application
```

#### demo

Run a demo application:

 1. __ask__: Marginal Tax rate calculator using AskFunction.
 2. __trip__: Trip calculator using FormFunction and TravelDirections.
 3. __ca__: Cellular Automaton demo gallery using URLDispatcher and GalleryView.
 4. __form__: ImageProcessing demo using FormFunction.

```
>>> python3 -m wolframwebengine --demo ca
----------------------------------------------------------------------
Address         http://localhost:18000/
File            /Users/rdv/Wolfram/git/wolframengineforpython/wolframwebengine/examples/demo/ca.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

#### path

The first argument can be a folder or a single file.

Write a file on your current folder:

```
>>> mkdir testapp
>>> echo 'ExportForm[{"hello", "from", "Kernel", UnixTime[]}, "JSON"]' > testapp/index.wl
```

Then from a command line run:

```
>>> python3 -m wolframwebengine testapp
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop/testapp
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

If the first argument is a file, requests will be redirected to files in that directory if the url extension is '.m', '.mx', '.wxf', '.wl'. If the extension cannot be handled by a kernel, the file will be served as static content.

If the request path is a folder the server will search for an index.wl in the same folder.

#### --index

Specify the default file name for the folder index.
Defaults to index.wl

```
python3 -m wolframwebengine --index index.wxf
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop
Index           index.wxf
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

#### --cached

If --cached is present the code in each file will be run only once, with subsequent requests retrieving the cached result.

```
>>> python3 -m wolframwebengine --cached
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

Visit the browser and refresh the page.

#### --port PORT

Allows you to specify the PORT of the webserver. Defaults to 18000.

```
>>> python3 -m wolframwebengine --port 9090
----------------------------------------------------------------------
Address         http://localhost:9090/
Folder          /Users/rdv/Desktop
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

#### --domain DOMAIN

Allows you to specify the DOMAIN of the webserver. By default the webserver only listens to localhost, use `<IP_ADDRESS>` to listen on all network interfaces.

```
>>> python3 -m wolframwebengine --domain <IP_ADDRESS>
----------------------------------------------------------------------
Address         http://<IP_ADDRESS>:18000/
Folder          /Users/rdv/Desktop
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

#### --initfile FILE

Allows you to specify a custom file containing code to be run when a new kernel is started

```
>>> python3 -m wolframwebengine --initfile myinit.m
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

#### --kernel KERNEL

Allows you to specify the Kernel path

```
>>> python3 -m wolframwebengine --kernel '/Applications/Wolfram Desktop 12.app/Contents/MacOS/WolframKernel'
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

#### --poolsize SIZE

Wolfram Web Engine for Python will launch a pool of Wolfram Language kernels to handle incoming requests. Running more than one kernel can improve responsiveness if multiple requests arrive at the same time. The --poolsize option lets you change the number of kernels that will be launched. Defaults to 1.
```
>>> python3 -m wolframwebengine --poolsize 4
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

#### --startuptimeout SECONDS

By default, an attempt to start a kernel will be aborted if the kernel is not ready after 20 seconds. If your application contains long-running initialization code, you may need to raise this timeout.
```
>>> python3 -m wolframwebengine
(...)
Kernel process started with PID: 485
Socket exception: Failed to read any message from socket tcp://<IP_ADDRESS>:5106 after 20.0 seconds and 245 retries.
Failed to start.

>>> python3 -m wolframwebengine --startuptimeout 50
(...)
Kernel process started with PID: 511
Connected to logging socket: tcp://<IP_ADDRESS>:5447
Kernel 511 is ready. Startup took 35.43 seconds.
```

#### --lazy

If the option is present the server will wait for the first request to spawn the kernels, instead of spawning them immediately.

#### --client_max_size MB

The maximum amount of megabytes allowed for file upload. Defaults to 10.
```
>>> python3 -m wolframwebengine --client_max_size 150
----------------------------------------------------------------------
Address         http://localhost:18000/
Folder          /Users/rdv/Desktop
Index           index.wl
----------------------------------------------------------------------
(Press CTRL+C to quit)
```

## Integrating an existing application

Wolfram Web Engine for Python can be used to augment an existing python application instead of creating a new one.
We currently support the following frameworks:

### Django

If you have an existing [Django](!https://www.djangoproject.com/) application you can use the `django_wl_view` decorator to evaluate Wolfram Language code during a web request.

```python
from __future__ import absolute_import, print_function, unicode_literals

from django.http import HttpResponse
from django.urls import path

from wolframclient.language import wl
from wolframclient.evaluation import WolframLanguageSession
from wolframwebengine.web import django_wl_view

session = WolframLanguageSession()

def django_view(request):
    return HttpResponse("hello from django")

@django_wl_view(session)
def form_view(request):
    return wl.FormFunction({"x": "String"}, wl.Identity, "JSON")

@django_wl_view(session)
def api_view(request):
    return wl.APIFunction({"x": "String"}, wl.Identity, "JSON")

urlpatterns = [
    path("", django_view, name="home"),
    path("form", form_view, name="form"),
    path("api", api_view, name="api"),
]
```

The decorator can be used with any kind of synchronous evaluator exposed and documented in [WolframClientForPython](!https://github.com/WolframResearch/WolframClientForPython).

### Aiohttp

If you have an existing [Aiohttp](!https://docs.aiohttp.org/en/stable/web_reference.html) server running you can use the `aiohttp_wl_view` decorator to evaluate Wolfram Language code during a web request.

```python
from aiohttp import web

from wolframclient.evaluation import WolframEvaluatorPool
from wolframclient.language import wl
from wolframwebengine.web import aiohttp_wl_view

session = WolframEvaluatorPool(poolsize=4)
routes = web.RouteTableDef()

@routes.get("/")
async def hello(request):
    return web.Response(text="Hello from aiohttp")

@routes.get("/form")
@aiohttp_wl_view(session)
async def form_view(request):
    return wl.FormFunction(
        {"x": "String"}, wl.Identity, AppearanceRules={"Title": "Hello from WL!"}
    )

@routes.get("/api")
@aiohttp_wl_view(session)
async def api_view(request):
    return wl.APIFunction({"x": "String"}, wl.Identity)

@routes.get("/app")
@aiohttp_wl_view(session)
async def app_view(request):
    return wl.Once(wl.Get("path/to/my/complex/wl/app.wl"))

app = web.Application()
app.add_routes(routes)

if __name__ == "__main__":
    web.run_app(app)
```

The decorator can be used with any kind of asynchronous evaluator exposed and documented in [WolframClientForPython](!https://github.com/WolframResearch/WolframClientForPython).

branch_name: refs/heads/master


text:
# How to locate the current 4D Folder?

## What is the 4D folder?

The 4D environment uses a specific folder to store the following information:

* Preferences files used by the 4D environment applications
* Shortcuts.xml file (custom keyboard shortcuts)
* Macros v2 folder (macro commands of Method editor)
* Favorites v1x folder, for example Favorites v13 (pathnames for local and remote databases that have been opened)
* Logs folder for maintenance logs and when the data is read-only
* The server-side cache for plugins and components

The active 4D folder is created by default at the following location:

1. **On Windows 7 and higher**: ``{Disk}:\Users\<userName>\AppData\Roaming\``
1. **On macOS**: ``{Disk}:Users:<userName>:Library:Application Support:``

Today this is true but may change in the future depending on the specifications of the operating system.

Here are the methods to simply locate the active 4D folder of the current 4D.

## Solution 1 - Manually

Open the Maintenance and Security Center (MSC) and on the Information page, click on the "4D Folder" item then select the "Show on disk" or "4D" item to open the folder.

## Solution 2 - Code

This code, to be put in a utility method that you can execute whenever you want, open the active 4D folder.

```4d
SHOW ON DISK (Get 4D folder (Active 4D Folder))
```
### • v17R5+
```4d
SHOW ON DISK (Folder(fk user preferences folder).platformPath)
```

## Solution 3 - Use 4DPop Bookmarks

The 4DPop Bookmarks development tool allow to directly open the used folders by the current database or the 4D Application: 4D Folder, Macros Folder, …

url: https://raw.githubusercontent.com/vdelachaux/tip-and-tricks/3ec89bb136e1bbd906087f970e2a45a3bdefae88/docs/How to locate the current 4D Folder.md

repository: vdelachaux/tip-and-tricks

filename: How to locate the current 4D Folder.md

repo_name: vdelachaux/tip-and-tricks


text:
# Exponential Backoff Retry Custom Policy

This is a implementation of the Exponential BackOff Retry algorithm that increases the backoff period for each retry attempt in case of app error. Applying this to your API or proxy you would be able to:

  - Define an initial interval whose first attempt should wait
  - Define a multiplier, used to increment the intervals between retries
  - Define a maximum interval, after which no increment on the interval will occur
  - Define a maximum elapsed time as a breaking point to stop retrying
  - Define expressions to validate the application's response. Expected responses can be configured in case no error occurs, or specific error expressions.
  - Perform a dynamic retry strategy, abstracting from the complexity of retrying at application level

### Why?
The idea behind the Exponential Backoff Retry algorithm is to provide a greater degree of resilience in our services when performing a backoff that is not static in the event of an error event. In this way, under a persistent error scenario, we do not overload the impacted system/service, but we provide a graceful degradation mechanism increasing the waiting time between retries after each retry failure.

### How?
The logic uses the values injected during the configuration of the policy to calculate the following variables:
- loopSize: this variable indicates the number of iterations to perform (used by the for-each). It is calculated at the beginning, and in the following way: ceil (ROUNDUP) of default_max_elapsed_time / 1000 / default_multiplier
- waitTime: this value indicates the time to wait. It is updated as follows:
	- At the beginning it is empty, because you have to try at least once to find out if there is an error
	- If there is an error the first time, it takes the value of default_initial_interval
	- If there are successive errors, it takes the value of waitTime * default_multiplier

Other variables are calculated during the process but are not specific to the algorithm, but are for internal use for flow control.
This policy does not have any dependency outside http-policy and mule-core components.

### Usage
After publishing to Exchange, follow these steps to apply the policy to an existing managed API (or proxy):

* Log into Anypoint Platform
* Enter API Manager
* Click on the API version for the application you want to apply the policy to
* Click on Policies
* Click on Apply New Policy
* Filter by 'Custom' category and select 'Exponential Backoff Retry'. Click on 'Configure Policy' button
* Give value to the policy's parameters:

| Parameter | Purpose |
| ------ | ------ |
| default_initial_interval | Indicates the initial wait time (when the first error happens) |
| default_max_elapsed_time | Indicates the maximum wait time. After this time, no retry will be performed. Similar to a timeout. |
| default_max_interval | Indicates the upper bound of the wait interval. Once this value is reached, the next retry will not be multiplied by the default_multiplier |
| default_multiplier | Indicates the increment value between repetitions. Between attempts, the calculation of the current wait time is given by previous interval value * multiplier |

#### Development

The following commands are required during development phase

| Task | Command |
| ------ | ------ |
| Package policy | mvn clean install |
| Publish to Exchange - Make sure to update the pom.xml file with your org ID - | mvn deploy |

### Limitations
This policy makes use of the for-each module. Since there is no break condition to exit the loop, this policy iterates through all the objects in the array (please see "How?" Section). This means that it is convenient to apply this policy with small values of intervals and elapsed time, to keep the loop fast to iterate (please see Benchmark section below). Of course, the current logic could be replaced with custom code (java module, script execution). It is up to the user to implement it. Just keep in mind that one of the main motivations for this policy is not to have too many dependencies.

### Benchmark
The policy has been tested using a Mule application that returns error or ok at random, based on a number generated with the random() Dataweave function (https://docs.mulesoft.com/mule-runtime/4.3/dw-core-functions-random). If it is odd, it returns an error (MULE:EXPRESSION, "org.mule.weave.v2.runtime.core.exception.DivisionByZeroException: Division by zero"), otherwise the result is satisfactory.  The purpose of this test was to emulate a transient error, i.e. network failure or server overload, to check effectiveness around error rate and overall performance. Please see the following results.

#### Application config

| Deployment Model | Runtime Version | Worker Size | Workers |
| ------ | ------ | ------ | ------ |
| CloudHub (US East - Ohio - ) | 4.3.0 | 0.1 | 1 |

#### Test #0 -  NO policy applied -

##### Test suite configuration

| # of request | # of threads | # of total concurrent requests |
| ------ | ------ | ------ |
| 100 | 2  | 200 |

##### Results

| Avg  | Median | Min | Max | Error Rate | Throughput |
| ------ | ------ | ------ | ------ | ------ | ------ |
| 398 ms | 378 ms | 349 ms | 1410 ms | %46.50 | 4.9/sec |

#### Test #1

##### Policy configuration

| default_initial_interval  | default_max_elapsed_time | default_max_interval | default_multiplier |
| ------ | ------ | ------ | ------ |
| 2000 ms | 10000 ms | 10000 ms | 1.5 |

##### Test suite configuration

| # of request | # of threads | # of total concurrent requests |
| ------ | ------ | ------ |
| 100 | 2  | 200 |

##### Results

| Loop Size | Avg  | Median | Min | Max | Error Rate | Throughput |
| ------ | ------ | ------ | ------ | ------ | ------ | ------ |
| 7 | 7813 ms | 3391 ms | 369 ms | 41822 ms | %00.00 | 15.1/min |

#### Test #2

##### Policy configuration

| default_initial_interval  | default_max_elapsed_time | default_max_interval | default_multiplier |
| ------ | ------ | ------ | ------ |
| 2000 ms | 10000 ms | 5000 ms | 1.5 |

##### Test suite configuration

| # of request | # of threads | # of total concurrent requests |
| ------ | ------ | ------ |
| 100 | 2  | 200 |

##### Results

| Loop Size | Avg  | Median | Min | Max | Error Rate | Throughput |
| ------ | ------ | ------ | ------ | ------ | ------ | ------ |
| 7 | 4584 ms | 2416 ms | 369 ms | 39133 ms | %00.00 | 25.4/min |

#### Test #3

##### Policy configuration

| default_initial_interval  | default_max_elapsed_time | default_max_interval | default_multiplier |
| ------ | ------ | ------ | ------ |
| 2000 ms | 10000 ms | 3500 ms | 1.5 |

##### Test suite configuration

| # of request | # of threads | # of total concurrent requests |
| ------ | ------ | ------ |
| 100 | 2  | 200 |

##### Results

| Loop Size | Avg  | Median | Min | Max | Error Rate | Throughput |
| ------ | ------ | ------ | ------ | ------ | ------ | ------ |
| 7 | 2019 ms | 1120 ms | 367 ms | 20428 ms | %00.00 | 55.4/min |

#### Test #4

##### Policy configuration

| default_initial_interval  | default_max_elapsed_time | default_max_interval | default_multiplier |
| ------ | ------ | ------ | ------ |
| 2000 ms | 600000 ms | 3500 ms | 1.5 |

##### Test suite configuration

| # of request | # of threads | # of total concurrent requests |
| ------ | ------ | ------ |
| 100 | 2  | 200 |

##### Results

| Loop Size | Avg  | Median | Min | Max | Error Rate | Throughput |
| ------ | ------ | ------ | ------ | ------ | ------ | ------ |
| 400 | 3579 ms | 1572 ms | 365 ms | 37890 ms | %00.00 | 32.6/min |

#### Test #5

##### Policy configuration

| default_initial_interval  | default_max_elapsed_time | default_max_interval | default_multiplier |
| ------ | ------ | ------ | ------ |
| 2000 ms | 600000 ms | 120000 ms | 1.5 |

##### Test suite configuration

| # of request | # of threads | # of total concurrent requests |
| ------ | ------ | ------ |
| 500 | 1  | 500 |

##### Results

| Loop Size | Avg  | Median | Min | Max | Error Rate | Throughput | 95% percentile |
| ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ |
| 400 | 2772 ms | 1385 ms | 361 ms | 299453 ms | %00.20 | 21.6/min | 5615 |

#### Test #6

##### Policy configuration

| default_initial_interval  | default_max_elapsed_time | default_max_interval | default_multiplier |
| ------ | ------ | ------ | ------ |
| 2000 ms | 600000 ms | 60000 ms | 1.5 |

##### Test suite configuration

| # of request | # of threads | # of total concurrent requests |
| ------ | ------ | ------ |
| 500 | 1  | 500 |

##### Results

| Loop Size | Avg  | Median | Min | Max | Error Rate | Throughput | 95% percentile |
| ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ |
| 400 | 1953 ms | 479 ms | 365 ms | 49785 ms | %00.00 | 30.7/min | 5220 |

### Contribution

Want to contribute? Great!

* For public contributions - Just fork the repo, make your updates and open a pull request!
* For internal contributions - Use a simplified feature workflow following these steps:
   - Clone the repo
   - Create a feature branch using the naming convention feature/name-of-the-feature
   - Once it's ready, push your changes
   - Open a pull request for a review

license: Unlicense


text:
---
title: |
    158. Seals My Pardon - Christ in Song
metadata:
    description: |
        Christ in Song 158. Seals My Pardon. I saw One hanging on the tree, In agony and blood, Who fixed His languid eyes on me, As near His cross I stood.
    keywords:  |
        Christ in Song, adventhymnals, advent hymnals, Seals My Pardon, I saw One hanging on the tree.
    author: Brian Onang'o
---

#### Advent Hymnals
## 158. SEALS MY PARDON
####  Christ in Song,

```txt
1.
I saw One hanging on the tree,
In agony and blood,
Who fixed His languid eyes on me,
As near His cross I stood.

2.
O, never till my latest breath
Can I forget that look;
It seemed to charge me with His death,
Tho' not a word He spoke.

3.

4.
Thus while His death my sin displays
In all its blackest hue,
Such is the mystery of grace,
It seals my pardon too.

```

- |   -  |
-------------|------------|
Title | Seals My Pardon |
Key | A♭ Major |
Titles | undefined |
First Line | I saw One hanging on the tree |
Author | Isaac Watts
Year | 1908
Composer| Rossini |
Hymnal|  - |
Tune| MANOAH |
Metrical pattern | |
# Stanzas |  |
Chorus |  |
Chorus Type |  |
Subjects | Christ: Christ's Sufferings; Christ: Christ Our Righteousness |
Texts | undefined |
Print Texts |
Scripture Song |  |

repository: GospelSounders/adventhymnals

repo_name: GospelSounders/adventhymnals


text:
# docker-ds

A proof of concept implementation for dockerizing the linux version of Docking Station

# building

Add `dockingstation_195_64.tar.bz2`, `glib-1.2.10-55.fc30.i686.rpm`, `gtk+-1.2.10-90.fc30.i686.rpm` and `SDL-1.2.9-1.i386.rpm` to `./app`

# usage (mac os x)

run `./launch-osx-xquartz.sh` after ensuring you have changed the settings to allow incomming network connections and restarted!

repository: Creatures-Developer-Network/docker-ds

gha_language: Dockerfile

repo_name: Creatures-Developer-Network/docker-ds


text:
# postcss-transform-animations

```
npm install --save postcss-transform-animations
```

Transforms all animations in a CSS file.

```js
import { camelCase } from 'lodash';
import transformAnimations from 'postcss-transform-animations';

return postcss([
  transformAnimations({
    transform: camelCase,
  }),
])
  .process(...)
```

By default will throw if two different animations produce the same output. In the example above, an error would be thrown if you had `@keyframes foo-bar` and `@keyframes fooBar`. You can disable this by setting `allowConflicts: true`.

Will also replace `animation` and `animation-name` declarations to match transformed keyframe names (spec compliant).


text:
---
title: "Managing users"
lang: en
layout: navgroup
navgroup: user-mgmt
keywords: LoopBack
tags: authentication
sidebar: lb3_sidebar
permalink: /doc/en/lb3/Managing-users.html
summary: LoopBack's built-in User model provides essential user management features.
---

## Overview

LoopBack's built-in [User](http://apidocs.strongloop.com/loopback/#user-new-user) model provides essential user management features such as:

* Registration and confirmation via email.
* Login and logout.
* Creating an access token.
* Password reset.

{% include_relative includes/User-model-note.md %}

## Creating and authenticating users

The basic process to create and authenticate users is:

1.  Register a new user with the [`User.create()`](http://apidocs.strongloop.com/loopback/#persistedmodel-create) method, inherited from the generic `PersistedModel` object.
    See [Registering users](Registering-users.html) for more information.
2.  Log in a user by calling [`User.login()`](https://apidocs.strongloop.com/loopback/#user-login) to get an access token.
    See [Logging in users](Logging-in-users.html) for more information.
3.  Make subsequent API calls using the access token.
    Provide the access token in the HTTP header or as a query parameter to the REST API call, as shown in
    [Making authenticated requests with access tokens](Making-authenticated-requests.html#making-authenticated-requests-with-access-tokens).

### Performance tip

To improve performance during login and user creation, try installing native [bcrypt](https://www.npmjs.com/package/bcrypt).

```shell
$ npm install --save bcrypt
```

{% include warning.html content="To run this package, you must [install compiler tools](Installing-compiler-tools.html) on your system, since it's a binary package.
" %}

## Understanding the built-in User model

By default, a LoopBack application has a [built-in User model](Using-built-in-models.html)
defined by [user.json](https://github.com/strongloop/loopback/blob/master/common/models/user.json)
(this file is part of the LoopBack framework.
Don't modify it; rather, follow the procedure in [Extending built-in models](Extending-built-in-models.html)).

{% include tip.html content="
For a basic introduction to how the LoopBack user model performs authentication,
see [Introduction to User model authentication](Introduction-to-User-model-authentication.html).
" %}

### Default access controls

The built-in User model has the following ACL:

```javascript
{
  "name": "User",
  "properties": {
    ...
    "acls": [{
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    }, {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "create"
    }, {
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW",
      "property": "deleteById"
    }, {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "login"
    }, {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "logout"
    }, {
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW",
      "property": "findById"
    }, {
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW",
      "property": "updateAttributes"
    }, {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "confirm"
    }, {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW",
      "property": "resetPassword",
      "accessType": "EXECUTE"
    }],
    //...
  }
}
```

The above ACL denies all operations to everyone, then selectively allows:

* Anyone to [create a new user](http://apidocs.strongloop.com/loopback/#persistedmodel-create) (User instance).
* Anyone to [log in](http://apidocs.strongloop.com/loopback/#user-login), [log out](http://apidocs.strongloop.com/loopback/#user-logout),
  [confirm their identity](http://apidocs.strongloop.com/loopback/#user-confirm), and
  [reset their own password](http://apidocs.strongloop.com/loopback/#user-resetpassword).
* A user to perform deleteById, findById, and updateAttributes on their own User record (instance).

{% include important.html content="
You cannot directly modify built-in models such as the User model with the [ACL generator](ACL-generator.html).

However, you can create a custom model that extends the built-in User model,
then use the ACL generator to define access controls that are added to those of the default User model.
For example, you could create a Customer or Client model that [extends the built-in User model](Extending-built-in-models.html), and then modify that model's ACL with the tool.
Since a model doesn't inherit ACLs from its base model, you must define ACLs for the new custom model.
" %}

### User realms

See [Partitioning users with realms](Partitioning-users-with-realms.html).

## Security considerations

When a user's account is compromised (for example their password is leaked or the attacker gains
access to their email account), the app needs to be able to prevent continued use of the hijacked account.

To address this case, LoopBack invalidates access tokens (logs out sessions)
when a change of password or email is detected. The access token used to
request the change (the current session) is preserved.

{% include important.html content="
To preserve backwards compatibility, LoopBack 2.x LTS does not enable this functionality by default, but prints a startup warning to notify the application developer about a potential security issue. See [AccessToken invalidation in LB 2.x](/doc/en/lb2/AccessToken-invalidation) for more details.
"%}

branch_name: refs/heads/gh-pages


text:
# JEm

JEm, short for Java Ember, is a 2D Game Engine designed to be intuitive, fast, and expressive.

## Features
- Expressive scripting system
- Intuitive APIs
- Fast prototyping
- A rich component system
-- Sprites
-- Physics
-- Sensors
-- Animation
-- and more..

repository: unpragmatic/jem

repo_name: unpragmatic/jem


text:
**May 5, 2021 —** [**Docs**](https://github.com/stas-ut21/ws-await/blob/v4.2.3/README.md)

- Hot fix: add `index.d.ts` for files in pack

**May 5, 2021 —** [**Docs**](https://github.com/stas-ut21/ws-await/blob/v4.2.2/README.md)

- Add Typescript definitions!
- Upgrade ws to 7.4.5
- Upgrade eslint to 7.25.0
- Upgrade mocha to 8.3.2
- Default `generateAwaitId` option now use `crypto` module
- Change `package-lock.json` to 2 version
- Fix some JSDOC bugs in `websocket.js`
- Update `.travis.yml` add NodeJS 15
- Update `.travis.yml`: drop NodeJS 8,9

**February 15, 2021 —** [**Docs**](https://github.com/stas-ut21/ws-await/blob/v4.2.1/README.md)

- Upgrade ws to 7.4.3

**December 15, 2020 —** [**Docs**](https://github.com/stas-ut21/ws-await/blob/v4.2.0/README.md)

- Upgrade ws to 7.4.1
- Upgrade mocha to 7.2.0
- Upgrade nyc to 15.1.0
- Update `.travis.yml` for NodeJS 14
- Update package-lock.json
- Upgrade `completeUpgrade` method in `websocket-server.js`

**March 26, 2020 —** [**Docs**](https://github.com/stas-ut21/ws-await/blob/v4.1.0/README.md)

- Upgrade ws to 7.2.3
- Upgrade eslint to 6.8.0
- Upgrade eslint-config-google to 0.14.0
- Upgrade mocha to 7.1.1
- Update `.travis.yml` for NodeJS 13
- Update package-lock.json
- Add new method `setAwaitTimeout` for update `awaitTimeout` option after create class instance
- Add new tests
- Update `wsAwait.md`

repository: remss/ws-await

repo_name: remss/ws-await


text:
---
layout: post
title: "Configuring a load balancer with Nginx on Debian Linux"
excerpt: "In this video I use Debian Linux on Virtualbox to show how a load balancer can be configured using Nginx, distributing the load among other instances"
tags: [nginx, debian, linux, virtualbox, loadbalancer, siege]
date: 2016-10-28T07:15:08+02:00
comments: true
image:
  feature: posts/cover-load-balancer.jpg
---

During the last 3 months (up to the date of this post), I've been developing a system using Node.js and the company needed a load balancer in order to deploy it.

I decided to record my first tutorial video and this was the theme I chose for it, as implementing this was very interesting for me and I hope it can be useful for more people.

I have some ideas for the next videos, which I intend to record soon, so stay tuned ;)

Click on the image below to watch it:

[![Configuring a load balancer with Nginx on Debian Linux](https://img.youtube.com/vi/3qFA5ZUiZfw/0.jpg)](https://www.youtube.com/watch?v=3qFA5ZUiZfw)

extension: markdown


text:
# Alfred Workflows

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A collection of personal [Alfred 3](https://www.alfredapp.com/) workflows that help me in my daily life and may help you as well.

*The following workflows have been added recently but I haven't fount the time yet to document them:*
  * *[AirPods Connector](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/AirPodsConnector.alfredworkflow)*
  * *[Airplane Mode](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/AirplaneMode.alfredworkflow)*
  * *[Brightness Selector](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/BrightnessSelector.alfredworkflow)*
  * *[Capture iOS Simulator](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/CaptureSimulator.alfredworkflow)*
  * *[UE Boom Connector](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/UEBoomConnector.alfredworkflow)*

## [Amphetamine Switcher](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/AmphetamineSwitcher.alfredworkflow)

*Requires [Amphetamine](https://itunes.apple.com/us/app/amphetamine/id937984704?mt=12), a little free app that lives in your menu bar. It gives you a graphical user interface for the caffeinate command line utility built into every Mac. With Amphetamine, you can easily and quickly override your energy saver settings and keep your Mac awake, without even lifting your fingers from the keyboard.*

With this workflow you can easily start and end Amphetamine sessions within a second. If a session is already running, it will be ended. Otherwise, a new endless session will be started.

``` applescript
tell application "System Events"
	keystroke "X" using {command down, shift down}
end tell
```

You have to set it with your hotkeys combo (mine is ⇧+⌘+X).

I kept the keyword as `caffeine` cause this workflow is a natural adaptation from my previous usage of Caffeine, but you can change it with the one you prefer.

## [Battery Time](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/BatteryTime.alfredworkflow)

*Since the macOS Sierra 10.12.2 update, we're no longer able to get the battery life time from the menubar. Altough it's still accessible in the Activity Monitor app, I find this solution tricky and no enough time-efficient.*

*Probably my best (and time-saving) Alfred workflow ever.*

This workflow helps you to see instantly the remainig battery life time. It is based on the `pmset -g batt`command, and can tell you wether the battery is charging or not, the remaining charging/discharging time and more.

I took advance of the Large Type option available in Alfred, which I believe is an underrated feature by most people. You may read more about it in the [dedicated article](https://alessandroaime.github.io/macos-sierra-battery-time-indicator-solution/) I wrote on my blog.

![Battery Time Animation](https://alessandroaime.com/images/battery-animation.gif)

Although the `time` keyword, I also included an ⇧+⌘+B hotkeys feature to make the call even faster.

## [Bluetooth Switcher](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/BluetoothSwitcher.alfredworkflow)

Part of my list of useful switchers. This one works with the `blueutil status` command utility, and turns ON or OFF the bluetooth based on its current status.

``` bash
if [[ $(./blueutil status) == 'Status: on' ]]
then
	./blueutil off
else
	./blueutil on
fi
```

The keyword is `bluetooth`, but you can change it with the one you prefer.

## [CleanMyMac Actions](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/CleanMyMac.alfredworkflow)

*Requires [CleanMyMac](http://macpaw.com/cleanmymac), an app that clean, optimize, and maintain your Mac. It scans every inch of your system, removes gigabytes of junk in just two clicks, and monitors the health of your Mac.*

Uninstalling apps and cleaning the Mac from junk files haesn't been so easy. I just have to call the trigger I want, and CleanMyMac does the job for me.

``` applescript
tell application "CleanMyMac"
	activate
end tell
tell application "System Events"
	tell process "CleanMyMac"
		keystroke return
	end tell
end tell
```

``` bash
open -a CleanMyMac.app {query}
```

The keyword are respectively `clean` and `uninstall` (plus the name of app you want get rid of), but you can change them with the ones you prefer.

## [Countdown](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/Countdown.alfredworkflow)

*I've never find myself a Pomodoro technique student, but I felt the need of a timer from time to time. I strived to find an app that let me interact through Alfred, so I came up with a built-in countdown workflow.*

The behaviour of this workflow is really simple: you call it with `timer` plus the minutes you countdown should run.

This workflow has been designed for scenarios where I'm really into something that I forget to take breaks. That's why I kept it really simple, so you won't be able too see how much time is missing to the end.

## [Files Visibility](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/FilesVisibility.alfredworkflow)

This workflow helps you change the files visibility in a click, wheter you need to `show` hidden files, or `hide` them.

``` bash
defaults write com.apple.finder AppleShowAllFiles ON
killall Finder
```

``` bash
defaults write com.apple.finder AppleShowAllFiles OFF
killall Finder
```

## [Force Empty Trash](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/ForceEmptyTrash.alfredworkflow)

When your Trash is moody and some files are stuck in it, you can force it to get rid of those junkies by typing `force` (or whatsoever word you think it is more appropriate).

``` bash
rm -rf ~/.Trash/*
```

## [Kill Application](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/KillApplication.alfredworkflow)

Sometimes can happen that an app stops working. This workflow is the simplest incarnation of the `killall` command utility: just call it via `kill` plus the app/process you want to kill, and let your computer do the dirty job.

``` bash
killall {query}
```

## [RAM Disk](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/RAMDisk.alfredworkflow)

*This is a feature I never really used, but I felt the need to build a workflow for too.*

This workflow creates a 1 GB RAM Disk, but you can easily improve it by asking a numerical argument, which will be the GB size of your disk.

``` bash
diskutil erasevolume HFS+ 'RAM Disk' `hdiutil attach -nomount ram://2097152`
```

The heyword is `ram`, but you can change it with the one you prefer.

## [Screen Recorder](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/ScreenRecorder.alfredworkflow)

*Even tough QuickTime Player is hardly used on a daily basis, it still have unique built-in features such as recording an iPhone/iPad screen while it's attached via USB or simply recording the Mac screen, and so forth.*

This workflow lets you easily record your Mac screen with QuickTime Player. Pretty straight forward.

``` applescript
tell application "QuickTime Player" to activate
tell application "System Events" to tell process "QuickTime Player"
	keystroke "n" using {command down, control down}
	delay 1
	keystroke space
end tell
```

The keyword is `record`, but you can change it with the one you prefer.

## [WiFi Switcher](https://github.com/AlessandroAime/AlfredWorkflows/raw/master/WiFiSwitcher.alfredworkflow)

Last but not least, the WiFi switcher. It works with the `networksetup` command utility, and turns ON or OFF the WiFi interface based on its current status.

``` bash
interface="en1"
ret=`networksetup -getairportpower $interface`
if [[ "$ret" == *On* ]]
then
	networksetup -setairportpower $interface off
else
	networksetup -setairportpower $interface on
fi
```

The keyword is `wifi`, but you can change it with the one you prefer.

repository: rkhozinov/AlfredWorkflows

repo_name: rkhozinov/AlfredWorkflows


text:
# LDA-Topic-Modeling

## Overview

This repository contains code to run a LDA (Latent Dirichlet Allocation) topic modeling. This model usually reuquires loads of memory and could be quite slow in Python. For this reason its is better to know a cuple of ways to run it quicker when datasets are outsize, in this case using Apache Spark with the Python API.

It has been done using Dataproc at Google Cloud using a cluster configuration which allows work with Jupyter Notebooks.

It has been used a dataset from Kaggle which contains over a million news headlines.

## Prerequisites

- A Google Cloud Account

- Python 3

- Pyspark v.2.2.1

- GENSIM Mallet Module

## Resources

- https://es.wikipedia.org/wiki/Latent_Dirichlet_Allocation

- https://www.kaggle.com/therohk/million-headlines

- https://radimrehurek.com/gensim/

- https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/

- https://cloud.google.com/dataproc/

- https://github.com/matthiasradtke/topic-modeling-codecentric-blog/blob/master/topicModeling-ccBlog.ipynb

- https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/

- https://medium.com/@connectwithghosh/topic-modelling-with-latent-dirichlet-allocation-lda-in-pyspark-2cb3ebd5678e

- http://spark.apache.org/docs/2.2.0/api/python/pyspark.ml.html#pyspark.ml.clustering.LDA

- https://spark.apache.org/docs/2.1.0/ml-clustering.html#latent-dirichlet-allocation-lda

- https://en.wikipedia.org/wiki/Gensim

## Python LDA Model

This notebook is based on GENSIM toolkit.

## pySpark LDA Model

There are 2 notebooks to make it quite different ways

repository: shinforest/LDA-Topic-Modeling

repo_name: shinforest/LDA-Topic-Modeling


text:
# solar_flares
A project for classifying images of solar flares (currently B and C flares during the peak flare time)

## Description
This project can load data from the NASA HESSI satellite and the NOAA GOES satellite into pandas DataFrame objects and combine matching flares.
It can use the flare information from these missions to download greyscale images taken by NASA's SDO in the 94A EUV part of the spectrum using the AIA instrument.
Finally it uses these images to train a CNN and classify images of the solar flares.

NASA - National Aeronautics and Space Administration
HESSI - High Energy Solar Spectroscopic Imager
NOAA - National Oceanic and Atmospheric Administration
GOES - Geostationary Operational Environment Satellite
SDO - Solar Dynamics Orbiter
94A - 94 angstrom wavelength
EUV - Extreame Ultra Violet
CNN - Convolutional Neural Network

## Data collection files include:
    hessi_df.py - this uses the HESSI mission to get a pandas dataframe with the HESSI data (primarily accurate flare locations and dates)\n
    goes_df.py - this uses the GOES mission to get a pandas dataframe with the GOES data (dates and class)\n
    interesct_hessi_goes.py - this combines the HESSI and GOES dataframes to create a new dataframe with the date, location and class\n
    download_images.py - this uses the combined data to download images of the flare\n

## Classification:
    cnn.py - uses a builds, trains, saves, loads and evalutes a CNN to classifiy images of solar flares

## Libraries include:
    numpy==1.17.2\n
    matplotlib==3.11\n
    pandas==0.25.1\n
    sunpy==1.1.0\n
    scikit-learn==0.22.1\n
    opencv-python==4.1.126\n
    tensorflow==1.14.0\n

## Instal dependancies with pip
```bash
pip install -r requirements.txt
```

## Roadmap
I want to include some options to use images of the solar active regioins some time before a flare to aid flare prediction capabilities.
I would also like to try using different wavlengths available from the AIA instrument and try a combination of wavelengths to improve accuracy.

## License

Copyright (c) [2020] [Matthew Wingham]

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

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

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


text:
#CustomTabGroup

A customized tab group view.

##Getting Started

To use CustomTabGroup in your project, copy the folder into the Resource directory of your project, and import the code:

```
var CustomTabGroup = require('CustomTabGroup/CustomTabGroup');
```

Then, create a new instance of the view:

```
var customTabGroup = CustomTabGroup();
```

Note: This call uses the default paramaters.  This can also be called using your own custom examples:

```
var customTabGroup = CustomTabGroup({
    position: 'bottom',
    height:   '80%',
    tabCount:  2
});
```

The following properties can be defined when creating a new custom navigation view:

        Property
        Type
        Default
        Description

        name
        string
        'default'
        Defines the name of the tab group, which is used as an identifier in notification events.

        height
        string
        'auto'
        Defines the height of the tab view (and subsequently the maximum height of all its views).

        width
        string
        'auto'
        Defines the width of the tab view (and subsequently the maximum width of all its views).

        tabBarHeight
        string
        '10%'
        Defines the height of the tab bar.

        position
        string
        'bottom'
        Defines where the tab bar will be on the view.  This can be either 'top' or 'bottom'.

        tabCount
        int
        0
        The number of tabs (and views) in the tab group.  Note: this parameter is MANDATORY

##Adding a Tab

Once a tab group has been created, the following method can be called to add a tab (and corresponding view):

```
customTabGroup.addTab();
```

Note: This call uses the default paramaters.  This can also be called using your own custom examples:

```
customTabGroup.addTab({
    tabText:  'Example Tab'
});
```

The following properties can be defined when adding a new tab:

        Property
        Type
        Default
        Description

        view
        Titanium.UI.View
        null
        The view being associated with this tab.  If not set, this method will create a default view.

        name
        string
        'default'
        Defines the name of the tab view, which is used as an identifier in notification events.

        tabButtonImageWidth
        string
        '80%'
        The width of the tab button image.

        tabButtonImageHeight
        string
        '50%'
        The height of the tab button image.

        tabButtonImage
        string
        '/CustomTabGroup/images/ tabgroup_button_off_default.png'
        The image of the tab button (normal state).

        tabButtonImageSelected
        string
        '/CustomTabGroup/images/ tabgroup_button_on_default.png'
        The image of the tab button (active state).

        tabText
        string
        'TEST'
        The title of the tab button.

        tabTextBottom
        string
        '5%'
        The padding between the bottom of the tab and the tab text.

        tabFont
        object
        {fontSize:'8dp', fontWeight:'bold', fontFamily:'Helvetica Neue'}
        The font of the tab text.

        tabFontColor
        string
        'white'
        The color of the title.

        tabFontColorSelected
        string
        'white'
        The color of the title when the tab is selected.

##Selecting a Tab

Once the tabs are created, the following method can be called to programmatically select a tab:

```
customTabGroup.selectTab(1);
```

This method is called with the following following parameters:

        Parameter
        Type
        Description

        index
        int
        The index of the tab to select.

##Notifications

These custom notifications are fired during the following circumstances:

###gainFocus

This is fired when a tab becomes selected.  The following parameters are passed to the event listener:

        Property
        Type
        Description

        tabName
        string
        The name of the specific tab to gain focus.

        tabGroupName
        string
        The name of the tab group to gain focus.

###loseFocus

This is fired when a tab becomes unselected.  The following parameters are passed to the event listener:

        Property
        Type
        Description

        tabName
        string
        The name of the specific tab to lose focus.

        tabGroupName
        string
        The name of the tab group to lose focus.

repository: ajaykoppisetty/TiCustomView

repo_name: ajaykoppisetty/TiCustomView


text:
# Changelog

## main

- NEW: Adds NodeJS v16 to Travis build
- NEW: Adds NodeJS node (latest) to Travis build
- CHANGED: Moves lockfileVersion to v2
- CHANGED: Deprecates support for NodeJS v10 (EOL)

## Release 4.4.0

- NEW: Added `registrar.getDomainPrices` to retrieve whether a domain is premium and the prices to register, transfer, and renew. (dnsimple/dnsimple-node#88)
- REMOVED: Drop the inexistent `domains.resetDomainToken` method (dnsimple-node#89)

## Release 4.3.0

- NEW: Adds NodeJS v15 to Travis build
- CHANGED: Removes NodeJS v13 from Travis build

## Release 4.2.1

- CHANGED: Bump semistandard from 14.2.0 to 14.2.2
- CHANGED: Bump nock from 12.0.3 to 13.0.0

## Release 4.2.0

- CHANGED: Bump mocha from 7.1.2 to 8.0.1
- CHANGED: Bump js-yaml from 3.13.1 to 3.14.0
- CHANGED: Domain object deprecates `expires_on` attribute in favor of `expires_at`. (dnsimple/dnsimple-node#43)
- CHANGED: Certificate object deprecates `expires_on` attribute in favor of `expires_at`. (dnsimple/dnsimple-node#45)

## Release 4.1.0

- NEW: Adds NodeJS v14 to Travis build
- NEW: Added `registrar.getDomainTransfer` to retrieve a domain transfer. (dnsimple/dnsimple-node#40)
- NEW: Added `registrar.cancelDomainTransfer` to cancel an in progress domain transfer. (dnsimple/dnsimple-node#40)
- CHANGED: Bump mocha from 7.1.1 to 7.1.2

## Release 4.0.0

- NEW: Adds NodeJS v13 to Travis build
- CHANGED: Deprecates support for NodeJS v8
- CHANGED: Deprecates JSCS usage. Implements https://www.npmjs.com/package/semistandard
- CHANGED: Simplifies testing instructions
- CHANGED: Bump lodash from 4.17.14 to 4.17.15
- CHANGED: Bump chai from 4.1.2 to 4.2.0
- CHANGED: Bump mocha from 5.2.0 to 7.1.1
- CHANGED: Bump nock from 9.3.2 to 12.0.3
- FIX: Fixes typo in test helper
- FIX: Fixes bad Certificates endpoint specs

## Release 3.0.3

- CHANGED: Default timeout is now hard-coded to ensure compatibility with Node.js 13. (GH-25) @jonchurch

## Release 3.0.2

- CHANGED: User-agent format has been changed to prepend custom token before default token.

## Release 3.0.1

- CHANGED: Dropped dependency on `npm`

## Release 3.0.0

- NEW: Updates to support Node v8. Node v6 is deprecated.

## Release 2.9.0

- NEW: Added WHOIS privacy renewal (GH-17)

## Release 2.8.0

- NEW: Added zone distribution and zone record distribution (GH-16)

## Release 2.7.0

- NEW: Added Let's Encrypt certificate methods (GH-14)

- CHANGED: Updated registrar URLs (GH-12)

repository: ajwcontreras/dnsimple-node

repo_name: ajwcontreras/dnsimple-node


text:
# plchdr-kt

Simple placeholder service.

## Features

- Customize placeholder `width x height`.
- Customize placeholder `color`.

## Usage

_TBD_

## Roadmap

- [x] `Width x Height`.
- [x] `Width x Height` and `Color`.
- [x] Optional `Height`.
- [ ] Image format (`JPEG`, `PNG`).
- [ ] Text with color.
- [ ] Contrast to color.
- [ ] `SVG` support.
- [ ] `WEBP` support.
- [ ] Placeholder logo.

## Changelog

See [CHANGELOG.md](CHANGELOG.md) file.

## License

This project is licensed under the [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) License - see the [LICENSE.md](LICENSE.md) file for details.

## Acknowledgments

- Classic [placeholder.com](https://placeholder.com/) for inspiration.

repository: dector/plchdr-kt

repo_name: dector/plchdr-kt


text:
dnsauth
=======

DNS Based Authentication

This project uses TXT records from DNS as a store for public keys which can then be used to authenticate signatures.

Install
-------

The package requires git and mecurial to be installed for go to fetch the dependancies.

    $ mkdir workspace
    $ cd workspace
    $ export GOPATH=`pwd`
    $ go get github.com/sour-is/dnsauth/dnsauth-cli

The finished executable will be in the bin directory.

Create a DNS entry
------------------

    $ bin/dnsauth-cli gentxt dummy1.sour.is dummy

    Private Key: 80ac0b83c0dcc9d91f59e8d865f7e409bad3749d2dcb379431fae3db830101f6f1
    dummy1.sour.is. IN TXT "algo:ecdsa curve:secp256k1 pubkey:BB7OT8hNBSqD8f0atJ6NH-MmZzSQNcSOKSjEjxOlKNHcL8lzVVPt_1XY9b37pZG1jkBn6rZlqCIAKbyc2aTa1P8"

Sign a token
------------

    $ bin/dnsauth-cli sign dummy1.sour.is dummy

    sig=IHcCY83WQwkS5REJY04yG9OAogq0f2qwiJGYljWyJcKl11-WgqaSU7EO1i3n9axIF0foXPpUqAROsDE6QgfERmkl5q3h

Verify a token
--------------

    $ bin/dnsauth-cli verify dummy1.sour.is IHcCY83WQwkS5REJY04yG9OAogq0f2qwiJGYljWyJcKl11-WgqaSU7EO1i3n9axIF0foXPpUqAROsDE6QgfERmkl5q3h

    Verify: true

Using the web interface
-----------------------

    $ bin/dnsauth-cli -v web
    INFO: 2014/05/26 12:28:47 web.go:17: Listen and Serve on port :8080

    $ curl localhost:8080/auth/dummy1.sour.is -d sig=IHcCY83WQwkS5REJY04yG9OAogq0f2qwiJGYljWyJcKl11-WgqaSU7EO1i3n9axIF0foXPpUqAROsDE6QgfERmkl5q3h

    INFO: 2014/05/26 12:29:35 web.go:27: Ident: dummy1.sour.is
    INFO: 2014/05/26 12:29:35 web.go:43: PubKey: BB7OT8hNBSqD8f0atJ6NH-MmZzSQNcSOKSjEjxOlKNHcL8lzVVPt_1XY9b37pZG1jkBn6rZlqCIAKbyc2aTa1P8
    INFO: 2014/05/26 12:29:35 web.go:95: Signature: IHcCY83WQwkS5REJY04yG9OAogq0f2qwiJGYljWyJcKl11-WgqaSU7EO1i3n9axIF0foXPpUqAROsDE6QgfERmkl5q3h
    INFO: 2014/05/26 12:29:35 web.go:110: AuthPass: dummy1.sour.is true

    {"ident": "dummy1.sour.is", "auth": true}

The web interface can take the following as input in the post data:

- sig=*[sig data]* where sig data is the signed signature generated by dnsauth-cli sign.
- sha=*[sha of password]* Where the value is the double sha256 of the password encoded with base64 (url-safe style '+/' => '-_').
- pass=*[password]* Were the password is passed in plantext.

OK, so how does it work?
-----------------------

It works by using [ECDSA](http://en.wikipedia.org/wiki/Elliptic_Curve_DSA)!

The private key is generated using the domain name and password. the following pseudo code will demonstrate.

    user = "dummy1.sour.is"
    pass = "dummy"

    // The private key in ECDSA is basically just a 256 bit value. (I am using the Koblitz curve as used for Bitcoin.)
    // I first take the SHA256 of the password. This allows the use of sending just the hash of the password to the web auth.
    sha = SHA256(SHA256(pass))

    // Then i use Scrypt for the key generation with user as salt.

    private = scrypt(user, sha, 16384, 8, 8, 32)

using the private key i can generate a public key which is stored in DNS.

For the authentication there are two steps.
First, is signing a random nonce and appending it to the end of the signature.

    nonce = rand(0, 2^32) // some random 4 byte value.

    R, S = sign(private, nonce)

    sig = base64(R + S + nonce)

Second, is verifying the signature.

    verify(public, nonce, R, S)

    // if true  : authentication passes
    // if false : authentication failed

repository: sour-is/dnsauth

repo_name: sour-is/dnsauth


text:
# Shrine::Storage::Fog

Provides [Fog] storage for [Shrine].

Fog is an abstraction over a variety of cloud storages (e.g. Google Cloud and
Dropbox).

## Installation

```ruby
gem "shrine-fog"
gem "fog-xyz" # Fog gem for the storage you want to use
```

## Usage

Require the appropriate Fog gem, and assign the parameters for initializing
the storage:

```rb
require "shrine/storage/fog"
require "fog/google"

Shrine.storages[:store] = Shrine::Storage::Fog.new(
  provider: "Google",                                    #
  google_storage_access_key_id: "ACCESS_KEY_ID",         # Fog credentials
  google_storage_secret_access_key: "SECRET_ACCESS_KEY", #
  directory: "uploads",
)
```

You can also assign a Fog storage object as the `:connection`:

```rb
require "shrine/storage/fog"
require "fog/google"

google = Fog::Storage.new(
  provider: "Google",
  google_storage_access_key_id: "ACCESS_KEY_ID",
  google_storage_secret_access_key: "SECRET_ACCESS_KEY",
)

Shrine.storages[:store] = Shrine::Storage::Fog.new(
  connection: google,
  directory: "uploads",
)
```

If both cache and store are a Fog storage, the uploaded file is copied to store
instead of reuploaded.

### URLs

By default the shrine-fog will generate public unsigned URLs, but if you want
to change that tell Fog not to store files publicly, you can set `:public` to
false:

```rb
fog = Shrine::Storage::Fog.new(**fog_options)
fog.url("image.jpg") #=> "https://my-bucket.s3-eu-west-1.amazonaws.com/image.jpg"

fog = Shrine::Storage::Fog.new(public: false, **fog_options)
fog.url("image.jpg") #=> "https://my-bucket.s3-eu-west-1.amazonaws.com/foo?X-Amz-Expires=3600&X-Amz-Date=20151217T102105Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<REDACTED_AWS_ACCESS_KEY>/20151217/eu-west-1/s3/aws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=6908d8cd85ce4469f141a36955611f26d29ae7919eb8a6cba28f9194a92d96c3"
```

The signed URLs by default expire in 1 hour, you set `:expires` to number of
seconds you want the URL to expire:

```rb
Shrine::Storage::Fog.new(expires: 24*60*60, **fog_options) # expires in 1 day
```

### S3 or Filesystem

If you want to store your files to Amazon S3 or the filesystem, you should use
the storages that ship with Shrine (instead of [fog-aws] or [fog-local]) as
they are much more advanced.

## Running tests

Tests use [fog-aws], so you'll have to create an `.env` file with appropriate
credentials:

```sh
# .env
S3_ACCESS_KEY_ID="..."
S3_SECRET_ACCESS_KEY="..."
S3_REGION="..."
S3_BUCKET="..."
```

Afterwards you can run the tests:

```sh
$ bundle exec rake test
```

## Inspiration

This gem was inspired by [refile-fog].

## License

[MIT](http://opensource.org/licenses/MIT)

[Fog]: http://fog.io/
[Shrine]: https://github.com/shrinerb/shrine
[fog-aws]: https://github.com/fog/fog-aws
[fog-local]: https://github.com/fog/fog-local
[refile-fog]: https://github.com/refile/refile-fog

repository: DocSpring/shrine-fog

repo_name: DocSpring/shrine-fog


text:
# The NCBI Style Hackathon Organizer Guide

This guide will contain information and tools to help organizers create their own NCBI-style hackathon.

![HAQmap flow diagram](HAQmap_flow_diagram.png)

## Tools in the kit
### [HackathonBuilder](https://purplegenie.shinyapps.io/Hackathon_builder/)
This Shiny app creates a push-button solution to creating a "hackathon starter kit."  Your kit will contain:
* a planning calendar containing tasks to be done in advance of your hackathon, based on your desired start date
* a form to accept applications from prospective participants
* a master planning spreadsheet for managing applicants, accepted participants, and teams
* a manuscript template for writing hackathon manuscripts
* and more, coming soon!

When this app is done, you'll be able to log in through Google and your kit will be created for you in a new Google Drive folder. Please note that as of now this app only works locally, but feel free to check out the in-progress version on [shinyapps.io](https://purplegenie.shinyapps.io/Hackathon_builder/).

### SlackBuilder
This Shiny app will automate the process of populating a Slack workspace with users and creating channels for each team.

It takes as input the URL for the Google Sheet containing your team list, in the original format from your HackathonBuilder kit (i.e. it will fail if you're changed the order of or removed any columns in your participant list) and the URL for your Slack workspace (you must create this manually).  It will then send email invitations to users, create channels for each team, and automatically invite users to the channel for their team.

repository: NCBI-Hackathons/HAQmap

gha_language: CSS

repo_name: NCBI-Hackathons/HAQmap


text:
# dswarm-web
Implementation of the dSwarm API for use in web browsers

## Using in an application

```
npm i -s dswarm-web
```

```js
// Based on example in dSwarm repo
// Try running the regular dSwarm demo with node
const dswarm = require('dswarm-web')
const crypto = require('crypto')

const swarm = dswarm({
  // Specify a server list of DSwarmServer instances
  bootstrap: ['ws://dswarmserver'],
  // You can also specify proxy and signal servers separated
  wsProxy: [
    'ws://proxy1.com',
    'ws://proxy2.com'
  ],
  webrtcBootstrap: [
    'ws://signal1.com',
    'ws://signal2.com'
  ],
  // The configuration passed to the SimplePeer constructor
  //See https://github.com/feross/simple-peer#peer--new-peeropts
  // for more options
  simplePeer:{
    // The configuration passed to the RTCPeerConnection constructor,for more details see
    // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#RTCConfiguration_dictionary
    config:{
      // List of STUN and TURN setvers to connect
      // Without the connection is limited to local peers
      iceServers:require("./ice-servers.json")
    }
  }
})

// look for peers listed under this topic
const topic = crypto.createHash('sha256')
  .update('my-dswarm-topic')
  .digest()

swarm.join(topic)

swarm.on('connection', (socket, details) => {
  console.log('new connection!', details)

  // you can now use the socket as a stream, eg:
  // socket.pipe(ddatabase.replicate()).pipe(socket)
})
```

Build it with [Browserify](http://browserify.org/) to get it running on the web.

You could also compile an existing codebase relying on dswarm to run on the web by adding a `browser` field set to `{"dswarm": "dswarm-web"}` to have Browserify alias it when compiling dependencies.

## Setting up a proxy server

`DSwarmServer` provides two services:

  - [dSwarmProxyWS](https://github.com/RangerMauve/dswarm-proxy-ws): to proxy dswarm connections over websockets. Path: `ws://yourserver/proxy`
  - [SignalServer](https://github.com/dwebprotocol/discovery-swarm-webrtc#server): for P2P WebRTC signaling connections. Path: `ws://yourserver/signal`

Running a `DSwarmServer` will allows you to use both services in one single process.

```
npm i -g dswarm-web

# Run it! Default port is 4977 (DWEB on a phone pad)
dswarm-web

# Run it with a custom port
dswarm-web --port 42069
```

### Running as a Linux service with SystemD

```bash
sudo cat << EOF > /etc/systemd/system/dswarm-web.service
[Unit]
Description=DSwarm proxy server which webpages can connect to.

[Service]
Type=simple
# Check that dswarm-web is present at this location
# If it's not, replace the path with its location
# You can get the location with 'whereis dswarm-web'
# Optionally add a --port parameter if you don't want 4977
ExecStart=/usr/local/bin/dswarm-web
Restart=always

[Install]
WantedBy=multi-user.target
EOF

sudo chmod 644 /etc/systemd/system/dswarm-web.service

sudo systemctl daemon-reload
sudo systemctl enable dswarm-web
sudo systemctl start dswarm-web

sudo systemctl status dswarm-web
```

repository: dwebprotocol/dswarm-web

repo_name: dwebprotocol/dswarm-web


text:
---
title: How to use the TextArea component (Starling version)
sidebar_label: TextArea
---

The [`TextArea`](/api-reference/feathers/controls/TextArea.html) class supports the editing of multiline, uniformly-formatted text.

<img src="/learn/as3-starling/images/text-area.png"<EMAIL_ADDRESS>2x" alt="Screenshot of a Feathers TextArea component" />

A TextArea component skinned with MetalWorksDesktopTheme

> `TextArea` is designed specifically for desktop apps, and it is _not_ recommended for use in mobile touchscreen apps. Instead, on mobile, you should use a [`TextInput`](./text-input.md) component with a [`StageTextTextEditor`](/api-reference/feathers/controls/text/StageTextTextEditor.html) with its [`multiline`](/api-reference/feathers/controls/text/StageTextTextEditor.html#multiline) property set to `true`. The underlying `StageText` will provide its own native scroll bar.

- [The Basics](#the-basics)

- [Customize input behavior](#customize-input-behavior)

- [Skinning a `TextArea`](#skinning-a-textarea)

- [Customize scrolling behavior](#customize-scrolling-behavior)

## The Basics

First, let's create a `TextArea` control and add it to the display list:

```actionscript
var textArea:TextArea = new TextArea();
this.addChild( textArea );
```

### Changing text programmatically

Text may be changed programatically by setting the [`text`](/api-reference/feathers/controls/TextArea.html#text) property:

```actionscript
textArea.text = "Hello\nWorld";
```

### Focus and Selection

You may programmatically set focus to the text area by calling [`setFocus()`](</api-reference/feathers/controls/TextArea.html#setFocus()>):

```actionscript
textArea.setFocus();
```

You can select part of the text too:

```actionscript
textArea.selectRange(0, textArea.text.length);
```

If you simply want to set the position of the cursor, you can omit the second argument to [`selectRange()`](</api-reference/feathers/controls/TextArea.html#selectRange()>):

```actionscript
textArea.selectRange(0);
```

### Events

Text areas provide some useful events. One of the most common requirements is knowing, in real time, when the value of the [`text`](/api-reference/feathers/controls/TextArea.html#text) property has changed:

```actionscript
textArea.addEventListener( Event.CHANGE, textArea_changeHandler );
```

We can listen for [`Event.CHANGE`](/api-reference/feathers/controls/TextArea.html#event:change).

You might also want to know when the text area receives and loses focus:

```actionscript
textArea.addEventListener( FeathersEventType.FOCUS_IN, textArea_focusInHandler );
textArea.addEventListener( FeathersEventType.FOCUS_OUT, textArea_focusOutHandler );
```

The [`FeathersEventType.FOCUS_IN`](/api-reference/feathers/controls/TextArea.html#event:focusIn) and [`FeathersEventType.FOCUS_OUT`](/api-reference/feathers/controls/TextArea.html#event:focusOut) events are specially dispatched by the `TextArea`, even if the [focus manager](./focus.md) is not enabled.

## Customize input behavior

Several properties allow you to customize a text area's behavior.

Set the [`isEditable`](/api-reference/feathers/controls/TextArea.html#isEditable) property to false to make the text uneditable, without giving the text area a disabled appearance:

```actionscript
textArea.isEditable = false;
```

To limit the number of characters that may be entered, use the [`maxChars`](/api-reference/feathers/controls/TextArea.html#maxChars) property:

```actionscript
textArea.maxChars = 16;
```

The [`restrict`](/api-reference/feathers/controls/TextArea.html#restrict) property limits the set of characters that can be entered into the text area. It works like the `restrict` property on `flash.text.TextField`.

```actionscript
textArea.restrict = "0-9";
```

In the example above, we restrict to numeric values only.

## Skinning a `TextArea`

A text area provides a number of properties to customize its appearance. For full details about what skin and style properties are available, see the [`TextArea` API reference](/api-reference/feathers/controls/TextArea.html). We'll look at a few of the most common ways of styling a text area below.

### Font Styles

The text area's font styles may be customized using the [`fontStyles`](/api-reference/feathers/controls/TextArea.html#fontStyles) property.

```actionscript
textArea.fontStyles = new TextFormat( "Helvetica", 20, 0x3c3c3c );
```

Pass in a [`starling.text.TextFormat`](http://doc.starling-framework.org/current/starling/text/TextFormat.html) object, which will work with any type of [text editor](./text-editors.md).

If the text area should use different font styles when it is disabled, you may set the [`disabledFontStyles`](/api-reference/feathers/controls/TextArea.html#disabledFontStyles) property too:

```actionscript
textArea.disabledFontStyles = new TextFormat( "Helvetica", 20, 0x9a9a9a );
```

Finally, we can even customize the font styles for each of the text area's specific states:

```actionscript
textArea.setFontStylesForState( TextInputState.ERROR,
    new TextFormat( "Helvetica", 20, 0xcc0000 ) );
```

Using the code above, the color of the text area's text will change when the text area displays an `errorString`, and the state changes to `TextInputState.ERROR`.

When font styles aren't available for a specific state, the text area will use the default `fontStyles` as a fallback. For example, we haven't provided font styles for `TextInputState.FOCUSED`, so the default styles will be used.

### Background Skin

Let's give our text area its background skin. In the following example, we'll use an [`ImageSkin`](/api-reference/feathers/skins/ImageSkin.html), but the skin may be any Starling display object:

```actionscript
var skin:ImageSkin = new ImageSkin( upTexture );
skin.scale9Grid = new Rectangle( 2, 3, 3, 8 );
textArea.backgroundSkin = skin;
```

We can change the appearance of the text area's skin when the state changes. In the next example, we provide another texture to the same `ImageSkin` for the text area's "focused" state:

```actionscript
skin.setTextureForState( TextInputState.FOCUSED, focusedTexture );
```

The `ImageSkin` automatically listens for changes to the text area's state and updates its appearance to match. When the text area is given focus, the `ImageSkin` will display this texture instead of the default one.

We can also provide different display objects for specific states, if needed. In the next example, we have a texture for the "disabled" state that requires a different `scale9Grid` than the other textures. We can create a separate `ImageSkin` for this state:

```actionscript
var disabledSkin:ImageSkin = new ImageSkin( disabledTexture );
textArea.scale9Grid = new Rectangle( 4, 2, 2, 10 );
textArea.setSkinForState( TextInputState.DISABLED, disabledSkin );
```

Pass in skins for any state using the [`setSkinForState()`](</api-reference/feathers/controls/TextArea.html#setSkinForState()>) function.

If a skin is not provided for a specific state, the text area will display its `backgroundSkin`. Similarly, when using an `ImageSkin`, and a texture isn't provided for a specific state, it will display its default texture.

### Layout

Padding may be added on each side of the text area:

```actionscript
textArea.paddingTop = 5;
textArea.paddingRight = 8;
textArea.paddingBottom = 5;
textArea.paddingLeft = 8;
```

If all four padding values should be the same, you may use the [`padding`](/api-reference/feathers/controls/Scroller.html#padding) property to quickly set them all at once:

```actionscript
textArea.padding = 6;
```

### Skinning the Scroll Bars

This section only explains how to access the horizontal scroll bar and vertical scroll bar sub-components. Please read [How to use the `ScrollBar` component](./scroll-bar.md) (or [`SimpleScrollBar`](./simple-scroll-bar.md)) for full details about the skinning properties that are available on scroll bar components.

#### With a Theme

If you're creating a [theme](./themes.md), you can target the [`Scroller.DEFAULT_CHILD_STYLE_NAME_HORIZONTAL_SCROLL_BAR`](/api-reference/feathers/controls/Scroller.html#DEFAULT_CHILD_STYLE_NAME_HORIZONTAL_SCROLL_BAR) style name for the horizontal scroll bar and the [`Scroller.DEFAULT_CHILD_STYLE_NAME_VERTICAL_SCROLL_BAR`](/api-reference/feathers/controls/Scroller.html#DEFAULT_CHILD_STYLE_NAME_VERTICAL_SCROLL_BAR) style name for the vertical scroll bar.

```actionscript
getStyleProviderForClass( ScrollBar )
    .setFunctionForStyleName( Scroller.DEFAULT_CHILD_STYLE_NAME_HORIZONTAL_SCROLL_BAR, setHorizontalScrollBarStyles );
getStyleProviderForClass( ScrollBar )
    .setFunctionForStyleName( Scroller.DEFAULT_CHILD_STYLE_NAME_VERTICAL_SCROLL_BAR, setVerticalScrollBarStyles );
```

The styling function for the horizontal scroll bar might look like this:

```actionscript
private function setHorizontalScrollBarStyles(scrollBar:ScrollBar):void
{
    scrollBar.trackLayoutMode = TrackLayoutMode.SINGLE;
}
```

You can override the default style names to use different ones in your theme, if you prefer:

```actionscript
textArea.customHorizontalScrollBarStyleName = "custom-horizontal-scroll-bar";
textArea.customVerticalScrollBarStyleName = "custom-vertical-scroll-bar";
```

You can set the funciton for the [`customHorizontalScrollBarStyleName`](/api-reference/feathers/controls/Scroller.html#customHorizontalScrollBarStyleName) and the [`customVerticalScrollBarStyleName`](/api-reference/feathers/controls/Scroller.html#customVerticalScrollBarStyleName) like this:

```actionscript
getStyleProviderForClass( ScrollBar )
    .setFunctionForStyleName( "custom-horizontal-scroll-bar", setCustomHorizontalScrollBarStyles );
getStyleProviderForClass( ScrollBar )
    .setFunctionForStyleName( "custom-vertical-scroll-bar", setCustomVerticalScrollBarStyles );
```

#### Without a Theme

If you are not using a theme, you can use [`horizontalScrollBarFactory`](/api-reference/feathers/controls/Scroller.html#horizontalScrollBarFactory) and [`verticalScrollBarFactory`](/api-reference/feathers/controls/Scroller.html#verticalScrollBarFactory) to provide skins for the text area's scroll bars:

```actionscript
textArea.horizontalScrollBarFactory = function():ScrollBar
{
    var scrollBar:ScrollBar = new ScrollBar();

    //skin the scroll bar here, if not using a theme
    scrollBar.trackLayoutMode = TrackLayoutMode.SINGLE;

    return scrollBar;
}
```

## Customize scrolling behavior

A number of properties are available to customize scrolling behavior and the scroll bars.

### Interaction Modes

Scrolling containers provide two main interaction modes, which can be changed using the [`interactionMode`](/api-reference/feathers/controls/Scroller.html#interactionMode) property.

By default, you can scroll using touch, just like you would on many mobile devices including smartphones and tablets. This mode allows you to grab the container anywhere within its bounds and drag it around to scroll. This mode is defined by the constant, [`ScrollInteractionMode.TOUCH`](/api-reference/feathers/controls/ScrollInteractionMode.html#TOUCH).

Alternatively, you can set `interactionMode` to [`ScrollInteractionMode.MOUSE`](/api-reference/feathers/controls/ScrollInteractionMode.html#MOUSE). This mode allows you to scroll using the horizontal or vertical scroll bar sub-components. You can also use the mouse wheel to scroll vertically.

Finally, you can set `interactionMode` to [`ScrollInteractionMode.TOUCH_AND_SCROLL_BARS`](/api-reference/feathers/controls/ScrollInteractionMode.html#TOUCH_AND_SCROLL_BARS). This mode allows you to scroll both by dragging the container's content and by using the scroll bars.

### Scroll Bar Display Mode

The [`scrollBarDisplayMode`](/api-reference/feathers/controls/Scroller.html#scrollBarDisplayMode) property controls how and when scroll bars are displayed. This value may be overridden by the scroll policy, as explained below.

The default value is [`ScrollBarDisplayMode.FLOAT`](/api-reference/feathers/controls/ScrollBarDisplayMode.html#FLOAT), which displays the scroll bars as an overlay above the view port's content, rather than affecting the size of the view port. When the scroll bars are floating, they fade out when the container is not actively scrolling. This is a familiar behavior for scroll bars in the touch interaction mode. In the mouse interaction mode, the scroll bars will appear when the mouse hovers over them and then disappear when the hover ends.

To completely hide the scroll bars, but still allow scrolling, you can set `scrollBarDisplayMode` to [`ScrollBarDisplayMode.NONE`](/api-reference/feathers/controls/ScrollBarDisplayMode.html#NONE).

If you want the scroll bars to always be visible outside of the content in a fixed position, you can set `scrollBarDisplayMode` to [`ScrollBarDisplayMode.FIXED`](/api-reference/feathers/controls/ScrollBarDisplayMode.html#FIXED). This is best for traditional desktop scrollable content.

Finally, you can set `scrollBarDisplayMode` to [`ScrollBarDisplayMode.FIXED_FLOAT`](/api-reference/feathers/controls/ScrollBarDisplayMode.html#FIXED_FLOAT) to display the scroll bar as an overlay above the view port's content, but it does not fade away.

### Scroll Policies

The two previous properties control how scrolling works. The [`horizontalScrollPolicy`](/api-reference/feathers/controls/Scroller.html#horizontalScrollPolicy) and [`verticalScrollPolicy`](/api-reference/feathers/controls/Scroller.html#verticalScrollPolicy) properties control whether scrolling is enabled or not.

The default scroll policy for both directions is [`ScrollPolicy.AUTO`](/api-reference/feathers/controls/ScrollPolicy.html#AUTO). If the content's width is greater than the view port's width, the text area may scroll horizontally (same for height and vertical scrolling). If not, then the text area will not scroll in that direction. In addition to the `scrollBarDisplayMode`, this can affect whether the scroll bar is visible or not.

You can completely disable scrolling in either direction, set the scroll policy to [`ScrollPolicy.OFF`](/api-reference/feathers/controls/ScrollPolicy.html#OFF). The scroll bar will not be visible, and the text area won't scroll, even if the content is larger than the view port.

Finally, you can ensure that scrolling is always enabled by setting the scroll policy to [`ScrollPolicy.ON`](/api-reference/feathers/controls/ScrollPolicy.html#ON). If combined with `hasElasticEdges` in the touch interaction mode, it will create a playful edge that always bounces back, even when the content is smaller than the view port. If using the mouse interaction mode, the scroll bar may always be visible under the same circumstances, though it may be disabled if the content is smaller than the view port.

## Related Links

- [`feathers.controls.TextArea` API Documentation](/api-reference/feathers/controls/TextArea.html)

- [How to use the `TextInput` Component](./text-input.md)

- [Introduction to Feathers Text Editors](./text-editors.md)

repository: brighttank/feathersui-website

gha_license_id: NOASSERTION

repo_name: brighttank/feathersui-website


text:
---
layout: single
title: 'PSQL: Terminating A Connection'
excerpt: Using the pg_terminate_backend command
date: 2017-02-02
last_modified_at: 2023-04-26 13:22:37
categories:
    - til
tags:
    - psql
    - sql
    - til
---

Consider the scenario where you are trying to drop a database, but there are
existing connections.

```bash
$ dropdb sample_db
dropdb: database removal failed:
ERROR:  database "sample_db" is being accessed by other users
DETAIL:  There is 1 other session using the database.
```

If you don't know where these connections are, you can terminate them within
a `psql` session. You just have to figure out the `pid` of those
connections.
Using the `pid` value and `pg_terminate_backend()`, you can terminate a connection.

```sql
> select pg_terminate_backend(12345);
 pg_terminate_backend
----------------------
 t
```

To terminate all connections to a particular database, use a query like the
following:

```sql
select pg_terminate_backend(pg_stat_activity.pid)
from pg_stat_activity
where pg_stat_activity.datname = 'sample_db'
  and pid <> pg_backend_pid();
 pg_terminate_backend
----------------------
 t
```

This excludes the current session, so you'll need to exit `psql` as well
before dropping the database.

Via [jbranchaud/til](https://github.com/jbranchaud/til).

gha_language: JavaScript


text:
**Table of Contents**

- [Push And Pull Docker Images](#push-and-pull-docker-images)
  - [Pushing Docker Images To Kraken Proxy](#pushing-docker-images-to-kraken-proxy)
  - [Pulling Docker Images From Kraken Agent](#pulling-docker-images-from-kraken-agent)
- [Upload and Download Generic Content Addressable Blobs](#upload-and-download-generic-content-addressable-blobs)
  - [Uploading Blobs To Kraken Origin](#uploading-blobs-to-kraken-origin)
  - [Downloading Blobs From Kraken Agent](#downloading-blobs-from-kraken-agent)

# Push And Pull Docker Images

Kraken proxy implements all [docker registry V2 endpoints](https://docs.docker.com/registry/spec/api/).
Kraken agent only implements the GET and HEAD endpoints of docker registry.

## Pushing Docker Images To Kraken Proxy

You can push images to proxy using normal docker push command:
```
docker push {proxy_host}:{proxy_port}/{repo}:{tag}
```
Proxy will then upload the blobs and tag to origin and build-index.

Yon can also pull from proxy directly without going through the p2p network:
```
docker pull {proxy_host}:{proxy_port}/{repo}:{tag}
```
Note: if you didn't configure Kraken with TLS, you might need to update your docker daemon config to whitelist kraken-proxy as an [insecure registry](https://docs.docker.com/registry/insecure/#deploy-a-plain-http-registry) first.

## Pulling Docker Images From Kraken Agent

To pull docker images from local kraken agent, run:
```
docker pull localhost:{agent_registry_port}/{repo}:{tag}
```
Note: kraken agent use different ports for docker registry endpoints and generic content addressable blobs. Please make sure you are using the port configured via `agent_registry_port`.

# Upload and Download Generic Content Addressable Blobs

Kraken's usecase is not limited to docker images.
It exposes a separate set of endpoints for uploading and downloading generic [content addressable](https://en.wikipedia.org/wiki/Content-addressable_storage) blobs that's identified by SHA256 hash of the content.
Kraken proxy and build-index are not used in this usecase.
Uploads will be handled by Kraken origin, and downloads still go through Kraken agent.

## Uploading Blobs To Kraken Origin

Blobs can be uploaded through the Kraken origin cluster and into your storage backend. All blobs
must be uploaded in chunks, using the following API:

```
POST /namespace/<namespace>/blobs/<digest>/uploads
```

Starts the upload. Returns an upload id in the "Location" response header, which is used for
uploading chunks of the blob.

```
PATCH /namespace/<namespace>/blobs/<digest>/uploads/<uid>
```

Uploads a chunk of the blob, using the previously returned upload id. Supply the chunk bytes in the
request body. The "Content-Range" header in the request must specify the range of the chunk
being uploaded, for example:

```
Content-Range: 128,256
```

This would upload the request body to bytes ``[128, 256)`` of the blob.

```
PUT /namespace/<namespace>/blobs/<digest>/uploads/<uid>?through=<through>
```

Commits the upload. If ``through`` is set to ``true``, the blob will be uploaded through the origin
cluster and into the storage backend configured for ``namespace``.

## Downloading Blobs From Kraken Agent

```
GET /namespace/<namespace>/blobs/<digest>
```

Once Kraken has been configured with your storage information and namespace, you can download your
blobs from any host with a Kraken agent running on it. The download endpoint takes your namespace
and the content digest of the blob you want to download, and blocks until agent has downloaded the
blob to its on-disk cache. Once the blob is downloaded locally, status 200 is returned and the
blob content is streamed over the response body.

Error codes:

- 404: Blob was not found in your storage backend.
- 5xx: Something went wrong. Check the response body for an error message, or reach out to the
  Kraken team.

repository: uber/kraken

gha_language: Go

repo_name: uber/kraken


text:
TShowInTaskbar is a trait to enable any morph to be shown in the taskbar. It implements the required parts so that the taskbar can build a button showing the given morph.

A morph implementing this trait must implement the methods located under "taskbar-required".

Adding a menu when the taskbarbutton is right clicked can be done by implemenenting  #taskbarButtonMenu: to return a custom menu.

For mouseOver action, #taskbarCanShowThumbnail must be implemented to return true, and the behaviour when the mouse enters and leaves the taskbar button in their respective methods.

repository: guillep/pharo

gha_language: Smalltalk

repo_name: guillep/pharo


text:
# --- Part Two ---

Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric.

The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs:

```
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
```

The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct boxes.

What letters are common between the two correct box IDs? (In the example above, this is found by removing the differing character from either ID, producing fgij.)