text:
package io.exponential.androidactivityandfragmentlifecycle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CActivity extends AppCompatActivity
    implements AlertDialogFragment.Callbacks {

    private static final String TAG = "CActivity";
    private static final String LOG_PREFIX = "lcm:";

    OnClickListener openFragmentDialog = new OnClickListener() {
        @Override
        public void onClick(View v) {
            String title = "Alert";
            String message = "The Activity has NOT been paused.";

            DialogFragment alertDialog = AlertDialogFragment.newInstance(title, message);
            alertDialog.show(getSupportFragmentManager(), "alertDialog");
        }
    };

    OnClickListener openActivityDialog = new OnClickListener() {
        @Override
        public void onClick(View v) {
            String title = "Alert";
            String message = "The Activity has been paused.";

            Intent intent = new Intent(CActivity.this, DialogActivity.class);
            intent.putExtra(DialogActivity.EXTRA_DIALOG_TITLE, title);
            intent.putExtra(DialogActivity.EXTRA_DIALOG_MESSAGE, message);
            startActivity(intent);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(TAG, "S:" + LOG_PREFIX + "onCreate");
        setContentView(R.layout.activity_c);

        // Event handlers
        ((Button) findViewById(R.id.activity_c_no_pause)).setOnClickListener(openFragmentDialog);
        ((Button) findViewById(R.id.activity_c_pause)).setOnClickListener(openActivityDialog);

        Log.v(TAG, "E:" + LOG_PREFIX + "onCreate");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.v(TAG, "S:" + LOG_PREFIX + "onStart");
        Log.v(TAG, "E:" + LOG_PREFIX + "onStart");
    }

    @Override
    protected void onResume() {
        Log.v(TAG, "S:" + LOG_PREFIX + "onResume");
        super.onResume();
        Log.v(TAG, "E:" + LOG_PREFIX + "onResume");
    }

    @Override
    protected void onPause() {
        Log.v(TAG, "S:" + LOG_PREFIX + "onPause");
        super.onPause();
        Log.v(TAG, "E:" + LOG_PREFIX + "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.v(TAG, "S:" + LOG_PREFIX + "onStop");
        Log.v(TAG, "E:" + LOG_PREFIX + "onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.v(TAG, "S:" + LOG_PREFIX + "onRestart");
        Log.v(TAG, "E:" + LOG_PREFIX + "onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "S:" + LOG_PREFIX + "onDestroy");
        Log.v(TAG, "E:" + LOG_PREFIX + "onDestroy");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_c, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // AlertDialogFragment.Callbacks
    @Override
    public void onClickAlertOK() {
        Log.v(TAG, "Close alert dialog");
    }

    @Override
    public void onClickAlertCancel() {
        Log.v(TAG, "Close alert dialog");
    }

}


text:
<?php

declare(strict_types=1);

namespace Brick\DateTime\Field;

use Brick\DateTime\DateTimeException;

/**
 * The proleptic year field.
 */
final class Year
{
    /**
     * The field name.
     */
    public const NAME = 'year';

    /**
     * The regular expression pattern of the ISO 8601 representation.
     */
    public const PATTERN = '\-?[0-9]{4,9}';

    /**
     * The minimum allowed value.
     */
    public const MIN_VALUE = -999999;

    /**
     * The maximum allowed value.
     */
    public const MAX_VALUE = 999999;

    /**
     * @param int $year The year to check.
     *
     * @throws DateTimeException If the year is not valid.
     */
    public static function check(int $year): void
    {
        if ($year < self::MIN_VALUE || $year > self::MAX_VALUE) {
            throw DateTimeException::fieldNotInRange(self::NAME, $year, self::MIN_VALUE, self::MAX_VALUE);
        }
    }

    /**
     * @param int $year The year, validated.
     */
    public static function isLeap(int $year): bool
    {
        return (($year & 3) === 0) && (($year % 100) !== 0 || ($year % 400) === 0);
    }
}

redpajama_set_name: RedPajamaGithub


text:
ANSIBLE_METADATA = {'status': ['preview'],
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = '''
---
module: ec2_vol_facts
short_description: Gather facts about ec2 volumes in AWS
description:
    - Gather facts about ec2 volumes in AWS
version_added: "2.1"
author: "Rob White (@wimnat)"
options:
  filters:
    description:
      - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVolumes.html) for possible filters.
    required: false
    default: null
extends_documentation_fragment:
    - aws
    - ec2
'''

EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.

# Gather facts about all volumes
- ec2_vol_facts:

# Gather facts about a particular volume using volume ID
- ec2_vol_facts:
    filters:
      volume-id: vol-00112233

# Gather facts about any volume with a tag key Name and value Example
- ec2_vol_facts:
    filters:
      "tag:Name": Example

# Gather facts about any volume that is attached
- ec2_vol_facts:
    filters:
      attachment.status: attached

'''

# TODO: Disabled the RETURN as it was breaking docs building. Someone needs to
# fix this
RETURN = '''# '''

try:
    import boto.ec2
    from boto.exception import BotoServerError
    HAS_BOTO = True
except ImportError:
    HAS_BOTO = False

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import connect_to_aws, ec2_argument_spec, get_aws_connection_info

def get_volume_info(volume):

    attachment = volume.attach_data

    volume_info = {
                    'create_time': volume.create_time,
                    'id': volume.id,
                    'iops': volume.iops,
                    'size': volume.size,
                    'snapshot_id': volume.snapshot_id,
                    'status': volume.status,
                    'type': volume.type,
                    'zone': volume.zone,
                    'region': volume.region.name,
                    'attachment_set': {
                        'attach_time': attachment.attach_time,
                        'device': attachment.device,
                        'instance_id': attachment.instance_id,
                        'status': attachment.status
                    },
                    'tags': volume.tags
                }

    return volume_info

def list_ec2_volumes(connection, module):

    filters = module.params.get("filters")
    volume_dict_array = []

    try:
        all_volumes = connection.get_all_volumes(filters=filters)
    except BotoServerError as e:
        module.fail_json(msg=e.message)

    for volume in all_volumes:
        volume_dict_array.append(get_volume_info(volume))

    module.exit_json(volumes=volume_dict_array)

def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            filters = dict(default=None, type='dict')
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

    if region:
        try:
            connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, StandardError) as e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="region must be specified")

    list_ec2_volumes(connection, module)

if __name__ == '__main__':
    main()


text:
/****************************************************************************
 * apps/include/hex2bin.h
 *
 *   Copyright (C) 2014 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#ifndef __APPS_INCLUDE_HEX2BIN_H
#define __APPS_INCLUDE_HEX2BIN_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <stdint.h>

#ifdef CONFIG_SYSTEM_HEX2BIN

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/
/* Configuration ************************************************************/

#ifndef CONFIG_SYSTEM_HEX2BIN_BASEADDR
#define CONFIG_SYSTEM_HEX2BIN_BASEADDR 0x00000000
#endif

#ifndef CONFIG_SYSTEM_HEX2BIN_ENDPADDR
#define CONFIG_SYSTEM_HEX2BIN_ENDPADDR 0x00000000
#endif

#ifndef CONFIG_SYSTEM_HEX2BIN_SWAP
#define CONFIG_SYSTEM_HEX2BIN_SWAP 0
#endif

/* Some environments may return CR as end-of-line, others LF, and others
 * both.  If not specified, the logic here assumes either (but not both) as
 * the default.
 */

#if defined(CONFIG_EOL_IS_CR)
#undef  CONFIG_EOL_IS_LF
#undef  CONFIG_EOL_IS_BOTH_CRLF
#undef  CONFIG_EOL_IS_EITHER_CRLF
#elif defined(CONFIG_EOL_IS_LF)
#undef  CONFIG_EOL_IS_CR
#undef  CONFIG_EOL_IS_BOTH_CRLF
#undef  CONFIG_EOL_IS_EITHER_CRLF
#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
#undef  CONFIG_EOL_IS_CR
#undef  CONFIG_EOL_IS_LF
#undef  CONFIG_EOL_IS_EITHER_CRLF
#elif defined(CONFIG_EOL_IS_EITHER_CRLF)
#undef  CONFIG_EOL_IS_CR
#undef  CONFIG_EOL_IS_LF
#undef  CONFIG_EOL_IS_BOTH_CRLF
#else
#undef  CONFIG_EOL_IS_CR
#undef  CONFIG_EOL_IS_LF
#undef  CONFIG_EOL_IS_BOTH_CRLF
#define CONFIG_EOL_IS_EITHER_CRLF 1
#endif

/* Debug from hex2bin code */

#ifdef CONFIG_CPP_HAVE_VARARGS
#ifdef CONFIG_SYSTEM_HEX2BIN_DEBUG
#define hex2bin_debug(format, ...) fprintf(stderr, format, ##__VA_ARGS__)
#else
#define hex2bin_debug(x...)
#endif
#else
#ifdef CONFIG_SYSTEM_HEX2BIN_DEBUG
#define hex2bin_debug printf
#else
#define hex2bin_debug (void)
#endif
#endif

/****************************************************************************
 * Public Types
 ****************************************************************************/
/* Intel HEX data steams are normally in big endian order.  The following
 * enumeration selects other ordering.
 */

enum hex2bin_swap_e {
	HEX2BIN_NOSWAP = 0,			/* No swap, stream is in the correct byte order */
	HEX2BIN_SWAP16 = 1,			/* Swap bytes in 16-bit values */
	HEX2BIN_SWAP32 = 2			/* Swap bytes in 32-bit values */
};

/****************************************************************************
 * Public Data
 ****************************************************************************/

#ifdef __cplusplus
// *INDENT-OFF*
#define EXTERN extern "C"
extern "C" {
#else
#define EXTERN extern
// *INDENT-ON*
#endif

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

/****************************************************************************
 * Name: hex2bin
 *
 * Description:
 *   Read the Intel HEX ASCII data provided on the serial IN stream and write
 *   the binary to the seek-able serial OUT stream.
 *
 *   These streams may be files or, in another usage example, the IN stream
 *   could be a serial port and the OUT stream could be a memory stream.  This
 *   would decode and write the serial input to memory.
 *
 * Input Parameters:
 *   instream  - The incoming stream from which Intel HEX data will be
 *               received.
 *   outstream - The outgoing stream in which binary data will be written.
 *   baseaddr  - The base address of the outgoing stream.  Seeking in the
 *               output stream will be relative to this address.
 *   endpaddr  - The end address (plus 1) of the outgoing stream.  This
 *               value is used only for range checking.  endpaddr must
 *               be larger than baseaddr.  A zero value for endpaddr
 *               disables range checking.
 *   swap      - Controls byte ordering.  See enum hex2bin_swap_e for
 *               description of the values.
 *
 * Returned Value
 *   Zero (OK) is returned on success; a negated errno value is returned on
 *   failure.
 *
 ****************************************************************************/

struct lib_instream_s;
struct lib_sostream_s;
int hex2bin(FAR struct lib_instream_s *instream, FAR struct lib_sostream_s *outstream, uint32_t baseaddr, uint32_t endpaddr, enum hex2bin_swap_e swap);

/****************************************************************************
 * Name hex2mem
 *
 * Description:
 *   Read the Intel HEX ASCII data provided on the file descriptor 'fd' and
 *   write the binary to memory.
 *
 *   If, for example, fd is zero (corresponding to stdin), then the HEX
 *   ASCII data would be taken from the console and written to memory.
 *
 * Input Parameters:
 *   fd        - The file descriptor from which Intel HEX data will be
 *               received.
 *   baseaddr  - The base address of the memory region stream.
 *   endpaddr  - The end address (plus 1) of the memory region.
 *   swap      - Controls byte ordering.  See enum hex2bin_swap_e for
 *               description of the values.
 *
 * Returned Value
 *   Zero (OK) is returned on success; a negated errno value is returned on
 *   failure.
 *
 ****************************************************************************/

int hex2mem(int fd, uint32_t baseaddr, uint32_t endpaddr, enum hex2bin_swap_e swap);

/****************************************************************************
 * Name fhex2mem
 *
 * Description:
 *   Read the Intel HEX ASCII data provided on the standard stream
 *   'instream' and write the binary to memory.
 *
 *   If, for example, instream is stdin, then the HEX ASCII data would be
 *   taken from the console and written to memory.
 *
 * Input Parameters:
 *   instream  - The incoming standard stream from which Intel HEX data
 *               will be received.
 *   baseaddr  - The base address of the memory region stream.
 *   endpaddr  - The end address (plus 1) of the memory region.
 *   swap      - Controls byte ordering.  See enum hex2bin_swap_e for
 *               description of the values.
 *
 * Returned Value
 *   Zero (OK) is returned on success; a negated errno value is returned on
 *   failure.
 *
 ****************************************************************************/

int fhex2mem(FAR FILE * instream, uint32_t baseaddr, uint32_t endpaddr, enum hex2bin_swap_e swap);

/****************************************************************************
 * Name: hex2bin_main
 *
 * Description:
 *   Main entry point when hex2bin is built as an NSH built-in task.
 *
 * Input Parameters:
 *   Standard task inputs
 *
 * Returned Value
 *   EXIT_SUCESS on success; EXIT_FAILURE on failure
 *
 ****************************************************************************/

#ifdef CONFIG_SYSTEM_HEX2BIN_BUILTIN
int hex2bin_main(int argc, char **argv);
#endif							/* CONFIG_SYSTEM_HEX2BIN_BUILTIN */

/****************************************************************************
 * Name: hex2mem_main
 *
 * Description:
 *   Main entry point when hex2mem is built as an NSH built-in task.
 *
 * Input Parameters:
 *   Standard task inputs
 *
 * Returned Value
 *   EXIT_SUCESS on success; EXIT_FAILURE on failure
 *
 ****************************************************************************/

#ifdef CONFIG_SYSTEM_HEX2MEM_BUILTIN
int hex2mem_main(int argc, char **argv);
#endif							/* CONFIG_SYSTEM_HEX2MEM_BUILTIN */

#undef EXTERN
#ifdef __cplusplus
// *INDENT-OFF*
}
// *INDENT-ON*
#endif

#endif							/* CONFIG_SYSTEM_HEX2BIN */
#endif							/* __APPS_INCLUDE_HEX2BIN_H */


text: search_result['4262']=["topic_0000000000000A27.html","GetDefaultInvoicePerson Field",""];


text:
<?php

class Buscador_Form_Buscar extends Zend_Form
{
    public function __construct($options=null)
    {
        parent::__construct($options);
        //Config del formulario
        $this->setName('frmBuscador');
        $this->setAction('/buscador/buscador/index');
        $this->setMethod('get');

        //Elementos del formulario
        $cadena = $this->createElement('text','cadena');
        $cadena->setAttrib("placeholder", Zend_Registry::get('Zend_Translate')->translate('m020'));
        $cadena->setRequired(false);
        $cadena->addValidator(new Zend_Validate_StringLength(2));
        $cadena->class = "xxlarge";

        $idiomaOrigen = $this->createElement('select','idiomaOrigen')->setRequired(false);

        $tablaIdiomas = new Buscador_Model_DbTable_Languages();

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $auth = Zend_Auth::getInstance();
            $data = $auth->getStorage()->read();
            $idioma = $data['lang'];
        } elseif (isset($_COOKIE['lang'])) {
            $idioma = $_COOKIE['lang'];
        } else {
            $idioma = 'gl_GL';
        }

        $idiomaOrigen->addMultiOption(NULL,'['.Zend_Registry::get('Zend_Translate')->translate('m021').']');
        //Lee los idiomas de la BBDD
        foreach ($tablaIdiomas->getListaIdiomas($idioma) as $i) {
            $idiomaOrigen->addMultiOption($i['unit_language'], $i['language_name']);
        }
        $idiomaOrigen->setValue('en');

        $boton = new Zend_Form_Element_Button('btnCambiarIdioma');
        $boton->setLabel("");
        $boton->setDecorators(array('ViewHelper'));
        $boton->class="btn cambiarIdioma";

        $idiomaDestino = $this->createElement('select','idiomaDestino');
        $idiomaDestino->setRequired(false);
        $idiomaDestino->addMultiOption(NULL,'['.Zend_Registry::get('Zend_Translate')->translate('m022').']');

        //Lee los idiomas de la BBDD
        foreach ($tablaIdiomas->getListaIdiomas($idioma) as $i) {
            $idiomaDestino->addMultiOption($i['unit_language'], $i['language_name']);
        }
        $idiomaDestino->setValue('gl');

        $submit = $this->createElement('submit','submit',array('label'=>Zend_Registry::get('Zend_Translate')->translate('m018')));
        $submit->class="submit btn btn-primary";

        $hidden = $this->createElement('hidden','oculto');

        //Añadir elementos creados al formulario
        $this->addElements(array($cadena, $submit, $hidden, $idiomaOrigen, $boton, $idiomaDestino));

        //Eliminar decoradores (Formatear form)
        $this->setElementDecorators(array(
            'ViewHelper',
            'Errors',
            array(array('data' => 'HtmlTag'), array('tag' => 'td')),
        ));
        $submit->setDecorators(array(
            'ViewHelper',
        ));

        $hidden->setDecorators(array(
            array(array('espacio2' => 'HtmlTag'), array('tag' => 'br')),
        ));

        $idiomaOrigen->setDecorators(array(
            'ViewHelper',
        ));

        $idiomaDestino->setDecorators(array(
            'ViewHelper',
        ));

        $this->setDecorators(array(
            'FormElements',
            'Form',
        ));

    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Jint.Native;
using System.Collections;

namespace Jint.PropertyBags
{
    public class HashedPropertyBag : IPropertyBag
    {
        public HashedPropertyBag()
        {
            keys = new Hashtable();
        }

        private Hashtable keys;

        #region IPropertyBag Members

        public Jint.Native.Descriptor Put(string name, Jint.Native.Descriptor descriptor)
        {
            keys.Add(name, descriptor);
            return descriptor;
        }

        public void Delete(string name)
        {
            keys.Remove(name);
        }

        public Jint.Native.Descriptor Get(string name)
        {
            return keys[name] as Descriptor;
        }

        public bool TryGet(string name, out Jint.Native.Descriptor descriptor)
        {
            descriptor = Get(name);
            return descriptor != null;
        }

        public int Count
        {
            get { return keys.Count; }
        }

        public IEnumerable<Jint.Native.Descriptor> Values
        {
            get
            {
                foreach (DictionaryEntry de in keys)
                {
                    yield return de.Value as Descriptor;
                }
            }
        }

        #endregion

        #region IEnumerable<KeyValuePair<string,Descriptor>> Members

        public IEnumerator<KeyValuePair<string, Jint.Native.Descriptor>> GetEnumerator()
        {
            foreach (DictionaryEntry de in keys)
            {
                yield return new KeyValuePair<string, Descriptor>(de.Key as string, de.Value as Descriptor);
            }
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}


text:
<?php

function mailgunAuthenticateWebhook() {
    // has timestamp variable?
    if (!isset($_POST['timestamp'])) return false;

    // get timestamp in UNIX time
    $timestamp = $_POST['timestamp'];
    if ((time() - 86400) > $timestamp) return false; // make sure timestamp from last 24 hours

    // token: Randomly generated string with length 50
    if (!isset($_POST['token'])) return false;
    $token = $_POST['token'];

    // get signature variable (HMAC)
    if (!isset($_POST['signature'])) return false;

    // concatenate
    $concat = $timestamp . $token;

    // get key
    $key = configurationGet('MAILGUN_API_KEY');

    // HMAC encode
    return (hash_hmac('sha256', $concat, $key) === $_POST['signature']);
}


text:
describe GroupingPolicy do
  let(:context) { { role: role, real_user: role.user } }
  let(:record) { grouping }
  let(:grouping) { create :grouping }
  let(:role) { create :instructor }

  describe_rule :member? do
    let(:grouping) { create :grouping_with_inviter }
    failed 'role is an instructor' do
      let(:role) { create :instructor }
    end
    failed 'role is an ta' do
      let(:role) { create :ta }
    end
    context 'role is a student' do
      failed 'role is not a member' do
        let(:role) { create :student }
      end
      succeed 'role is a member' do
        let(:role) { grouping.inviter }
      end
    end
  end

  describe_rule :not_in_progress? do
    succeed 'test not in progress' do
      before { allow(grouping).to receive(:student_test_run_in_progress?).and_return false }
    end
    failed 'test in progress' do
      before { allow(grouping).to receive(:student_test_run_in_progress?).and_return true }
    end
  end

  describe_rule :tokens_available? do
    succeed 'when test tokens exist' do
      let(:grouping) { create :grouping, test_tokens: 1 }
    end
    succeed 'when there are unlimited tokens available' do
      let(:grouping) do
        create :grouping, assignment: create(:assignment, assignment_properties_attributes: { unlimited_tokens: true })
      end
    end
    failed 'when there are no tokens and tokens are limited' do
      let(:grouping) do
        create :grouping,
               assignment: create(:assignment, assignment_properties_attributes: { unlimited_tokens: false }),
               test_tokens: 0
      end
    end
  end

  describe_rule :invite_member? do
    let(:grouping) { create :grouping, assignment: assignment }
    let(:assignment) { create :assignment, assignment_properties_attributes: properties }
    succeed 'students form groups, has no extension, before collection date' do
      let(:properties) { { invalid_override: false } }
    end
    failed 'students do not form groups, has no extension, before collection date' do
      let(:properties) { { invalid_override: true } }
    end
    failed 'students form groups, has an extension, before collection date' do
      let(:properties) { { invalid_override: false } }
      before { create :extension, grouping: grouping }
    end
    failed 'students form groups, has no extension, after collection date' do
      let(:properties) { { invalid_override: false } }
      let(:assignment) { create :assignment, due_date: 1.day.ago, assignment_properties_attributes: properties }
    end
  end

  describe_rule :students_form_groups? do
    let(:grouping) { create :grouping, assignment: assignment }
    succeed 'invalid override is false' do
      let(:assignment) { create :assignment, assignment_properties_attributes: { invalid_override: false } }
    end
    failed 'invalid override is true' do
      let(:assignment) { create :assignment, assignment_properties_attributes: { invalid_override: true } }
    end
  end

  describe_rule :before_due_date? do
    succeed 'before collection date' do
      before { allow(grouping).to receive(:past_collection_date?).and_return false }
    end
    failed 'before collection date' do
      before { allow(grouping).to receive(:past_collection_date?).and_return true }
    end
  end

  describe_rule :disinvite_member? do
    let(:role) { create :student }
    let(:context) { { role: role, real_user: role.user, membership: membership } }
    succeed 'role is inviter and the membership status is pending' do
      let(:grouping) { create :grouping_with_inviter, inviter: role }
      let(:membership) { create :student_membership, grouping: grouping }
    end
    failed 'role is not the inviter and the membership status is pending' do
      let(:membership) { create :student_membership, grouping: grouping }
    end
    failed 'role is inviter and the membership status is not pending' do
      let(:grouping) { create :grouping_with_inviter, inviter: role }
      let(:membership) { create :accepted_student_membership, grouping: grouping }
    end
  end

  describe_rule :delete_rejected? do
    let(:role) { create :student }
    let(:context) { { role: role, real_user: role.user, membership: membership } }
    succeed 'role is inviter and the membership status is rejected' do
      let(:grouping) { create :grouping_with_inviter, inviter: role }
      let(:membership) { create :rejected_student_membership, grouping: grouping }
    end
    failed 'role is not the inviter and the membership status is rejected' do
      let(:membership) { create :rejected_student_membership, grouping: grouping }
    end
    failed 'role is inviter and the membership status is not rejected' do
      let(:grouping) { create :grouping_with_inviter, inviter: role }
      let(:membership) { create :student_membership, grouping: grouping }
    end
  end

  describe_rule :destroy? do
    succeed 'grouping is deletable by the user and there is no submission' do
      before { allow(grouping).to receive(:deletable_by?).and_return true }
    end
    failed 'grouping is not deletable by the user and there is no submission' do
      before { allow(grouping).to receive(:deletable_by?).and_return false }
    end
    failed 'grouping is deletable by the user but there is a submission' do
      before { allow(grouping).to receive(:deletable_by?).and_return true }
      let(:grouping) { create :grouping_with_inviter_and_submission }
    end
  end

  describe_rule :deletable_by? do
    succeed 'grouping is deletable by the user' do
      before { allow(grouping).to receive(:deletable_by?).and_return true }
    end
    failed 'grouping is not deletable by the user' do
      before { allow(grouping).to receive(:deletable_by?).and_return false }
    end
  end

  describe_rule :no_submission? do
    succeed 'grouping has no submission'
    failed 'grouping has a submission' do
      let(:grouping) { create :grouping_with_inviter_and_submission }
    end
  end

  describe_rule :no_extension? do
    succeed 'grouping has no extension'
    failed 'grouping has an extension' do
      before { create :extension, grouping: grouping }
    end
  end

  describe_rule :view_file_manager? do
    failed 'role is an instructor' do
      let(:role) { create :instructor }
    end
    failed 'role is a ta' do
      let(:role) { create :ta }
    end
    context 'role is a student' do
      let(:role) { create :student }
      let(:grouping) { create :grouping, assignment: assignment }
      succeed 'when the assignment is not scanned or a peer review or timed' do
        let(:assignment) { create :assignment }
      end
      failed 'when the assignment is scanned' do
        let(:assignment) { create :assignment_for_scanned_exam }
      end
      failed 'when the assignment is a peer review' do
        let(:assignment) { create :peer_review_assignment }
      end
      context 'when the assignment is timed' do
        let(:assignment) { create :timed_assignment }
        succeed 'and it has started' do
          let(:grouping) { create :grouping, assignment: assignment, start_time: 1.minute.ago }
        end
        failed 'and it has not started yet'
      end
    end
  end

  describe_rule :start_timed_assignment? do
    failed 'role is an instructor' do
      let(:role) { create :instructor }
    end
    failed 'role is a ta' do
      let(:role) { create :ta }
    end
    context 'role is a student' do
      let(:role) { create :student }
      let(:past_collection_date) { false }
      let(:past_assessment_start_time) { true }
      before do
        allow(grouping).to receive(:past_collection_date?).and_return past_collection_date
        allow(grouping).to receive(:past_assessment_start_time?).and_return past_assessment_start_time
      end
      succeed 'assignment has not started, not passed collection date, passed start time'
      failed 'assignment has been started' do
        let(:grouping) { create :grouping, start_time: 1.minute.ago }
      end
      failed 'passed collection date' do
        let(:past_collection_date) { true }
      end
      failed 'not passed assessment start time' do
        let(:past_assessment_start_time) { false }
      end
    end
  end

  describe_rule :download_starter_file? do
    failed 'role is an instructor' do
      let(:role) { create :instructor }
    end
    failed 'user is a ta' do
      let(:role) { create :ta }
    end
    context 'role is a student' do
      let(:role) { create :student }
      let(:grouping) { create :grouping, assignment: assignment }
      context 'when the assignment is not timed' do
        failed 'and is hidden' do
          let(:assignment) { create :assignment, is_hidden: true }
        end
        context 'and is visible' do
          succeed { let(:assignment) { create :assignment } }
          context 'and starter_files_after_due is false' do
            failed 'and grouping has passed collection time' do
              let(:assignment) do
                create :assignment,
                       due_date: 1.hour.ago,
                       assignment_properties_attributes: { starter_files_after_due: false }
              end
            end
            succeed 'and grouping is before the collection time' do
              let(:assignment) do
                create :assignment,
                       due_date: 1.hour.from_now,
                       assignment_properties_attributes: { starter_files_after_due: false }
              end
            end
          end
        end
      end
      context 'when the assignment is timed' do
        let(:assignment) { create :timed_assignment }
        succeed 'and it has started' do
          let(:grouping) { create :grouping, assignment: assignment, start_time: 1.minute.ago }
        end
        context 'and grouping has passed collection time' do
          succeed 'and starter_files_after_due is true' do
            let(:assignment) do
              create :timed_assignment,
                     due_date: 1.hour.ago,
                     assignment_properties_attributes: { starter_files_after_due: true }
            end
          end
          failed 'and starter_files_after_due is false' do
            let(:assignment) do
              create :timed_assignment,
                     due_date: 1.hour.ago,
                     assignment_properties_attributes: { starter_files_after_due: false }
            end
          end
        end
        context 'and grouping is before the collection time' do
          failed 'and starter_files_after_due is true' do
            let(:assignment) do
              create :timed_assignment,
                     due_date: 1.hour.from_now,
                     assignment_properties_attributes: { starter_files_after_due: true }
            end
          end
          failed 'and starter_files_after_due is false' do
            let(:assignment) do
              create :timed_assignment,
                     due_date: 1.hour.from_now,
                     assignment_properties_attributes: { starter_files_after_due: false }
            end
          end
        end
      end
    end
  end

  describe_rule :access_repo? do
    let(:assignment) { create :assignment, is_hidden: true }
    context 'role is a student' do
      let(:role) { create :student }
      let(:grouping) { create :grouping, assignment: assignment }
      context 'when the assignment is not timed' do
        succeed 'and version control submission is enabled' do
          let(:assignment) { create :assignment, assignment_properties_attributes: { vcs_submit: true } }
        end
        failed 'and version control submission is disabled' do
          let(:assignment) { create :assignment, assignment_properties_attributes: { vcs_submit: false } }
        end
      end
      context 'when the assignment is timed and version control submission is enabled' do
        let(:assignment) { create :timed_assignment, assignment_properties_attributes: { vcs_submit: true } }
        succeed 'and the grouping has started' do
          let(:grouping) { create :grouping, assignment: assignment, start_time: 1.minute.ago }
        end
        failed 'and the grouping has not yet started' do
          let(:grouping) { create :grouping, assignment: assignment, start_time: nil }
        end
      end
    end
  end
end


text:
<!doctype html>

	<meta charset="utf-8">
	<title>The Knowledge Tree</title>
	<link href="css/ui-lightness/jquery-ui-1.10.3.custom.css" rel="stylesheet">

	<input type="text" id="query">
	<input type="submit" id ='submit'>

Contact

Docs

About

Home

<canvas id="viewport" width="900" height="600"></canvas>

	<input type="submit" id="delete_edge" value="Delete Edge">
	<input type="submit" id="add_edge" value ="Add Edge">
	<input type="submit" id="add_button" value="Edit" onclick="Display(1)">
	<input type="submit" id="add_node" value="Add Node">

<textarea name="editor" id="text_editor"><p>Initial value.</p></textarea>


text:
namespace System.Activities.Statements
{
    using System;
    using System.Activities.DynamicUpdate;
    using System.Collections.Generic;
    using System.Runtime;
    using System.Collections.ObjectModel;

    sealed class CompensationParticipant : NativeActivity
    {
        InArgument<long> compensationId;

        Variable<CompensationToken> currentCompensationToken;

        public CompensationParticipant(Variable<long> compensationId)
            : base()
        {
            this.compensationId = compensationId;

            this.currentCompensationToken = new Variable<CompensationToken>();

            DefaultCompensation = new DefaultCompensation()
                {
                    Target = new InArgument<CompensationToken>(this.currentCompensationToken),
                };

            DefaultConfirmation = new DefaultConfirmation()
                {
                    Target = new InArgument<CompensationToken>(this.currentCompensationToken),
                };
        }

        public Activity CompensationHandler
        {
            get;
            set;
        }

        public Activity ConfirmationHandler
        {
            get;
            set;
        }

        public Activity CancellationHandler
        {
            get;
            set;
        }

        Activity DefaultCompensation
        {
            get;
            set;
        }

        Activity DefaultConfirmation
        {
            get;
            set;
        }

        protected override bool CanInduceIdle
        {
            get
            {
                return true;
            }
        }

        protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)
        {
            metadata.AllowUpdateInsideThisActivity();
        }

        protected override void CacheMetadata(NativeActivityMetadata metadata)
        {
            metadata.SetImplementationVariablesCollection(
                new Collection<Variable>
                {
                    this.currentCompensationToken,
                });

            Collection<Activity> children = new Collection<Activity>();

            if (this.CompensationHandler != null)
            {
                children.Add(CompensationHandler);
            }

            if (this.ConfirmationHandler != null)
            {
                children.Add(ConfirmationHandler);
            }

            if (this.CancellationHandler != null)
            {
                children.Add(CancellationHandler);
            }

            metadata.SetChildrenCollection(children);

            Collection<Activity> implementationChildren = new Collection<Activity>();
            Fx.Assert(DefaultCompensation != null, "DefaultCompensation must be valid");
            implementationChildren.Add(DefaultCompensation);

            Fx.Assert(DefaultConfirmation != null, "DefaultConfirmation must be valid");
            implementationChildren.Add(DefaultConfirmation);

            metadata.SetImplementationChildrenCollection(implementationChildren);

            RuntimeArgument compensationIdArgument = new RuntimeArgument("CompensationId", typeof(long), ArgumentDirection.In);
            metadata.Bind(this.compensationId, compensationIdArgument);
            metadata.AddArgument(compensationIdArgument);
        }

        protected override void Execute(NativeActivityContext context)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            long compensationId = this.compensationId.Get(context);
            Fx.Assert(compensationId != CompensationToken.RootCompensationId, "CompensationId passed to the SecondaryRoot must be valid");

            CompensationTokenData compensationToken = compensationExtension.Get(compensationId);
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            CompensationToken token = new CompensationToken(compensationToken);
            this.currentCompensationToken.Set(context, token);

            compensationToken.IsTokenValidInSecondaryRoot = true;
            context.Properties.Add(CompensationToken.PropertyName, token);

            Fx.Assert(compensationToken.BookmarkTable[CompensationBookmarkName.OnConfirmation] == null, "Bookmark should not be already initialized in the bookmark table.");
            compensationToken.BookmarkTable[CompensationBookmarkName.OnConfirmation] = context.CreateBookmark(new BookmarkCallback(OnConfirmation));

            Fx.Assert(compensationToken.BookmarkTable[CompensationBookmarkName.OnCompensation] == null, "Bookmark should not be already initialized in the bookmark table.");
            compensationToken.BookmarkTable[CompensationBookmarkName.OnCompensation] = context.CreateBookmark(new BookmarkCallback(OnCompensation));

            Fx.Assert(compensationToken.BookmarkTable[CompensationBookmarkName.OnCancellation] == null, "Bookmark should not be already initialized in the bookmark table.");
            compensationToken.BookmarkTable[CompensationBookmarkName.OnCancellation] = context.CreateBookmark(new BookmarkCallback(OnCancellation));

            Bookmark onSecondaryRootScheduled = compensationToken.BookmarkTable[CompensationBookmarkName.OnSecondaryRootScheduled];
            Fx.Assert(onSecondaryRootScheduled != null, "onSecondaryRootScheduled bookmark must be already registered.");

            compensationToken.BookmarkTable[CompensationBookmarkName.OnSecondaryRootScheduled] = null;

            context.ResumeBookmark(onSecondaryRootScheduled, compensationId);
        }

        void OnConfirmation(NativeActivityContext context, Bookmark bookmark, object value)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            long compensationId = (long)value;
            Fx.Assert(compensationId != CompensationToken.RootCompensationId, "CompensationId must be passed when resuming the Completed bookmark");

            CompensationTokenData compensationToken = compensationExtension.Get(compensationId);
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            Fx.Assert(compensationToken.CompensationState == CompensationState.Confirming, "CompensationState should be in Confirming state");

            if (TD.CompensationStateIsEnabled())
            {
                TD.CompensationState(compensationToken.DisplayName, compensationToken.CompensationState.ToString());
            }

            compensationToken.RemoveBookmark(context, CompensationBookmarkName.OnCancellation);
            compensationToken.RemoveBookmark(context, CompensationBookmarkName.OnCompensation);

            if (ConfirmationHandler != null)
            {
                context.ScheduleActivity(ConfirmationHandler, new CompletionCallback(OnConfirmationHandlerComplete), new FaultCallback(OnExceptionFromHandler));
            }
            else
            {
                this.currentCompensationToken.Set(context, new CompensationToken(compensationToken));
                if (compensationToken.ExecutionTracker.Count > 0)
                {
                    context.ScheduleActivity(DefaultConfirmation, new CompletionCallback(this.OnConfirmationComplete));
                }
                else
                {
                    compensationExtension.NotifyMessage(context, compensationToken.CompensationId, CompensationBookmarkName.Confirmed);
                }
            }
        }

        void OnConfirmationHandlerComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            Fx.Assert(context != null, "context must be valid");
            Fx.Assert(completedInstance != null, "completedInstance must be valid");

            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationTokenData compensationToken = compensationExtension.Get(this.compensationId.Get(context));
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            if (completedInstance.State == ActivityInstanceState.Closed)
            {
                Fx.Assert(compensationToken.CompensationState == CompensationState.Confirming, "CompensationParticipant should be in Confirming State");

                this.currentCompensationToken.Set(context, new CompensationToken(compensationToken));
                if (compensationToken.ExecutionTracker.Count > 0)
                {
                    context.ScheduleActivity(DefaultConfirmation, new CompletionCallback(this.OnConfirmationComplete));
                }
                else
                {
                    compensationExtension.NotifyMessage(context, compensationToken.CompensationId, CompensationBookmarkName.Confirmed);
                }
            }
        }

        void OnConfirmationComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            Fx.Assert(context != null, "context must be valid");
            Fx.Assert(completedInstance != null, "completedInstance must be valid");

            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationTokenData compensationToken = compensationExtension.Get(this.compensationId.Get(context));
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            if (completedInstance.State == ActivityInstanceState.Closed)
            {
                compensationExtension.NotifyMessage(context, compensationToken.CompensationId, CompensationBookmarkName.Confirmed);
            }
        }

        void OnCompensation(NativeActivityContext context, Bookmark bookmark, object value)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            long compensationId = (long)value;
            Fx.Assert(compensationId != CompensationToken.RootCompensationId, "CompensationId must be passed when resuming the Completed bookmark");

            CompensationTokenData compensationToken = compensationExtension.Get(compensationId);
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            Fx.Assert(compensationToken.CompensationState == CompensationState.Compensating, "CompensationState should be in Compensating state");

            if (TD.CompensationStateIsEnabled())
            {
                TD.CompensationState(compensationToken.DisplayName, compensationToken.CompensationState.ToString());
            }

            // Cleanup Bookmarks..
            compensationToken.RemoveBookmark(context, CompensationBookmarkName.OnCancellation);
            compensationToken.RemoveBookmark(context, CompensationBookmarkName.OnConfirmation);

            if (CompensationHandler != null)
            {
                context.ScheduleActivity(CompensationHandler, new CompletionCallback(this.OnCompensationHandlerComplete), new FaultCallback(OnExceptionFromHandler));
            }
            else
            {
                this.currentCompensationToken.Set(context, new CompensationToken(compensationToken));
                if (compensationToken.ExecutionTracker.Count > 0)
                {
                    context.ScheduleActivity(DefaultCompensation, new CompletionCallback(this.OnCompensationComplete));
                }
                else
                {
                    this.InternalOnCompensationComplete(context, compensationExtension, compensationToken);
                }
            }
        }

        void OnCompensationHandlerComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            Fx.Assert(context != null, "context must be valid");
            Fx.Assert(completedInstance != null, "completedInstance must be valid");

            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationTokenData compensationToken = compensationExtension.Get(this.compensationId.Get(context));
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            if (completedInstance.State == ActivityInstanceState.Closed)
            {
                Fx.Assert(compensationToken.CompensationState == CompensationState.Compensating, "CompensationParticipant should be in Compensating State");

                this.currentCompensationToken.Set(context, new CompensationToken(compensationToken));
                if (compensationToken.ExecutionTracker.Count > 0)
                {
                    context.ScheduleActivity(DefaultConfirmation, new CompletionCallback(this.OnCompensationComplete));
                }
                else
                {
                    this.InternalOnCompensationComplete(context, compensationExtension, compensationToken);
                }
            }
        }

        void OnCancellation(NativeActivityContext context, Bookmark bookmark, object value)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            long compensationId = (long)value;
            Fx.Assert(compensationId != CompensationToken.RootCompensationId, "CompensationId must be passed when resuming the Completed bookmark");

            CompensationTokenData compensationToken = compensationExtension.Get(compensationId);
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            Fx.Assert(compensationToken.CompensationState == CompensationState.Canceling, "CompensationState should be in Canceling state");

            if (TD.CompensationStateIsEnabled())
            {
                TD.CompensationState(compensationToken.DisplayName, compensationToken.CompensationState.ToString());
            }

            // remove bookmarks.
            compensationToken.RemoveBookmark(context, CompensationBookmarkName.OnCompensation);
            compensationToken.RemoveBookmark(context, CompensationBookmarkName.OnConfirmation);

            this.currentCompensationToken.Set(context, new CompensationToken(compensationToken));
            if (CancellationHandler != null)
            {
                context.ScheduleActivity(CancellationHandler, new CompletionCallback(this.OnCancellationHandlerComplete), new FaultCallback(OnExceptionFromHandler));
            }
            else
            {
                if (compensationToken.ExecutionTracker.Count > 0)
                {
                    context.ScheduleActivity(DefaultCompensation, new CompletionCallback(this.OnCompensationComplete));
                }
                else
                {
                    this.InternalOnCompensationComplete(context, compensationExtension, compensationToken);
                }
            }
        }

        void OnCancellationHandlerComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationTokenData compensationToken = compensationExtension.Get(this.compensationId.Get(context));
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            if (completedInstance.State == ActivityInstanceState.Closed)
            {
                Fx.Assert(compensationToken.CompensationState == CompensationState.Canceling, "CompensationParticipant should be in Canceling State");

                this.currentCompensationToken.Set(context, new CompensationToken(compensationToken));
                if (compensationToken.ExecutionTracker.Count > 0)
                {
                    context.ScheduleActivity(DefaultConfirmation, new CompletionCallback(this.OnCompensationComplete));
                }
                else
                {
                    this.InternalOnCompensationComplete(context, compensationExtension, compensationToken);
                }
            }
        }

        void OnCompensationComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationTokenData compensationToken = compensationExtension.Get(this.compensationId.Get(context));
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            InternalOnCompensationComplete(context, compensationExtension, compensationToken);
        }

        void InternalOnCompensationComplete(NativeActivityContext context, CompensationExtension compensationExtension, CompensationTokenData compensationToken)
        {
            switch (compensationToken.CompensationState)
            {
                case CompensationState.Canceling:
                    compensationExtension.NotifyMessage(context, compensationToken.CompensationId, CompensationBookmarkName.Canceled);
                    break;
                case CompensationState.Compensating:
                    compensationExtension.NotifyMessage(context, compensationToken.CompensationId, CompensationBookmarkName.Compensated);
                    break;
                default:
                    Fx.Assert(false, "CompensationState is in unexpected state!");
                    break;
            }
        }

        void OnExceptionFromHandler(NativeActivityFaultContext context, Exception propagatedException, ActivityInstance propagatedFrom)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationTokenData compensationToken = compensationExtension.Get(this.compensationId.Get(context));
            Fx.Assert(compensationToken != null, "CompensationTokenData must be valid");

            InvalidOperationException exception = null;

            switch (compensationToken.CompensationState)
            {
                case CompensationState.Confirming:
                    exception = new InvalidOperationException(SR.ConfirmationHandlerFatalException(compensationToken.DisplayName), propagatedException);
                    break;
                case CompensationState.Compensating:
                    exception = new InvalidOperationException(SR.CompensationHandlerFatalException(compensationToken.DisplayName), propagatedException);
                    break;
                case CompensationState.Canceling:
                    exception = new InvalidOperationException(SR.CancellationHandlerFatalException(compensationToken.DisplayName), propagatedException);
                    break;
                default:
                    Fx.Assert(false, "CompensationState is in unexpected state!");
                    break;
            }

            context.Abort(exception);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="Todo.Android">
	<uses-sdk android:minSdkVersion="15" />
	<application android:label="Todo.Android" android:icon="@drawable/check2x">
	</application>
