text:
# Misc

[Index](Index.md "Jsi Documentation Index") /  [Reference](Reference.md "Generated Command Reference")

## Options

Options are parameters handled by builtin commands.
These get passed in an object:

``` js
var db = new Sqlite('/tmp/testsql.db',{maxStmts:1000, readonly:true});
```

Usually there is a conf() method providing access to options after creation:

``` js
Interp.conf(); // Dump all options
Interp.conf('strict'); // Get one option
Interp.conf({strict:false, maxDepth:99}); // Set one or more options.
```

**Note**:
    Some options may be readOnly. And an option that is initOnly
    may only be set at object creation time.

    Internally, option parsing is implemented via [C Options](Extensions.md#options).

## Introspection

There are several levels of introspection built-in to Jsi.
One is displayed when calling an invalid method:

``` js
Array.xxx();
error: 'Array' sub-commands are: concat fill filter forEach indexOf join lastIndexOf map pop push reverse shift sizeOf slice some sort splice unshift.    (at or near "xxx")
```

Another, is querying with the
[Info](Reference.md#Info) command:

``` js
Info.platform();
{ crc:7, hasThreads:true, intSize:4, isBigEndian:false, numberSize:8, os:"linux", platform:"unix", pointerSize:8, timeSize:8, wideSize:8 }

Info.cmds();
[  "Array", "Boolean", "File", "FileIO", "Function", "Interp", "Info", "JSON", "Math", "Number",
   "Object", "RegExp", "Signal", "Sqlite", "String", "Sys", "Websocket", "Zvfs", "assert", "clearInterval",
   "console", "decodeURI", "encodeURI", "exit", "source",
   "isFinite", "isNaN", "load", "parseFloat", "parseInt", "puts", "quote",
   "setInterval", "setTimeout", "format" ]

Info.cmds('Array.*');
[ "concat", "fill", "filter", "forEach", "indexOf", "join", "lastIndexOf", "map", "pop", "push",
  "reverse", "shift", "sizeOf", "slice", "some", "sort", "splice", "unshift" ]

Info.named();
[ "Socket", "Channel", "MySql", "WebSocket", "Sqlite", "Interp" ]

var ii = new Interp();
Info.named('Interp');
[ "#Interp_1" ]
```

and so on.

## Syntax

The following syntax is implemented by Jsi (see [Reference](Reference.md) for commands):

```
continue [IDENT] ;
break [IDENT] ;
debugger ;
delete IDENT ;
do { STMTS; } while( EXPR ) ;
for ([var] IDENT = EXPR; EXPR; EXPR) { STMTS; }
for ([var] IDENT in EXPR) { STMTS; }
for ([var] IDENT of EXPR) { STMTS; }
IDENT in OBJECT
function [IDENT] ([IDENT, IDENT, ...]) { STMTS; }
function [IDENT] ([IDENT:TYPE[=PRIMATIVE], IDENT:TYPE[=PRIMATIVE], ...]):TYPE { STMTS; }
([IDENT, IDENT, ...]) => EXPR
([IDENT, IDENT, ...]) => { STMTS; }
if (EXPR) { STMTS; } [ else { STMTS; } ]
IDENT instanceof IDENT ;
[new] FUNC( ARGS ) ;
return [EXPR] ;
switch (EXPR) { case EXPR: STMTS; [break;] case EXPR: STMTS; [break;]  ... [default EXPR;] }
throw EXPR ;
try { EXPR; } catch(IDENT) { STMTS; } [finally { STMTS; }]
typeof EXPR ;
var IDENT [ = EXPR ] [, ...] ;
let IDENT [ = EXPR ] [, ...] ;
const IDENT [ = EXPR ] [, ...] ;
with ( EXPR ) { STMTS; }
```

- Square brackets indicate optional.
- Curley braces are just for illustrative purposes and except for function and switch are not required.

### Expressions
Expressions take the usual form:

```
IDENT*.*IDENT
IDENT*[*EXPR]
IDENT*(*ARGS)
(EXPR)
EXPR ? STMTS :  STMTS
STMTS , STMTS [, ...]
EXPR OP EXPR
```

where OP is one of the binary operators +, -, *, /, etc.

### Terminals
| Name      | Description                                                                       |
|-----------|-----------------------------------------------------------------------------------|
| ARGS      | Zero or more comma-seperated arguments                                            |
| EXPR      | An expression (see below)                                                         |
| FUNC      | A function value                                                                  |
| IDENT     | Is an valid identifier                                                            |
| PRIMITIVE | A primitive value acceptable as an [argument type](Functions.md).           |
| STMTS     | Is zero or more statements                                                        |
| TYPE      | A type value acceptable as defaults                                               |

### Keywords
Keywords can be displayed using Info.keywords():

``` js
["...", "any", "arguments", "array", "boolean", "break", "case", "catch",
"continue", "debugger", "default", "delete", "do", "else", "false",
"finally", "for", "function", "if", "in", "instanceof", "new", "null",
"number", "object", "of", "regexp", "return", "string", "switch",
"this", "throw", "true", "try", "typeof", "undefined", "userobj", "var",
"void", "while", "with"]
```

## Language Comparisons

Following is a feature comparison of various languages with Jsi.

| Feature          | Jsi     | NodeJs | Tcl | Lua   | Perl | Python |
|------------------|---------|--------|-----|-------|------|--------|
| Standard         | ES 5.2+ | ES 6+  |     |       |      |        |
| Implemention     | C/C++   | C++    | C   | C/C++ | C    | C      |
| C++ Compatible   | Y       | Y      |     |       |      |        |
| Embeddable       | Y       | N      | Y   | Y     | Y    | Y      |
| C API            | Y       | N      | Y   | Y     | Y    | Y      |
| Non-Script API   | Y       |        |     |       |      |        |
| Standalone       | Y       |        | Y   | Y     |      |        |
| Type Checking    | Y       |        |     |       |      |        |
| Sub-Interps      | Y       |        |     |       |      |        |
| Introspection    | Y       |        |     |       |      |        |
| Error Navigation | Y       |        |     |       |      |        |
| Logging          | Y       |        |     |       |      |        |
| Builtin Debugger | Y       | Y      |     |       | Y    |        |
| Debugger GUI     | Y       |        |     |       |      |        |
| Web Ready        | Y       |        |     |       |      |        |
| Modular Apps     | Y       |        |     |       |      |        |
| Shrink Wrap      | Y       |        | Y   |       |      |        |
| Applications     | Y       |        |     |       |      |        |
| Self Configure   | Y       |        |     |       |      |        |

These comparisons are of software out-of-the-box.

**Note**::
    As of version 5.3.4, Lua also supports native C++.

## Design and Origin

Jsi is a Javascript interpreter written in C.
Additional functionality, implemented with scripts is bundled as "jsish".

Jsi is a byte-code oriented interpreter originally designed for interfacing-with, and embedding into C.

This makes it very different from [Node-js](https://nodejs.org) which is a compiler written in **C++**,
and which is not designed to be embedded.

Jsi is **C**-centric whereas Node is **JS**-centric.  Meaning that with Jsi, the locus of
control can resides in C-code.

Although Jsi was originally was based off source from [quad-wheel](https://code.google.com/archive/p/quad-wheel),
it is now internally modelled after [Tcl](https://www.tcl.tk/doc/scripting.html).

Extensions include:

- Functions parameters may have [types and defaults](Functions.md).
- [Testing](Testing.md) support that leverages type-checking.
- Select features from newer versions of the standard (eg. Array **of** and **forEach**).
- Limited basic arrow functions: no default values, and single parameters may not be braced.
- Non-standard object functions such as **merge** are available, eg. **o = o1.merge({a:1,b:2});**

## Goals

Following are principle goals  Jsi:

- Support embedded development using plain **C** (C99).
- But should also be compilable by **native GNU g++**, without use of *"extern C"*.
- Have as few dependencies as possible.
- Be generally free of value/object/memory leaks (verified with -fsanitize).
- Provide amalgamated source for simplified [application integration](Building.md#Embedding) .
- Low-level C-functions available in a **C-only** [Lite](#jsi-lite) version.
- Come with a [Debugger](Debug.md).
- Support Web applications, particularly with database and websockets.
- Support [standalone applications](Builtins.md#zvfs) via self-mounting .zip.
- [Package](Start.md) and extension support.

Compiling as C++ is supported, mostly for integrity checks.

**Note**:
    C-integration is the main priority in Jsi, not speed of script execution.

## Rational

- Desktop applications are held hostage by their user interface, be it QT, GTK, IOS or .NET.
- Increasingly web browsers are becoming the GUI, usually over the Internet.
- Moderately complex applications often end up requiring some form of script support, eg. Lua.
- If an application employs a Web GUI, a script language already is being used: Javascript.
- Time, energy and resources can be saved by using the same language on both ends.
- In fact, the same scripts can even be run in both the browser and the app.
- JSON provides seamless data interchange, thus avoiding data structure compatibility issues.

## Packaging

A [deploy](Deploy.md) is a zip/sqlar archive or fossil
repository containing one or more applications, which Jsi can mount and execute.

But deploying any application inevitably entails dealing with version dependencies.
Jsi handles this in a novel way by mounting **tagged** releases from a fossil repository.
If an application restart is set to automatically update the repository,
it ensures the latest supported release always gets run.
New code may be committed by developers at any time,
but only tagged releases will be used.

## Security

As Jsi is self contained, running it standalone in a chroot-jail needs only
a few files from /dev and /etc.
And if this is not secure enough, Jsi offers [Safe-mode](Interp.md#safe-mode).

In addition, serving content from a zip or fossil repository adds
another abstraction layer, making it that much harder to corrupt or hijack content.

An advantage of the chroot approach as compared with something like containers, is
that far less disk space and system memory is required.
Jsi and fossil together total around 10Meg of disk. Using hard links you
could create hundreds of chrooted apps with little-to-no additional disk space.
But more important is the
reduction in [Attack Surface](https://en.wikipedia.org/wiki/Attack_surface).
There is far less code involved and far less complexity.

## Web-Serve

### Nginx

Although Jsi can serve web content directly, on the Internet
it is more common to reverse proxy to a web-server via localhost:

Following config is for setting up jsish as a reverse proxy under Nginx

    location /App00/Ledger { proxy_pass http://localhost:8800; include proxy_params; }

And jsish might be invoked as:

    jsish -a jsi-app.fossil Ledger -port 8800 -urlPrefix /App00/Ledger -noGui true

Or run via chroot/su.

### Chroot Setup

Given it's small size, jsish is well suited for chroot deployments.

``` bash
ls -RF jsiusr00

jsiusr00:
bin/  dev/  etc/  ledgerjs.db  tmp/  usr/

jsiusr00/bin:
fossil*  jsish*

jsiusr00/dev:
null  random  urandom

jsiusr00/etc:
hosts  resolv.conf

jsiusr00/tmp:

jsiusr00/usr:
jsi-app.fossil  jsi-app.sqlar  jsi-app.zip  ledgerjs.db
```

To scale this up while saving space, multiple users "jsiusrNN" are created with readonly files hard-linked to "jsiusr00".

Finally "chattr +i" is used make them immutable.

Thus incremental size for each additional
user is really only the data file "ledgerjs.db".

``` bash
 du -s jsiusr*
 12468   jsiusr00
 980 jsiusr01
 960 jsiusr02
 960 jsiusr03
 ...
 1224    jsiusr10
 960 jsiuser11
 ...
 960 jsiuser19
```

All previous directories have no shell, so with the addition of quotas and ulimits we end up with a
deployment that is simple but secure.

**NOTE:** The slight bump in "jsiusr10" is due to the addition of "sh", to allow execing fossil in a chroot.

### Wget

To download a file from the web we can use:

``` bash
jsish -w -O NAME.zip URL
```

### Websrv

The builtin web server can open it in a
local browser and serve out html to it, from the command-line:

``` bash
jsish -W index.html
```

and programmatically:

``` js
    Jsi_Websrv('index.html');
    update(-1);
```

## Packages

### pkgDirs

Packages are searched for are specified by pkgDirs, which can be set pkgDirs using:

``` js
Interp.conf({pkgDirs:['/usr/local/lib', '/usr/share']});
```

When a package is not found in pkgDirs, the executable and main script directories are checked.

**Note**: Sub-interps inherit pkgDirs from the parent.

### Auto-Load
Because it is sometimes desirable to defer loading code until first invocation,
Jsi provides a mechanism
using  member values in the object Jsi_Auto to evaluate.
For example, given the file myfunc.js:

``` js
provide('myfunc');
function double(n) { return n*2; };
function half(n)   { return n/2; };

// We can arrange for dynamic sourcing with:
Jsi_Auto.double =
Jsi_Auto.half   = 'require("myfunc");';

double(4); // Load is triggered!
half(4);

// This also works for object commands:
Jsi_Auto.MySql = "require('MySql')";
//...
var db = new MySql({user:'root', database:'jsitest'});
```

### Auto-Files

Jsi_Auto will demand-load files by
traversing the list **Interp.autoFiles**, eg:

``` js
Interp.conf('autoFiles');
[ "/zvfs/lib/autoload.jsi" ]
```

In addition, if an application is invoked from a **.zip** file, it's **autoload.jsi** file is appended.

#### Object Functions
Autoloading non-constructor object functions can use the following approach
(the example ignores the fact that JSON is not actually loadable):

``` js
var JSON = {
   parse:     function() { require('JSON'); return JSON.parse.apply(this,arguments); },
   stringify: function() { require('JSON'); return JSON.stringify.apply(this,arguments); }
   //...
}
JSON.parse(str); // Load is triggered!
```

Although that works, it suffers from one problem: the first call will not type-check functions.

We could fix this shortcoming with:

``` js
var JSON = {
    check: function(str:string, strict:boolean=false):boolean { require('JSON'); return JSON.check.apply(this,arguments); },
    //...
};
```

But correctly transcribing function signatures is more complicated.

Fortunately there is a helper:
:  function Jsi_AutoMake(objName:string):string

This can be used to generate the auto file:

    File.write( Jsi_AutoMake('JSON'), 'autoload.jsi');

The file autoload.jsi now contains calls and load and type-check correctly:

``` js
var JSON = {
    check: function(str:string, strict:boolean=true):boolean { require('JSON'); return JSON.check.apply(this,arguments); },
    parse: function(str:string, strict:boolean=true):any { require('JSON'); return JSON.parse.apply(this,arguments); },
    stringify: function(obj:object, strict:boolean=true):string { require('JSON'); return JSON.stringify.apply(this,arguments); },
};
```

## CAPI

### DString

DString provides dynamic string functionality via a struct
which uses the stack when strings are short:

``` clike
    Jsi_DString d = {"Here is your score "};
    puts(Jsi_DSPrintf(&d, "%s: -> %d/%d", user, n, m));
    Jsi_DSFree(&d);
```

Since the above strings are under 200 characters, no malloc call is required.

``` clike
    Jsi_DString d = {};
    Jsi_DSPrintf(&d , "%0300d", 1); // Malloc
    Jsi_DSSetLength(&d, 0);
    Jsi_DSPrintf(&d , "%0300d", 1); // No-malloc
    Jsi_DSFree(&d);
    Jsi_DSPrintf(&d , "%0300d", 1); // Malloc
    Jsi_DSFree(&d);
```

Space is discared with Jsi_DSFree, and can be reused with Jsi_DSSetLength:

You can also use Jsi_DSInit():

``` clike
    Jsi_DString d;
    Jsi_DSInit(&d);
    Jsi_DSAppend(&d, "Some stuff", NULL);
    Jsi_DSAppendLen(&d, "!", 1);
    Jsi_DSFree(&d);
```

| Name            | Description                                                                                |
|-----------------|------------------------------------------------------------------------------------------------|
| Jsi_DSAppend    | Append one or more string arguments (plus NULL sentinal).                                      |
| Jsi_DSAppendLen | Append a string of given length (or -1 for strlen).                                            |
| Jsi_DSFree      | Release allocated memory and sets variable back to re-initialized/empty.                       |
| Jsi_DSFreeDup   | Return malloced string, then calls Jsi_DSFree.                                                 |
| Jsi_DSInit      | Initialize the variable, ignoring current data therein.                                        |
| Jsi_DSLength    | Return the length.                                                                             |
| Jsi_DSPrintf    | Format output and append to DString. Returns string from the current printf.                   |
| Jsi_DSSet       | Same as Jsi_DSSetLength(dsPtr,0) plus Jsi_AppendLen.                                           |
| Jsi_DSSetLength | If < current length truncates string. Else sets min allocated space. Return allocated size. |
| Jsi_DSValue     | Return string value.                                                                           |
| JSI_DSTRING_VAR | Macro that declares a large DString on the stack.                                              |

``` clike
    char*   Jsi_DSAppend(Jsi_DString *dsPtr, const char *str, ...);
    char*   Jsi_DSAppendLen(Jsi_DString *dsPtr, const char *bytes, int length);
    void    Jsi_DSFree(Jsi_DString *dsPtr);
    char*   Jsi_DSFreeDup(Jsi_DString *dsPtr);
    void    Jsi_DSInit(Jsi_DString *dsPtr);
    uint    Jsi_DSLength(Jsi_DString *dsPtr);
    char*   Jsi_DSPrintf(Jsi_DString *dsPtr, const char *fmt, ...);
    char*   Jsi_DSSet(Jsi_DString *dsPtr, const char *str);
    uint    Jsi_DSSetLength(Jsi_DString *dsPtr, uint length);
    char*   Jsi_DSValue(Jsi_DString *dsPtr);
    #define JSI_DSTRING_VAR(varPtr,size) //...
```

### Large String Buffers
When working with larger strings, we may want to preallocate a large
string in order to avoid repeated calls to realloc() as the string grows.
The normal approach might be something like:

``` clike
    Jsi_DString dStr;
    Jsi_DSInit(&dStr);
    Jsi_DSSetLength(&dStr, 50000);
```

Another alternative is to use the `JSI_DSTRING_VAR` macro, which avoids using malloc entirely.
`JSI_DSTRING_VAR` efficiently declares a Jsi_DString* pointing to an enlarged static DString upon the stack: eg:

``` clike
    JSI_DSTRING_VAR(dsPtr, 50000);
    Jsi_DSPrintf(dsPtr, "%04999d", 1); // No malloc.
```

### C++ Strings

Consider C++ stringstream, which provides convenient dynamic string support with type safety.

    std::stringstream str;
    str << "ABC " << 123;
    puts(str.str().c_str());

The tradeoffs of stringstream are:

- Implicit memory allocation.
- Implicit code execution.
- Hard to inspect in gdb.
- Awkward to obtain the C string value.
- Not available in plain C-code.

DString provides familiar printf style formatting:

    Jsi_DString dstr = {};
    puts(Jsi_DSPrintf(&dstr, "ABC %d", 123));

Printf style modifiers can be significantly simpler than stringstream:

``` clike
    Jsi_DSPrintf(&dstr, "%02d%-3d%04d", v1, v2, v3);
    str << std::setfill('0') << std::setw(2) << v1
        << std::setfill(' ') << std::setw(3) << std::left  << v2
        << std::setfill('0') << std::setw(4) << std::right << v3;
```

### Safety
The gcc compiler makes DString usage quite safe.

- It generates warnings for Jsi_DSPrintf argument mismatches.
- It warns when Jsi_DSAppend is missing NULL terminator.

There however are some gotchas to be aware of:

- DStrings greater than 200 bytes can not be assigned to one another.
- Failing to call Jsi_DSFree can leak memory.
- A DString has a maximum (compile time limit) of a 100 Meg.

## JSON

Jsi implements a non-validating JSON parser.  That is, will accept JSON that
is not strictly compliant.

### High-Level

#### Jsi_JSONParse

The main function for parsing JSON to generate a Jsi_Value is:

    Jsi_RC Jsi_JSONParse(Jsi_Interp *interp, const char *js, Jsi_Value ret, int flags);

If the bit flags field does not contain JSI_JSON_STRICT, the parser will accept
non-standard, unquoted property names, as in:

    {file:"FF", line:NN}

#### Jsi_JSONParseFmt

This function is used primarily to reduce C-code.

    Jsi_RC Jsi_JSONParseFmt(Jsi_Interp *interp, Jsi_Value ret, const char *fmt, ...);

Consider a simple example where we wish to return a javascript object:

    {file:"File", line:1}

In C we would write something like:

``` clike
    Jsi_Obj *nobj;
    Jsi_ValueMakeObject(interp, ret, nobj = Jsi_ObjectNew(interp));
    Jsi_ObjInsertFromValue( interp, nobj, Jsi_ValueNewStringKey(interp, "file"),
        Jsi_ValueNewStringKey(interp, file));
    Jsi_ObjInsertFromValue( interp, nobj, Jsi_ValueNewStringKey(interp, "line"),
       Jsi_ValueNewNumber(interp, line));

    // Alternatively, this can be simplified to:
    return Jsi_JSONParse(interp, ret, "{file:\"%s\", line:%d}", file, line);

    // The more deeply nested the object, the more code is simplified, eg:
    Jsi_JSONParseFmt(interp, ret, "{ a: [ {x:%d, y:%d}, {x:%d, y:[%d,%d,%d]}] }",a,b,c,d,e,f);
```

Due to the efficiency nature of low-level parsing, this adds very little extra overhead.

This approach can save a lot of code, particularly when writing commands
that return nested objects and/or arrays.
.

**Note**:
    Permissive mode is the default.  So there is no need to quote property names which in C rapidly becomes tedious:

    "{\"os\":\"%s\", \"platform\":\"%s\", \"hasThreads\":%s, \"pointerSize\":%d, "

**Warning**:
    The above works only for cases where data does not contain special JSON characters.

### Low-Level
For the low level,
parses JSON into an array of tokens in a highly stack efficient manner.
It uses a single
array of tokens for output so that for limited size JSON strings,
no memory gets allocated during the parse.
When memory does get allocated, it is only to resize the token array.

Any data sent between sub-[interps](Interp.md) will first be converted to/from JSON.
This because all data objects are private to an interp.

## Jsi-Lite

Jsi-Lite, which is a subset of the Jsi C source code which can be used without the script engine:

``` clike
    #define JSI_LITE_ONLY
    #include "jsi.c"
    //Your code goes here.
```

It include [DString](#dstring), Hash, List, Map, and Tree.

Tree is the underlying data structure for objects in JSI using Red-Black trees with invariant node
pointers: nodes are allocated using a single malloc, including space for the key.
This introduces a problem in that varying string keys can not be copied between nodes,
which is required when re-balancing the tree. Although tree supports swapping node positions
instead of keys, objects instead use a key of type STRINGPTR, a combination Hash table and and Tree,
which is fairly efficient because objects often share keys.

## Options

A Jsi_OptionSpec array provides details of fields in a struct. This information is used for
translating values to/from and from C struct fields, both for Javascript and
by the [Sqlite C-API](DBQuery.md).

A Jsi_OptionSpec array specifies for a struct field the
name, type, offset, help string, etc.  This specification is passed, along with a pointer
to the actual data,
to `Jsi_OptionProcess()` and `Jsi_OptionConf()`.

### Example Usage
The following example is a subset of the Jsi Sqlite command:

``` clike
    enum { MUTEX_DEFAULT, MUTEX_NONE, MUTEX_FULL };
    static const char *mtxStrs[] = { "default", "none", "full", 0 };

    static Jsi_OptionSpec Options[] =
    {
        JSI_OPT(INT,    SqliteDb, debug,    .help="Set debugging level"),
        JSI_OPT(CUSTOM, SqliteDb, execOpts, .help="Default options for exec", .custom=&Jsi_OptSwitchSuboption, .data=ExecFmtOptions),

        JSI_OPT(INT,    SqliteDb, maxStmts, .help="Max cache size for compiled statements"),
        JSI_OPT(BOOL,   SqliteDb, readonly, .help="Database is readonly", .flags=JSI_OPT_INIT_ONLY ),
        JSI_OPT(VALUE,  SqliteDb, vfs,      .help="VFS to use", .flags=JSI_OPT_INIT_ONLY),
        JSI_OPT(CUSTOM, SqliteDb, mutex,    .help="Mutex type to use", .custom=&Jsi_OptSwitchEnum, .data=mtxStrs),
        JSI_OPT_END(SqliteDb)
    };

      //...
    if (Jsi_OptionsProcess(interp, Options, optObj, &opts, 0) < 0) {
         return JSI_ERROR;
    }
    if (opts.debug)
        puts("Sqlite created");
```

### Field Specification
Options are specified using the JSI_OPT() macro. The first 3 arguments are TYPE,STRUCT,NAME,
where the NAME is a field name in STRUCT.  Additional attributes can be specified using ".name=value" form.

<a name=opttypes></a>
#### Option Types

The option TYPE is one of:

| Name      | C-Type      | Description                                                                   |
|-----------|-------------|-------------------------------------------------------------------------------|
| BOOL      | bool        | Boolean (stored in a "char" variable).                                        |
| INT       | int         | An integer.                                                                   |
| UINT      | uint        | An unsigned integer.                                                          |
| LONG      | long        | An long integer.                                                              |
| ULONG     | ulong       | An long unsigned integer.                                                     |
| SHORT     | short       | An short integer.                                                             |
| USHORT    | ushort      | An short unsigned integer.                                                    |
| INT8      | int8_t      | An 8-bit integer.                                                             |
| INT16     | int16_t     | A 16-bit integer.                                                             |
| INT32     | int32_t     | A 32-bit integer.                                                             |
| INT64     | int64_t     | A 64-bit integer.                                                             |
| UINT8     | uint8_t     | An unsigned 8-bit integer.                                                    |
| UINT16    | uint16_t    | An unsigned 16-bit integer.                                                   |
| UINT32    | uint32_t    | An unsigned 32-bit integer.                                                   |
| UINT64    | uint64_t    | An unsigned 64-bit integer.                                                   |
| SIZE_T    | size_t      | An size_t integer.                                                            |
| INTPTR_T  | intptr_t    | An pointer sized integer.                                                     |
| UINTPTR_T | uintptr_t   | An pointer sized unsigned integer.                                            |
| FLOAT     | float       | A floating point.                                                             |
| DOUBLE    | double      | Double floating point.                                                        |
| LDOUBLE   | ldouble     | Long double floating point.                                                   |
| DSTRING   | Jsi_DString | A Jsi_DString value.                                                          |
| STRKEY    | const char* | A char* string key.                                                           |
| STRBUF    | char[]      | A fixed size char string buffer.                                              |
| VALUE     | Jsi_Value*  | A Jsi_Value.                                                                  |
| STRING    | Jsi_Value*  | A Jsi_Value referring to a string.                                            |
| VAR       | Jsi_Value*  | A Jsi_Value referring to a variable.                                          |
| OBJ       | Jsi_Value*  | A Jsi_Value referring to an object.                                           |
| ARRAY     | Jsi_Value*  | A Jsi_Value referring to an array.                                            |
| FUNC      | Jsi_Value*  | A Jsi_Value referring to a function.                                          |
| TIME_T    | time_t      | A date variable, milliseconds since 1970 stored in a time_t/long.             |
| TIME_D    | double      | A date variable, milliseconds since 1970 stored in a Jsi_Number/double.       |
| TIME_W    | int64_t     | A date variable, milliseconds since 1970 stored in a Jsi_Wide/64 bit integer. |
| CUSTOM    | void*       | Custom parsed value.                                                          |

#### Flags
The following flags are predefined for individual items in an OptionSpec:

| Name                   | Description                                    |
|------------------------|------------------------------------------------|
| `JSI_OPT_INIT_ONLY`    | Allow set only at init, disallow update/conf   |
| `JSI_OPT_NO_DUPVALUE`  | Values/Strings are not to be duped (dangerous) |
| `JSI_OPT_READ_ONLY`    | Value can never be set.                        |
| `JSI_OPT_DIRTY_FIELD`  | Used for DB update.                            |
| `JSI_OPT_IS_SPECIFIED` | User set the option.                           |
| `JSI_OPT_DB_IGNORE`    | Field is not to be used for DB.                |
| `JSI_OPT_CUST_NOCASE`  | Ignore case (eg. for ENUM and BITSET)          |
| `JSI_OPT_CUST_FLAG2`   | Reserved for custom flags                      |
| `JSI_OPT_CUST_FLAG2`   | Reserved for custom flags                      |
| `JSI_OPT_CUST_FLAG2`   | Reserved for custom flags                      |

#### Custom Types
Custom types provide parsing/formatting functions to interpret javascript data to/from a C struct-field.
Again, the best example is the Jsi source itself.

The following predefined custom types come builtin:

| Name                     | Description                    | .data      |
|--------------------------|--------------------------------|------------|
| Jsi_OptSwitchEnum        | Enum match                     | stringlist |
| Jsi_OptSwitchBitset      | Set of zero or more enum match | stringlist |
| Jsi_OptSwitchValueVerify | Provide callback to verify     | Callback   |
| Jsi_OptSwitchSuboption   | Recursive sub-option support   | sub-Option |

Refer to the Jsi source for example usage and declarations.

#### OptionSpec Fields
The following fields are defined in Jsi_OptionSpec:

| Field   | Type              | Description                                                            |
|---------|-------------------|------------------------------------------------------------------------|
| type    | enum              | Field type (from above)                                                |
| name    | char*             | Name of field                                                          |
| offset  | int               | Offset in array                                                        |
| size    | const char*       | Sizeof of field.                                                       |
| iniVal  | union             | Used for compile-time validation                                       |
| flags   | int               | Flags (from above)                                                     |
| custom  | Jsi_OptionCustom* | Custom parsing struct                                                  |
| data    | void*             | User data for custom options.                                          |
| help    | char*             | Short 1 line help string.                                              |
| info    | char*             | Longer command description: re-define JSI_DETAIL macro to compile-out. |
| init    | const char*       | Initial string value (used by info.cmds).                              |
| extName | const char*       | External name: used by the DB interface.                               |

The first five fields are implicitly set by the JSI_OPT() macro.
The JSI_END() macro also sets extName.

All others are available for setting by the user with .FIELD=VALUE notation.

### Parse Flags
The following flags are available for use with Jsi_OptionProcess/Jsi_OptionConf:

| Name                    | Description                                                 |
|-------------------------|-------------------------------------------------------------|
| `JSI_OPTS_IS_UPDATE`    | This is an update/conf (do not reset the specified flags)   |
| `JSI_OPTS_IGNORE_EXTRA` | Ignore extra members not found in spec                      |
| `JSI_OPTS_FORCE_STRICT` | Complain about unknown options, even when noStrict is used. |
| `JSI_OPTS_PREFIX`       | Allow matching unique prefix of object members.             |
| `JSI_OPTS_VERBOSE`      | Dump verbose options                                        |

### Compile-time Validation
Compile-time validation checks option values to ensure that stated type and the field
type actually match.  If they don't, the program will likely crash at runtime.
The implementation uses an implicit assignment to iniVal which should
generate a compiler warning if there is a type mismatch.

Here is an example:

``` clike
    typedef struct {
        int val;
        //...
    } MyData;

    Jsi_OptionSpec opts[] = {
        JSI_OPT(STRING, MyData, val),
        JSI_OPT_END(    MyData)
    };

==>

    test.c:7:6: warning: initialization from incompatible pointer type [enabled by default]
    test.c:7:6: warning: (near initialization for ‘opts[0].iniVal.ini_STRING’) [enabled by default]
```

### Is Specified
When a user provides a value for an option, the flag `JSI_OPT_IS_SPECIFIED` is set in the option flags.
Call Jsi_OptionChanged to determine if an option was specified.

**Note**:
    The Jsi header file [jsi.h](https://github.com/pcmacdon/jsish/blob/master/src/jsi.h) and source are best consulted for complete examples.

**Warning**:
    There are known concurrency issues with this feature.

## License

Jsi source is generally is covered by an MIT.

## Vue
Vue related components included:

- [Vue](https://vuejs.org/), [Vuex](https://vuex.vuejs.org/), [Vue-Router](https://router.vuejs.org/)
- [Bootstrap](https://getbootstrap.com/), [Bootstrap-Vue](https://bootstrap-vue.org/)
- [vue-markdown-pdq](https://github.com/pdqi/vue-markdown-pdq)
- [Vue Prism Editor](https://www.npmjs.com/package/vue-prism-editor)
- [Vue Draggable](https://github.com/SortableJS/Vue.Draggable)
- [Prism](http://prism.com/download.html#themes=prism-coy&languages=markup+css+clike+javascript+bash+c+css-extras+json+markdown+markup-templating+php+python+sql+typescript&plugins=line-numbers+show-language+toolbar+copy-to-clipboard)

<!-- meta:{"file":{"index":1002}} -->

repository: pcmacdon/jsish

repo_name: pcmacdon/jsish


text:
# forg20k

My submission to a [Gynvael's Winter GameDev Challenge 2017](http://gynvael.coldwind.pl/?id=668). The challenge was to make a turn-based strategy game that fit in 20KB and ran on the latest version of Chrome. No other browsers are guaranteed to be supported.

Play online: **(Only guaranteed to work in latest version of Chrome)** https://ajaxgb.github.io/forg20k/

- Left click to select FORGS.
- A FORG's moves are listed at the bottom, along with HP and MP.
- Click on moves or scroll between them with the mousewheel.
- When a move is selected, valid targets will be shown.
- Targets will display the number of MP they cost.
- Right click on a valid target to perform the selected move.
- MP is regained at the beginning of each turn.
- Eat BUGGS to regain health.

Note that the HTML file cannot be run as a file:// URL or it will not work.
It must be hosted on a server.

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# ✨ Spigot Plugin Template
A Spigot template that I use for Spigot plugin development! This includes the API, bStats, and the shading configuration. Sometimes JARs also need to be added in case NMS is required.

To build, simply run:
```
mvn package
```

The JAR will get exported directly into the server folder, making testing a breeze.

repository: theseedmc/SeedBookban

repo_name: theseedmc/SeedBookban


text:
# Kicking-N-Screaming

### A drag-n-drop helper

Somewhat tames HTML5's insane DnD system. Allows you to associate meta-type data to your draggable and droppable elements and to recieve the events *dragenter, dragleave, and dragover* only when both the draggable and droppable elements have one or more `types` that match.

### Node.js

For *Node.js*, use `npm`:

````console
npm install kickingnscreaming
````

..then `require` KickingNScreaming:

````javascript
var KickingNScreaming = require('kickingnscreaming');
````

### In the browser, traditional

For the *browser*, add the following to your pages:

````html
<script src="kickingnscreaming.js"></script>
````

And the global function `KickingNScreaming` will be available.

### In the browser, using AMD (require.js)

...Or using AMD in the browser:

````javascript
require(["kickingnscreaming"], function(KickingNScreaming) {
	// ...
});
````

## Usage

````javascript
var dragHelper = KickingNScreaming({
	dragover: function(e){
		console.log("BAZ");
	}
});

// Make two draggable elements
dragHelper.makeDraggable(draggableFoo, "foo");
dragHelper.makeDraggable(draggableBar, "bar");
dragHelper.makeDraggable(draggableBaz, "foo baz");

// Setup drop targets
dragHelper.makeDroppable(dropTargetFoo, "foo");
dragHelper.makeDroppable(dropTargetBar, ["bar", "baz"]);
dragHelper.makeDroppable(dropTargetAny, "foo bar baz");
````

The `dragover` function will print "BAZ" under the following conditions:

* Whenever `draggableFoo` is dragged over `dropTargetFoo`

* Whenever `draggableBar` is dragged over `dropTargetBar`

* Whenever `draggableBaz` is dragged over **any** drag target

* Whenever **any** draggable is dragged over `dropTargetAny`

## API

#### `KickingNScreaming([options])`

Construct a new KickingNScreaming object

* `options` is an object that can override the following default properties:

````javascript
{
	// MIME-type prefix to use for storing drag data in the "dataTransfer" object
	mimePrefix: 'application/x-drag',

	// Data attribute specifying draggable's type(s)
	draggableDataAttribute: 'data-drag-classes',

	// Data attribute specifying droppable's type(s)
	droppableDataAttribute: 'data-accept-drag-classes',

	// dataTransfer.effectsAllowed
	effectAllowed: "move",

	// Drag-n-Drop events
	dragstart: noop,
	dragenter: noop,
	dragover: noop,
	dragleave: noop,
	drag: noop,
	drop: noop,
	dragend: noop
}
````

#### `makeDroppable(element[, types])`

Adds DnD events to a drag target

* `element` - DOM node that will become draggable

* `types` - optional string or array that specifies the type(s) of this element

#### `makeDraggable(element[, types])`

Adds DnD events to a drop target

* `element` - DOM node that will become a drop-target

* `types` - optional string or array that specifies the type(s) of this element

## License - MIT

> Copyright (C) 2012 Jon-Carlos Rivera
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

repository: imbcmdth/kickingnscreaming

extension: markdown

repo_name: imbcmdth/kickingnscreaming


text:
# fpga-cascade
## Concept

This project proposal is based around the idea of streamed-blocking (time/space decomposition approach).
Although this approach was not well suited to Software implementation, the fact it models the F.E.M as
a pipeline process may make it more amenable to FPGA implementation.

Two potential architectures occur at present. The first would see a machine with a large RAM and FPGA 'scan'
the FPGA across the simulation area, with input vectors being read from the input area and output vectors being
written to it a few indexes behind. The second would see a grid of FPGAs stream data between themselves.

## Concept 2
FPGA Floating Point support and performance are known issues. The circuitry needed to support IEEE floating point is complex and requires too many logical blocks to be a sensible approach on most FPGAs. Fixed point numbers are much easier to represent, but they lack the dynamic range and accuracy of the FP number system. To counter this, the suggestion is preconditioning the simulation mesh such that each cell/element's value sits near the centre of our fixed point representationss value. We devote as many bits to precision as we can, and keep the numeric range of values expected as small as possible. In essence, we partition the space in units of ~1 stuffs, and each time too much stuffs gets into a cell we split it. We AMR the space around the limitations of the fixed point number system.

## Concept 3
Higher order stencils: Use larger stencils to improve numerical accuracy and allow partial sums within
Compiler-Directed Transformation for Higher-Order Stencils

### Hardware
From a chat with Pete: Nallatech 395 in 2 nodes

# Existing work
http://www.cs.ucla.edu/~pouchet/doc/ics-article.12.pdf Time blocking. N threads wavefront their way through the code.
FPGA-Based Systolic Computational-Memory Array for Scalable Stencil Computations

# Notes
Systolic arrays are what we enable
Read: A framework for FPGA acceleration of large graph problems: graphlet counting case study
Read: GraphGen: An FPGA Framework for Vertex-Centric Graph Computation

# Tools
https://eclipse.org/Xtext/ For the DSL. (Also means a switch to java for interpreter.)

repository: csrhau/fpga-cascade-paper

repo_name: csrhau/fpga-cascade-paper


text:
---
title: Categoric
page_title: Category Axis
position: 2
---

## Chart for Xamarin.iOS: Categoric Axis

TKChart uses Categoric axis to plot data that contains categoric values. The axis is valid only in the context of Cartesian series. It also introduces several important properties:

- MajorTickInterval - defines an interval among major axis ticks.

- MinorTickInterval - defines an interval among minor axis ticks.

- Baseline - contains a value, which defines how the series data should be aligned. For example, The TKChartBarSeries might render its bars up and down depending on whether its value is greater or less than the baseline value.

- Offset - determines an axis value where the axis is crossed with another axis.

## Configure a TKChartCategoryAxis##

You can configure a category axis by settings its categories property. You should use the following code snippet as a sample:

```C#
List<TKChartDataPoint> list = new List<TKChartDataPoint> ();
string[] categories = new []{"Apple", "Google", "Microsoft", "Samsung"};
for (int i = 0; i < categories.Length; i++) {
    list.Add(new TKChartDataPoint(new NSString(categories[i]), new NSNumber(r.Next() % 100)));
}

TKChartColumnSeries series = new TKChartColumnSeries (list.ToArray());
series.Selection = TKChartSeriesSelection.Series;

TKChartCategoryAxis xAxis = new TKChartCategoryAxis ();
xAxis.Position = TKChartAxisPosition.Bottom;
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
series.XAxis = xAxis;
```

You can specify the axis range by setting the minimum and maximum indexes of categories.

## Setting the plot mode of axis##

 The TKChartAxisPlotMode is used by the axis to plot the data. Possible values are TKChartAxisPlotModeBetweenTicks and TKChartAxisPlotModeOnTicks. TKChartAxisPlotModeBetweenTicks plots points in the middle of the range, defined by two ticks. OnTicks plots the points over each tick.

 You should use the following lines of code to alter this behavior:

<snippet id='chart-category-plot'/>
<snippet id='chart-category-plot-swift'/>
```C#
xAxis.PlotMode = TKChartAxisPlotMode.BetweenTicks;
```

<snippet id='chart-category-plot-onticks'/>
<snippet id='chart-category-plot-onticks-swift'/>
```C#
xAxis.PlotMode = TKChartAxisPlotMode.OnTicks;
```

repository: telerik/xamarin-forms-docs

gha_language: JavaScript

repo_name: telerik/xamarin-forms-docs


text:
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/

title: "Essential SQL"
subtitle: ""
summary: ""
authors: []
tags: [data-science]
categories: []
date: 2018-11-23T16:22:10-05:00
lastmod: 2018-11-23T16:22:10-05:00
featured: false
draft: false

# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
  caption: ""
  focal_point: ""
  preview_only: false

# Projects (optional).
#   Associate this post with one or more of your projects.
#   Simply enter your project's folder or file name without extension.
#   E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
#   Otherwise, set `projects = []`.
projects: []
---
Given the rise of ‘big-data’, effectively managing and working with that stored data becomes very important — you’re only able to ask better questions if you can quickly glean insights from the data you have.
Unlike smaller datasets that can fit easily into a local computer’s hard disk, big data by definition won’t fit into local storage and must instead be stored in a database — a structured set of information that can be queried, accessed, and updated in various ways.
A database management system (DBMS) is the software that the end-user interacts with to use the database. To access the DBMS and database, we use a language called Structured Query Language (SQL) which provides a codified way to communicate with the DBMS and modify data stored in the database. SQL can be used to query and process data from DBMS tools like SQLite or Postgres or from the Hadoop Distributed File System (HDFS) using SQL-like languages like HiveQL or Spark SQL, for example.
## Basic SQL Query
In the SQL workflow, most of the time is spent writing requests (queries) that fetch a subset of or edit values from tables contained in the database. An example query looks like:
```SQL
SELECT *
FROM table_name
LIMIT 5;
```
Breaking down the statement above,
`SELECT *:` selects which columns we want (* denotes all the columns)
`FROM table_name:` the table we want to query (`table_name`)
`LIMIT 5:` the number of rows we want (first 5 in this case)

To filter rows by a specific criteria, we use the `WHERE` statement.
```SQL
SELECT *
FROM table_name
WHERE column_name > 0.5
LIMIT 5;
```
A `WHERE` statement contains three things:
- The column name we want to filter on (column_name)
- A comparison operator (<,≤,>,≥,=,!=)
- The value we want the database to compare each value to (0.5 in this case)

We can also use a conditional operator like `AND` or `OR` to further filter our results and the `ORDER BY` clause to order our results by ascending (`ASC`) or descending (`DESC`) order.
```SQL
...
WHERE [condition1] AND [condition2]
ORDER BY column_name DESC;
```
## Summary Statistics
We can use SQL to code and execute summary statistics like mean and standard deviation and aggregate functions like count, max, and min. We can also use the alias syntax AS to temporarily rename a table or a column in a query and the `DISTINCT` keyword in conjunction with the `SELECT` statement to fetch only the unique records and disregard duplicates. The query below, for example, aggregates all the unique values of `col1` in `table_name`(which has been renamed as `table_alias_name`), renames `col1` as `col_alias_name` and returns the row count.
```SQL
SELECT COUNT(DISTINCT(column_name)) AS col_alias_name
FROM table_name AS table_alias_name
WHERE [condition1];
```
## Grouping
The `GROUP BY` clause allows us to further compute summary statistics by combining identical data into groups. It follows the `WHERE` clause and precedes the `ORDER BY` clause. To place conditions and filter on groups created by the `GROUP BY` clause, we can use the `HAVING` clause.
```SQL
SELECT col1_name, ROUND(AVG(col2_name) / AVG(col3_name), 3) AS percentage
FROM table_name
WHERE [condition1]
GROUP BY col1_name
HAVING percentage > .8
ORDER BY percentage;
```
Oftentimes it’s useful to know the type of each column when doing arithmetic — this can be done using the `PRAGMA TABLE_INFO(table_name)` command. And if we want to cast a column as a specific type, we can use the `CAST` clause:
```SQL
SELECT CAST(col1_name as Float) / CAST(col2_name as Float) AS alias_name
FROM table_name
LIMIT 5;
```
## Subqueries
Unlike imperative, object-oriented programming languages like Python or C++, SQL doesn’t have variables you can define and use. Instead, SQL is a declarative programming language where we focus on expressing computations instead of defining how to do them. So since we can’t assign variables, we’ll have to use something called subqueries, or a query nested within another query. Subqueries must be enclosed within parenthesis and can be used within the `WHERE` clause:
```SQL
...
WHERE column_name OPERATOR
   (SELECT AVG(column_name)
    FROM table_name);
```

or within the `SELECT` clause:
```SQL
SELECT COUNT(*), (SELECT COUNT(*) FROM table_name)
FROM table_name
WHERE [condition];
```
or within both the `WHERE` and `SELECT` clauses:
```SQL
SELECT COUNT(*), (SELECT COUNT(*) FROM table_name)
FROM table_name
WHERE column_name OPERATOR
   (SELECT AVG(column_name)
    FROM table_name);
```
## Joining Data
Data will often be spread across multiple tables and in those cases, joining datasets together is often the first thing to do before doing analysis. In SQL, the JOIN clause combines data from two tables by using values common to each. The most common way to join data using SQL is by using an `INNER JOIN`:
```SQL
SELECT *
FROM table_name1
INNER JOIN table_name2
ON [join_constraint]
```
An `INNER JOIN` won’t include any rows where there isn’t a mutual match from both tables — in this way we could end up losing data that is only present in one table. One solution is to use a `LEFT JOIN`, which includes all the rows from the left (first) table that are not selected with the `INNER JOIN`.
```SQL
SELECT col5_name
FROM table_name1
LEFT JOIN table_name2
ON table_name2.col1_name = table_name1.col3_name
```
The figure below shows the difference between `INNER JOIN` and `LEFT JOIN`.
![joins](joins.png)*Source: http://www.sql-join.com/sql-join-types/*

## Creating Tables
To add tables in a database, we use the `CREATE TABLE` clause.
```SQL
CREATE TABLE table_name (
    column1_name column1_type,
    column2_name column2_type,
    column3_name column3_type,
    ...
);
```
Data types define what type of data a column can contain. There are many different types you can choose from including, `TEXT`, `NUMERIC`, `INTEGER`, `FLOAT`, `BLOB`, many others.
If you make a mistake creating a table using the command `DROP TABLE table_name` will delete the created table. You can use the dot command `.schema table_name` to view the schema for the table you created and you can use the `ALTER` command to add, delete, or modify columns in an existing table.

*I hope this gets you started on your SQL journey. As always, there’s much more to learn and queries can become quite complicated. However, these basics will guide you as you practice — so here’s to more querying!*
## Resources:
- These are my notes from the DataQuest learning track. Check them out and subscribe at www.dataquest.io
- Check out Luke Harrison's excellent SQL Cheat Sheet: https://websitesetup.org/sql-cheat-sheet/
- For a complete list of SQL commands, check out: https://www.tutorialspoint.com/sqlite
- A SQL style guide: https://www.sqlstyle.guide/


text:
Introduction
============
I'm using this script to download the latest footage from my [Xiaomi Xiaoyi Ants (720p)](http://www.yitechnology.com/homecamera.php?id=1) security cam, which contains the latest [Yi Hack custom firmware](https://github.com/fritz-smh/yi-hack/) that allows to access the camera via FTP.

Flow
====
My server checks every 30seconds whether there was a motion by calling the REST API of the camera. As soon as some footage has been captures, it will send the filename to a certain (configured) topic on my [Mosquitto MQTT queue](http://mosquitto.org/). This script listens to the topic and will download that file from the camera.

Configuration
=============
The configuration is pretty self-explaining. Just have a look at the ftpdownloader_demo.ini file. Just edit that file and rename it to ftpDownloader.ini.

Usage
=====
To run the script manually you must pass the ini file to the script.

`sudo python ftpDownloader ftpDownloader.ini`

If it has been installed as a systemd service (see config/install.sh for more information), run:

`sudo systemctl start ftpDownloader`

Dependencies
============
This script depends on the [paho library for MQTT](https://pypi.python.org/pypi/paho-mqtt/1.2), which must be installed.

# Support
I won't be able to give you premium support here. So you should be able to understand the code when something unexpected happens. I also won't take any responsibility if something messes up your system.

repository: asaenko/mqtt-ftp-downloader

repo_name: asaenko/mqtt-ftp-downloader


text:
# fixGB
Hi there, this is my little GB and GBC Emulator project, its essentially the GB version of my NES Emulator, fixNES.
If you want to check it out for some reason I do include a windows binary in the "Releases" tab, if you want to compile it go check out the "build" files.
You will need freeglut as well as openal-soft to compile the project, it should run on most systems since it is fairly generic C code.

Right now GB and GBC titles using MBC1, 2, 3, 5 and HuC1 should work just fine and also save into standard .sav files.
You can also listen to .gbs files, changing tracks works by pressing left/right.
To load a file, just drag and drop the .gb/.gbc/.gbs file into the application or call it via command line like "fixGB your_rom.gb".
You can also use a .zip file, the first found supported file from that .zip will be used.

The GBC BIOS is supported, have it in the same folder as your .gb/.gbc file called "gbc_bios.bin", when you load a game you will get the GBC logo and sound.
Using the GBC BIOS allows for colors in old GB games and gives you the palette selection the original GBC had during the GBC logo as well.

If you want to play older hacks such as colorization hacks and they dont look right, try adding "InvVRAM" into the filename, for example changing
"SML2.gb" to "SML2 (InvVRAM).gb". This will allow certain writes that are normally not supported by GB hardware to be accepted, older hacks did not
know about this limitation, thus requiring an exception in more accurate emulators like this one.

Controls right now are keyboard only and do the following:
Y/Z is A
X is B
A is Start
S is select
Arrow Keys is DPad
Keys 1-9 integer-scale the window to number
P is Pause
If you really want controller support and you are on windows, go grab joy2key, it works just fine with fixGB (and fixNES).

That is all I can say about it right now, who knows if I will write some more on it.

gha_language: C

gha_license_id: MIT


text:
---
layout: post
title: "Manage Certificates in Azure Key Vault"
comments: true
categories:
- Azure Key Vault
tags:
date: 2017-03-01
completedDate: 2017-01-23 09:02:20 +1100
keywords:
description:
primaryImage: pfx_security.jpg
---

In one of my earlier posts, [PFX Certificate in Azure Key Vault](http://www.rahulpnath.com/blog/pfx-certificate-in-azure-key-vault/), we saw how to save PFX Certificate files in Key Vault as Secrets. Azure Key Vault now [supports certificates as a first class citizen](https://blogs.technet.microsoft.com/kv/2016/09/26/get-started-with-azure-key-vault-certificates/). This means one can manage certificates as a separate entity in KeyVault. At the time of writing, Key Vault supports managing certificates using Powershell. The [portal UI](http://www.rahulpnath.com/blog/managing-key-vault-through-azure-portal/) is still to catch up on this feature. Using the Key Vault's certificate feature, we can create a new certificate: self-signed or signed by a supported certificate authority, import an existing certificate, retrieve the certificate with or without a private key part.

### Setting up the Vault

With the introduction of the certificates feature, a new command line switch is added to [Set-AzureRmKeyVaultAccessPolicy](https://docs.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.2.0/set-azurermkeyvaultaccesspolicy) cmdlet *[-PermissionToCertificates](https://docs.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.2.0/set-azurermkeyvaultaccesspolicy#PermissionsToCertificates)*. It supports the following values - *all, get, create, delete, import, list, update, deleteissuers, getissuers, listissuers, setissuers, managecontacts*. For a key vault created after the introduction of this feature, the property is set to *all* for the creator's access policy. For any vault created before the introduction of the feature, this property needs to be explicitly set to start using it.

### Create Certificate

To create a new certificate in the vault use the [Add-AzureKeyVaultCertificate](https://docs.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.2.0/add-azurekeyvaultcertificate) cmdlet. The cmdlet requires a Certificate Policy that specifies the subject name, issuer name, validity, etc.

``` powershell
$certificatepolicy = New-AzureKeyVaultCertificatePolicy   -SubjectName "CN=www.rahulpnath.com"   -IssuerName Self   -ValidityInMonths 12
Add-AzureKeyVaultCertificate -VaultName "VaultFromCode" -Name "TestCertificate" -CertificatePolicy $certificatepolicy
```

Executing the above creates a certificate in the vault with the given name. To retrieve the certificates in the key vault use the. The certificate object identifier is similar to that of Keys and Secrets as shown below. This identifier is used to identify a certificate uniquely.

``` text
https://vaultfromcode.vault.azure.net:443/certificates/TestCertificate
```

To retrieve all the certificates in a vault use the [Get-AzureKeyVaultCertificate](https://docs.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.2.0/get-azurekeyvaultcertificate) cmdlet passing in the VaultName. To get details of a certificate pass in the Certificate Name as well.

When creating a new certificate make sure that a Key or Secret does not exist with the same name in the vault. Azure adds in a key and secret with the same name as that of the certificate when creating a new certificate as shown in the above image. The key is required when for certificates created with non-exportable key (-[KeyNotExportable](https://docs.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.1.0/new-azurekeyvaultcertificatepolicy#KeyNotExportable)). Non-exportable certificates do not have the private portion contained in secret. Any certificate operation requiring the private part should use the key. For consistency, the key exists for exportable certificates as well.

To import an existing certificate into the key vault, we can use [Import-AzureKeyVaultCertificate](https://docs.microsoft.com/en-us/powershell/resourcemanager/azurerm.keyvault/v2.1.0/import-azurekeyvaultcertificate) cmdlet. The certificate file should be either PFX or PEM format.

### Recreate Certificate Locally from Key Vault

Often we will have to recreate the certificate on the machine where the application using it is running. To create the private portion of the certificate retrieve it from the Secret, load it into a certificate collection, export and save the file locally.

``` powershell
$kvSecret = Get-AzureKeyVaultSecret -VaultName 'VaultFromCode' -Name 'TestCertificate'
$kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$protectedCertificateBytes = $certCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, 'test')
$pfxPath = 'C:\cert\test.pfx'
[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertificateBytes)
```

Similarly to export the public portion of the certificate

``` powershell
$cert = Get-AzureKeyVaultCertificate -VaultName 'VaultFromCode' -Name 'TestCertificate'
$filePath ='C:\cert\TestCertificate.cer'
$certBytes = $cert.Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
[System.IO.File]::WriteAllBytes($filePath, $certBytes)
```

### Delete Certificate

To delete a certificate use the Remove-AzureKeyVaultCertificate cmdlet and pass in the vault name and certificate name.

``` powershell
Remove-AzureKeyVaultCertificate -VaultName 'VaultFromCode' -Name 'TestCertificate'
```

Hope this helps you to get started with managing certificates in Azure Key Vault.


text:
---
title: StateXProvider
sidebar_label: StateXProvider
---

### <StateXProvider ...props />

Provides the context in which atoms have values. Must be an ancestor of any component that uses any StateX hooks. Multiple roots may co-exist; atoms will have distinct values within each root. If they are nested, the innermost root will completely mask any outer roots.

- `props` (Optional)

  - `initialState` Object or Array

    You application's intial state.

  - `handleError` (error) => void;

    This method will be invoked whenever an exception is thrown from a selector.

### Example

```jsx
import { StateXProvider } from '@cloudio/statex';

function AppRoot() {
  return (
    <StateXProvider>
      <App />
    </StateXProvider>
  );
}
```

repository: CloudIOInc/statex

gha_language: TypeScript

repo_name: CloudIOInc/statex


text:
# Description
Get your current IP address as seen from the Internet. Ex: Get-ShodanClientIP -API

This is the IP that the outside world sees you as; for example, if you are at home this would be your ISP provided modem's IP address.

**Note:** If your service provider supports IPV6, the IPV6 address will be prioritized instead of your public IPV4 address.

## Prerequisites
You will need to have downloaded and installed the script already. Please see [Downloading](https://github.com/simeononsecurity/Shodan_PS#Download) and [Installing](https://github.com/simeononsecurity/Shodan_PS#Install) for further instruction.

## Usage
Run the script by entering the module name with with the API parameter followed by the api key in quotes.
```
PS C:\WINDOWS\system32> Get-ShodanClientIP -API "ApiKeyStringGoesHere"
PS C:\WINDOWS\system32>
"PublicIpAddressReturnedHere"
```

branch_name: refs/heads/main

gha_language: PowerShell


text:
### Build Steps

#### build go code as a c-shared-library
```
go build -o usedByC.o -buildmode=c-shared main.go
```

#### compile C code
```
gcc -o willUseGo willUseGo.c ./usedByC.o
```

repository: nikhil-thomas/technik-dojo

gha_language: Go

repo_name: nikhil-thomas/technik-dojo


text:
# Yet Another Filament Bank

## Why another Filament Buffering Solution?

I wanted a solution that met the following requirements:

- Does a decent job of handling retracting filament (duh)
- Fully 3d printable while ideally using a minimal amount of filament
- Retains maximum visibility of filament in the system
- Easy to change filament

## Bill of Materials

While a focus of this design is maximizing 3d printable parts, there are of course, some parts which you will need that cannot be effectively printed.

- 10x PC4-M6 Quick Fitting Push to Connect PTFE fittings
- 5x 604z bearings
- 2x M3 screws/nuts and bolts for affixing assembled bank to your printer stand (I used spare Prusa parts)
- Enough PTFE Teflon tubing (2mm Inner Diameter(ID) X 4mm Outer Diameter (OD)) to connect the bank to your printer and filament stands

## License

This project is licensed under the terms of the  [MIT license](LICENSE.txt).

## Step One: Printing Guide

The first step is to print the pieces required for the buffer chambers. You can start from scratch with the .stl files, or printable files for building this out of PLA exist both in pre-arranged .3mf files for PrusaSlicer or gcode files for direct printing from a Prusa i3 MK3S printer.

### Buffering chambers

#### 1x bottom bracket

This is the bottom part that holds the separator walls and sidewalls in place.

I recommend printing this with transparent filament and minimal infill (downloadable gcodes are 5% hexagonal infill). This model is included as part of `brackets_pegs.3mf` and its associated gcode file.

#### 1x top bracket

This holds the tops of the separator walls and sidewalls in place, holds the wheel assemblies in place, and has tabs for hanging the assembly on your printer stand.

I recommend printing this with transparent filament and minimal infill (downloadable gcodes are 5% hexagonal infill). This model is included as part of `brackets_pegs.3mf` and its associated gcode file.

#### 2x side wall

The sidewalls fit into the top and bottom brackets and hold the separator walls in place.

I recommend printing this with transparent filament to allow more visibility to the filament chambers. Printing these with standard settings will create a sturdier chamber, but I recommend printing them with 10% hex infill with no top/bottom layers. This will allow maximum visibility into the buffer chambers. Both copies of this model are included as part of `sidewalls.3mf` and its associated gcode file.

#### 1x side pegs

This model includes four pegs that secure the separator walls into the top and bottom brackets. The longer pegs go into the top bracket. All pegs include threading at the end to hold them securely in place.

I recommend printing this with either 20% gyroid infill or 100% infill. This model is included as part of `brackets_pegs.3mf` and its associated gcode file.

#### 6x separator wall

The separator walls isolate each color of filament into separate chambers.

I recommend printing these with transparent filament to allow more visibility to the filament chambers. Printing these with standard settings will create a sturdier chamber, but I recommend printing them with 10% hex infill with no top/bottom layers. This will allow maximum visibility into the buffer chambers. Both copies of this model are included as part of `separator_wall.3mf` and its associated gcode file.

### Five wheel assemblies

#### 5x filament wheels

This is the wheel that the filament rotates against when the printer is printing.

The default 20% gyroid infill profile is fine here. I recommend printing each of these five wheels in a different color, it will make it easy to tell at a glance which wheel is turning.

This model is included as part of `wheel_and_peg.3mf` and its associated gcode file.

#### 5x thumb pegs

These pegs lock the brackets into place with the buffering chamber.

The default 20% gyroid infill profile is fine here. I recommend printing each of these in a different color as with the five wheels, it will make it easy to tell at a glance which bracket to pull out when you're changing filament

This model is included as part of `wheel_and_peg.3mf` and its associated gcode file.

#### 5x filament wheel mount bottom

This is the bottom half of the bracket that holds the filament wheel in place and connects to the buffering chambers.

I recommend printing these with transparent filament to allow more visibility to the filament chambers, although it will not matter as much with these parts. I recommend printing them with 10% hex infill with no top/bottom layers. This model is included as part of `wheel_assembly.3mf` and its associated gcode file.

#### 5x filament wheel mount top

This is the top half of the bracket that holds the filament wheel in place and connects to the buffering chambers.

I recommend printing these with transparent filament to allow more visibility to the filament chambers, although it will not matter as much with these parts. I recommend printing them with 10% hex infill with no top/bottom layers. This model is included as part of `wheel_assembly.3mf` and its associated gcode file.

#### 5x filament wheel axle

This is the axle that will screw in place, holding the bearing and brackets in place. These are easy to break while assembling, you may find it useful to print some spares.

The default 20% gyroid infill profile is fine here. This model is included as part of `wheel_assembly.3mf` and its associated gcode file.

#### 10x filament wheel connector

You'll need 10 connectors that hold the filament wheel mount brackets together.

The default 20% gyroid infill profile is fine here. This model is included as part of `wheel_assembly.3mf` and its associated gcode file.

## Modifying

Many changes that you would like to make can be made by modifying `src/filament_bank_values.scad`. For example, increasing the thickness of walls for a more solid assembly. If you make improvements to the design, please submit a pull request on github!

## Assembly

YouTube videos of the assemby process are available:

- [Part One - Filament Buffer Assembly](https://youtu.be/NMZ75zq5oWg)
- [Part Two -- Wheel Bracket Assembly](https://youtu.be/zj1OsbUYNdQ)
- [Part Three -- Final Assembly](https://youtu.be/MDklB2XTeAQ)

### Buffering Chamber Assembly

Start with the bottom bracket. It may be helpful to use a utility knife to clean any printing artifacts out of the 6 slots along the bracket. Note that on the one side, next the round hole for the peg, there is a small notch. That side is the "deeper" section, and your separator walls should be aligned to match.

Slide each of the six separator walls into the slots on the bottom bracket. With the notch on the right of the bottom bracket, slide in the two shorter pegs, then use a pair of pliers to give each peg a twist or two clockwise to lock the pegs in place.

Then carefully align one of the sidewalls with the separator walls, and slide it down into the bottom bracket until it is firmly in place. Repeat with the other side.

Align the top bracket with the sidewall and separator walls and slide into place. With the back bracket facing to the right, slide in the two longer pegs, then use a pair of pliers to give each peg a twist or two clockwise to lock the pegs in place.

Congratulations, you've finished the buffering chambers! Why don't you reward yourself with some gummi bears :)

### Wheel Bracket Assembly

First, fit one of the printed axles through the top filament wheel mount (when inserted properly, it will sit flush on the plate). Place this on a flat surface so that the axle is pointing upwards.

Now, push one of the bearings into a the center of a wheel. Push the combined wheel/bearing onto the axle which is facing upwards.

Carefully align the bottom filament wheel mount so that the socket for the axle aligns with the axle, then carefully pick up the assembled bracket and gently turn the axle a bit by hand or using a coin to turn it. TIGHTEN VERY GENTLY, or the axle may break.

> IF the axle breaks, you will need to get the remaining part out of the bottom bracket. Using a utility knife and stabbing the center of the broken axle and turning it is effective in this case.

Once you have the axle in place, insert the two 3d printed connector bolts to hold the top and bottom brackets in place. When all of the screws are in place, make sure they are all flush with the bottom bracket, or the brackets will not all fit into the buffering chamber.

Finally, make sure the wheel spins freely. You may need to carefully push the wheel towards the top or bottom bracket to eliminate friction and allow it to freely turn.

Screw two of the two PTFE tube quick releases into the top of the bracket, and you'll have assembled a wheel bracket.

Repeat 4 more times and then reward yourself with some gummi bears.

## Installation

The top bracket of the buffering chamber has brackets for hanging. Using M3 screws, secure the buffering chamber to a wall or your print stand. Ideally, there should be a short line of travel from the MMU2s unit downward to the buffering chamber.

Insert each of the wheel assemblies into the top bracket. Note that the back should be angled down as you insert them, so that the guide along the back lines up with the protrusion along the back of the top bracket. Then drop the front of the wheel assembly down and secure it with one of the thumb pegs. If you printed the pegs and wheels in five different colors as suggested in the printing instructions, be sure to match them up.

Now you're ready to print!

## Credit

This is a filament buffering system designed for use with the Prusa MMU2s, but should be easily adaptable to suit similar requirements or MMU2S modifications adding additional filaments.

The original inspiration for this comes from [David Shealey](https://www.thingiverse.com/TNDave/about)'s brilliant design for his [Prusa MMU2 Filament Retract Bank](https://www.thingiverse.com/thing:3373895). His concept of a simple wheel releasing filament into a channel was the first workable buffering system for the MMU2S, as far as I'm concerned. However, this design suffers from two flaws. First, the walls of the chambers were designed to be acrylic plastic -- which had the advantage of being clear, but required some knowlege of working with acrylic.

This led [Piotr Karkovski](https://www.thingiverse.com/Karkovski/about) to create a modified [Fully printable Prusa MMU2 Filament Retract Bank (Buffer)](https://www.thingiverse.com/thing:3670379). This solved the orignial issue, and Piotr's instructions suggested maintaining visibility by using hex infill with no top or bottom layers. This was a very nice innovation, but it didn't help to solve the other issue with Shealey's original design.

Shealy's design relies on a paddle that slides up and down that, as you feed filament in, is supposed to force the filament to return up the other side. While this occasionally worked for me, I found it to be frustating in practice. [Garth Gangaway](https://www.thingiverse.com/GVader/about) set out to solve this problem with a new design, but this again relied on acrylic panels, and I did not like the clipping solution used on this model.

I am super grateful to all of these designers and their innovation. While I haven't used their original designs in creating this project, it certainly wouldn't exist without their original work, especially David Shealey's original design.

repository: Eisbaeeer/Filament-Bank

repo_name: Eisbaeeer/Filament-Bank


text:
ffho-autoupdater-wifi-fallback
==============================

If a node has no connection to the mesh, neither via wlan-mesh nor via
mesh-vpn, it ist not possible to update this node via `autoupdater`. Therefor
the *wifi-fallback* was developed. It checks hourly whether the node is part of
a fully operative mesh or not. Else the node connects to a visible "Freifunknetz"
and tries downloads an update as wlan-client via executing `autoupdater -f`.

Actually this needs `iw connect` patched into `iw`. See our patch within our
[site repository](https://git.ffho.net/freifunkhochstift/ffho-site).

/etc/config/autoupdater-wifi-fallback
-------------------------------------

**autoupdater-wifi-fallback.settings.enabled:**
- `0` disables the fallback mode
- `1` enables the fallback mode

### example
```
config autoupdater-wifi-fallback 'settings'
	option enabled '1'
```

repository: FreifunkHochstift/ffho-packages

gha_language: Lua

gha_license_id: NOASSERTION

repo_name: FreifunkHochstift/ffho-packages


text:
# sudo_per_token
This script is used to setup a debian box to use a securecard to protect
sudo.

This is really rough. There is no errorhandling. The tokeen has to be
inserted. Only use this script once!

the following files will be added/altered
* /etc/poldi/localdb/keys/$APPID
* /etc/pam.d/sudo
* /etc/poldi/localdb/users


text:
#DEPRECATED IN CDM V6.0 +. Below documentation only applies for V5+ < V6

# CDM Table: DEATH

- DOD: this table will be sourced from the table **Death** - except for persons not in person table and based on logic below.
- SES: this table will be algorithmically derived from observations in claims data.
- Cause of death is not present in source data.

## **DEATH Table Logic**
- Delete person if not in PERSON table.
- For DOD only,
    - If there are outpatient or pharmacy visits (VISIT_CONCEPT_ID in 9202, 581458) with visit start date after 30 days of death date, delete the visit record.
    - If there are inpatient or ER visits (VISIT_CONCEPT_ID in 9202, 9203) with visit start date after 30 days of death date, delete the death record.
    - If the death date occurs before the patient's date of birth, then delete the death record.

## **Deriving date of death in SES**
- In SES data only, date of death will be derived from claims as follows.
- The date of death will be associated to the VISIT_END_DATE.
- These fields will be scanned for death information:
  1. **MEDICAL_CLAIMS** DSTATUS (Discharge Status)
  1. **MED_DIAGNOSIS** DIAG (ICD10CM or ICD9CM diagnosis codes)
  1. **MEDICAL_CLAIMS** DRG

### **Mapping DEATH_TYPE_CONCEPT_ID**

If a person in the **DOD** database has a death record sourced from the **DEATH** table use **DEATH_TYPE_CONCEPT_ID = 32885**

#### Using **MEDICAL_CLAIMS** DSTATUS

| Source Field       | Source Code | Source Code Description               | DEATH_TYPE_CONCEPT_ID |
|------------------|--------------|-----------------------------------------|--------------------------|
| **MEDICAL_CLAIMS** DSTATUS | 20           | EXPIRED                                 | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 21           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 22           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 23           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 24           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 25           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 26           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 27           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 27           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 28           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 29           | EXPIRED TO BE DEFINED AT STATE LEVEL    | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 40           | EXPIRED AT HOME (HOSPICE)               | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 41           | EXPIRED IN A MEDICAL FACILITY (HOSPICE) | 32812        |
| **MEDICAL_CLAIMS** DSTATUS | 42           | EXPIRED – PLACE UNKNOWN (HOSPICE)       | 32812        |

#### Using ICD9CM and ICD10CM from **MED_DIAGNOSIS** DIAG

Use [Source to Source](code_snippets.md#source-to-source) and filter with
```WHERE SOURCE_VOCABULARY_ID IN ('JNJ_DEATH')``` to find DEATH records using the diagnosis codes. Give these records **DEATH_TYPE_CONCEPT_ID = 32508**

#### Using ICD9CM and ICD10CM from **MEDICAL_CLAIMS** DRG

For DRGs, use the following query.  DRGs are date-sensitve so we need to only pick up DRGs that fall within the valid start and end dates.

```
SELECT CONCEPT_ID, CONCEPT_NAME, CONCEPT_CODE, valid_start_date, valid_end_date
FROM concept
WHERE CONCEPT_ID IN (
  38000421,38001111,38001112,38001113
)
```
Any records that have a DRG indicating the person is deceased should use the **DEATH_TYPE_CONCEPT_ID = 32509**

The **DEATH_TYPE_CONCEPT_ID**s should be treated hierarchically, where **MEDICAL_CLAIMS** DSTATUS > **MED_DIAGNOSIS** DIAG > **MEDICAL_CLAIMS** DRG

***

**Destination Field**|**Source Field**|**Applied Rule**|**Comment**
:-----:|:-----:|:-----:|:-----:
PERSON_ID|PATID||
DEATH_DATE|**SES: VISIT_OCCURRENCE** VISIT_END_DATE

 **DOD: DEATH**
 ymdod|**(DOD only) DEATH**
 Use the last day of the month|
DEATH_DATETIME|Set time to 00:00:00 UTC Tz||
DEATH_TYPE_CONCEPT_ID|Derived field|[See mapping logic](#Mapping-DEATH_TYPE_CONCEPT_ID) |These CONCEPT_IDs fall under VOCABULARY_ID = 'Death Type' in CONCEPT table.
CAUSE_OF_DEATH_CONCEPT_ID|0||
CAUSE_OF_DEATH_SOURCE_VALUE|0||
CAUSE_SOURCE_CONCEPT_ID|0||
---
*Common Data Model ETL Mapping Specification for Optum Extended SES & Extended DOD*

*CDM Version = 6.0.0, Clinformatics Version = v8.0*

repository: OHDSI/ETL-LambdaBuilder

gha_language: C#

repo_name: OHDSI/ETL-LambdaBuilder


text:
# Tenant Dashboard

ASP.NET Zero startup project also includes a **sample** dashboard. It's just for demo purposes, you can make it starting point for your actual dashboard. It's implemented with app/main/**dashboard.component** in **main.module**.

<img src="images/tenant-dashboardV5.png" alt="Dashboard" class="img-thumbnail"/>

Client gets all data from server, server generates random data.

## Next

- [Notifications](Features-Angular-Notifications)

repository: aspnetzero/documents

gha_language: HTML

repo_name: aspnetzero/documents


text:
---
layout: default
---

# 1996-05-08 - Re: Why I Pay Too Much in Taxes

## Header Data

From<EMAIL_ADDRESS>(Anonymous)

To<EMAIL_ADDRESS>Message Hash: 7952faa0bcc49fa5be37a70f8b313ce621e21b15c4a477495975d28eaad58740

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1996-05-08 12:29:22 UTC

Raw Date: Wed, 8 May 1996 20:29:22 +0800

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(Anonymous)
Date: Wed, 8 May 1996 20:29:22 +0800
To<EMAIL_ADDRESS>Subject: Re: Why I Pay Too Much in Taxes
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

Black Unicorn wrote:
>Where does the company get the funds to pay you?

>From Tim's day work. It's a consulting company, i.e. it sells his
services to whomever is employing him today. The whole idea
was to hide Tim's income sources, or that's what he asked for anyway.

You can hide your income by putting it in another jurisdiction.

>What pay?  I don't get it.  Where does this friend gets his money?

As a cut from the money Tim's employer gives him.

>> By the way, are there any PGP encrypted mailing lists for
>> discussing serious tax fraud?
>
>If such a list existed, would we tell an anonymous poster/fed?

>If your above scheme is intended merely to conceal funds it is a fairly
>poor example as it depends on the secrecy of each and every 'employee' of
>the company.

No it doesn't. One person knows where they money went when it left the
country (and he is getting paid for the risk of doing time). Nobody knows
where the funds are concealed. Probably in a trust that you can access
when you are on vacation abroad.

Mr.X.

{% endraw %}
```

## Thread

+ Return to [May 1996](/archive/1996/05)

+ Return to "[Black Unicorn <unicorn@schloss.li>](/authors/black_unicorn_unicorn_at_schloss_li_)"
+ Return to<EMAIL_ADDRESS>(Anonymous)](/authors/nobody_at_replay_com_anonymous_)"

+ 1996-05-08 (Wed, 8 May 1996 20:29:22 +0800) - Re: Why I Pay Too Much in Taxes -<EMAIL_ADDRESS>(Anonymous)_
  + 1996-05-09 (Thu, 9 May 1996 14:12:25 +0800) - [Re: Why I Pay Too Much in Taxes](/archive/1996/05/42cc5b592c7d8fb095d82d7e602d260132a687e7c5f253c0406de303f7bddcd9) - _Black Unicorn<EMAIL_ADDRESS>


text:
## Importance of Naming

It is very important that we give our variables and function significant names.
For example, `x` is a very non-descriptive name for a variable or function.
As we tackle more complicated problems and our code grows to be more complex, we
are likely to forget what it originally stood for and its purpose. Non-descriptive
names make our code error-prone. **Great code reads like English and almost explains
itself.**

### It's on the tip of my tongue...

Let's get motivated. What is the purpose of the following function?

```js
function x(n, j) {
  var z = (j / n) * 100;

  if (z < 15) {
    return false;
  } else {
    return true;
  }
}
```

Hmm, it's pretty hard to tell. The function, parameter, and variable names that are
used give us no indication of what is happening. Let's rewrite it and give our data
significant names:

```js
function isGoodTip(mealCost, amountTipped) {
  var percentage = (amountTipped / mealCost) * 100;
  var badTip = 15;

  if (percentage < badTip) {
    return false;
  } else {
    return true;
  }
}
```

Wow. Now that's a whole lot better. The names used in the code above provide much
more clarity as to **what** problem we are trying to solve and **how** we are solving it!

### Why Does Naming Matter?

Whenever you write a piece code, consider the possibility that you will have to come back to
it a year later. Would you be able to understand what is happening in the code? Furthermore, would
*someone else* be able to understand what you wrote? After all, despite popular belief,
programmers do not code in a dark basement by themselves; they work in a team! As programmers, our
goal is to write code that is not only "correct", but also elegant, readable, and maintainable! Hold yourself to this high standard.

### Examples:

Whenever you are naming a variable or a function use a **concise but also descriptive** name.
Aim for that happy medium:

```js
var x = 5 + 5; // not descriptive.

var sumOfFiveAndFive = 5 + 5; // not concise.

var num = 5 + 5; // concise and descriptive! We have a sense of what type data is contained.

var string = 5 + 5; // misleading.

var fish = 5 + 5; // please no, for the love of Bill Gates.
```


text:
#  akka-cluster-custom-downing

[![CI](https://github.com/sisioh/akka-cluster-custom-downing/workflows/CI/badge.svg)](https://github.com/sisioh/akka-cluster-custom-downing/actions?query=workflow%3ACI)
[![Scala Steward badge](https://img.shields.io/badge/Scala_Steward-helping-blue.svg?style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAMAAAARSr4IAAAAVFBMVEUAAACHjojlOy5NWlrKzcYRKjGFjIbp293YycuLa3pYY2LSqql4f3pCUFTgSjNodYRmcXUsPD/NTTbjRS+2jomhgnzNc223cGvZS0HaSD0XLjbaSjElhIr+AAAAAXRSTlMAQObYZgAAAHlJREFUCNdNyosOwyAIhWHAQS1Vt7a77/3fcxxdmv0xwmckutAR1nkm4ggbyEcg/wWmlGLDAA3oL50xi6fk5ffZ3E2E3QfZDCcCN2YtbEWZt+Drc6u6rlqv7Uk0LdKqqr5rk2UCRXOk0vmQKGfc94nOJyQjouF9H/wCc9gECEYfONoAAAAASUVORK5CYII=)](https://scala-steward.org)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.sisioh/akka-cluster-custom-downing_2.13/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.j5ik2o/akka-persistence-dynamodb-journal_2.13)
[![Scaladoc](http://javadoc-badge.appspot.com/org.sisioh/akka-cluster-custom-downing_2.13.svg?label=scaladoc)](http://javadoc-badge.appspot.com/org.sisioh/akka-cluster-custom-downing_2.13/com/github/j5ik2o/akka/persistence/dynamodb/index.html?javadocio=true)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

akka-cluster-custom-downing provides a configurable auto-downing strategy that you can choose based on your distributed application design.
It lets you configure which nodes can be downed automatically and who is responsible to execute a downing action.

## Introduction

Akka cluster has an `akka.cluster.auto-down-unreachable-after` configuration property.
It enables marking unreachable nodes as DOWN automatically after a specified duration.
As [the Akka documentation](http://doc.akka.io/docs/akka/current/scala/cluster-usage.html#Automatic_vs__Manual_Downing) says,
using the auto-down feature is dangerous because it may cause a split-brain scenario which leads to multiple clusters.
The fundamental problem is that an actual down node and a temporary network partition cannot be distinguished from each other.
You must realize that an auto-downed node may be actually alive and establishing its own cluster.  One of the worst consequences is that resources that must not be shared are now accessible by multiple Cluster Singletons or duplicatively sharded by Cluster Sharding.

## Theoretical background

It is noteworthy that there exists **no** perfect split brain resolving strategy.
According to so called "FLP impossibility result", no deterministic consensus can be made in an asynchronous system even if only one process fails.
As you know, akka cluster is an asynchronous system and therefore cannot make a consensus about its view synchronised with gossip protocol if faulty processes exist.

It is always beneficial to clarify what kind of failure a distributed algorithm handles.
Akka cluster has a failure detector and a split brain resolver (and also auto-down) handles its failure.
In this case the failure indicates the process crashes and does not differentiate a crash from the omission of a heartbeat.
Actually the failure detector cannot differentiate a crash and the omission of a heartbeat.
In the case of omission, i.e. when the process marked as faulty by the failure detector are actually alive, some algorithms go wrong.
For example the auto-down feature of akka cluster is based on election of a leader which may diverge under an omission fault, so may result in a split-brain scenario.

Note that leader election in Akka cluster is based on asynchronously replicated state.
A leader is the first member selected from sorted members that are not unreachable.
Under network partition some partition may have different view of unreachable members from the others so leader will diverge.

The Split brain resolver included in akka-cluster-custom-downing basically resolves the problem in a way that,

1. do not depends on a leader (or leader only)
1. force some resolved processes to crash, i.e. omission fault is same as crash fault
1. not perfect as indicated in FLP impossibility, but occurrence of the imperfection is pretty rare

My slide may help you understand these things. I am sorry it is written in japanese. Let me know if there are better documents that explain the split brain problem.
http://www.slideshare.net/TanUkkii/akka-cluster-66880662

## Status

akka-cluster-custom-downing is currently under development.

akka-cluster-custom-downing is for general purpose.
In some case you find it is better to implement your system specific strategy by yourself.
akka-cluster-custom-downing shows how to implement split brain resolving strategies so may be your help.

Distributed systems are challenging. Actually I do not use akka cluster or akka-cluster-custom-downing in production.
I hope to know how you use them.

## Installation

For sbt, add following lines to build.sbt.

```
libraryDependencies += "org.sisioh" %% "akka-cluster-custom-downing" % "0.1.0"
```

Scala 2.12 and 2.13 are supported.

## Usage of split brain resolving strategy

### OldestAutoDowning

`OldestAutoDowning` automatically downs unreachable members.
A node responsible to down is the oldest member of a specified role.
If `oldest-member-role` is not specified, the oldest member among all cluster members fulfills its duty.

You can enable this strategy with following configuration.

```
akka.cluster.downing-provider-class = "org.sisioh.akka.cluster.custom.downing.OldestAutoDowning"

custom-downing {
  stable-after = 20s

  oldest-auto-downing {
    oldest-member-role = ""
    down-if-alone = true
  }
}
```

Unlike leader based downing strategy, the oldest based downing strategy is much safer.
It is because the oldest member is uniquely determined by all members even if gossip is not converged,
while different leader might be viewed by members under gossip unconvergence.

Downside of the oldest based downing strategy is loss of downing functionality when the oldest member itself fails.
If `down-if-alone` is set to be true, such scenario can be avoided because the secondary oldest member will down the oldest member if the oldest member get unreachable alone.

![OldestAutoDowning](img/keep_oldest.png)

### QuorumLeaderAutoDowning

`QuorumLeaderAutoDowning` automatically downs unreachable nodes after specified duration if the number of remaining members are larger than or equal to configured `quorum size`.
This strategy is same as [static quorum](http://doc.akka.io/docs/akka/rp-15v09p02/scala/split-brain-resolver.html#Static_Quorum) strategy of Split Brain Resolver from Typesafe reactive platform.
If `down-if-out-of-quorum` is set to be true, remaining members which number is under quorum size will shutdown ActorSystem by themselves.
If `role` is specified, the number of remaining members in the role is used to be compared with quorum size.

```scala

akka.cluster.downing-provider-class = "org.sisioh.akka.cluster.custom.downing.QuorumLeaderAutoDowning"

custom-downing {
  stable-after = 20s

  quorum-leader-auto-downing {
    role = ""
    quorum-size = 0
    down-if-out-of-quorum = true
  }
}

```

![QuorumLeaderAutoDowning](img/static_quorum.png)

### MajorityLeaderAutoDowning

`MajorityLeaderAutoDowning` is similar to `QuorumLeaderAutoDowning`. However, instead of a static specified quorum size this strategy automatically keeps the partition with the largest amount of nodes. If the partitions are of equal size, the partition that contains the node with the globally lowest address is kept. The strategy is the same as the [keep majority](http://doc.akka.io/docs/akka/rp-15v09p02/scala/split-brain-resolver.html#Keep_Majority) strategy of Split Brain Resolver from Typesafe reactive platform.
If a role is set by `majority-member-role`, the strategy is only enforced to the nodes with the specified role.

```scala

akka.cluster.downing-provider-class = "org.sisioh.akka.cluster.custom.downing.MajorityLeaderAutoDowning"

custom-downing {
  stable-after = 20s

  majority-leader-auto-downing {
    majority-member-role = ""
    down-if-in-minority = true
    shutdown-actor-system-on-resolution = true
  }
}

```

## Usage of Leader based downing strategies

It is not recommended that your auto-down strategy depends on a leader.

With careful consideration, however you may use auto-down feature safely for a specific design of distributed application.

If following conditions are met, nodes can be safely down automatically.

1. a node will be isolated from incoming requests if the node is detached from the other cluster members
1. a node mutates shared resources only if it receives a request

How this conditions are applied is vary according to application design.

### LeaderAutoDowningRoles

`LeaderAutoDowningRoles` automatically downs nodes with specified roles.
Like `akka.cluster.AutoDowning`, which is provided with Akka Cluster, a node responsible to down is the leader.

You can enable this strategy with following configuration.

```
akka.cluster.downing-provider-class = "org.sisioh.akka.cluster.custom.downing.LeaderAutoDowningRoles"

custom-downing {
  stable-after = 20s

  leader-auto-downing-roles {
    target-roles = [worker]
  }
}
```

### RoleLeaderAutoDowningRoles

`RoleLeaderAutoDowningRoles` automatically downs nodes with specified roles.
A node responsible to down is the role leader of a specified role.

You can enable this strategy with following configuration.

```
akka.cluster.downing-provider-class = "org.sisioh.akka.cluster.custom.downing.RoleLeaderAutoDowningRoles"

custom-downing {
  stable-after = 20s

  role-leader-auto-downing-roles {
    leader-role = "master"
    target-roles = [worker]
  }
}
```

repository: sisioh/akka-cluster-custom-downing

gha_language: Scala

repo_name: sisioh/akka-cluster-custom-downing


text:
# CookiePro Consent management helper

This package exposes a host type and an error type to determine how to display embedded video from third party providers like youtube and vimeo.

The application has to implement ports in order to feed data about the user's cookie consent.

## app.js example

```js
// listen for cookie consent changes to display placeholder messages for embeds from hosts without consent
window.OptanonWrapper = function () {
    if (app?.ports?.onCookieConsentChange && window.Optanon?.GetDomainData?.().Groups && OptanonActiveGroups) {
        app.ports.onCookieConsentChange.send({
            allGroups: window.Optanon.GetDomainData().Groups,
            activeGroupIdsString: OptanonActiveGroups
        });
    }
}
```

## Session.elm example

```elm
cookieChanges : (Session -> msg) -> Session -> Sub msg
cookieChanges toMsg session =
    onCookieConsentChange (\value -> toMsg (mapUI (\ui -> { ui | cookieHosts = decodeCookieHosts value }) session))

decodeCookieHosts : Value -> List Cookie.Host
decodeCookieHosts value =
    Result.withDefault Cookie.defaultHosts (Decode.decodeValue Cookie.decoder value)

port onCookieConsentChange : (Value -> msg) -> Sub msg
```

# Release

1. Update documentation: `elm make --docs=docs.json`
2. Create the next tag according to semver in main branch. `git tag -a 1.2.3 -m "Short description of changes in the new version"` The tag should look something like this: "1.2.3", NOT "v1.2.3"
3. Push it real good!

repository: Specialelektronik/elm-cookie-consent

repo_name: Specialelektronik/elm-cookie-consent


text:
# crunchpow-model
[![travis build](https://img.shields.io/travis/TheOneTheOnlyDavidBrown/crunchpow-model.svg)](https://travis-ci.org/TheOneTheOnlyDavidBrown/crunchpow-model/)
![MIT License](https://img.shields.io/github/license/TheOneTheOnlyDavidBrown/crunchpow-model.svg)
[![version](https://img.shields.io/npm/v/crunchpow-model.svg)](https://www.npmjs.com/package/crunchpow-model)

This is a microlibrary for better handling of models with schemas. Includes CRUD functions to alter the model on the backend without having to write the CRUD functions (promise returned) in your service.

## Installation
`npm install --save --save-exact crunchpow-model`

or

`yarn add -E crunchpow-model`

or

Use a CDN: `https://npmcdn.com/crunchpow-model/dist/index.umd.min.js` but it's best to go to this in the browser and copy what it directs to because it will keep the correct version for you.

## Model Usage:
- Import package `require('crunchpow-model')`.
- Set up schema as `const schema = {myProp: 'string', multipleTypes: 'string|number', user: {name:'string'}}`. Type can be `string|number|array|boolean`.
- `let myModel = new CrunchPowModel('myModelName', schema);`.
- `myModel.create([dataObj])`. dataObj must be in a format that validates against the schema. This is for getting a model from the back-end and casting it as a crunchpow-model.
- Use `myModel.prop('myProp','new value')` to set. Nested properties can be set by `myModel.prop('user.name', 'new value').
- Use `myModel.myProp` to get property.

## HTTP usage:
- Default endpoints mimic the default Ruby on Rails routes.
- Using myModel.save() saves the current model
- Using myModel.destroy(id) destroys a model based on the passed in id. Probably will update this to have the id optional and delete the current model.
- Using myModel.fetch([id]) gets the model if id is passed in. Otherwise, it returns a list of all models 'myModel'.
- By using `myModel.setBaseEndpoint(newBaseEndpoint)` you can change the root endpoint. Default: `/api/:modelName`.

repository: TheOneTheOnlyDavidBrown/crunchpow-model

repo_name: TheOneTheOnlyDavidBrown/crunchpow-model