text:
const fPin _fGetPin_v(const uint8_t pin) {
	return _fGetPin_c(pin);
}

void _fPinMode_v(const fPin pin, const uint8_t mode) {
	_fPinMode_c(pin, mode);
}

void _fDigitalWrite_v(const fPin pin, const uint8_t value) {
	_fDigitalWrite_c(pin, value);
}

void _fDigitalToggle_v(const fPin pin) {
	_fDigitalToggle_c(pin);
}

uint8_t _fDigitalRead_v(const fPin pin) {
	return _fDigitalRead_c(pin);
}


text:
#dvSeries {
  margin: 20px;
  padding: 20px;
}

#tblSeries {
  background-color: lightgray;
  font-size:18pt;
}

#dvTitle {
  margin: 20px;
  padding: 10px;
  background-color: green;
  color: white;
  font-size: 16pt
}

#dvError {
  display: none;
  color: white;
  background-color: red;
  margin: 20px;
  padding: 10px;
  font-size: 16pt;
  font-weight: bold;
}

#dvActions {
  margin: 20px;
  padding: 10px;
  background-color: black;
  font-weight: bolder;
  font-size: 16pt
}

#dvHeader {
  margin: 20px;
  padding: 20px;
  font-size: 14px;
  font-style: italic;
  text-transform: capitalize;
  color: white;
  background-color: black;
  font-size: 16pt
}

input.button {
  background-color: black;
  color: green
}

/* Hyperlinks */
a {
	color: green;
	text-decoration:none;
}

a:hover {
	color: darkgreen;
	text-decoration:none
}

a:visited {
	color: green;
	text-decoration:none
}