</manifest>


text:
import re
import sys

RE_TOK = re.compile('\W')

MAP_RE = (('\|\|','(//|\.)'),
          ('\^', r'[/\\:+!@#\$^\^&\*\(\)\|]'),
          ('\*', r'.*'))

class RuleSyntaxError(Exception):
    pass

TYPE_OPTS = (('script', 'external scripts loaded via HTML script tag'),
             ('image', 'regular images, typically loaded via HTML img tag'),
             ('stylesheet', 'external CSS stylesheet files'),
             ('object', 'content handled by browser plugins, e.g. Flash or Java'),
             ('xmlhttprequest', 'requests started by the XMLHttpRequest object'),
             ('object-subrequest', 'requests started plugins like Flash'),
             ('subdocument', 'embedded pages, usually included via HTML frames'),
             ('document', 'the page itself (only exception rules can be applied to the page)'),
             ('elemhide', 'for exception rules only, similar to document but only disables element hiding rules on the page rather than all filter rules (Adblock Plus 1.2 and higher required)'),
             ('other', 'types of requests not covered in the list above'))
TYPE_OPT_IDS = [x[0] for x in TYPE_OPTS]

class Rule(object):
    def __init__(self, rule_str):
        self.rule_str = rule_str.strip()
        if '$' in rule_str:
            try:
                self.pattern, self.optstring = rule_str.split('$')
            except ValueError:
                raise RuleSyntaxError()
        else:
            self.pattern = self.rule_str
            self.optstring = ''
        self.regex = self._to_regex()
        opts = self.optstring.split(',')
        self.excluded_elements = []
        self.matched_elements = []
        for o in opts:
            if o.startswith('~') and o[1:] in TYPE_OPT_IDS:
                self.excluded_elements.append(o)
            elif o in TYPE_OPT_IDS:
                self.matched_elements.append(o)
        if self.matched_elements == []:
            self.matched_elements = TYPE_OPT_IDS

    def get_tokens(self):
        return RE_TOK.split(self.pattern)

    def match(self, url, elementtype=None):
        if elementtype:
            if elementtype in self.excluded_elements or\
                    (elementtype not in self.matched_elements and\
                         'other' not in self.matched_elements):
                return False
        return self.regex.search(url)

    def _to_regex(self):
        re_str = re.escape(self.pattern)
        for m in MAP_RE:
            re_str = re_str.replace(*m)
        return re.compile(re_str)

    def __unicode__(self):
        return self.rule_str

class Filter(object):
    def __init__(self, f, **kwargs):
        self.index = {}
        self.is_local = kwargs.get('is_local',False)
        for rul in f.xreadlines():
            if rul.startswith('!'): # Comment
                continue
            if '##' in rul: # HTML rule
                continue
            try:
                rule = Rule(rul)
            except RuleSyntaxError:
                sys.stderr.write('syntax error in rule: ' + f.name + ' ' + unicode(rul))
            for tok in rule.get_tokens():
                if len(tok) > 2:
                    if tok not in self.index:
                        self.index[tok] = []
                    self.index[tok].append(rule)

	def get_list(self):
		return self.index.values()

    def match(self, url, elementtype=None):
        matchlist = []
        tokens = RE_TOK.split(url)
        for tok in tokens:
            if len(tok) > 2:
                if tok in self.index:
                    for rule in self.index[tok]:
                        if rule.match(url, elementtype=elementtype):
                            matchlist.append(rule)

                            if self.is_local:
                                print unicode(rule)
        return matchlist

#~ if __name__ == '__main__':
    #~ f = Filter(file('easylist.txt'), is_local=True)
    #~ print 'start matching'
    #~ f.match(sys.argv[1])


text:
package io.quarkus.arc.impl;

import java.lang.annotation.Annotation;