/* Buttons */
.styled-button {
	background:#5CCD00;
	background:-moz-linear-gradient(top,#5CCD00 0%,#4AA400 100%);
	background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#5CCD00),color-stop(100%,#4AA400));
	background:-webkit-linear-gradient(top,#5CCD00 0%,#4AA400 100%);
	background:-o-linear-gradient(top,#5CCD00 0%,#4AA400 100%);
	background:-ms-linear-gradient(top,#5CCD00 0%,#4AA400 100%);
	background:linear-gradient(top,#5CCD00 0%,#4AA400 100%);
	filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#5CCD00', endColorstr='#4AA400',GradientType=0);
	padding:10px 15px;
	color:#fff;
	font-family:'Helvetica Neue',sans-serif;
	font-size:16px;
	border-radius:5px;
	-moz-border-radius:5px;
	-webkit-border-radius:5px;
	border:1px solid #459A00
}

redpajama_set_name: RedPajamaGithub


text:
import decode from 'jwt-decode'

export default {
  user (state) {
    try {
      return decode(state.token)
    } catch (e) {
      return {}
    }
  }
}


text:
module.exports = copy

var slice = [].slice

function copy(source, target, target_start, source_start, source_end) {
  target_start = arguments.length < 3 ? 0 : target_start
  source_start = arguments.length < 4 ? 0 : source_start
  source_end = arguments.length < 5 ? source.length : source_end

  if(source_end === source_start) {
    return
  }

  if(target.length === 0 || source.length === 0) {
    return
  }

  if(source_end > source.length) {
    source_end = source.length
  }

  if(target.length - target_start < source_end - source_start) {
    source_end = target.length - target_start + start
  }

  if(source.buffer !== target.buffer) {
    return fast_copy(source, target, target_start, source_start, source_end)
  }
  return slow_copy(source, target, target_start, source_start, source_end)
}

function fast_copy(source, target, target_start, source_start, source_end) {
  var len = (source_end - source_start) + target_start

  for(var i = target_start, j = source_start;
      i < len;
      ++i,
      ++j) {
    target[i] = source[j]
  }
}

function slow_copy(from, to, j, i, jend) {
  // the buffers could overlap.
  var iend = jend + i
    , tmp = new Uint8Array(slice.call(from, i, iend))
    , x = 0

  for(; i < iend; ++i, ++x) {
    to[j++] = tmp[x]
  }
}


text:
package antlr;

/* ANTLR Translator Generator
 * Project led by Terence Parr at http://www.jGuru.com
 * Software rights: http://www.antlr.org/license.html
 *
 * $Id: //depot/code/org.antlr/release/antlr-2.7.5/antlr/TokenStreamRecognitionException.java#1 $
 */

/**
 * Wraps a RecognitionException in a TokenStreamException so you
 * can pass it along.
 */
public class TokenStreamRecognitionException extends TokenStreamException {
    public RecognitionException recog;

    public TokenStreamRecognitionException(RecognitionException re) {
        super(re.getMessage());
        this.recog = re;
    }

    public String toString() {
        return recog.toString();
    }
}


text:
export * from './app.component';
export * from './app.service';
export * from './app.routes';

import { AppState } from './app.service';
import {Http, HTTP_PROVIDERS} from '@angular/http';

// Application wide providers
export const APP_PROVIDERS = [
  AppState,
  Http,
  HTTP_PROVIDERS
];


text:
class PaymentMethod
  belongs_to :subscription
end


text:
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />

		<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
		<title>trivial space - experiments - area light</title>

		<style media="screen">
			body,
			html {
				margin: 0;
				padding: 0;
				width: 100%;
				height: 100%;
			}

			canvas {
				width: 800px;
				height: 800px;
			}
		</style>
	</head>

	<body>
		<canvas id="canvas"></canvas>
		<script src="./index.ts" type="module" charset="utf-8"></script>
	</body>
</html>


text:
using System;

namespace TestStack.BDDfy.Configuration
{
    public class TestRunnerFactory : ProcessorFactory
    {
        internal TestRunnerFactory(Func<IProcessor> factory) : base(factory)
        {
            StopExecutionOnFailingThen = false;
        }

        internal TestRunnerFactory(Func<IProcessor> factory, bool active) : base(factory, active)
        {
            StopExecutionOnFailingThen = false;
        }

        /// <summary>
        /// Set to true if you want the execution pipleline to stop when a Then step fails. Defaulted to false
        /// </summary>
        public bool StopExecutionOnFailingThen { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Xaml
{
    /// <summary>
    /// Примитивные типы, такие как строки, целые числа, - могут быть заданы в XAML
    /// отдельным тегом. Но так как у примитивов нет свойств и Content-свойства тем более,
    /// то для удобства написания парсера задание таких примитивов производится через обёртки.
    /// Класс-обёртка имеет свойство соответствующего примитивного типа, пользователь задаёт его
    /// в XAML, а при обработке парсер видит, что это именно IFactory-объект, и вместо самого
    /// объекта подставляет результат вызова метода GetObject(). В результате в родительский объект
    /// приходит значение примитива, которое можно задавать различными способами (в том числе
    /// и с использованием расширений разметки).
    /// </summary>
    public interface IFactory
    {
        object GetObject( );
    }

    /// <summary>
    /// Available in XAML markup as "string", "int", "double",
    /// "float", "char", "bool" elements.
    /// </summary>
    class Primitive<T> : IFactory
    {
        public T Content { get; set; }

        public object GetObject( ) {
            return Content;
        }
    }

    /// <summary>
    /// Allows to construct an object of a specified type, with specified constructor
    /// arguments and properties values. In XAML it can be used with convenient alias "object".
    /// You can read documentation to find usage examples.
    /// </summary>
    [ContentProperty("ParametersAndProperties")]
    class ObjectFactory : IFactory
    {
        /// <summary>
        /// Full type name, with generics allowed like this:
        /// System.Collections.Generic.Dictionary`2[System.String,MyType]
        /// View Type.GetType(string name) method documentation to find syntax examples.
        /// </summary>
        public String TypeName { get; set; }

        private readonly Dictionary<String,Object> parametersAndProperties = new Dictionary< string, object >();

        public Dictionary<String, Object> ParametersAndProperties { get { return parametersAndProperties; } }

        private struct CtorArg
        {
            public int index;
            public Object obj;
        }

        public object GetObject( ) {
            if (string.IsNullOrEmpty( TypeName ))
                throw new InvalidOperationException("TypeName is not specified.");

            Type type = Type.GetType( TypeName );
            if (null == type) throw new TypeLoadException(string.Format(
                "Type {0} not found. Try to use assembly-qualified type name.",
                TypeName));

            // Construct object accoring to passed ctor arguments
            List< CtorArg > ctorArgs = new List< CtorArg >( );
            foreach ( var pair in parametersAndProperties ) {
                string name = pair.Key;
                int result;
                if ( int.TryParse( name, out result ) ) {
                    ctorArgs.Add( new CtorArg( )
                        {
                            index = result,
                            obj = pair.Value
                        } );
                }
            }

            // Using OrderBy instead List<T>.Sort() because the last one is unstable
            // and can reorder elements with equal keys
            ctorArgs = ctorArgs.OrderBy(arg => arg.index).ToList();

            ConstructorInfo[ ] constructors = type.GetConstructors( );
            ConstructorInfo ctorInfo = constructors.Single( ctor => ctor.GetParameters( ).Length == ctorArgs.Count );
            object createdObject = ctorInfo.Invoke( ctorArgs.Select( arg => arg.obj ).ToArray( ) );

            // Fill properties using XamlParser's default conversion rules
            foreach ( var pair in parametersAndProperties ) {
                string name = pair.Key;
                int result;
                if ( !int.TryParse( name, out result ) ) {
                    PropertyInfo propertyInfo = type.GetProperty( name );
                    object value = pair.Value;
                    if ( null != value ) {
                        object convertedValue = XamlParser.ConvertValueIfNeed( value.GetType( ),
                                                                               propertyInfo.PropertyType,
                                                                               value );
                        propertyInfo.SetValue( createdObject, convertedValue, null );
                    }
                }
            }

            return createdObject;
        }
    }
}


text:
import { h, computed } from 'vue'

import QIcon from '../icon/QIcon.js'

import { createComponent } from '../../utils/private/create.js'
import { hMergeSlot } from '../../utils/private/render.js'
import useRouterLink, { useRouterLinkProps } from '../../composables/private/use-router-link.js'

export default createComponent({
  name: 'QBreadcrumbsEl',

  props: {
    ...useRouterLinkProps,

    label: String,
    icon: String,

    tag: {
      type: String,
      default: 'span'
    }
  },

  emits: [ 'click' ],

  setup (props, { slots }) {
    const { linkTag, linkAttrs, linkClass, navigateOnClick } = useRouterLink()

    const data = computed(() => {
      return {
        class: 'q-breadcrumbs__el q-link '
          + 'flex inline items-center relative-position '
          + (props.disable !== true ? 'q-link--focusable' + linkClass.value : 'q-breadcrumbs__el--disable'),
        ...linkAttrs.value,
        onClick: navigateOnClick
      }
    })

    const iconClass = computed(() =>
      'q-breadcrumbs__el-icon'
      + (props.label !== void 0 ? ' q-breadcrumbs__el-icon--with-label' : '')
    )

    return () => {
      const child = []

      props.icon !== void 0 && child.push(
        h(QIcon, {
          class: iconClass.value,
          name: props.icon
        })
      )

      props.label !== void 0 && child.push(props.label)

      return h(
        linkTag.value,
        { ...data.value },
        hMergeSlot(slots.default, child)
      )
    }
  }
})


text:
package com.stratio.cassandra.examples.spark.utils

import com.stratio.cassandra.lucene.search.condition.builder.ConditionBuilder

object JavaConversions {

  import scala.language.implicitConversions

  implicit def conditionBuilder[K,V](cb: ConditionBuilder[_,_]): ConditionBuilder[Nothing,Nothing]  =
    cb.asInstanceOf[ConditionBuilder[Nothing,Nothing]]

}


text:
package rtrk.pnrs1.ra174_2014.taskmanager.TaskManagerMainScreen;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import java.io.FileDescriptor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rtrk.pnrs1.ra174_2014.taskmanager.ListAdapterStuff.ListData;
import rtrk.pnrs1.ra174_2014.taskmanager.R;

public class TaskReminderService extends Service{

    ReminderThread remThread = new ReminderThread();
    ArrayList<ListData> tasks = new ArrayList<>();
    private static final String TAG = "RemService";
    IBinder reminderBinder = new ReminderBinder();

    public TaskReminderService() {
    }

    public class ReminderBinder extends Binder {
        public TaskReminderService getService() {
            return TaskReminderService.this;
        }
    }

    @Override
    public void onCreate(){
        super.onCreate();
        remThread.start();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        remThread.interrupt();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Bundle bundle = intent.getExtras();
        tasks = ((ArrayList<ListData>) bundle.get("Task"));

        if(!tasks.isEmpty()){
            for(ListData t:tasks) {
                Log.d(TAG, "onBind: Task: " + t.toString());
            }

        } else {
            Log.d(TAG,"onBind: Tasks empty");
        }

        return reminderBinder;
    }

     class ReminderThread extends Thread {

         List<ListData> tasksWithReminder = new ArrayList<ListData>();
         Date currDate;
         String dateFormat = "dd/MM/yyyy";
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);

         public ReminderThread(){}

         @Override
         public synchronized void start(){
             super.start();
         }

         public void run(){
             if(!isInterrupted()){
                 currDate = new Date();

                 if(!tasks.isEmpty()) {
                     for (ListData t : tasks) {
                         Log.d(TAG, "NOTIFICATION THREAD RUN: Task: " + t.toString());
                                       }
                 } else {
                     Log.d(TAG, "NOTIFICATION THREAD RUN: Tasks empty");
                 }

                 while(true){
                     Log.d(TAG,"NOTIFICATION THREAD RUN: Checking tasks with reminders");

                     for(ListData t : tasks){
                         Date taskDate = new Date();
                         int hour = t.hour;
                         int minute = t.minute;
                         try {
                             taskDate = simpleDateFormat.parse(Integer.toString(t.day) +
                                     "/" + Integer.toString(t.month) + "/" + Integer.toString(t.year));
                         } catch (ParseException e) {
                             e.printStackTrace();
                         }

                         if(taskDate.getYear() == currDate.getYear()){
                             if(taskDate.getMonth() == currDate.getMonth()){
                                 if(taskDate.getDay() == currDate.getDay()){
                                     if(hour == currDate.getHours()){
                                         if(minute - currDate.getMinutes() <=15){
                                             if(t.reminder){
                                                 tasksWithReminder.add(t);
                                                 t.reminder = false;
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }

                     Log.d(TAG,"NOTIFICATION THREAD RUN, creating notifications");

                     for(ListData t: tasksWithReminder){
                         android.support.v4.app.NotificationCompat.Builder remBuilder =
                                 new NotificationCompat.Builder(TaskReminderService.this)
                                        .setContentTitle("Task Notification")
                                        .setContentText(t.taskName)
                                        .setSmallIcon(R.mipmap.ic_launcher);

                         Intent resultIntent = new Intent(TaskReminderService.this, StartScreen.class);
                         PendingIntent pendingIntent = PendingIntent.getActivity(
                                 TaskReminderService.this,
                                 0,
                                 resultIntent,
                                 PendingIntent.FLAG_UPDATE_CURRENT
                         );

                         remBuilder.setContentIntent(pendingIntent);

                         int reminderNotificationId = 001;
                         NotificationManager reminderNotifMan =
                                 (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                         reminderNotifMan.notify(reminderNotificationId,remBuilder.build());

                         tasksWithReminder.remove(t);
                     }

                     try {
                         Thread.sleep(1000);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }

             }
         }

     }
    public void updateTasks(ArrayList<ListData> t){

        tasks = new ArrayList<ListData>(t);
    }

}


text:
code: false
type: page
title: Clauses
description: Koncorde clauses list
order: 100
---

# Clauses

Filters in Koncorde are constituted of **clauses** and **operators**.

In this section, you will find an exhaustive listing of all the available clauses.

Clauses allow you to **express a predicate to apply on a data stream**.

One clause can **constitute a filter on its own** or be **combined with other clauses** in the same filters using the [operators](/core/2/api/koncorde-filters-syntax/operators).

## Testing Nested Fields

Examples described in this documentation show how to test for fields at the root of the provided data objects, but it is also possible to add filters on nested properties.

To do that, instead of giving the name of the property to test, its path must be supplied as follows: `path.to.property`

### Example

Given the following document:

```json
{
  "name": {
    "first": "Grace",
    "last": "Hopper"
  }
}
```

Here is a filter, testing for equality on the field `last` in the `name` object:

```json
{
  "equals": {
    "name.last": "Hopper"
  }
}
```

## Matching array values

A few keywords, like [exists](/core/2/api/koncorde-filters-syntax/clauses#exists) or [missing](/core/2/api/koncorde-filters-syntax/clauses#missing), allow searching for array values.

These values can be accessed with the following syntax: `<array path>[<value>]`
Only one array value per `exists`/`missing` keyword can be searched in this manner.

Array values must be scalar. Allowed types are `string`, `number`, `boolean` and the `null` value.

The array value must be provided using the JSON format:

- Strings: the value must be enclosed in double quotes. Example: `foo["string value"]`
- Numbers, booleans and `null` must be used as is. Examples: `foo[3.14]`, `foo[false]`, `foo[null]`

Array values can be combined with [nested properties](/core/2/api/koncorde-filters-syntax/clauses#testing-nested-fields): `nested.array["value"]`

### Example

Given the following document:

```json
{
  "name": {
    "first": "Grace",
    "last": "Hopper",
    "hobbies": ["compiler", "COBOL"]
  }
}
```

Here is a filter, testing whether the value `compiler` is listed in the array `hobbies`:

```js
{
    "exists": 'name.hobbies["compiler"]'
}
```

## `equals`

Matches attributes using strict equality.
The tested attribute must be a scalar (number, string or boolean), and of the same type than the provided filter value.

### Syntax

```
equals: {
  <field name>: <value>
}
```

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper'
},
{
  firstName: 'Ada',
  lastName: 'Lovelace'
}
```

The following filter validates the first document:

```js
{
  equals: {
    firstName: 'Grace';
  }
}
```

## `exists`

Test for the existence of a key in an object, or of a scalar in an array.

### Syntax

Since Koncorde 1.2, the `exists` syntax is as follows:

`exists: 'nested.field.path'`
(see [nested field syntax](/core/2/api/koncorde-filters-syntax/clauses#testing-nested-fields))

`exists: 'nested.array[value]'`
(see [array value syntax](/core/2/api/koncorde-filters-syntax/clauses#matching-array-values))

The following syntax is deprecated since Koncorde 1.2, and supported for backward compatibility only:

`exists: { field: 'nested.field.path' }`

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper',
  city: 'NYC',
  hobby: ['compiler', 'COBOL'],
  alive: false
},
{
  firstName: 'Ada',
  lastName: 'Lovelace',
  city: 'London',
  hobby: ['programming', 'algorithm']
}
```

The following filter validates the first document:

```js
{
  exists: 'alive';
}
```

And this filter validates the second document:

```js
{
  exists: 'hobby["algorithm"]';
}
```

## `geoBoundingBox`

Filter documents containing a geographical point confined within a bounding box:

![Illustration of geoBoundingBox](/geolocation/geoBoundingBox.png)

A bounding box is a 2D box that can be defined using either of the following formats:

- 2 [geopoints](/core/2/api/koncorde-filters-syntax/geo-space#geopoints), defining the top left (`topLeft` or `top_left`) and bottom right (`bottomRight` or `bottom_right`) corners of the box
- 4 distinct values defining the 4 box corners: `top` and `bottom` are latitudes, `left` and `right` are longitudes

The bounding box description must be stored in an attribute, named after the geographical point to be tested in future documents.

### Syntax

```
geoBoundingBox: {
  <geopoint field name>: {
    <bounding box description>
  }
}
```

### Bounding box description

All syntaxes below are accepted, as they describe the same bounding box, with the following properties:

- top-left corner of latitude `43.5810609` and longitude `3.8433703`
- bottom-right corner of latitude `43.6331979` and longitude `3.9282093`

```js
{
  point: {
    top: 43.5810609,
    left: 3.8433703,
    bottom: 43.6331979,
    right: 3.9282093
  }
}
```

```js
{
  point: {
    topLeft: { lat: 43.5810609, lon: 3.8433703 },
    bottomRight: { lat: 43.6331979, lon: 3.9282093 }
  }
}
```

```js
{
  point: {
    top_left: "43.5810609, 3.8433703",
    bottom_right: "43.6331979, 3.9282093"
  }
}
```

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper',
  location: {
    lat: 32.692742,
    lon: -97.114127
  }
},
{
  firstName: 'Ada',
  lastName: 'Lovelace',
  location: {
    lat: 51.519291,
    lon: -0.149817
  }
}
```

The following filter will match the second document only:

```js
{
  geoBoundingBox: {
    location: {
      top: -2.939744,
      left: 52.394484,
      bottom: 1.180129,
      right: 51.143628
    }
  }
}
```

## `geoDistanceRange`

Filter documents containing a geographical point, whose position is within a distance range from a given point of origin:

![Illustration of geoDistanceRange](/geolocation/geoDistanceRange.png)

A `geoDistanceRange` filter contains the following properties:

- a [geopoint](/core/2/api/koncorde-filters-syntax/geo-space) defining the center point of the distance range. This geopoint attribute must be named after the geographical point to test in future documents
- a `from` attribute, describing the minimum distance from the center point, using a [geodistance format](/core/2/api/koncorde-filters-syntax/geo-space#geodistances)
- a `to` attribute, describing the maximum distance from the center point, using a [geodistance format](/core/2/api/koncorde-filters-syntax/geo-space#geodistances)

### Syntax

```
geoDistanceRange: {
  <geopoint field name>: {
    <geopoint description>
  },
  from: <geodistance>,
  to: <geodistance>
}
```

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper',
  location: {
    lat: 32.692742,
    lon: -97.114127
  }
},
{
  firstName: 'Ada',
  lastName: 'Lovelace',
  location: {
    lat: 51.519291,
    lon: -0.149817
  }
}
```

The following filter will match the second document only:

```js
{
  geoDistanceRange: {
    location: [51.5029017, -0.1606903],
    from: '1km',
    to: '10 kilometers'
  }
}
```

## `geoDistance`

Filter documents containing a geographical point, whose position is within a distance radius centered around a provided point of origin:

![Illustration of geoDistance](/geolocation/geoDistance.png)

A `geoDistance` filter contains the following properties:

- a [geopoint](/core/2/api/koncorde-filters-syntax/geo-space#geopoints) defining the point of origin. This geopoint attribute must be named after the geographical point to test in future documents
- a `distance` parameter in [geodistance format](/core/2/api/koncorde-filters-syntax/geo-space#geodistances)

### Syntax

```
geoDistance: {
  <geopoint field name>: {
    <geopoint description>
  },
  distance: <geodistance>
}
```

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper',
  location: {
    lat: 32.692742,
    lon: -97.114127
  }
},
{
  firstName: 'Ada',
  lastName: 'Lovelace',
  location: {
    lat: 51.519291,
    lon: -0.149817
  }
}
```

The following filter will match the second document only:

```js
{
  geoDistance: {
    location: {
      lat: 51.5029017,
      lon: -0.1606903
    },
    distance: '10km'
  }
}
```

## `geoPolygon`

Filter documents containing a geographical point, confined within a polygon that has an arbitrary number of sides:

![Illustration of geoPolygon](/geolocation/geoPolygon.png)

A `geoPolygon` filter is described using a `points` array, containing an arbitrary number of [geopoints](/core/2/api/koncorde-filters-syntax/geo-space#geopoints) (at least 3).

Koncorde automatically closes geopolygons.

Different geopoint formats can be used to describe different corners of a polygon.

### Syntax

```
geoPolygon: {
  <geopoint field name>: {
    points: <geopoints array>
  }
}
```

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper',
  location: {
    lat: 32.692742,
    lon: -97.114127
  }
},
{
  firstName: 'Ada',
  lastName: 'Lovelace',
  location: {record
    lat: 51.519291,
    lon: -0.149817
  }
}
```

The following filter will match the second document only:

```js
{
  geoPolygon: {
    location: {
      points: [
        { lat: 51.523029, lon: -0.160793 },
        [51.522842, -0.145043],
        '51.518303, -0.146116',
        { latLon: { lat: 51.516487, lon: -0.162295 } },
        'gcpvh6uxh60x1'
      ];
    }
  }
}
```

## `ids`

This filter returns only documents having their unique document ID listed in the provided list.

### Syntax

`ids: <array of strings>`

### Example

Given the following documents:

```js
{
  _id: 'a',
  firstName: 'Grace',
  lastName: 'Hopper'
},
{
  _id: 'b',
  firstName: 'Ada',
  lastName: 'Lovelace'
},
{
  _id: 'c',
  firstName: 'Marie',
  lastName: 'Curie'
}
```

The following filter validates first document:

```js
{
  ids: {
    values: ['a'];
  }
}
```

## `in`

Like [equals](#equals), but accepts an array of possible scalar values to be tested.

#### Syntax

`in: { <field name>: <array of values> }`

#### Example

Given the following documents:

```javascript
{
  firstName: 'Grace',
  lastName: 'Hopper'
},
{
  firstName: 'Ada',
  lastName: 'Lovelace'
},
{
  firstName: 'Marie',
  lastName: 'Curie'
}
```

The following filter validates the first two documents:

```javascript
{
  in: { firstName: ['Grace', 'Ada'] }
}
```

## `missing`

A filter matching documents either with a missing field in an object, or with a missing value in an array.

A `missing` filter used to match arrays without a specific value will also match if:

- the tested array property is entirely missing from the provided document
- the tested property in the provided document is not an array

### Syntax

Since Koncorde 1.2, the `missing` syntax is as follows:

`missing: 'nested.field.path'`
(see [nested field syntax](/core/2/api/koncorde-filters-syntax/clauses#testing-nested-fields))

`missing: 'nested.array[value]'`
(see [array value syntax](/core/2/api/koncorde-filters-syntax/clauses#matching-array-values)

The following syntax is deprecated since Koncorde 1.2, and supported for backward compatibility only:

`missing: { field: 'nested.field.path' }`

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper',
  city: 'NYC',
  hobbies: ['compiler', 'COBOL'],
  alive: false
},
{
  firstName: 'Ada',
  lastName: 'Lovelace',
  city: 'London',
  hobbies: ['algorithm', 'programming'],
}
```

The following filter validates the second document:

```js
{
  missing: 'alive';
}
```

And this filter validates the first document:

```js
{
  missing: 'hobbies["algorithm"]';
}
```

## `range`

Filters documents with number attributes within a provided interval.

A range can be defined with at least one of the following arguments:

- `gte`: Greater-than or equal to `<number>`
- `gt`: Greater-than `<number>`
- `lte`: Less-than or equal to
- `lt`: Less-than

Ranges can be either bounded or half-bounded.

### Syntax

```
range: {
  <field to be tested>: {
    [gte]: <number>,
    [gt]: <number>,
    [lte]: <number>,
    [lt]: <number>
  }
}
```

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper',
  age: 85,
  city: 'NYC',
  hobby: 'computer'
},
{
  firstName: 'Ada',
  lastName: 'Lovelace',
  age: 36
  city: 'London',
  hobby: 'computer'
},
{
  firstName: 'Marie',
  lastName: 'Curie',
  age: 55,
  city: 'Paris',
  hobby: 'radium'
}
```

The following filter validates the last two documents:

```js
{
  range: {
    age: {
      lt: 85;
    }
  }
}
```

## `regexp`

The `regexp` filter matches attributes using [PCREs](https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions).

### Syntax

A `regexp` filter has the following structure, splitting the usual `/pattern/flags` into two parts:

```js
regexp: {
  <field name>: {
    value: '<search pattern>',
    flags: '<modifier flags>'
  }
}
```

If you don't need any modifier flag, then you may also use the following simplified form:

```js
  regexp: {
    <field name>: '<search pattern>'
  }
```

### Example

Given the following documents:

```js
{
  firstName: 'Grace',
  lastName: 'Hopper'
},
{
  firstName: 'Ada',
  lastName: 'Lovelace'
}
```

The following filter validates the first document:

```js
{
  regexp: {
    firstName: {
      value: '^g\w+',
      flags: 'i'
    }
  }
}
```


text:
package com.stickercamera.app.camera.util;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.view.Surface;

import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.GINGERBREAD;

public class CameraHelper {
    private final CameraHelperImpl mImpl;

    public CameraHelper(final Context context) {
        if (SDK_INT >= GINGERBREAD) {
            mImpl = new CameraHelperGB();
        } else {
            mImpl = new CameraHelperBase(context);
        }
    }

    public interface CameraHelperImpl {
        int getNumberOfCameras();

        Camera openCamera(int id);

        Camera openDefaultCamera();

        Camera openCameraFacing(int facing);

        boolean hasCamera(int cameraFacingFront);

        void getCameraInfo(int cameraId, CameraInfo2 cameraInfo);
    }

    public int getNumberOfCameras() {
        return mImpl.getNumberOfCameras();
    }

    public Camera openCamera(final int id) {
        return mImpl.openCamera(id);
    }

    public Camera openDefaultCamera() {
        return mImpl.openDefaultCamera();
    }

    public Camera openFrontCamera() {
        return mImpl.openCameraFacing(CameraInfo.CAMERA_FACING_FRONT);
    }

    public Camera openBackCamera() {
        return mImpl.openCameraFacing(CameraInfo.CAMERA_FACING_BACK);
    }

    public boolean hasFrontCamera() {
        return mImpl.hasCamera(CameraInfo.CAMERA_FACING_FRONT);
    }

    public boolean hasBackCamera() {
        return mImpl.hasCamera(CameraInfo.CAMERA_FACING_BACK);
    }

    public void getCameraInfo(final int cameraId, final CameraInfo2 cameraInfo) {
        mImpl.getCameraInfo(cameraId, cameraInfo);
    }

    public void setCameraDisplayOrientation(final Activity activity, final int cameraId,
                                            final Camera camera) {
        int result = getCameraDisplayOrientation(activity, cameraId);
        camera.setDisplayOrientation(result);
    }

    public int getCameraDisplayOrientation(final Activity activity, final int cameraId) {
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        CameraInfo2 info = new CameraInfo2();
        getCameraInfo(cameraId, info);
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
        } else { // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        return result;
    }

    public static class CameraInfo2 {
        public int facing;
        public int orientation;
    }
}


text:
@interface PodsDummy_Pods_Facebook_iOS_SDK_RACExtensions_Bolts : NSObject
@end
@implementation PodsDummy_Pods_Facebook_iOS_SDK_RACExtensions_Bolts
@end


text:
layout: post
title:  "Using Cognitect's aws-api with AWS Transcribe"
date:   2019-02-24 00:00:00
tags:   clojure aws api aws-api transcribe
---

Using Cognitect's [aws-api](https://github.com/cognitect-labs/aws-api) library to work with AWS is nice and easy (and simple). This post shows how to use it with [AWS Transcribe](https://aws.amazon.com/transcribe/) for speech-to-text.

>aws-api is an idiomatic, data-oriented Clojure library for invoking AWS APIs.

## Comparisons

Previously I'd used [Amazonica](https://github.com/mcohen01/amazonica) for working with general AWS services, or more focused libraries like [Faraday](https://github.com/ptaoussanis/faraday) for working with DynamoDB. Amazonica takes a conceptually similar approach to aws-api in that its code is (mostly) generated by reflecting on AWS-published API specs. Faraday wraps Dynamo's API in an idiomatic Clojure API, with some other niceties e.g. serializing Clojure data to/from Dynamo JSON.

Compared to these projects, aws-api's approach has some key similarities and differences:
- The majority of **Amazonica** and **aws-api**'s API surface is _derived_ from AWS API definitions.
- **Amazonica** and **Faraday** depend directly on AWS SDK libraries, but **aws-api** takes a "clean room" approach by calling AWS API endpoints directly — no AWS SDK dependencies.
- **Faraday** provides a very Clojure-y wrapper for AWS Dynamo SDK. **Amazonica** provides generated (and bespoke) wrappers for AWS APIs that look/feel like idiomatic Clojure. **aws-api** takes a very data-centric approach, providing _one function_ to invoke any AWS API operation.

I like that aws-api requires no transitive dependencies on AWS SDK. (No more transitive Jackson conflicts!) It has [relatively few dependencies](https://github.com/cognitect-labs/aws-api/blob/master/deps.edn) overall.

It's _extremely_ data-centric and doesn't attempt to obscure the nature of data in AWS API requests/responses behind a Clojure-y façade. Considering it as a fairly mechanical translation of AWS API specs, it's very much data-as-code.

The `:TitleCase` keywords were a little jarring at first but I came to appreciate only needing to reference the AWS API docs, as opposed to understanding both the AWS API _and_ a bespoke Clojure wrapper. For example, I'd often need to reference Faraday's source to see how its custom data shapes mapped to their Dynamo request/response counterparts, because they were often different for the sake of idiomacy (is this a word 🤷♂).

Because it's so data-centric, it's trivial to enumerate all types of operations you can perform against each AWS service, along with their inputs and outputs. This makes it a very REPL-friendly tool.

## API Interactions

First, we need to authenticate ourselves. The default provider covers most use cases:
```clojure
(require '[cognitect.aws.credentials :as creds])
(def credentials
  (creds/default-credentials-provider))
```
If you've used AWS API you're probably familiar with the concept of the default credentials provider chain, and maybe (or unfortunately) its order of precedence.
Something I found very useful was the ability to create a custom credential provider chain (which I'd done with much less elegance before aws-api). Here I defined a single, chained provider that works locally and when deployed to EC2 or ECS:
```clojure
(def credentials
  (creds/chain-credentials-provider
    [(creds/instance-profile-credentials-provider)
     (creds/container-credentials-provider)
     (creds/profile-credentials-provider "my-custom-profile")]))
```

The next thing we'll need is a client to our AWS API, in this case Transcribe:
```clojure
(require '[cognitect.aws.client.api :as aws])
(def transcribe
  (aws/client {:api :transcribe
               :region :us-east-1
               :credentials-provider credentials}))
```

Because aws-api is so data-centric, there's only one function for interacting with the API: `invoke`. Everything else is data. If you want to see all operations for an API, you can use the `ops` function.
```clojure
(aws/ops transcribe)
=>
{...
 :DeleteVocabulary {:name "DeleteVocabulary",
                    :documentation "<p>Deletes a vocabulary from Amazon Transcribe. </p>",
                    :request {:VocabularyName string},
                    :required [:VocabularyName],
                    :response nil}
 ...}
```
You can then pick/filter those results and get detailed documentation for each with the `doc` function. This tells us what the operation does, what inputs it requires, and what we can expect in the response. We can print docs for each of these operations in the REPL:
```clojure
(aws/doc transcribe :StartTranscriptionJob)
-------------------------
StartTranscriptionJob

<p>Starts an asynchronous job to transcribe speech to text. </p>

-------------------------
Request

{:TranscriptionJobName string,
 :LanguageCode string,
 :MediaSampleRateHertz integer,
 :MediaFormat string,
 :Media {:MediaFileUri string},
 :OutputBucketName string,
 :Settings
 {:VocabularyName string,
  :ShowSpeakerLabels boolean,
  :MaxSpeakerLabels integer,
  :ChannelIdentification boolean}}

Required

[:TranscriptionJobName :LanguageCode :MediaFormat :Media]

-------------------------
Response

{:TranscriptionJob
 {:MediaFormat string,
  :CompletionTime timestamp,
  :MediaSampleRateHertz integer,
  :TranscriptionJobName string,
  :Settings
  {:VocabularyName string,
   :ShowSpeakerLabels boolean,
   :MaxSpeakerLabels integer,
   :ChannelIdentification boolean},
  :CreationTime timestamp,
  :Transcript {:TranscriptFileUri string},
  :TranscriptionJobStatus string,
  :FailureReason string,
  :LanguageCode string,
  :Media {:MediaFileUri string}}}
```

Invocation is easy, because the `:op` and `:request` values are easily interpretable from the output of the `ops` or `doc` functions:
```clojure
(aws/invoke
  transcribe                        ;; the client
  {:op :StartTranscriptionJob       ;; the operation
   :request                         ;; the operation input
   {:TranscriptionJobName job-name
    :LanguageCode         "en-US"
    :MediaFormat          "wav"
    :Media                {:MediaFileUri s3-path}}})
```

## Doing Things

I needed to transcribe some speech to text, and of course AWS has a service for that called Transcribe. It's not very fast but it's cheap and fairly easy to use. You can put your audio in a S3 bucket and request a transcription. Unfortunately you have to poll (or use SNS + Lambda?) for the resulting transcription, which will also go into a S3 bucket.

We can create a transcription job:
```clojure
(defn start-transcribe [s3-path job-name]
  (aws/invoke
    transcribe
    {:op :StartTranscriptionJob
     :request
     {:TranscriptionJobName job-name
      :LanguageCode         "en-US"
      :MediaFormat          "wav"
      :Media                {:MediaFileUri s3-path}
      ;; NOTE output bucket is optional
      ;; AWS otherwise puts the transcript in a random bucket
      :OutputBucketName     "my-unique-bucket"}}))

(start-transcribe
 "https://s3.us-east-1.amazonaws.com/my-unique-bucket/sample.wav"
 "my-random-job-name")
=>
{:TranscriptionJob {:MediaFormat "wav",
                    :TranscriptionJobName "my-random-job-name",
                    :CreationTime #inst"2019-02-25T12:51:45.000-00:00",
                    :TranscriptionJobStatus "IN_PROGRESS",
                    :LanguageCode "en-US",
                    :Media {:MediaFileUri "https://s3.us-east-1.amazonaws.com/my-unique-bucket/sample.wav"}}}
```

But this only tells us the job is in progress, and we must wait for it to complete. I define another simple helper function to get the details of a job:
```clojure
(defn get-transcribe-job [job-name]
  (aws/invoke transcribe
              {:op      :GetTranscriptionJob
               :request {:TranscriptionJobName job-name}}))

(get-transcribe-job "my-random-job-name")
=>
{:TranscriptionJob {:MediaFormat "wav",
                    :MediaSampleRateHertz 8000,
                    :TranscriptionJobName "my-random-job-name",
                    :Settings {:ChannelIdentification false},
                    :CreationTime #inst"2019-02-25T13:08:06.000-00:00",
                    :Transcript {},
                    :TranscriptionJobStatus "IN_PROGRESS",
                    :LanguageCode "en-US",
                    :Media {:MediaFileUri "https://s3.us-east-1.amazonaws.com/my-unique-bucket/sample.wav"}}}
```
We can see it's still in progress, but when it's finished it will contain a path to the transcript JSON in S3. I use a simple function to read the JSON from S3:
```clojure
(defn read-file [bucket key]
  (-> (aws/invoke s3 {:op :GetObject, :request {:Bucket bucket :Key key}})
      (:Body)
      (slurp)))
```
And finally, a convenience function to poll for the results of a given job:
```clojure
(defn await-transcription [job-name]
  (loop [job (get-transcribe-job job-name)]
    (case (get-in job [:TranscriptionJob :TranscriptionJobStatus])
      "IN_PROGRESS"
      (do (Thread/sleep 5000) ;; I have no shame
          (recur (get-transcribe-job job-name)))

      "COMPLETED"
      (-> (read-file "my-unique-bucket" (str job-name ".json"))
          (json/read-str) ;; clojure.data.json
          (get-in ["results" "transcripts" 0 "transcript"]))

      (throw (ex-info "Transcribe failed" job)))))

(await-transcription "my-random-job-name") ;; spins for ~1 minute
=> "Bravo, November Papa Romeo, Oscar."    ;; sample.wav contained an audio captcha
```

I was impressed with how easy it was to interact with an AWS API I'd never used before via aws-api. Everything I needed was right there in the REPL with a handful of functions: `client`, `ops`, and `invoke`. The immediacy and transparency of working with AWS via aws-api makes for a great Clojure experience.


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CalculationServices;
using System.Windows.Forms; // key

namespace UnitTest_Parser
{
    [TestClass]
    public class UnitTestToken
    {
        [TestMethod]
        public void TestMethod_isOperator()
        {
            Assert.AreEqual(true, Token.isOperator('+'));
            Assert.AreEqual(true, Token.isOperator('-'));
            Assert.AreEqual(true, Token.isOperator('*'));
            Assert.AreEqual(true, Token.isOperator('/'));
        }
        [TestMethod]
        public void TestMethod_isParenthesis()
        {
            Assert.AreEqual(true, Token.isParenthesis('('));
            Assert.AreEqual(true, Token.isParenthesis(')'));
        }
        [TestMethod]
        public void TestMethod_isNumber()
        {
            Assert.AreEqual(true, Token.isNumber('0'));
            Assert.AreEqual(true, Token.isNumber('1'));
            Assert.AreEqual(true, Token.isNumber('2'));
            Assert.AreEqual(true, Token.isNumber('3'));
            Assert.AreEqual(true, Token.isNumber('4'));
            Assert.AreEqual(true, Token.isNumber('5'));
            Assert.AreEqual(true, Token.isNumber('6'));
            Assert.AreEqual(true, Token.isNumber('7'));
            Assert.AreEqual(true, Token.isNumber('8'));
            Assert.AreEqual(true, Token.isNumber('9'));
            Assert.AreEqual(false, Token.isNumber('a'));
            Assert.AreEqual(false, Token.isNumber('b'));
            Assert.AreEqual(false, Token.isNumber('c'));
            Assert.AreEqual(false, Token.isNumber('d'));
            Assert.AreEqual(false, Token.isNumber('e'));
            Assert.AreEqual(false, Token.isNumber('f'));
        }
        [TestMethod]
        public void TestMethod_isMinusSign()
        {
            Assert.AreEqual(true, Token.isMinusSign('-'));
            Assert.AreEqual(false, Token.isMinusSign('+'));
        }
        [TestMethod]
        public void TestMethod_isEqual()
        {
            Assert.AreEqual(true, Token.isEqual('='));
        }
        [TestMethod]
        public void TestMethod_isBackSpace()
        {
            Assert.AreEqual(true, Token.isBackSpace((char)Keys.Back));
        }
        [TestMethod]
        public void TestMethod_isToken()
        {
            char[] tokens = new char[]{
                '0','1','2','3','4','5','6','7','8','9',
                '+','-','*','/',
                '(',')',
            };
            foreach(var v in tokens)
            {
                Assert.AreEqual(true,Token.isToken(v));
            }
            Assert.AreEqual(false, Token.isToken('='));
        }

    }
}


text:
1. Output exe file in separate folder
2. Show how to install different output to destnation

```
cmake -DCMAKE_INSTALL_PREFIX=/tmp/usr ..
make
make install
```


text:
package com.google.cloud.run.v2.samples;

// [START run_v2_generated_Revisions_ListRevisions_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.run.v2.ListRevisionsRequest;
import com.google.cloud.run.v2.Revision;
import com.google.cloud.run.v2.RevisionsClient;
import com.google.cloud.run.v2.ServiceName;

public class AsyncListRevisions {

  public static void main(String[] args) throws Exception {
    asyncListRevisions();
  }

  public static void asyncListRevisions() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RevisionsClient revisionsClient = RevisionsClient.create()) {
      ListRevisionsRequest request =
          ListRevisionsRequest.newBuilder()
              .setParent(ServiceName.of("[PROJECT]", "[LOCATION]", "[SERVICE]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .setShowDeleted(true)
              .build();
      ApiFuture<Revision> future = revisionsClient.listRevisionsPagedCallable().futureCall(request);
      // Do something.
      for (Revision element : future.get().iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END run_v2_generated_Revisions_ListRevisions_async]


text:
namespace samp_sdk
{

#ifndef AMX_H_INCLUDED
#define AMX_H_INCLUDED

#if defined __linux || defined __linux__
#define __LINUX__
#endif
#if defined FREEBSD && !defined __FreeBSD__
#define __FreeBSD__
#endif
#if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__
#include "sclinux.h"
#endif

#if defined HAVE_STDINT_H
  #include <stdint.h>
#else
  #if defined __LCC__ || defined __DMC__ || defined __LINUX__ || (defined __WATCOMC__ && __WATCOMC__ >= 1200)
    #if defined HAVE_INTTYPES_H
      #include <inttypes.h>
    #else
      #include <stdint.h>
    #endif
  #elif !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L
    /* The ISO C99 defines the int16_t and int_32t types. If the compiler got
     * here, these types are probably undefined.
     */
    #if defined __MACH__
      #include <ppc/types.h>
      typedef unsigned short int  uint16_t;
      typedef unsigned long int   uint32_t;
    #elif defined __FreeBSD__
      #include <inttypes.h>
    #else
      typedef short int           int16_t;
      typedef unsigned short int  uint16_t;
      #if defined SN_TARGET_PS2
        typedef int               int32_t;
        typedef unsigned int      uint32_t;
      #else
        typedef long int          int32_t;
        typedef unsigned long int uint32_t;
      #endif
      #if defined __WIN32__ || defined _WIN32 || defined WIN32
        typedef __int64	          int64_t;
        typedef unsigned __int64  uint64_t;
        #define HAVE_I64
      #elif defined __GNUC__
        typedef long long         int64_t;
        typedef unsigned long long uint64_t;
        #define HAVE_I64
      #endif
    #endif
  #endif
  #define HAVE_STDINT_H
#endif
#if defined _LP64 || defined WIN64 || defined _WIN64
  #if !defined __64BIT__
    #define __64BIT__
  #endif
#endif

#if HAVE_ALLOCA_H
  #include <alloca.h>
#endif
/*#if defined __WIN32__ || defined _WIN32 || defined WIN32
  #if !defined alloca
    #define xalloca(n)   _alloca(n)
  #endif
#endif*/

#if !defined arraysize
  #define arraysize(array)  (sizeof(array) / sizeof((array)[0]))
#endif

#ifdef  __cplusplus
extern  "C" {
#endif

#if defined PAWN_DLL
  #if !defined AMX_NATIVE_CALL
    #define AMX_NATIVE_CALL __stdcall
  #endif
  #if !defined AMXAPI
    #define AMXAPI          __stdcall
  #endif
#endif

/* calling convention for native functions */
#if !defined AMX_NATIVE_CALL
  #define AMX_NATIVE_CALL
#endif
/* calling convention for all interface functions and callback functions */
#if !defined AMXAPI
  #if defined STDECL
    #define AMXAPI      __stdcall
  #elif defined CDECL
    #define AMXAPI      __cdecl
  #elif defined GCC_HASCLASSVISIBILITY
    #define AMXAPI __attribute__ ((visibility("default")))
  #else
    #define AMXAPI
  #endif
#endif
#if !defined AMXEXPORT
  #define AMXEXPORT
#endif

/* File format version                          Required AMX version
 *   0 (original version)                       0
 *   1 (opcodes JUMP.pri, SWITCH and CASETBL)   1
 *   2 (compressed files)                       2
 *   3 (public variables)                       2
 *   4 (opcodes SWAP.pri/alt and PUSHADDR)      4
 *   5 (tagnames table)                         4
 *   6 (reformatted header)                     6
 *   7 (name table, opcodes SYMTAG & SYSREQ.D)  7
 *   8 (opcode STMT, renewed debug interface)   8
 */
#define CUR_FILE_VERSION  8     /* current file version; also the current AMX version */
#define MIN_FILE_VERSION  6     /* lowest supported file format version for the current AMX version */
#define MIN_AMX_VERSION   8     /* minimum AMX version needed to support the current file format */

#if !defined PAWN_CELL_SIZE
  #define PAWN_CELL_SIZE 32     /* by default, use 32-bit cells */
#endif
#if PAWN_CELL_SIZE==16
  typedef uint16_t  ucell;
  typedef int16_t   cell;
#elif PAWN_CELL_SIZE==32
  typedef uint32_t  ucell;
  typedef int32_t   cell;
#elif PAWN_CELL_SIZE==64
  typedef uint64_t  ucell;
  typedef int64_t   cell;
#else
  #error Unsupported cell size (PAWN_CELL_SIZE)
#endif

#define UNPACKEDMAX   ((1L << (sizeof(cell)-1)*8) - 1)
#define UNLIMITED     (~1u >> 1)

struct tagAMX;
typedef cell (AMX_NATIVE_CALL *AMX_NATIVE)(struct tagAMX *amx, cell *params);
typedef int (AMXAPI *AMX_CALLBACK)(struct tagAMX *amx, cell index,
                                   cell *result, cell *params);
typedef int (AMXAPI *AMX_DEBUG)(struct tagAMX *amx);
#if !defined _FAR
  #define _FAR
#endif

#if defined _MSC_VER
  #pragma warning(disable:4103)  /* disable warning message 4103 that complains
                                  * about pragma pack in a header file */
  #pragma warning(disable:4100)  /* "'%$S' : unreferenced formal parameter" */
#endif

/* Some compilers do not support the #pragma align, which should be fine. Some
 * compilers give a warning on unknown #pragmas, which is not so fine...
 */
#if (defined SN_TARGET_PS2 || defined __GNUC__) && !defined AMX_NO_ALIGN
  #define AMX_NO_ALIGN
#endif

#if defined __GNUC__
  #define PACKED        __attribute__((packed))
#else
  #define PACKED
#endif

#if !defined AMX_NO_ALIGN
  #if defined __LINUX__ || defined __FreeBSD__
    #pragma pack(1)         /* structures must be packed (byte-aligned) */
  #elif defined MACOS && defined __MWERKS__
	#pragma options align=mac68k
  #else
    #pragma pack(push)
    #pragma pack(1)         /* structures must be packed (byte-aligned) */
    #if defined __TURBOC__
      #pragma option -a-    /* "pack" pragma for older Borland compilers */
    #endif
  #endif
#endif

typedef struct tagAMX_NATIVE_INFO {
  const char _FAR *name PACKED;
  AMX_NATIVE func       PACKED;
} PACKED AMX_NATIVE_INFO;

#define AMX_USERNUM     4
#define sEXPMAX         19      /* maximum name length for file version <= 6 */
#define sNAMEMAX        31      /* maximum name length of symbol name */

typedef struct tagAMX_FUNCSTUB {
  ucell address         PACKED;
  char name[sEXPMAX+1];
} PACKED AMX_FUNCSTUB;

typedef struct tagFUNCSTUBNT {
  ucell address         PACKED;
  uint32_t nameofs      PACKED;
} PACKED AMX_FUNCSTUBNT;

/* The AMX structure is the internal structure for many functions. Not all
 * fields are valid at all times; many fields are cached in local variables.
 */
typedef struct tagAMX {
  unsigned char _FAR *base PACKED; /* points to the AMX header plus the code, optionally also the data */
  unsigned char _FAR *data PACKED; /* points to separate data+stack+heap, may be NULL */
  AMX_CALLBACK callback PACKED;
  AMX_DEBUG debug       PACKED; /* debug callback */
  /* for external functions a few registers must be accessible from the outside */
  cell cip              PACKED; /* instruction pointer: relative to base + amxhdr->cod */
  cell frm              PACKED; /* stack frame base: relative to base + amxhdr->dat */
  cell hea              PACKED; /* top of the heap: relative to base + amxhdr->dat */
  cell hlw              PACKED; /* bottom of the heap: relative to base + amxhdr->dat */
  cell stk              PACKED; /* stack pointer: relative to base + amxhdr->dat */
  cell stp              PACKED; /* top of the stack: relative to base + amxhdr->dat */
  int flags             PACKED; /* current status, see amx_Flags() */
  /* user data */
  long usertags[AMX_USERNUM] PACKED;
  void _FAR *userdata[AMX_USERNUM] PACKED;
  /* native functions can raise an error */
  int error             PACKED;
  /* passing parameters requires a "count" field */
  int paramcount;
  /* the sleep opcode needs to store the full AMX status */
  cell pri              PACKED;
  cell alt              PACKED;
  cell reset_stk        PACKED;
  cell reset_hea        PACKED;
  cell sysreq_d         PACKED; /* relocated address/value for the SYSREQ.D opcode */
  #if defined JIT
    /* support variables for the JIT */
    int reloc_size      PACKED; /* required temporary buffer for relocations */
    long code_size      PACKED; /* estimated memory footprint of the native code */
  #endif
} PACKED AMX;

/* The AMX_HEADER structure is both the memory format as the file format. The
 * structure is used internaly.
 */
typedef struct tagAMX_HEADER {
  int32_t size          PACKED; /* size of the "file" */
  uint16_t magic        PACKED; /* signature */
  char    file_version;         /* file format version */
  char    amx_version;          /* required version of the AMX */
  int16_t flags         PACKED;
  int16_t defsize       PACKED; /* size of a definition record */
  int32_t cod           PACKED; /* initial value of COD - code block */
  int32_t dat           PACKED; /* initial value of DAT - data block */
  int32_t hea           PACKED; /* initial value of HEA - start of the heap */
  int32_t stp           PACKED; /* initial value of STP - stack top */
  int32_t cip           PACKED; /* initial value of CIP - the instruction pointer */
  int32_t publics       PACKED; /* offset to the "public functions" table */
  int32_t natives       PACKED; /* offset to the "native functions" table */
  int32_t libraries     PACKED; /* offset to the table of libraries */
  int32_t pubvars       PACKED; /* the "public variables" table */
  int32_t tags          PACKED; /* the "public tagnames" table */
  int32_t nametable     PACKED; /* name table */
} PACKED AMX_HEADER;

#if PAWN_CELL_SIZE==16
  #define AMX_MAGIC     0xf1e2
#elif PAWN_CELL_SIZE==32
  #define AMX_MAGIC     0xf1e0
#elif PAWN_CELL_SIZE==64
  #define AMX_MAGIC     0xf1e1
#endif

enum
{
  AMX_ERR_NONE,
  /* reserve the first 15 error codes for exit codes of the abstract machine */
  AMX_ERR_EXIT,         /* forced exit */
  AMX_ERR_ASSERT,       /* assertion failed */
  AMX_ERR_STACKERR,     /* stack/heap collision */
  AMX_ERR_BOUNDS,       /* index out of bounds */
  AMX_ERR_MEMACCESS,    /* invalid memory access */
  AMX_ERR_INVINSTR,     /* invalid instruction */
  AMX_ERR_STACKLOW,     /* stack underflow */
  AMX_ERR_HEAPLOW,      /* heap underflow */
  AMX_ERR_CALLBACK,     /* no callback, or invalid callback */
  AMX_ERR_NATIVE,       /* native function failed */
  AMX_ERR_DIVIDE,       /* divide by zero */
  AMX_ERR_SLEEP,        /* go into sleepmode - code can be restarted */
  AMX_ERR_INVSTATE,     /* invalid state for this access */

  AMX_ERR_MEMORY = 16,  /* out of memory */
  AMX_ERR_FORMAT,       /* invalid file format */
  AMX_ERR_VERSION,      /* file is for a newer version of the AMX */
  AMX_ERR_NOTFOUND,     /* function not found */
  AMX_ERR_INDEX,        /* invalid index parameter (bad entry point) */
  AMX_ERR_DEBUG,        /* debugger cannot run */
  AMX_ERR_INIT,         /* AMX not initialized (or doubly initialized) */
  AMX_ERR_USERDATA,     /* unable to set user data field (table full) */
  AMX_ERR_INIT_JIT,     /* cannot initialize the JIT */
  AMX_ERR_PARAMS,       /* parameter error */
  AMX_ERR_DOMAIN,       /* domain error, expression result does not fit in range */
  AMX_ERR_GENERAL,      /* general error (unknown or unspecific error) */
};

/*      AMX_FLAG_CHAR16   0x01     no longer used */
#define AMX_FLAG_DEBUG    0x02  /* symbolic info. available */
#define AMX_FLAG_COMPACT  0x04  /* compact encoding */
#define AMX_FLAG_BYTEOPC  0x08  /* opcode is a byte (not a cell) */
#define AMX_FLAG_NOCHECKS 0x10  /* no array bounds checking; no STMT opcode */
#define AMX_FLAG_NTVREG 0x1000  /* all native functions are registered */
#define AMX_FLAG_JITC   0x2000  /* abstract machine is JIT compiled */
#define AMX_FLAG_BROWSE 0x4000  /* busy browsing */
#define AMX_FLAG_RELOC  0x8000  /* jump/call addresses relocated */

#define AMX_EXEC_MAIN   -1      /* start at program entry point */
#define AMX_EXEC_CONT   -2      /* continue from last address */

#define AMX_USERTAG(a,b,c,d)    ((a) | ((b)<<8) | ((long)(c)<<16) | ((long)(d)<<24))

#if !defined AMX_COMPACTMARGIN
  #define AMX_COMPACTMARGIN 64
#endif

/* for native functions that use floating point parameters, the following
 * two macros are convenient for casting a "cell" into a "float" type _without_
 * changing the bit pattern
 */
#if PAWN_CELL_SIZE==32
  #define amx_ftoc(f)   ( * ((cell*)&f) )   /* float to cell */
  #define amx_ctof(c)   ( * ((float*)&c) )  /* cell to float */
#elif PAWN_CELL_SIZE==64
  #define amx_ftoc(f)   ( * ((cell*)&f) )   /* float to cell */
  #define amx_ctof(c)   ( * ((double*)&c) ) /* cell to float */
#else
  #error Unsupported cell size
#endif

#define amx_StrParam(amx,param,result)                                      \
    do {                                                                    \
      cell *amx_cstr_; int amx_length_;                                     \
      amx_GetAddr((amx), (param), &amx_cstr_);                              \
      amx_StrLen(amx_cstr_, &amx_length_);                                  \
      if (amx_length_ > 0 &&                                                \
          ((result) = (char*)alloca((amx_length_ + 1) * sizeof(*(result)))) != NULL) \
        amx_GetString((char*)(result), amx_cstr_, sizeof(*(result))>1, amx_length_ + 1); \
      else (result) = NULL;                                                 \
    } while (0)

uint16_t * AMXAPI amx_Align16(uint16_t *v);
uint32_t * AMXAPI amx_Align32(uint32_t *v);
#if defined _I64_MAX || defined HAVE_I64
  uint64_t * AMXAPI amx_Align64(uint64_t *v);
#endif
int AMXAPI amx_Allot(AMX *amx, int cells, cell *amx_addr, cell **phys_addr);
int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params);
int AMXAPI amx_Cleanup(AMX *amx);
int AMXAPI amx_Clone(AMX *amxClone, AMX *amxSource, void *data);
int AMXAPI amx_Exec(AMX *amx, cell *retval, int index);
int AMXAPI amx_FindNative(AMX *amx, const char *name, int *index);
int AMXAPI amx_FindPublic(AMX *amx, const char *funcname, int *index);
int AMXAPI amx_FindPubVar(AMX *amx, const char *varname, cell *amx_addr);
int AMXAPI amx_FindTagId(AMX *amx, cell tag_id, char *tagname);
int AMXAPI amx_Flags(AMX *amx,uint16_t *flags);
int AMXAPI amx_GetAddr(AMX *amx,cell amx_addr,cell **phys_addr);
int AMXAPI amx_GetNative(AMX *amx, int index, char *funcname);
int AMXAPI amx_GetPublic(AMX *amx, int index, char *funcname);
int AMXAPI amx_GetPubVar(AMX *amx, int index, char *varname, cell *amx_addr);
int AMXAPI amx_GetString(char *dest,const cell *source, int use_wchar, size_t size);
int AMXAPI amx_GetTag(AMX *amx, int index, char *tagname, cell *tag_id);
int AMXAPI amx_GetUserData(AMX *amx, long tag, void **ptr);
int AMXAPI amx_Init(AMX *amx, void *program);
int AMXAPI amx_InitJIT(AMX *amx, void *reloc_table, void *native_code);
int AMXAPI amx_MemInfo(AMX *amx, long *codesize, long *datasize, long *stackheap);
int AMXAPI amx_NameLength(AMX *amx, int *length);
AMX_NATIVE_INFO * AMXAPI amx_NativeInfo(const char *name, AMX_NATIVE func);
int AMXAPI amx_NumNatives(AMX *amx, int *number);
int AMXAPI amx_NumPublics(AMX *amx, int *number);
int AMXAPI amx_NumPubVars(AMX *amx, int *number);
int AMXAPI amx_NumTags(AMX *amx, int *number);
int AMXAPI amx_Push(AMX *amx, cell value);
int AMXAPI amx_PushArray(AMX *amx, cell *amx_addr, cell **phys_addr, const cell array[], int numcells);
int AMXAPI amx_PushString(AMX *amx, cell *amx_addr, cell **phys_addr, const char *string, int pack, int use_wchar);
int AMXAPI amx_RaiseError(AMX *amx, int error);
int AMXAPI amx_Register(AMX *amx, const AMX_NATIVE_INFO *nativelist, int number);
int AMXAPI amx_Release(AMX *amx, cell amx_addr);
int AMXAPI amx_SetCallback(AMX *amx, AMX_CALLBACK callback);
int AMXAPI amx_SetDebugHook(AMX *amx, AMX_DEBUG debug);
int AMXAPI amx_SetString(cell *dest, const char *source, int pack, int use_wchar, size_t size);
int AMXAPI amx_SetUserData(AMX *amx, long tag, void *ptr);
int AMXAPI amx_StrLen(const cell *cstring, int *length);
int AMXAPI amx_UTF8Check(const char *string, int *length);
int AMXAPI amx_UTF8Get(const char *string, const char **endptr, cell *value);
int AMXAPI amx_UTF8Len(const cell *cstr, int *length);
int AMXAPI amx_UTF8Put(char *string, char **endptr, int maxchars, cell value);

#if PAWN_CELL_SIZE==16
  #define amx_AlignCell(v) amx_Align16(v)
#elif PAWN_CELL_SIZE==32
  #define amx_AlignCell(v) amx_Align32(v)
#elif PAWN_CELL_SIZE==64 && (defined _I64_MAX || defined HAVE_I64)
  #define amx_AlignCell(v) amx_Align64(v)
#else
  #error Unsupported cell size
#endif

#define amx_RegisterFunc(amx, name, func) \
  amx_Register((amx), amx_NativeInfo((name),(func)), 1);

#if !defined AMX_NO_ALIGN
  #if defined __LINUX__ || defined __FreeBSD__
    #pragma pack()    /* reset default packing */
  #elif defined MACOS && defined __MWERKS__
    #pragma options align=reset
  #else
    #pragma pack(pop) /* reset previous packing */
  #endif
#endif

#ifdef  __cplusplus
}
#endif

#endif /* AMX_H_INCLUDED */

}


text:
<?php

abstract class RolesAbstract extends Collection {

  // cache for the default role
  protected $default = null;

  /**
   * Constructor
   */
  public function __construct() {

    $kirby = kirby();

    // fetch a list of roles from roles dir & registry
    foreach($kirby->get('role') as $roleName) {
      $role = $kirby->get('role', $roleName);
      if(is_array($role)) {
        $role['id'] = $roleName;
        $role = new Role($role);
        $this->data[$role->id()] = $role;
      }
    }

    // fetch roles from the Kirby "roles" option (deprecated)
    foreach($kirby->option('roles') as $role) {
      if(is_array($role)) {
        $role = new Role($role);
        $this->data[$role->id()] = $role;
      }
    }

    // set the default set of roles if roles are not configured
    if(empty($this->data)) {
      $editor = new Role([
        'id'          => 'editor',
        'name'        => 'Editor',
        'permissions' => [
          '*'                 => true,
          'panel.site.update' => false,
          'panel.avatar.*'    => function() {
            return $this->user()->is($this->target()->user());
          },
          'panel.user.*'      => false,
          'panel.user.read'   => true,
          'panel.user.update' => function() {
            return $this->user()->is($this->target()->user());
          }
        ]
      ]);
      $this->data = ['editor' => $editor];
    }

    // check for a valid admin role and provide a default one otherwise
    if(!isset($this->data['admin'])) {
      $this->data['admin'] = new Role([
        'id'   => 'admin',
        'name' => 'Admin'
      ]);
    }

    // check for a valid default role
    if(!$this->findDefault()) {
      $this->data['admin']->default = true;
    }

  }

  /**
   * Returns the default role for new users
   *
   * @return Role
   */
  public function findDefault() {
    if(!is_null($this->default)) return $this->default;
    return $this->default = $this->findBy('isDefault', true);
  }

  /**
   * Improved @var_dump output
   *
   * @return array
   */
  public function __debuginfo() {
    return array_keys($this->data);
  }

}


text:
import { CorePlugin } from '@snowplow/tracker-core';
import { BrowserTracker } from './tracker/types';

/**
 * Interface which defines Core Plugins
 */
export interface BrowserPlugin extends CorePlugin {
  /**
   * Called when the plugin is initialised during the Tracker construction
   *
   * @remarks
   * Use to capture the specific Tracker instance for each instance of a Browser Plugin
   */
  activateBrowserPlugin?: (tracker: BrowserTracker) => void;
}