import io.quarkus.arc.CurrentContext;
import io.quarkus.arc.CurrentContextFactory;
import io.quarkus.arc.InjectableContext.ContextState;

/**
 * The default implementation makes use of {@link ThreadLocal} variables.
 *
 * @see ThreadLocalCurrentContext
 */
final class ThreadLocalCurrentContextFactory implements CurrentContextFactory {

    @Override
    public <T extends ContextState> CurrentContext<T> create(Class<? extends Annotation> scope) {
        return new ThreadLocalCurrentContext<>();
    }

}


text:
This repo has been merged with the api.

See [this repo instead](https://github.com/FarmBot/Farmbot-Web-App).


text:
![Java CI with Gradle](https://github.com/derveloper/kotlin-openapi3-dsl/workflows/Java%20CI%20with%20Gradle/badge.svg)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/cc.vileda/kotlin-openapi3-dsl/badge.svg)](https://maven-badges.herokuapp.com/maven-central/cc.vileda/kotlin-openapi3-dsl)

Build your OpenApi3 spec in kotlin!

## import

kotlin-openapi3-dsl is available on maven central

### gradle

```groovy
compile "cc.vileda:kotlin-openapi3-dsl:1.2.0"
```

### maven
```xml
<dependency>
    <groupId>cc.vileda</groupId>
    <artifactId>kotlin-openapi3-dsl</artifactId>
    <version>1.2.0</version>
</dependency>
```

## example

for a complete example [look at the test](src/test/kotlin/cc/vileda/openapi/dsl/OpenApiDslTest.kt)

### complete vertx.io example

```kotlin

import cc.vileda.openapi.dsl.*
import io.swagger.oas.models.parameters.Parameter
import io.swagger.oas.models.security.SecurityScheme
import io.vertx.core.Handler
import io.vertx.core.json.JsonObject.mapFrom
import io.vertx.kotlin.core.http.HttpServerOptions
import io.vertx.reactivex.core.Vertx
import io.vertx.reactivex.ext.web.Router
import io.vertx.reactivex.ext.web.api.contract.openapi3.OpenAPI3RouterFactory
import io.vertx.reactivex.ext.web.handler.CorsHandler

private val vertx = Vertx.vertx()

data class HelloResponse(
        val message: String
)

data class HelloRequest(
        val message: String
)

private val api3 = openapiDsl {
    info {
        title = "test api"
        version = "0.0.1"
    }

    components {
        schema<HelloResponse>()
        schema<HelloRequest>()
        securityScheme {
            name = "apiKey"
            type = SecurityScheme.Type.APIKEY
            `in` = SecurityScheme.In.HEADER
        }
    }

    security {
        put("apiKey", emptyList())
    }

    paths {
        path("/hello") {
            get {
                tags = listOf("without params")
                operationId = "hello"
                description = "hello get"
                parameter {
                    name = "id"
                    `in` = "query"
                    required = true
                    style = Parameter.StyleEnum.SIMPLE
                    schema<String>()
                }
                responses {
                    response("200") {
                        description = "a 200 response"
                        content {
                            mediaTypeRef<HelloResponse>("application/json") {
                                description = "Hello response"
                                example = HelloResponse("World")
                            }
                        }
                    }
                }
            }
            post {
                tags = listOf("without params")
                operationId = "postHello"
                description = "hello post"
                extension("x-stable", true)
                responses {
                    response("201") {
                        description = "created response"
                        requestBody {
                            content {
                                mediaTypeRef<HelloRequest>("application/json") {
                                    description = "Hello request"
                                    example(HelloRequest("World")) {
                                        description = "hello request"
                                    }
                                }
                            }
                        }
                        content {
                            mediaType<HelloResponse>("application/json") {
                                description = "Hello response"
                                example = HelloResponse("World")
                            }
                        }
                    }
                }
            }
        }
        path("/greetings") {
            get {
                tags = listOf("without params")
                operationId = "greetings"
                description = "greetings get"
                responses {
                    response("200"){
                        description = "a 200 response"
                        content {
                            mediaTypeArrayOfRef<HelloResponse>("application/json") {
                                description = "An array of HelloResponses"
                                example = HelloResponse("Greetings")
                            }
                        }
                    }
                }
            }
        }
    }
}

fun main(args: Array<String>) {
    val apiFile = api3.asFile()
    println(api3.asJson().toString(2))
    OpenAPI3RouterFactory.rxCreateRouterFactoryFromFile(vertx, apiFile.absolutePath)
            .doOnError { it.printStackTrace() }
            .doOnSuccess(::createOperationHandlers)
            .doOnSubscribe { println("Server started") }
            .subscribe(::startServer)
}

fun startServer(routerFactory: OpenAPI3RouterFactory) {
    val mainRouter = Router.router(vertx)
    bindAdditionalHandlers(mainRouter)
    mainRouter.mountSubRouter("/", routerFactory.router)
    val server = vertx.createHttpServer(HttpServerOptions(
            port = 8080,
            host = "localhost"))
    server.requestHandler({ mainRouter.accept(it) }).listen(8080)
}

fun bindAdditionalHandlers(router: Router) {
    val create = CorsHandler.create("^.*$")
            .allowedHeaders(setOf(
                    "Content-Type",
                    "apiKey"
            ))
    router.route().handler(create)

    router.get("/spec.json").handler { routingContext ->
        routingContext.response()
                .putHeader("Content-Type", "application/json")
                .end(api3.asJson().toString(2))
    }
}

private fun createOperationHandlers(routerFactory: OpenAPI3RouterFactory) {
    routerFactory.addSecurityHandler("apiKey", Handler {
        if (it.request().getHeader("apiKey") == "foo") it.next()
        else it.fail(401)
    })

    routerFactory.addHandlerByOperationId("postHello", { routingContext ->
        routingContext.response()
                .putHeader("Content-Type", "application/json")
                .end(mapFrom(HelloResponse("Hello World!")).encode())
    })

    routerFactory.addHandlerByOperationId("hello", { routingContext ->
        routingContext.response()
                .putHeader("Content-Type", "application/json")
                .end(mapFrom(HelloResponse("Hello World!")).encode())
    })

    routerFactory.addFailureHandlerByOperationId("hello", { routingContext ->
        println("FAIL")
        routingContext.fail(500)
    })
}
```

## todo

- [x] Make compatible to vertx [OpenAPI3RouterFactory](src/main/kotlin/OpenApi3Vertx.kt)
- [ ] Implement all OpenApi3 fields
  - [ ] paths
    - [x] all HTTP methods
    - [x] minimal features
    - [x] security features
    - [ ] complete features
    - [ ] requestBody
       - [x] minimal features
       - [ ] examples
       - [ ] complete features
    - [ ] parameters
      - [x] minimal features
      - [ ] complete features
  - [x] components
  - [x] $ref to components
- [x] Publish on bintray
- [x] Publish on jcenter
- [x] Publish on maven central

## license
```
Copyright 2017 Tristan Leo

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

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

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