text:
#include "properties.h"

#include <exception>
#include <iostream>
#include <fstream>

using std::cout;
using std::endl;
using std::exception;
using odbc_jdbc::properties;
using std::ofstream;
using std::ifstream;

void write_properties() {
	properties props;
	props.setProperty("bob", "engineer");
	props.setProperty("phil", "pm");

	ofstream f("test.properties");

	f << props << endl;
	f.close();
}

void read_properties() {
	properties props;
	props.setProperty("bob", "engineer");

	ifstream f("test.properties");

	f >> props;

	cout << props << endl;
	f.close();
}

int main(int argc, char** argv) {
	try {
		write_properties();
		read_properties();
	} catch (exception& e) {
		cout << "Caught an exception:  " << e.what() << endl;
	} catch (...) {
		cout << "Something was thrown that was not a standard exception" << endl;
	}
}


text:
id: ae540960-5109-4ee2-b848-d180c30cc681
post_id: 6dc0e869-b713-490e-8c80-70a682af6aa0
draft: false
author:
    name: chaostangent
    email: john.noel@chaostangent.com
    ip: 93.96.16.21
---

I certainly don't disagree, it was just a case of realigning expectations with BONES. It's great fun and refreshingly unpretentious, there's no messages about Really Important Things or an excessive overflowing of manliness. The music is something I noticed though, it seemed to have a Persona 3/4 edge to it with some of the action scenes.

Unfortunately I can't really comment on either "old-school mecha" or "American comic book fare" being familiar with neither of them, so whether the styling gels both of them together is something I'll have to take your word on.

redpajama_set_name: RedPajamaGithub


text:
require File.dirname(__FILE__) + '/base'
require File.dirname(__FILE__) + '/stacked_mixin'

class Gruff::StackedBar < Gruff::Base
    include StackedMixin

    # Spacing factor applied between bars
    attr_accessor :bar_spacing

    # Draws a bar graph, but multiple sets are stacked on top of each other.
    def draw
      get_maximum_by_stack
      super
      return unless @has_data

      # Setup spacing.
      #
      # Columns sit stacked.
      @bar_spacing ||= 0.9
      @bar_width = @graph_width / @column_count.to_f
      padding = (@bar_width * (1 - @bar_spacing)) / 2

      @d = @d.stroke_opacity 0.0

      height = Array.new(@column_count, 0)

      @norm_data.each_with_index do |data_row, row_index|
        data_row[DATA_VALUES_INDEX].each_with_index do |data_point, point_index|
          @d = @d.fill data_row[DATA_COLOR_INDEX]

          # Calculate center based on bar_width and current row
          label_center = @graph_left + (@bar_width * point_index) + (@bar_width * @bar_spacing / 2.0)
          draw_label(label_center, point_index)

          next if (data_point == 0)
          # Use incremented x and scaled y
          left_x = @graph_left + (@bar_width * point_index) + padding
          left_y = @graph_top + (@graph_height -
                                 data_point * @graph_height -
                                 height[point_index]) + 1
          right_x = left_x + @bar_width * @bar_spacing
          right_y = @graph_top + @graph_height - height[point_index] - 1

          # update the total height of the current stacked bar
          height[point_index] += (data_point * @graph_height )

          @d = @d.rectangle(left_x, left_y, right_x, right_y)

        end

      end

      @d.draw(@base_image)
    end

end


text:
FactoryGirl.define do
  factory :admin_user do
    sequence(:email) { |n| "example#{n}@example.com" }
    password 'password'
    password_confirmation 'password'
  end
end unless FactoryGirl.factories.registered?(:admin_user)


text:
/*
Here we will learn how to count the number of documents that
meet certain criteria.

Use the parrots collection to count all documents where age
is greater than the first argument passed to your script.

Using console.log, print the number to stdout.

-------------------------------------------------------------------------------

## HINTS

To count the number of documents meeting certain criteria,
we must use the collection.count() function.

Here is an example:

    collection.count({
      name: 'foo'
    }, function(err, count) {

    })

If your program does not finish executing, you may have forgotten to
close the db. That can be done by calling db.close() after you
have finished.
*/

var mongo = require('mongodb').MongoClient

// URL to the database for this exercise
var url = 'mongodb://localhost:27017/learnyoumongo'
// read the min age from stdin
var minAge = parseInt(process.argv[2], 10)
mongo.connect(url, function(err, db) {
	// db gives access to the database
	if (err) {
		console.log(err)
		return
	}
	// collection returns a named collection
	db.collection('parrots')
		// counts results
		.count({
      'age' : {
        // $gt performs a query `greater than`
        $gt: minAge
      }
		}, function(err, count) {
			// print the results
			console.log(count)
			// don't forget to close the db connection
			db.close()
		})
})


text:
package com.opensymphony.xwork2.ognl;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.conversion.NullHandler;
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor;
import com.opensymphony.xwork2.util.CompoundRoot;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import ognl.MethodAccessor;
import ognl.OgnlRuntime;
import ognl.PropertyAccessor;

import java.util.Map;
import java.util.Set;

/**
 * Creates an Ognl value stack
 */
public class OgnlValueStackFactory implements ValueStackFactory {

    private XWorkConverter xworkConverter;
    private CompoundRootAccessor compoundRootAccessor;
    private TextProvider textProvider;
    private Container container;
    private boolean allowStaticMethodAccess;

    @Inject
    public void setXWorkConverter(XWorkConverter conv) {
        this.xworkConverter = conv;
    }

    @Inject("system")
    public void setTextProvider(TextProvider textProvider) {
        this.textProvider = textProvider;
    }

    @Inject(value="allowStaticMethodAccess", required=false)
    public void setAllowStaticMethodAccess(String allowStaticMethodAccess) {
        this.allowStaticMethodAccess = "true".equalsIgnoreCase(allowStaticMethodAccess);
    }

    public ValueStack createValueStack() {
        ValueStack stack = new OgnlValueStack(xworkConverter, compoundRootAccessor, textProvider, allowStaticMethodAccess);
        container.inject(stack);
        stack.getContext().put(ActionContext.CONTAINER, container);
        return stack;
    }

    public ValueStack createValueStack(ValueStack stack) {
        ValueStack result = new OgnlValueStack(stack, xworkConverter, compoundRootAccessor, allowStaticMethodAccess);
        container.inject(result);
        stack.getContext().put(ActionContext.CONTAINER, container);
        return result;
    }

    @Inject
    public void setContainer(Container container) throws ClassNotFoundException {
        Set<String> names = container.getInstanceNames(PropertyAccessor.class);
        for (String name : names) {
            Class cls = Class.forName(name);
            if (cls != null) {
                if (Map.class.isAssignableFrom(cls)) {
                    PropertyAccessor acc = container.getInstance(PropertyAccessor.class, name);
                }
                OgnlRuntime.setPropertyAccessor(cls, container.getInstance(PropertyAccessor.class, name));
                if (compoundRootAccessor == null && CompoundRoot.class.isAssignableFrom(cls)) {
                    compoundRootAccessor = (CompoundRootAccessor) container.getInstance(PropertyAccessor.class, name);
                }
            }
        }

        names = container.getInstanceNames(MethodAccessor.class);
        for (String name : names) {
            Class cls = Class.forName(name);
            if (cls != null) {
                OgnlRuntime.setMethodAccessor(cls, container.getInstance(MethodAccessor.class, name));
            }
        }

        names = container.getInstanceNames(NullHandler.class);
        for (String name : names) {
            Class cls = Class.forName(name);
            if (cls != null) {
                OgnlRuntime.setNullHandler(cls, new OgnlNullHandlerWrapper(container.getInstance(NullHandler.class, name)));
            }
        }
        if (compoundRootAccessor == null) {
            throw new IllegalStateException("Couldn't find the compound root accessor");
        }
        this.container = container;
    }
}


text:
Manual Installation
===================

Firstly, open up a command line shell in your new projects directory.

1. **Create a virtual environment**

  **Linux/Mac OSX:** :code:`pyvenv venv`

  **Windows:** :code:`c:\Python34\python -m venv myenv`

  **Python 2.7**

  ``pyvenv`` is only included with Python 3.3 onwards.
  To get virtual environments on Python 2, use the ``virtualenv`` package:

  .. code-block:: bash

      pip install virtualenv
      virtualenv venv

  **Virtualenvwrapper**

  virtualenvwrapper_ provides a set of commands which makes working with virtual environments much more pleasant. It also places all your virtual environments in one place.

  To install (make sure virtualenv is already installed):

  .. code-block:: bash

      pip install virtualenvwrapper
      export WORKON_HOME=~/Envs
      source /usr/local/bin/virtualenvwrapper.sh
      mkvirtualenv venv

  *Windows*:

  .. code-block:: bash

      pip install virtualenvwrapper-win
      mkvirtualenv venv

  .. _virtualenvwrapper: http://virtualenvwrapper.readthedocs.org/en/latest/index.html

2. **Activate the virtual environment**

  **Linux/Mac OSX:** :code:`source venv/bin/activate`

  **Windows:** :code:`venv/Scripts/activate.bat`

  **Virtualenvwrapper:** :code:`workon venv`

3. **Install PIP requirements**

  :code:`pip install -r requirements/dev.txt`

.. _Fabric: http://www.fabfile.org/

4. **Create the database and migrate**

  By default require ``PostgreSQL`` to be installed

.. code-block:: sh

    createdb my_site
   ./manage.py migrate

5. **Load the Initial Data**
   The cookiecutter comes with some pages already created for your
   convenience including the Homepage with a working ``bx_slider`` slide show,
   contact page, events and news/blog pages. To generate these pages run:

  :code:`./manage.py load_initial_data`

  The default Admin username is *admin*

  The default Admin password is *admin123*

6. **Install Packages (Foundation, Font-Awesome etc.) using Bower package manager**

  We use bower_ for front-end dependency management. To install front
  dependencies use

  :code:`bower install`

  This will install the supported version of `Zurb Foundation`_, `Font
  Awesome`_ and bxSlider_ as well as their dependencies.

  ..  _bower: http://bower.io
  ..  _bxSlider: http://bxslider.com
  ..  _`Font Awesome`: http://fontawesome.io

7. **Run the development server**

  :code:`./manage.py runserver`

  Your site is now accessible at ``http://localhost:8000``,
  with the admin backend available at ``http://localhost:8000/admin/``.

.. _`Zurb Foundation`: https://foundation.zurb.com


text:
<?php

include("general_header.php");

ob_start();
include('./template/register.html');
$js_array = array (
	'jquery',
	'register.js'
	);

$str = ob_get_contents();
ob_end_clean();

$register_form = '
	<form action="" method="post" id="register-form">

			<fieldset>

Change account password

					Current Password
					<input type="password" id="change-password-current" name="password" class="round full-size-input" />

					New Password
					<input type="password" id="change-password-new1" name="password" class="round full-size-input" />

					Confirm New Password
					<input type="password" id="change-password-new2" name="password" class="round full-size-input" />

				<input type="submit" value"Login" class="button round blue text-upper image-right ic-right-arrow" id="btn-change-password"/>

Invalid password. Your password should be between 4 to 20 characters.

Confirmation error. Your inputted passwords do not match.

Your current password is not correct.

Password.

			</fieldset>

		</form>';

$str = str_replace('{JS-AREA-HERE}', load_js($js_array), $str);
$str = str_replace('{URL-BASE}', $url . 'template/', $str);
$str = str_replace('{REGISTER-FORM-HERE}', $register_form, $str);
$str = top_bar($str);
$str = str_replace('{CUBOCUBE-BOOK-ID}', $_SESSION['cubogroup'], $str);

echo $str;

//echo $register_form;
//echo $str_register;

?>


text:
<?php

namespace Adldap\Models\Concerns;

trait HasDescription
{
    /**
     * Returns the models's description.
     *
     * @link https://msdn.microsoft.com/en-us/library/ms675492(v=vs.85).aspx
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->getFirstAttribute($this->schema->description());
    }

    /**
     * Sets the models's description.
     *
     * @param string $description
     *
     * @return $this
     */
    public function setDescription($description)
    {
        return $this->setFirstAttribute($this->schema->description(), $description);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <groupId>org.drools</groupId>
    <artifactId>drools-wb-screens</artifactId>
    <version>6.4.0-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>drools-wb-globals-editor</artifactId>
  <packaging>pom</packaging>

  <name>Drools Workbench - Globals Editor</name>
  <description>Drools Workbench - Globals Editor</description>

  <modules>
    <module>drools-wb-globals-editor-api</module>
    <module>drools-wb-globals-editor-backend</module>
    <module>drools-wb-globals-editor-client</module>
  </modules>

</project>


text:
package org.pentaho.big.data.kettle.plugins.job;

/**
 * Represents visible states of the UI and the execution mode.
 *
 * User: RFellows Date: 6/11/12
 */
public enum JobEntryMode {
  QUICK_SETUP, ADVANCED_LIST, ADVANCED_COMMAND_LINE
}


text:
from CommonServerPython import *

import json
import io
from unittest import mock
from unittest.mock import patch
import SailPointIdentityNow

''' TEST CONSTANTS '''

MOCK_IDENTITYNOW_BASE_URL = 'https://org.api.identitynow.com'
MOCK_BEARER_TOKEN = 'RXAxTEQ0ZkhUVm94dmhIWDd1M2Q0TjU3NDRnQUYzN2ouZXVlV2h1WUk4OW9jMi95Zml'
MOCK_HEADERS = {
    'Authorization': 'Bearer %s' % MOCK_BEARER_TOKEN,
    'Content-Type': 'application/json'
}
MOCK_CLIENT = SailPointIdentityNow.Client(base_url=MOCK_IDENTITYNOW_BASE_URL, verify=False, proxy=False,
                                          headers=MOCK_HEADERS, max_results=250, request_timeout=10)

''' HELPER/UTILITY FUNCTIONS '''

def util_load_txt(path: str):
    """
    Utility to load text data from a local folder.
    """
    with io.open(path, mode='r', encoding='utf-8') as file:
        return file.read()

def util_load_json(path: str):
    """
    Utility to load json data from a local folder.
    """
    with io.open(path, mode='r', encoding='utf-8') as file:
        return json.loads(file.read())

def util_mock_http_resp(status: int, json_data=None):
    """
    Utility to mock http response.
    """
    response = mock.Mock()
    response.status_code = status
    if json_data is not None:
        response.json = mock.Mock(return_value=json_data)
    return response

def verify_identity(identity):
    """
    Verify IdentityNow Identity/User.
    """
    assert identity['id'] is not None
    assert identity['name'] is not None
    assert identity['displayName'] is not None
    assert identity['firstName'] is not None
    assert identity['lastName'] is not None
    assert identity['email'] is not None
    assert identity['created'] is not None
    assert identity['modified'] is not None
    assert isinstance(identity['inactive'], (bool))
    assert identity['protected'] is not None
    assert identity['status'] is not None
    assert isinstance(identity['isManager'], (bool))
    assert identity['identityProfile'] is not None
    assert identity['source'] is not None
    assert identity['attributes'] is not None
    assert identity['accounts'] is not None
    assert identity['accountCount'] >= 0
    assert identity['appCount'] >= 0
    assert identity['accessCount'] >= 0
    assert identity['entitlementCount'] >= 0
    assert identity['roleCount'] >= 0
    assert identity['accessProfileCount'] >= 0
    assert identity['pod'] is not None
    assert identity['org'] is not None
    assert identity['type'] == 'identity'

def verify_account(account):
    """
    Verify IdentityNow Account.
    """
    assert account['id'] is not None
    assert account['name'] is not None
    assert account['sourceId'] is not None
    # assert account['identityId'] is not None
    assert account['nativeIdentity'] is not None
    assert account['created'] is not None
    assert account['modified'] is not None
    assert isinstance(account['disabled'], (bool))
    assert isinstance(account['locked'], (bool))
    assert isinstance(account['authoritative'], (bool))
    assert isinstance(account['systemAccount'], (bool))
    assert isinstance(account['uncorrelated'], (bool))
    assert isinstance(account['manuallyCorrelated'], (bool))
    assert isinstance(account['hasEntitlements'], (bool))
    assert account['attributes'] is not None

def verify_account_activity(account_activity):
    """
    Verify IdentityNow Account Activity.
    """
    assert account_activity['id'] is not None
    assert account_activity['name'] is not None
    assert account_activity['created'] is not None
    assert account_activity['modified'] is not None
    assert account_activity['completed'] is not None
    assert account_activity['completionStatus'] is not None
    assert account_activity['type'] is not None
    assert account_activity['requesterIdentitySummary'] is not None
    assert account_activity['targetIdentitySummary'] is not None
    assert account_activity['items'] is not None
    assert account_activity['executionStatus'] is not None
    assert isinstance(account_activity['cancelable'], (bool))

def verify_access_profile(access_profile):
    """
    Verify IdentityNow Access profile.
    """
    assert access_profile['id'] is not None
    assert access_profile['name'] is not None
    assert access_profile['source'] is not None
    assert access_profile['entitlements'] is not None
    assert access_profile['entitlementCount'] is not None
    assert access_profile['created'] is not None
    assert access_profile['modified'] is not None
    assert access_profile['synced'] is not None
    assert isinstance(access_profile['enabled'], (bool))
    assert isinstance(access_profile['requestable'], (bool))
    assert isinstance(access_profile['requestCommentsRequired'], (bool))
    assert access_profile['owner'] is not None
    assert access_profile['pod'] is not None
    assert access_profile['org'] is not None
    assert access_profile['type'] == 'accessprofile'

def verify_role(role):
    """
    Verify IdentityNow Role.
    """
    assert role['id'] is not None
    assert role['name'] is not None
    assert role['accessProfiles'] is not None
    assert role['created'] is not None
    assert role['modified'] is not None
    assert role['synced'] is not None
    assert isinstance(role['enabled'], (bool))
    assert isinstance(role['requestable'], (bool))
    assert isinstance(role['requestCommentsRequired'], (bool))
    assert role['owner'] is not None
    assert role['pod'] is not None
    assert role['org'] is not None
    assert role['type'] == 'role'

def verify_entitlement(entitlement):
    """
    Verify IdentityNow Entitlement.
    """
    assert entitlement['id'] is not None
    assert entitlement['name'] is not None
    assert entitlement['displayName'] is not None
    assert entitlement['modified'] is not None
    assert entitlement['synced'] is not None
    assert entitlement['source'] is not None
    assert isinstance(entitlement['privileged'], (bool))
    # assert entitlement['identityCount'] >= 0
    assert entitlement['attribute'] is not None
    assert entitlement['value'] is not None
    assert entitlement['schema'] is not None
    assert entitlement['pod'] is not None
    assert entitlement['org'] is not None
    assert entitlement['type'] == 'entitlement'

def verify_event(event):
    """
    Verify IdentityNow Event.
    """
    assert event['id'] is not None
    assert event['name'] is not None
    assert event['stack'] is not None
    assert event['created'] is not None
    assert event['synced'] is not None
    assert event['objects'] is not None
    assert event['technicalName'] is not None
    assert event['target'] is not None
    assert event['actor'] is not None
    assert event['action'] is not None
    assert event['attributes'] is not None
    assert event['operation'] is not None
    assert event['status'] is not None
    assert event['pod'] is not None
    assert event['org'] is not None
    assert event['type'] is not None

''' TESTS (UTILITY)'''

def test_get_headers_all_none():
    headers = SailPointIdentityNow.get_headers(None, None, None, None)
    assert headers is None

def test_get_headers_base_url_none():
    headers = SailPointIdentityNow.get_headers(None, 'test', 'test', 'client_credentials')
    assert headers is None

def test_get_headers_client_id_none():
    headers = SailPointIdentityNow.get_headers(MOCK_IDENTITYNOW_BASE_URL, None, 'test', 'client_credentials')
    assert headers is None

def test_get_headers_client_secret_none():
    headers = SailPointIdentityNow.get_headers(MOCK_IDENTITYNOW_BASE_URL, 'test', None, 'client_credentials')
    assert headers is None

@patch('SailPointIdentityNow.get_headers')
def test_get_headers_grant_type(mock_header):
    mock_header.return_value = {
        'Authorization': 'Bearer RXAxTEQ0ZkhUVm94dmhIWDd1M2Q0TjU3NDRnQUYzN2ouZXVlV2h1WUk4OW9jMi95Zml',
        'Content-Type': 'application/json'
    }
    headers = SailPointIdentityNow.get_headers(MOCK_IDENTITYNOW_BASE_URL, 'test', 'test', None)
    assert headers['Authorization'] == 'Bearer RXAxTEQ0ZkhUVm94dmhIWDd1M2Q0TjU3NDRnQUYzN2ouZXVlV2h1WUk4OW9jMi95Zml'
    assert headers['Content-Type'] == 'application/json'

@patch('SailPointIdentityNow.get_headers')
def test_get_headers_success(mock_header):
    mock_header.return_value = {
        'Authorization': 'Bearer RXAxTEQ0ZkhUVm94dmhIWDd1M2Q0TjU3NDRnQUYzN2ouZXVlV2h1WUk4OW9jMi95Zml',
        'Content-Type': 'application/json'
    }
    headers = SailPointIdentityNow.get_headers(MOCK_IDENTITYNOW_BASE_URL, 'test', 'test', 'client_credentials')
    assert headers['Authorization'] == 'Bearer RXAxTEQ0ZkhUVm94dmhIWDd1M2Q0TjU3NDRnQUYzN2ouZXVlV2h1WUk4OW9jMi95Zml'
    assert headers['Content-Type'] == 'application/json'

def test_build_query_object_all_none():
    query_object = SailPointIdentityNow.build_query_object(None, None)
    assert query_object is None

def test_build_query_object_object_type_none():
    query_object = SailPointIdentityNow.build_query_object(None, "*")
    assert query_object is None

def test_build_query_object_query_none():
    query_object = SailPointIdentityNow.build_query_object("identities", None)
    assert query_object is None

def test_build_query_invalid_object_type():
    query_object = SailPointIdentityNow.build_query_object("test", "*")
    assert query_object is None

def test_build_query():
    query_object = SailPointIdentityNow.build_query_object("identities", "*")
    assert query_object['indices'] == ["identities"]
    assert query_object['query']['query'] == "*"

def test_get_markdown_none():
    markdown = SailPointIdentityNow.get_markdown(None, None)
    assert markdown == ''

def test_get_markdown_object_type_none():
    json_data = util_load_json('test_data/Identity.json')
    markdown = SailPointIdentityNow.get_markdown(None, json_data)
    assert markdown == ''

def test_get_markdown_objects_none():
    markdown = SailPointIdentityNow.get_markdown('IdentityNow.Identity', None)
    headers = ['id', 'name', 'displayName', 'firstName', 'lastName', 'email', 'created', 'modified', 'inactive',
               'protected', 'status', 'isManager', 'identityProfile', 'source', 'attributes', 'accounts',
               'accountCount', 'appCount', 'accessCount', 'entitlementCount', 'roleCount', 'accessProfileCount',
               'pod', 'org', 'type']
    assert markdown == tableToMarkdown('Identity(Identities)', None, headers=headers)

def test_get_markdown():
    json_data = util_load_json('test_data/Identity.json')
    markdown = SailPointIdentityNow.get_markdown('IdentityNow.Identity', json_data)
    headers = ['id', 'name', 'displayName', 'firstName', 'lastName', 'email', 'created', 'modified', 'inactive',
               'protected', 'status', 'isManager', 'identityProfile', 'source', 'attributes', 'accounts',
               'accountCount', 'appCount', 'accessCount', 'entitlementCount', 'roleCount', 'accessProfileCount',
               'pod', 'org', 'type']
    assert markdown == tableToMarkdown('Identity(Identities)', json_data, headers=headers)

def test_build_results_none():
    response = util_mock_http_resp(500, None)
    results = SailPointIdentityNow.build_results(None, None, response)
    assert results is None

def test_build_results_non_2xx_status():
    status_txt = util_load_txt('test_data/404_Not_Found.txt')
    response = util_mock_http_resp(404, status_txt)
    results = SailPointIdentityNow.build_results('Test.prefix', 'Test.key_field', response)
    assert results is None

def test_build_results_2xx_status():
    json_data = util_load_json('test_data/Identity.json')
    response = util_mock_http_resp(200, json_data)
    results = SailPointIdentityNow.build_results('IdentityNow.Identity', 'IdentityNow.Identity', response)
    assert results.readable_output == '### Results:\n' + SailPointIdentityNow.get_markdown('IdentityNow.Identity',
                                                                                json_data)
    assert results.outputs_prefix == 'IdentityNow.Identity'
    assert results.outputs_key_field == 'IdentityNow.Identity'
    verify_identity(results.outputs)

''' TESTS (COMMAND)'''

@patch('SailPointIdentityNow.get_headers')
def test_connection_fail(mock_header):
    mock_header.side_effect = ConnectionError('Unable to fetch headers from IdentityNow!')
    test_connection = SailPointIdentityNow.test_connection(MOCK_IDENTITYNOW_BASE_URL, 'test', 'test',
                                                           'client_credentials')
    assert test_connection == 'Error Connecting : Unable to fetch headers from IdentityNow!'

@patch('SailPointIdentityNow.get_headers')
def test_connection_unauthorized(mock_header):
    mock_header.side_effect = ConnectionError('Bad client credentials')
    test_connection = SailPointIdentityNow.test_connection(MOCK_IDENTITYNOW_BASE_URL, 'test', 'test',
                                                           'client_credentials')
    assert test_connection == 'Error Connecting : Bad client credentials'

@patch('SailPointIdentityNow.get_headers')
def test_connection_success(mock_header):
    mock_header.return_value = {
        'Authorization': 'Bearer RXAxTEQ0ZkhUVm94dmhIWDd1M2Q0TjU3NDRnQUYzN2ouZXVlV2h1WUk4OW9jMi95Zml',
        'Content-Type': 'application/json'
    }
    test_connection = SailPointIdentityNow.test_connection(MOCK_IDENTITYNOW_BASE_URL, 'test', 'test',
                                                           'client_credentials')
    assert test_connection == 'ok'

def test_search_object_type_none():
    response = SailPointIdentityNow.search(MOCK_CLIENT, None, '*', 0, 0)
    assert response is None

def test_search_object_type_not_in_list():
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'test', '*', 0, 0)
    assert response is None

@patch('SailPointIdentityNow.Client.send_request')
def test_search_negative_offset(mock_search_empty_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_search_empty_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'identities', '*', -1, 0)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_search_exceeds_limit(mock_search_empty_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_search_empty_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'identities', '*', 0, 1000)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_search_identity_not_found(mock_search_identity_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_search_identity_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'identities', 'id:2c918084740346d5017408d79229489ex', 0, 250)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_search_identity_found(mock_search_identity_response):
    json_data = util_load_json('test_data/Identity.json')
    mock_search_identity_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'identities', 'id:2c918084740346d5017408d79229489e', 0, 250)
    assert response.status_code == 200
    verify_identity(response.json())
    assert response.json().get('id') == '2c918084740346d5017408d79229489e'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_accounts_id_not_found(mock_account_response):
    text = util_load_txt('test_data/404_Not_Found.txt')
    mock_account_response.return_value = util_mock_http_resp(404, text)
    response = SailPointIdentityNow.get_accounts(MOCK_CLIENT, '2c918084705f18bd01706349f23e5eb3x', None, None, 0, 250)
    assert response.status_code == 404
    assert response.json() == 'Link with ID or name 2c918084705f18bd01706349f23e5eb3x was not found.'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_accounts_id_found(mock_account_response):
    json_data = util_load_json('test_data/Account.json')
    mock_account_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_accounts(MOCK_CLIENT, '2c918084740346d30174088afa6d625e', None, None, 0, 250)
    assert response.status_code == 200
    verify_account(response.json())
    assert response.json().get('id') == '2c918084740346d30174088afa6d625e'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_accounts_name_not_found(mock_account_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_account_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_accounts(MOCK_CLIENT, None, 'Tes.Testerson', None, 0, 250)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_get_accounts_name_found(mock_account_response):
    json_data = util_load_json('test_data/Account.json')
    mock_account_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_accounts(MOCK_CLIENT, None, 'Testy.Testerson', 'native_identity', 0, 250)
    assert response.status_code == 200
    verify_account(response.json())
    assert response.json().get('name') == 'Testy.Testerson'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_accounts_native_identity_not_found(mock_account_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_account_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_accounts(MOCK_CLIENT, None, None, '412632345', 0, 250)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_get_accounts_native_identity_found(mock_account_response):
    json_data = util_load_json('test_data/Account.json')
    mock_account_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_accounts(MOCK_CLIENT, None, None, '41263', 0, 250)
    assert response.status_code == 200
    verify_account(response.json())
    assert response.json().get('nativeIdentity') == '41263'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_id_not_found(mock_account_activities_response):
    json_data = util_load_json('test_data/404_Not_Found.json')
    mock_account_activities_response.return_value = util_mock_http_resp(404, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, '2c918084705f18bd01706349f23e5eb3x', None, None,
                                                           None, None, 0, 250)
    assert response.status_code == 404
    assert response.json().get('detailCode') == '404 Not found'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_id_found(mock_account_activities_response):
    json_data = util_load_json('test_data/Account_Activity.json')
    mock_account_activities_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, '4fcac89c839f4e4dbeef2810a435f9f6', None, None,
                                                           None, None, 0, 250)
    assert response.status_code == 200
    verify_account_activity(response.json())
    assert response.json().get('id') == '4fcac89c839f4e4dbeef2810a435f9f6'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_requested_for_not_found(mock_account_activities_response):
    json_data = util_load_json('test_data/400_Bad_Request_Content.json')
    mock_account_activities_response.return_value = util_mock_http_resp(400, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, '2c91808a6fca28a6016fd7f5ec3f5228x', None,
                                                           None, None, 0, 250)
    assert response.status_code == 400
    assert response.json().get('detailCode') == '400.1 Bad request content'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_requested_for_found(mock_account_activities_response):
    json_data = util_load_json('test_data/Account_Activity.json')
    mock_account_activities_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, '2c91808a6fca28a6016fd7f5ec3f5228', None,
                                                           None, None, 0, 250)
    assert response.status_code == 200
    verify_account_activity(response.json())
    assert response.json().get('targetIdentitySummary').get('id') == '2c91808a6fca28a6016fd7f5ec3f5228'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_requested_by_not_found(mock_account_activities_response):
    json_data = util_load_json('test_data/400_Bad_Request_Content.json')
    mock_account_activities_response.return_value = util_mock_http_resp(400, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, None, '2c91808363f06ad80163fb690fae55b8x',
                                                           None, None, 0, 250)
    assert response.status_code == 400
    assert response.json().get('detailCode') == '400.1 Bad request content'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_requested_by_found(mock_account_activities_response):
    json_data = util_load_json('test_data/Account_Activity.json')
    mock_account_activities_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, None, '2c91808363f06ad80163fb690fae55b8',
                                                           None, None, 0, 250)
    assert response.status_code == 200
    verify_account_activity(response.json())
    assert response.json().get('requesterIdentitySummary').get('id') == '2c91808363f06ad80163fb690fae55b8'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_regarding_identity_not_found(mock_account_activities_response):
    json_data = util_load_json('test_data/400_Bad_Request_Content.json')
    mock_account_activities_response.return_value = util_mock_http_resp(400, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, None, None,
                                                           '2c91808a6fca28a6016fd7f5ec3f5228x', None, 0, 250)
    assert response.status_code == 400
    assert response.json().get('detailCode') == '400.1 Bad request content'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_regarding_identity_found(mock_account_activities_response):
    json_data = util_load_json('test_data/Account_Activity.json')
    mock_account_activities_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, None, None,
                                                           '2c91808a6fca28a6016fd7f5ec3f5228', None, 0, 250)
    assert response.status_code == 200
    verify_account_activity(response.json())
    assert response.json().get('requesterIdentitySummary').get('id') == '2c91808363f06ad80163fb690fae55b8'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_type_not_found(mock_account_activities_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_account_activities_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, None, None, None, 'Test', 0, 250)
    assert response.status_code == 200

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities_type_found(mock_account_activities_response):
    json_data = util_load_json('test_data/Account_Activity.json')
    mock_account_activities_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, None, None, None, 'appRequest', 0, 250)
    assert response.status_code == 200
    verify_account_activity(response.json())
    assert response.json().get('type') == 'appRequest'

@patch('SailPointIdentityNow.Client.send_request')
def test_get_account_activities(mock_account_activities_response):
    json_data = util_load_json('test_data/Account_Activity.json')
    mock_account_activities_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.get_account_activities(MOCK_CLIENT, None, '2c91808a6fca28a6016fd7f5ec3f5228',
                                                           '2c91808363f06ad80163fb690fae55b8', None, None, 0, 250)
    assert response.status_code == 200
    verify_account_activity(response.json())
    assert response.json().get('targetIdentitySummary').get('id') == '2c91808a6fca28a6016fd7f5ec3f5228'
    assert response.json().get('requesterIdentitySummary').get('id') == '2c91808363f06ad80163fb690fae55b8'

@patch('SailPointIdentityNow.Client.send_request')
def test_search_access_profile_not_found(mock_search_access_profile_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_search_access_profile_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'accessprofiles', 'id:2c91808a700d408901701223fb6b007d', 0, 250)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_search_access_profile_found(mock_search_access_profile_response):
    json_data = util_load_json('test_data/Access_Profile.json')
    mock_search_access_profile_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'accessprofiles', 'id:2c91808a700d408901701223fb6b0077', 0, 250)
    assert response.status_code == 200
    verify_access_profile(response.json())
    assert response.json().get('id') == '2c91808a700d408901701223fb6b0077'

@patch('SailPointIdentityNow.Client.send_request')
def test_search_role_not_found(mock_search_role_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_search_role_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'roles', 'id:2c9180846ff9c50201700beb2e9000dd', 0, 250)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_search_role_found(mock_search_role_response):
    json_data = util_load_json('test_data/Role.json')
    mock_search_role_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'roles', 'id:2c9180846ff9c50201700beb2e9000da', 0, 250)
    assert response.status_code == 200
    verify_role(response.json())
    assert response.json().get('id') == '2c9180846ff9c50201700beb2e9000da'

@patch('SailPointIdentityNow.Client.send_request')
def test_search_entitlement_not_found(mock_search_entitlement_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_search_entitlement_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'entitlements', 'id:2c9180846ff7e56b01700bb399f60ead', 0, 250)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_search_entitlement_found(mock_search_entitlement_response):
    json_data = util_load_json('test_data/Entitlement.json')
    mock_search_entitlement_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'entitlements', 'id:2c9180846ff7e56b01700bb399f60eaa', 0, 250)
    assert response.status_code == 200
    verify_entitlement(response.json())
    assert response.json().get('id') == '2c9180846ff7e56b01700bb399f60eaa'

@patch('SailPointIdentityNow.Client.send_request')
def test_search_event_not_found(mock_search_event_response):
    json_data = util_load_json('test_data/200_Empty_Response.json')
    mock_search_event_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'events', 'id:2bd61299-d986-4c27-bd37-408b9c9ba11d', 0, 250)
    assert response.status_code == 200
    assert response.json() == []

@patch('SailPointIdentityNow.Client.send_request')
def test_search_event_found(mock_search_event_response):
    json_data = util_load_json('test_data/Event.json')
    mock_search_event_response.return_value = util_mock_http_resp(200, json_data)
    response = SailPointIdentityNow.search(MOCK_CLIENT, 'events', 'id:2bd61299-d986-4c27-bd37-408b9c9ba118', 0, 250)
    assert response.status_code == 200
    verify_event(response.json())
    assert response.json().get('id') == '2bd61299-d986-4c27-bd37-408b9c9ba118'

def test_access_request_requested_for_none():
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', None,
                                                   '2c918086775e1f5d0177653720ea0381', 'ROLE', 'Testing')
    assert response is None

def test_access_request_requested_item_none():
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', '2c91808363f06ad80163fb690fae55b8',
                                                   None, 'ROLE', 'Testing')
    assert response is None

def test_access_request_requested_item_type_none():
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', '2c91808363f06ad80163fb690fae55b8',
                                                   '2c918086775e1f5d0177653720ea0381', None, 'Testing')
    assert response is None

@patch('SailPointIdentityNow.Client.send_request')
def test_access_request_requested_for_not_found(mock_access_request_grant_response):
    json_data = util_load_json('test_data/400_Bad_Request_Object_Not_Found.json')
    mock_access_request_grant_response.return_value = util_mock_http_resp(400, json_data)
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', '2c9180886ccef167016cdb658fb6547d',
                                                   '2c918086775e1f5d0177653720ea0381', 'ROLE', 'Testing')
    assert response.get('detailCode') == '400.1.404 Referenced object not found'

@patch('SailPointIdentityNow.Client.send_request')
def test_access_request_requested_item_not_found(mock_access_request_grant_response):
    json_data = util_load_json('test_data/400_Bad_Request_Object_Not_Found.json')
    mock_access_request_grant_response.return_value = util_mock_http_resp(400, json_data)
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', '2c9180886ccef167016cdb658fb6547d',
                                                   '2c918086775e1f5d0177653720ea038d', 'ROLE', 'Testing')
    assert response.get('detailCode') == '400.1.404 Referenced object not found'

@patch('SailPointIdentityNow.Client.send_request')
def test_access_request_requested_item_type_invalid(mock_access_request_grant_response):
    json_data = util_load_json('test_data/400_Bad_Request_Illegal_Value.json')
    mock_access_request_grant_response.return_value = util_mock_http_resp(400, json_data)
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', '2c9180886ccef167016cdb658fb6547d',
                                                   '2c918086775e1f5d0177653720ea038d', 'TEST', 'Testing')
    assert response.get('detailCode') == '400.1.3 Illegal value'

@patch('SailPointIdentityNow.Client.send_request')
def test_access_request_re_grant(mock_access_request_grant_response):
    json_data = util_load_json('test_data/400_Bad_Request_Content.json')
    mock_access_request_grant_response.return_value = util_mock_http_resp(400, json_data)
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', '2c9180886ccef167016cdb658fb6547a',
                                                   '2c918086775e1f5d01776530eb67037b', 'TEST', 'Testing')
    assert response.get('detailCode') == '400.1 Bad request content'

@patch('SailPointIdentityNow.Client.send_request')
def test_access_request_grant(mock_access_request_grant_response):
    mock_access_request_grant_response.return_value = util_mock_http_resp(200, None)
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'GRANT_ACCESS', '2c91808363f06ad80163fb690fae55b8',
                                                   '2c918086775e1f5d0177653720ea0381', 'ROLE', 'Testing')
    assert response == 'Access request was successful!'

@patch('SailPointIdentityNow.Client.send_request')
def test_access_request_revoke(mock_access_request_revoke_response):
    mock_access_request_revoke_response.return_value = util_mock_http_resp(200, None)
    response = SailPointIdentityNow.access_request(MOCK_CLIENT, 'REVOKE_ACCESS', '2c91808363f06ad80163fb690fae55b8',
                                                   '2c918086775e1f5d0177653720ea0381', 'ROLE', 'Testing')
    assert response == 'Access request was successful!'


text:
// Code generated by lister-gen. DO NOT EDIT.

package internalversion

import (
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
	storage "k8s.io/kubernetes/pkg/apis/storage"
)

// VolumeAttachmentLister helps list VolumeAttachments.
type VolumeAttachmentLister interface {
	// List lists all VolumeAttachments in the indexer.
	List(selector labels.Selector) (ret []*storage.VolumeAttachment, err error)
	// Get retrieves the VolumeAttachment from the index for a given name.
	Get(name string) (*storage.VolumeAttachment, error)
	VolumeAttachmentListerExpansion
}

// volumeAttachmentLister implements the VolumeAttachmentLister interface.
type volumeAttachmentLister struct {
	indexer cache.Indexer
}

// NewVolumeAttachmentLister returns a new VolumeAttachmentLister.
func NewVolumeAttachmentLister(indexer cache.Indexer) VolumeAttachmentLister {
	return &volumeAttachmentLister{indexer: indexer}
}

// List lists all VolumeAttachments in the indexer.
func (s *volumeAttachmentLister) List(selector labels.Selector) (ret []*storage.VolumeAttachment, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*storage.VolumeAttachment))
	})
	return ret, err
}

// Get retrieves the VolumeAttachment from the index for a given name.
func (s *volumeAttachmentLister) Get(name string) (*storage.VolumeAttachment, error) {
	obj, exists, err := s.indexer.GetByKey(name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(storage.Resource("volumeattachment"), name)
	}
	return obj.(*storage.VolumeAttachment), nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Wox.Infrastructure.Logger;
using Wox.Plugin;

namespace Wox.Core.Plugin
{
    internal class CSharpPluginLoader : IPluginLoader
    {
        public IEnumerable<PluginPair> LoadPlugin(List<PluginMetadata> pluginMetadatas)
        {
            var plugins = new List<PluginPair>();
            List<PluginMetadata> CSharpPluginMetadatas = pluginMetadatas.Where(o => o.Language.ToUpper() == AllowedLanguage.CSharp.ToUpper()).ToList();

            foreach (PluginMetadata metadata in CSharpPluginMetadatas)
            {
                try
                {
                    Assembly asm = Assembly.Load(AssemblyName.GetAssemblyName(metadata.ExecuteFilePath));
                    List<Type> types = asm.GetTypes().Where(o => o.IsClass && !o.IsAbstract &&  o.GetInterfaces().Contains(typeof(IPlugin))).ToList();
                    if (types.Count == 0)
                    {
                        Log.Warn(string.Format("Couldn't load plugin {0}: didn't find the class that implement IPlugin", metadata.Name));
                        continue;
                    }

                    foreach (Type type in types)
                    {
                        PluginPair pair = new PluginPair()
                        {
                            Plugin = Activator.CreateInstance(type) as IPlugin,
                            Metadata = metadata
                        };

                        plugins.Add(pair);
                    }
                }
                catch (System.Exception e)
                {
                    Log.Error(string.Format("Couldn't load plugin {0}: {1}", metadata.Name, e.Message));
#if (DEBUG)
                    {
                        throw;
                    }
#endif
                }
            }

            return plugins;
        }
    }
}


text:
There are many starter kits that will help you get started with React and Redux. This is the one created by, maintained by and used by [Atomic Jolt](http://www.atomicjolt.com). Atomic Jolt uses this as application as a starting place for our [Ruby on Rails React starter application](https://github.com/atomicjolt/react_starter_app) and our [Firebase React starter appliction](https://github.com/atomicjolt/react_firebase_starter_app).

#Getting Started:
-----------------------

Make sure to install git and npm before you start then:

1. git clone https://github.com/atomicjolt/react_client_starter_app.git my_project_name
2. Rename .env.example to .env. This file contains the port the server will use. The default 8080 should be fine, but you can also use a local domain or ngrok if you wish.
3. npm install
4. Start server with:

  `npm run hot`

then visit http://localhost:8080

# Using the Color Keys Printing App
-----------------------
Source code lives in the client directory. Modify html and js files in that directory to build your application.

## React.js
-----------
React code can be found in client/js. We use Redux and the React-Router.

## Html
-----------
All html files live in client/html. The build process will properly process ejs in any html files as well as process markdown for files that end in .md. All front matter in .md files will be available to the ejs templates. See about.md for an example.

## Assets
-----------
Any files added to the assets directory can be used by in code and assigned to a variable. This
allows for referring to assets using dynamically generated strings. The assets will be built according to
the rules specified in your webpack configuration. Typically, this means that in production the names will
be changed to include a SHA.

First importing the assets:
  `import assets from '../libs/assets';`

Then assign the assest to a variable:
  `const img = assets("./images/atomicjolt.jpg");`

The value can then be used when rendering:
  `render(){
    const img = assets("./images/atomicjolt.jpg");
    return

;
  }`

## Static
-----------
Files added to the static directory will be copied directly into the build. These files will not be renamed.

#Tests
-----------
Karma and Jasmine are used for testing. To run tests run:

  `npm run test`

#Check for updates
-----------
Inside the client directory run:

  `npm-check-updates`

#Setup Deploy:
-----------------------

  1. Install the s3_website gem:

    `gem install s3_website`

  2. Create s3_website.yml:

    `s3_website cfg create`

  3. Setup and AWS user:

    1. Login to your AWS console
    2. Find Identity & Access Management (IAM)
    3. Click 'Users'
    4. Click 'Create New Users'
    5. Save the user's credentials
    6. Click on the user
    7. Click the permissions tab.
    8. Under 'Inline Policies' create a new custom policy and paste in the policy below. Be sure to change the domains:

    For more details see the [s3_website gem instructions](https://github.com/laurilehmijoki/s3_website).

    ###IAM Policy:
    ```json

      {
        "Statement": [
            {
                "Action": [
                    "s3:ListBucket"
                ],
                "Effect": "Allow",
                "Resource": "arn:aws:s3:::www.reactclientstarterapp.com"
            },
            {
                "Action": "s3:*",
                "Effect": "Allow",
                "Resource": [
                    "arn:aws:s3:::www.reactclientstarterapp.com",
                    "arn:aws:s3:::www.reactclientstarterapp.com/*"
                ]
            }
        ]
      }
    ```

  4. Configure bucket as website:

    `s3_website cfg apply`

#Production
-----------------------
If you want to see what your application will look like in production run

  `npm run live`

This will serve files from the build/prod directory.

#Deploy:
-----------------------

  Build a development release without deploying:

  `npm run build_dev`

  Build a release without deploying:

  `npm run build`

  Build a release and deploy:

  `npm run release`

License and attribution
-----------------------
MIT


text:
import { AxiosResponse } from 'axios';
import { IResponse } from '~model/response';

export interface IServiceOpt {
  method?: string;
  url?: string;
  params?: object;
  responseType?: string;
  data?: object;
}

export function isValidRes<T>(res: AxiosResponse<IResponse<T>> | Error): res is AxiosResponse<IResponse<T>> {
  return (<AxiosResponse>res).data;
}

export type IServiceHttpRes<Q> = AxiosResponse<Q> | Error;
export interface IService<Q> {
  cancel(): void;
  http(data: IServiceOpt): Promise<IServiceHttpRes<Q>>;
}


text:
module ModelDisplaysHelper
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keywords" content="Fort Lauderdale, Oakland Park, Plantation, Wilton Manors, Lauderdale-By-The-Sea, Davie, Weston, Cooper City, Southwest Ranches, Sunrise, Tamarac, Hollywood, Hallandale Beach, Pembroke Pines, residential, commercial, real estate, real, estate">
    <meta name="author" content="Matthew Consolo | Realtor | Fort Lauderdale">

    <title>About: Matthew Consolo</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                VP Realty Group

                        Home

                        About

                        Blog Post

                        Contact

About Me

                        More than just an agent.

I am a real estate agent that prides myself in taking care of my clients. Communication is important in any type of relationship. In real estate that is no different. When you have an agent that is good at communicating with you throughout the whole process then you know hat is happening the whole time.

Here are three ways to get in contact with me.

Cell: 954-667-9781 (call or text)

Email: matthewmconsolo@gmail.com

Fax: 888-206-4950

Copyright © VP Realty Group, Inc. 2016


text:
package com.github.katjahahn.tools

import java.io.File
import com.github.katjahahn.parser.PELoader
import com.github.katjahahn.parser.optheader.WindowsEntryKey
import java.nio.channels.FileChannel
import java.nio.ByteBuffer
import java.nio.ByteOrder
import com.github.katjahahn.parser.PEData

object ChecksumVerifier {

  def hasValidChecksum(peData: PEData): Boolean = {
    val checksum = peData.getOptionalHeader.get(WindowsEntryKey.CHECKSUM)
    val computedChecksum = computeChecksum(peData)
    checksum == computedChecksum
  }

  def computeChecksum(peData: PEData): Long = {
    val file = peData.getFile
    val ch = FileChannel.open(file.toPath)
    val checksumOffset = peData.getOptionalHeader.getField(WindowsEntryKey.CHECKSUM).getOffset
    ch.position(0)
    var sum = 0L
    val top = Math.pow(2, 32).toLong
    val overlay = new Overlay(file)
    val length = (if (overlay.exists) overlay.getOffset else ch.size)
    val byteArray: Array[Byte] = Array.fill(length.toInt)(0.toByte)
    var buffer = ByteBuffer.wrap(byteArray)
    buffer.order(ByteOrder.LITTLE_ENDIAN)

    ch.read(buffer)
    buffer.putInt(checksumOffset.toInt, 0x0000)

    buffer.position(0)
    while (buffer.hasRemaining() && buffer.remaining() >= 4) {
      sum += buffer.getInt() & 0xffffffffL
      if (sum > top) {
        sum = (sum & 0xffffffffL) + (sum >> 32)
      }
    }
    sum = (sum & 0xffff) + (sum >> 16)
    sum = sum + (sum >> 16)
    sum = sum & 0xffff
    sum += length
    sum
  }

}


text:
package vultura.factor.inference.conditioned

import vultura.factor.Problem
import vultura.factor.inference.{JunctionTree, MargParI, VariableOrderer}
import vultura.util.TreeWidth

/** A `CBPSolverPlugin` handles the inference within an instance of [[ConditionedInference]].
  * This trait offers the possibility to perform incremental inference using the `incremental` method.
  */
trait CBPSolverPlugin[S]{
  def name: String
  implicit def result2mpi: S <:< MargParI
  /** @return Left is an exact result, while right is the approximate result. */
  def create(p: Problem): Either[MargParI,S]
  def incremental(oldState: S, newProblem: Problem): Either[MargParI,S] = create(newProblem)
}

/** A CBPSolverPlugin that is build through a combination of an exact and an (incremental) approximate solver. */
case class HybridSolver[S](exact: ExactSolver, approximate: ApproximateSolver[S]) extends CBPSolverPlugin[S]{
  override def name: String = s"Hyb(${exact.name},${approximate.name})"
  override implicit def result2mpi: <:<[S, MargParI] = approximate.result2mpi
  override def create(p: Problem): Either[MargParI, S] =
    exact.attempt(p).map(Left(_)).getOrElse(Right(approximate.create(p)))
  override def incremental(oldState: S, newProblem: Problem): Either[MargParI, S] =
    exact.attempt(newProblem).map(Left(_)).getOrElse(Right(approximate.increment(oldState, newProblem)))
}

/** Attempts to solve a problem exactly. Currently no means of threading state. */
trait ExactSolver{
  def name: String
  def attempt(p: Problem): Option[MargParI]
}

object ExactSolver{
  /** Solves the problem if the tree width is at most `maxWidth`. */
  def maxMinDegreeJT(maxWidth: Int): ExactSolver = new ExactSolver {
    override val name: String = s"Max-MinDegree-JT($maxWidth)"
    override def attempt(p: Problem): Option[MargParI] = {
      val prob = p.fixUncoveredVariables
      val (ordering,width) = TreeWidth.minDegreeOrderingAndWidth(prob.factors.map(_.variables.toSet))
      if(width <= maxWidth) Some(new JunctionTree(prob, VariableOrderer.fromOrder(ordering)))
      else None
    }
  }
}

trait ApproximateSolver[S]{
  def name: String
  def result2mpi: S <:< MargParI
  def create(p: Problem): S
  def increment(oldState: S, newProblem: Problem): S
}


text:
using System;
using System.Collections.Generic;
using Kopigi.Utils.Class;

namespace Kopigi.Utils.Helpers
{
    /// <summary>
    /// Gestion des valeurs String pour l'attibut StringEnumAttribute
    /// </summary>
    /// <remarks>Inspiré par http://www.codeproject.com/Articles/11130/String-Enumerations-in-C</remarks>
    public static class StringEnum
    {
        private static readonly IDictionary<Enum, StringEnumAttribute> StringValues = new Dictionary<Enum, StringEnumAttribute>();

        /// <summary>
        /// Permet de retrouver la valeur string d'un enum marqué par StringEnumAttribute
        /// </summary>
        /// <param name="value">l'enum voulu</param>
        /// <returns>la valeur String associé ou null si non trouvé</returns>
        public static string GetStringValue(Enum value)
        {
            var output = StringValues.ContainsKey(value) ? GetValueInCache(value) : ReadValueOnAttribute(value, value.GetType());
            return output;
        }

        private static string ReadValueOnAttribute(Enum value, Type type)
        {
            var output= string.Empty;
            var fi = type.GetField(value.ToString());
            if (fi.GetCustomAttributes(typeof(StringEnumAttribute), false) is StringEnumAttribute[] attrs && attrs.Length > 0)
            {
                StringValues.Add(value, attrs[0]);
                output = attrs[0].Value;
            }
            return output;
        }

        private static string GetValueInCache(Enum value)
        {
            var output= string.Empty;
            if (StringValues[value] is StringEnumAttribute stringEnumAttribute)
            {
                output = stringEnumAttribute.Value;
            }

            return output;
        }
    }
}


text:
<?php

namespace Metrol\HTML\Table;

/**
 * Specifies all the different settings that can be applied to a Table
 */
class Settings
{
  /**
   * Should the table make all the column widths even?
   *
   * @var boolean
   */
  private $evenColumnWidthsFlag;

  /**
   * The Table section will need to figure out what the column widths should
   * be if they are set to be even.  Here is where that value is stored.
   *
   * @var string
   */
  private $columnWidthVal;

  /**
   */
  public function __construct()
  {
    $this->evenColumnWidthsFlag = false;
  }

  /**
   *
   * @param boolean
   */
  public function setEventColumnWidths($flag)
  {
    if ( $flag )
    {
      $this->evenColumnWidthsFlag = true;
    }
    else
    {
      $this->evenColumnWidthsFlag = false;
    }

    return $this;
  }

  /**
   * Set the column width that will be applied to the table cells if the even
   * widths flag is enabled.
   *
   * @param string
   * @return \Metrol\HTML\Table\Settings
   */
  public function setColumnWidth($width)
  {
    $this->columnWidthVal = $width;
  }
}


text:
<?php

namespace Phitly;

class BitlyError extends \Exception {}


text:
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Database.SQLite3 (
    -- * Connection management
    open,
    open2,
    close,

    -- * Simple query execution
    -- | <https://sqlite.org/c3ref/exec.html>
    exec,
    execPrint,
    execWithCallback,
    ExecCallback,

    -- * Statement management
    prepare,
    prepareUtf8,
    step,
    stepNoCB,
    reset,
    finalize,
    clearBindings,

    -- * Parameter and column information
    bindParameterCount,
    bindParameterName,
    columnCount,
    columnName,

    -- * Binding values to a prepared statement
    -- | <https://www.sqlite.org/c3ref/bind_blob.html>
    bindSQLData,
    bind,
    bindNamed,
    bindInt,
    bindInt64,
    bindDouble,
    bindText,
    bindBlob,
    bindZeroBlob,
    bindNull,

    -- * Reading the result row
    -- | <https://www.sqlite.org/c3ref/column_blob.html>
    --
    -- Warning: 'column' and 'columns' will throw a 'DecodeError' if any @TEXT@
    -- datum contains invalid UTF-8.
    column,
    columns,
    typedColumns,
    columnType,
    columnInt64,
    columnDouble,
    columnText,
    columnBlob,

    -- * Result statistics
    lastInsertRowId,
    changes,

    -- * Create custom SQL functions
    createFunction,
    createAggregate,
    deleteFunction,
    -- ** Extract function arguments
    funcArgCount,
    funcArgType,
    funcArgInt64,
    funcArgDouble,
    funcArgText,
    funcArgBlob,
    -- ** Set the result of a function
    funcResultSQLData,
    funcResultInt64,
    funcResultDouble,
    funcResultText,
    funcResultBlob,
    funcResultZeroBlob,
    funcResultNull,
    getFuncContextDatabase,

    -- * Create custom collations
    createCollation,
    deleteCollation,

    -- * Interrupting a long-running query
    interrupt,
    interruptibly,

    -- * Incremental blob I/O
    blobOpen,
    blobClose,
    blobReopen,
    blobBytes,
    blobRead,
    blobReadBuf,
    blobWrite,

    -- * Online Backup API
    -- | <https://www.sqlite.org/backup.html> and
    -- <https://www.sqlite.org/c3ref/backup_finish.html>
    backupInit,
    backupFinish,
    backupStep,
    backupRemaining,
    backupPagecount,

    -- * Types
    Database,
    Statement,
    SQLData(..),
    SQLOpenFlag(..),
    SQLVFS(..),
    SQLError(..),
    ColumnType(..),
    FuncContext,
    FuncArgs,
    Blob,
    Backup,

    -- ** Results and errors
    StepResult(..),
    BackupStepResult(..),
    Error(..),

    -- ** Special integers
    ParamIndex(..),
    ColumnIndex(..),
    ColumnCount,
    ArgCount(..),
    ArgIndex,
) where

import Database.SQLite3.Direct
    ( Database
    , Statement
    , ColumnType(..)
    , StepResult(..)
    , BackupStepResult(..)
    , Error(..)
    , ParamIndex(..)
    , ColumnIndex(..)
    , ColumnCount
    , Utf8(..)
    , FuncContext
    , FuncArgs
    , ArgCount(..)
    , ArgIndex
    , Blob
    , Backup

    -- Re-exported from Database.SQLite3.Direct without modification.
    -- Note that if this module were in another package, source links would not
    -- be generated for these functions.
    , clearBindings
    , bindParameterCount
    , columnCount
    , columnType
    , columnBlob
    , columnInt64
    , columnDouble
    , funcArgCount
    , funcArgType
    , funcArgInt64
    , funcArgDouble
    , funcArgBlob
    , funcResultInt64
    , funcResultDouble
    , funcResultBlob
    , funcResultZeroBlob
    , funcResultNull
    , getFuncContextDatabase
    , lastInsertRowId
    , changes
    , interrupt
    , blobBytes
    , backupRemaining
    , backupPagecount
    )

import qualified Database.SQLite3.Direct as Direct

import Prelude hiding (error)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Control.Concurrent
import Control.Exception
import Control.Monad        (when, zipWithM, zipWithM_)
import Data.ByteString      (ByteString)
import Data.Int             (Int64)
import Data.Bits            ((.|.))
import Data.Maybe           (fromMaybe)
import Data.Text            (Text)
import Data.Text.Encoding   (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (UnicodeException(..), lenientDecode)
import Data.Typeable
import Foreign.Ptr          (Ptr)
import GHC.Generics

data SQLData
    = SQLInteger    !Int64
    | SQLFloat      !Double
    | SQLText       !Text
    | SQLBlob       !ByteString
    | SQLNull
    deriving (Eq, Show, Typeable, Generic)

-- | These flags are used when using the `open2` function.
-- <https://www.sqlite.org/c3ref/c_open_autoproxy.html>
data SQLOpenFlag
    = SQLOpenReadOnly      -- Ok for sqlite3_open_v2()
    | SQLOpenReadWrite     -- Ok for sqlite3_open_v2()
    | SQLOpenCreate        -- Ok for sqlite3_open_v2()
    | SQLOpenDeleteOnClose -- VFS only
    | SQLOpenExclusive     -- VFS only
    | SQLOpenAutoProxy     -- VFS only
    | SQLOpenURI           -- Ok for sqlite3_open_v2()
    | SQLOpenMemory        -- Ok for sqlite3_open_v2()
    | SQLOpenMainDB        -- VFS only
    | SQLOpenTempDB        -- VFS only
    | SQLOpenTransientDB   -- VFS only
    | SQLOpenMainJournal   -- VFS only
    | SQLOpenTempJournal   -- VFS only
    | SQLOpenSubJournal    -- VFS only
    | SQLOpenMasterJournal -- VFS only
    | SQLOpenNoMutex       -- Ok for sqlite3_open_v2()
    | SQLOpenFullMutex     -- Ok for sqlite3_open_v2()
    | SQLOpenSharedCache   -- Ok for sqlite3_open_v2()
    | SQLOpenPrivateCache  -- Ok for sqlite3_open_v2()
    | SQLOpenWAL           -- VFS only
    | SQLOpenNoFollow      -- Ok for sqlite3_open_v2()
    deriving (Eq, Show)

-- | These VFS names are used when using the `open2` function.
data SQLVFS
    = SQLVFSDefault
    | SQLVFSUnix
    | SQLVFSUnixDotFile
    | SQLVFSUnixExcl
    | SQLVFSUnixNone
    | SQLVFSUnixNamedSem
    | SQLVFSCustom Text
    deriving (Eq, Show)

-- | Exception thrown when SQLite3 reports an error.
--
-- direct-sqlite may throw other types of exceptions if you misuse the API.
data SQLError = SQLError
    { sqlError          :: !Error
        -- ^ Error code returned by API call
    , sqlErrorDetails   :: Text
        -- ^ Text describing the error
    , sqlErrorContext   :: Text
        -- ^ Indicates what action produced this error,
        --   e.g. @exec \"SELECT * FROM foo\"@
    }
    deriving (Eq, Typeable, Generic)

-- NB: SQLError is lazy in 'sqlErrorDetails' and 'sqlErrorContext',
-- to defer message construction in the case where a user catches and
-- immediately handles the error.

instance Show SQLError where
    show SQLError{ sqlError        = code
                 , sqlErrorDetails = details
                 , sqlErrorContext = context
                 }
         = T.unpack $ T.concat
         [ "SQLite3 returned "
         , T.pack $ show code
         , " while attempting to perform "
         , context
         , ": "
         , details
         ]

instance Exception SQLError

-- | Like 'decodeUtf8', but substitute a custom error message if
-- decoding fails.
fromUtf8 :: String -> Utf8 -> IO Text
fromUtf8 desc utf8 = evaluate $ fromUtf8' desc utf8

fromUtf8' :: String -> Utf8 -> Text
fromUtf8' desc (Utf8 bs) =
    decodeUtf8With (\_ c -> throw (DecodeError desc c)) bs

toUtf8 :: Text -> Utf8
toUtf8 = Utf8 . encodeUtf8

data DetailSource
    = DetailDatabase    Database
    | DetailStatement   Statement
    | DetailMessage     Utf8

renderDetailSource :: DetailSource -> IO Utf8
renderDetailSource src = case src of
    DetailDatabase db ->
        Direct.errmsg db
    DetailStatement stmt -> do
        db <- Direct.getStatementDatabase stmt
        Direct.errmsg db
    DetailMessage msg ->
        return msg

throwSQLError :: DetailSource -> Text -> Error -> IO a
throwSQLError detailSource context error = do
    Utf8 details <- renderDetailSource detailSource
    throwIO SQLError
        { sqlError        = error
        , sqlErrorDetails = decodeUtf8With lenientDecode details
        , sqlErrorContext = context
        }

checkError :: DetailSource -> Text -> Either Error a -> IO a
checkError ds fn = either (throwSQLError ds fn) return

checkErrorMsg :: Text -> Either (Error, Utf8) a -> IO a
checkErrorMsg fn result = case result of
    Left (err, msg) -> throwSQLError (DetailMessage msg) fn err
    Right a         -> return a

appendShow :: Show a => Text -> a -> Text
appendShow txt a = txt `T.append` (T.pack . show) a

-- | <https://www.sqlite.org/c3ref/open.html>
open :: Text -> IO Database
open path =
    Direct.open (toUtf8 path)
        >>= checkErrorMsg ("open " `appendShow` path)

-- | <https://www.sqlite.org/c3ref/open.html>
open2 :: Text -> [SQLOpenFlag] -> SQLVFS -> IO Database
open2 path flags zvfs =
    Direct.open2 (toUtf8 path) (makeFlag flags) (toMUtf8 zvfs)
        >>= checkErrorMsg ("open2 " `appendShow` path)
    where
        toMUtf8 = fmap toUtf8 . toMText

        toMText SQLVFSDefault           = Nothing
        toMText SQLVFSUnix              = Just "unix"
        toMText SQLVFSUnixDotFile       = Just "unix-dotfile"
        toMText SQLVFSUnixExcl          = Just "unix-excl"
        toMText SQLVFSUnixNone          = Just "unix-none"
        toMText SQLVFSUnixNamedSem      = Just "unix-namedsem"
        toMText (SQLVFSCustom custom)   = Just custom

        makeFlag = foldr (.|.) 0 . fmap toNum

        toNum SQLOpenReadOnly       = 0x00000001
        toNum SQLOpenReadWrite      = 0x00000002
        toNum SQLOpenCreate         = 0x00000004
        toNum SQLOpenDeleteOnClose  = 0x00000008
        toNum SQLOpenExclusive      = 0x00000010
        toNum SQLOpenAutoProxy      = 0x00000020
        toNum SQLOpenURI            = 0x00000040
        toNum SQLOpenMemory         = 0x00000080
        toNum SQLOpenMainDB         = 0x00000100
        toNum SQLOpenTempDB         = 0x00000200
        toNum SQLOpenTransientDB    = 0x00000400
        toNum SQLOpenMainJournal    = 0x00000800
        toNum SQLOpenTempJournal    = 0x00001000
        toNum SQLOpenSubJournal     = 0x00002000
        toNum SQLOpenMasterJournal  = 0x00004000
        toNum SQLOpenNoMutex        = 0x00008000
        toNum SQLOpenFullMutex      = 0x00010000
        toNum SQLOpenSharedCache    = 0x00020000
        toNum SQLOpenPrivateCache   = 0x00040000
        toNum SQLOpenWAL            = 0x00080000
        toNum SQLOpenNoFollow       = 0x01000000

-- | <https://www.sqlite.org/c3ref/close.html>
close :: Database -> IO ()
close db =
    Direct.close db >>= checkError (DetailDatabase db) "close"

-- | Make it possible to interrupt the given database operation with an
-- asynchronous exception.  This only works if the program is compiled with
-- base >= 4.3 and @-threaded@.
--
-- It works by running the callback in a forked thread.  If interrupted,
-- it uses 'interrupt' to try to stop the operation.
interruptibly :: Database -> IO a -> IO a
interruptibly db io
  | rtsSupportsBoundThreads =
      mask $ \restore -> do
          mv <- newEmptyMVar
          tid <- forkIO $ try' (restore io) >>= putMVar mv

          let interruptAndWait =
                  -- Don't let a second exception interrupt us.  Otherwise,
                  -- the operation will dangle in the background, which could
                  -- be really bad if it uses locally-allocated resources.
                  uninterruptibleMask_ $ do
                      -- Tell SQLite3 to interrupt the current query.
                      interrupt db

                      -- Interrupt the thread in case it's blocked for some
                      -- other reason.
                      --
                      -- NOTE: killThread blocks until the exception is delivered.
                      -- That's fine, since we're going to wait for the thread
                      -- to finish anyway.
                      killThread tid

                      -- Wait for the forked thread to finish.
                      _ <- takeMVar mv
                      return ()

          e <- takeMVar mv `onException` interruptAndWait
          either throwIO return e
  | otherwise = io
  where
    try' :: IO a -> IO (Either SomeException a)
    try' = try

-- | Execute zero or more SQL statements delimited by semicolons.
exec :: Database -> Text -> IO ()
exec db sql =
    Direct.exec db (toUtf8 sql)
        >>= checkErrorMsg ("exec " `appendShow` sql)

-- | Like 'exec', but print result rows to 'System.IO.stdout'.
--
-- This is mainly for convenience when experimenting in GHCi.
-- The output format may change in the future.
execPrint :: Database -> Text -> IO ()
execPrint !db !sql =
    interruptibly db $
    execWithCallback db sql $ \_count _colnames -> T.putStrLn . showValues
  where
    -- This mimics sqlite3's default output mode.  It displays a NULL and an
    -- empty string identically.
    showValues = T.intercalate "|" . map (fromMaybe "")

-- | Like 'exec', but invoke the callback for each result row.
execWithCallback :: Database -> Text -> ExecCallback -> IO ()
execWithCallback db sql cb =
    Direct.execWithCallback db (toUtf8 sql) cb'
        >>= checkErrorMsg ("execWithCallback " `appendShow` sql)
  where
    -- We want 'names' computed once and shared with every call.
    cb' count namesUtf8 =
       let names = map fromUtf8'' namesUtf8
           {-# NOINLINE names #-}
        in cb count names . map (fmap fromUtf8'')

    fromUtf8'' = fromUtf8' "Database.SQLite3.execWithCallback: Invalid UTF-8"

type ExecCallback
     = ColumnCount    -- ^ Number of columns, which is the number of items in
                      --   the following lists.  This will be the same for
                      --   every row.
    -> [Text]         -- ^ List of column names.  This will be the same
                      --   for every row.
    -> [Maybe Text]   -- ^ List of column values, as returned by 'columnText'.
    -> IO ()

-- | <https://www.sqlite.org/c3ref/prepare.html>
--
-- Unlike 'exec', 'prepare' only executes the first statement, and ignores
-- subsequent statements.
--
-- If the query string contains no SQL statements, this 'fail's.
prepare :: Database -> Text -> IO Statement
prepare db sql = prepareUtf8 db (toUtf8 sql)

-- | <https://www.sqlite.org/c3ref/prepare.html>
--
-- It can help to avoid redundant Utf8 to Text conversion if you already
-- have Utf8
--
-- If the query string contains no SQL statements, this 'fail's.
prepareUtf8 :: Database -> Utf8 -> IO Statement
prepareUtf8 db sql = do
    m <- Direct.prepare db sql
            >>= checkError (DetailDatabase db) ("prepare " `appendShow` sql)
    case m of
        Nothing   -> fail "Direct.SQLite3.prepare: empty query string"
        Just stmt -> return stmt

-- | <https://www.sqlite.org/c3ref/step.html>
step :: Statement -> IO StepResult
step statement =
    Direct.step statement >>= checkError (DetailStatement statement) "step"

-- | <https://www.sqlite.org/c3ref/step.html>
--
-- Faster step for statements that don't callback to Haskell
-- functions (e.g. by using custom SQL functions).
stepNoCB :: Statement -> IO StepResult
stepNoCB statement =
    Direct.stepNoCB statement >>= checkError (DetailStatement statement) "stepNoCB"

-- Note: sqlite3_reset and sqlite3_finalize return an error code if the most
-- recent sqlite3_step indicated an error.  I think these are the only times
-- these functions return an error (barring memory corruption and misuse of the API).
--
-- We don't replicate that behavior here.  Instead, 'reset' and 'finalize'
-- discard the error.  Otherwise, we would get "double jeopardy".
-- For example:
--
--  ok <- try $ step stmt :: IO (Either SQLError StepResult)
--  finalize stmt
--
-- If 'finalize' threw its error, it would throw the exception the user was
-- trying to catch.
--
-- 'reset' and 'finalize' might return a different error than the step that
-- failed, leading to more cryptic error messages [1].  But we're not
-- completely sure about this.
--
--  [1]: https://github.com/yesodweb/persistent/issues/92#issuecomment-7806421

-- | <https://www.sqlite.org/c3ref/reset.html>
--
-- Note that in the C API, @sqlite3_reset@ returns an error code if the most
-- recent @sqlite3_step@ indicated an error.  We do not replicate that behavior
-- here.  'reset' never throws an exception.
reset :: Statement -> IO ()
reset statement = do
    _ <- Direct.reset statement
    return ()

-- | <https://www.sqlite.org/c3ref/finalize.html>
--
-- Like 'reset', 'finalize' never throws an exception.
finalize :: Statement -> IO ()
finalize statement = do
    _ <- Direct.finalize statement
    return ()

-- | <https://www.sqlite.org/c3ref/bind_parameter_name.html>
--
-- Return the N-th SQL parameter name.
--
-- Named parameters are returned as-is.  E.g. \":v\" is returned as
-- @Just \":v\"@.  Unnamed parameters, however, are converted to
-- @Nothing@.
--
-- Note that the parameter index starts at 1, not 0.
bindParameterName :: Statement -> ParamIndex -> IO (Maybe Text)
bindParameterName stmt idx = do
    m <- Direct.bindParameterName stmt idx
    case m of
        Nothing   -> return Nothing
        Just name -> Just <$> fromUtf8 desc name
  where
    desc = "Database.SQLite3.bindParameterName: Invalid UTF-8"

-- | <https://www.sqlite.org/c3ref/column_name.html>
--
-- Return the name of a result column.  If the column index is out of range,
-- return 'Nothing'.
columnName :: Statement -> ColumnIndex -> IO (Maybe Text)
columnName stmt idx = do
    m <- Direct.columnName stmt idx
    case m of
        Just name -> Just <$> fromUtf8 desc name
        Nothing -> do
            -- sqlite3_column_name only returns NULL if memory allocation fails
            -- or if the column index is out of range.
            count <- Direct.columnCount stmt
            if idx >= 0 && idx < count
                then throwIO outOfMemory
                else return Nothing
  where
    desc = "Database.SQLite3.columnName: Invalid UTF-8"
    outOfMemory = SQLError
        { sqlError        = ErrorNoMemory
        , sqlErrorDetails = "out of memory (sqlite3_column_name returned NULL)"
        , sqlErrorContext = "column name"
        }

bindBlob :: Statement -> ParamIndex -> ByteString -> IO ()
bindBlob statement parameterIndex byteString =
    Direct.bindBlob statement parameterIndex byteString
        >>= checkError (DetailStatement statement) "bind blob"

bindZeroBlob :: Statement -> ParamIndex -> Int -> IO ()
bindZeroBlob statement parameterIndex len =
    Direct.bindZeroBlob statement parameterIndex len
        >>= checkError (DetailStatement statement) "bind zeroblob"

bindDouble :: Statement -> ParamIndex -> Double -> IO ()
bindDouble statement parameterIndex datum =
    Direct.bindDouble statement parameterIndex datum
        >>= checkError (DetailStatement statement) "bind double"

bindInt :: Statement -> ParamIndex -> Int -> IO ()
bindInt statement parameterIndex datum =
    Direct.bindInt64 statement
                     parameterIndex
                     (fromIntegral datum)
        >>= checkError (DetailStatement statement) "bind int"

bindInt64 :: Statement -> ParamIndex -> Int64 -> IO ()
bindInt64 statement parameterIndex datum =
    Direct.bindInt64 statement parameterIndex datum
        >>= checkError (DetailStatement statement) "bind int64"

bindNull :: Statement -> ParamIndex -> IO ()
bindNull statement parameterIndex =
    Direct.bindNull statement parameterIndex
        >>= checkError (DetailStatement statement) "bind null"

bindText :: Statement -> ParamIndex -> Text -> IO ()
bindText statement parameterIndex text =
    Direct.bindText statement parameterIndex (toUtf8 text)
        >>= checkError (DetailStatement statement) "bind text"

-- | If the index is not between 1 and 'bindParameterCount' inclusive, this
-- fails with 'ErrorRange'.  Otherwise, it succeeds, even if the query skips
-- this index by using numbered parameters.
--
-- Example:
--
-- >> stmt <- prepare conn "SELECT ?1, ?3, ?5"
-- >> bindSQLData stmt 1 (SQLInteger 1)
-- >> bindSQLData stmt 2 (SQLInteger 2)
-- >> bindSQLData stmt 6 (SQLInteger 6)
-- >*** Exception: SQLite3 returned ErrorRange while attempting to perform bind int64.
-- >> step stmt >> columns stmt
-- >[SQLInteger 1,SQLNull,SQLNull]
bindSQLData :: Statement -> ParamIndex -> SQLData -> IO ()
bindSQLData statement idx datum =
    case datum of
        SQLInteger v -> bindInt64  statement idx v
        SQLFloat   v -> bindDouble statement idx v
        SQLText    v -> bindText   statement idx v
        SQLBlob    v -> bindBlob   statement idx v
        SQLNull      -> bindNull   statement idx

-- | Convenience function for binding values to all parameters.  This will
-- 'fail' if the list has the wrong number of parameters.
bind :: Statement -> [SQLData] -> IO ()
bind statement sqlData = do
    ParamIndex nParams <- bindParameterCount statement
    when (nParams /= length sqlData) $
        fail ("mismatched parameter count for bind.  Prepared statement "++
              "needs "++ show nParams ++ ", " ++ show (length sqlData) ++" given")
    zipWithM_ (bindSQLData statement) [1..] sqlData

-- | Convenience function for binding named values to all parameters.
-- This will 'fail' if the list has the wrong number of parameters or
-- if an unknown name is used.
--
-- Example:
--
-- @
-- stmt <- prepare conn \"SELECT :foo + :bar\"
-- bindNamed stmt [(\":foo\", SQLInteger 1), (\":bar\", SQLInteger 2)]
-- @
bindNamed :: Statement -> [(T.Text, SQLData)] -> IO ()
bindNamed statement params = do
    ParamIndex nParams <- bindParameterCount statement
    when (nParams /= length params) $
        fail ("mismatched parameter count for bind.  Prepared statement "++
              "needs "++ show nParams ++ ", " ++ show (length params) ++" given")
    mapM_ bindIdx params
    where
        bindIdx (name, val) = do
            idx <- Direct.bindParameterIndex statement $ toUtf8 name
            case idx of
                Just i ->
                    bindSQLData statement i val
                Nothing ->
                    fail ("unknown named parameter "++show name)

-- | This will throw a 'DecodeError' if the datum contains invalid UTF-8.
-- If this behavior is undesirable, you can use 'Direct.columnText' from
-- "Database.SQLite3.Direct", which does not perform conversion to 'Text'.
columnText :: Statement -> ColumnIndex -> IO Text
columnText statement columnIndex =
    Direct.columnText statement columnIndex
        >>= fromUtf8 "Database.SQLite3.columnText: Invalid UTF-8"

column :: Statement -> ColumnIndex -> IO SQLData
column statement idx = do
    theType <- columnType statement idx
    typedColumn theType statement idx

columns :: Statement -> IO [SQLData]
columns statement = do
    count <- columnCount statement
    mapM (column statement) [0..count-1]

typedColumn :: ColumnType -> Statement -> ColumnIndex -> IO SQLData
typedColumn theType statement idx = case theType of
    IntegerColumn -> SQLInteger <$> columnInt64  statement idx
    FloatColumn   -> SQLFloat   <$> columnDouble statement idx
    TextColumn    -> SQLText    <$> columnText   statement idx
    BlobColumn    -> SQLBlob    <$> columnBlob   statement idx
    NullColumn    -> return SQLNull

-- | This avoids extra API calls using the list of column types.
-- If passed types do not correspond to the actual types, the values will be
-- converted according to the rules at <https://www.sqlite.org/c3ref/column_blob.html>.
-- If the list contains more items that number of columns, the result is undefined.
typedColumns :: Statement -> [Maybe ColumnType] -> IO [SQLData]
typedColumns statement = zipWithM f [0..] where
    f idx theType = case theType of
        Nothing -> column statement idx
        Just t  -> typedColumn t statement idx

-- | <https://sqlite.org/c3ref/create_function.html>
--
-- Create a custom SQL function or redefine the behavior of an existing
-- function. If the function is deterministic, i.e. if it always returns the
-- same result given the same input, you can set the boolean flag to let
-- @sqlite@ perform additional optimizations.
createFunction
    :: Database
    -> Text           -- ^ Name of the function.
    -> Maybe ArgCount -- ^ Number of arguments. 'Nothing' means that the
                      --   function accepts any number of arguments.
    -> Bool           -- ^ Is the function deterministic?
    -> (FuncContext -> FuncArgs -> IO ())
                      -- ^ Implementation of the function.
    -> IO ()
createFunction db name nArgs isDet fun =
    Direct.createFunction db (toUtf8 name) nArgs isDet fun
        >>= checkError (DetailDatabase db) ("createFunction " `appendShow` name)

-- | Like 'createFunction' except that it creates an aggregate function.
createAggregate
    :: Database
    -> Text           -- ^ Name of the function.
    -> Maybe ArgCount -- ^ Number of arguments.
    -> a              -- ^ Initial aggregate state.
    -> (FuncContext -> FuncArgs -> a -> IO a)
                      -- ^ Process one row and update the aggregate state.
    -> (FuncContext -> a -> IO ())
                      -- ^ Called after all rows have been processed.
                      --   Can be used to construct the returned value
                      --   from the aggregate state.
    -> IO ()
createAggregate db name nArgs initSt xStep xFinal =
    Direct.createAggregate db (toUtf8 name) nArgs initSt xStep xFinal
        >>= checkError (DetailDatabase db) ("createAggregate " `appendShow` name)

-- | Delete an SQL function (scalar or aggregate).
deleteFunction :: Database -> Text -> Maybe ArgCount -> IO ()
deleteFunction db name nArgs =
    Direct.deleteFunction db (toUtf8 name) nArgs
        >>= checkError (DetailDatabase db) ("deleteFunction " `appendShow` name)

funcArgText :: FuncArgs -> ArgIndex -> IO Text
funcArgText args argIndex =
    Direct.funcArgText args argIndex
        >>= fromUtf8 "Database.SQLite3.funcArgText: Invalid UTF-8"

funcResultSQLData :: FuncContext -> SQLData -> IO ()
funcResultSQLData ctx datum =
    case datum of
        SQLInteger v -> funcResultInt64  ctx v
        SQLFloat   v -> funcResultDouble ctx v
        SQLText    v -> funcResultText   ctx v
        SQLBlob    v -> funcResultBlob   ctx v
        SQLNull      -> funcResultNull   ctx

funcResultText :: FuncContext -> Text -> IO ()
funcResultText ctx value =
    Direct.funcResultText ctx (toUtf8 value)

-- | <https://www.sqlite.org/c3ref/create_collation.html>
createCollation
    :: Database
    -> Text                       -- ^ Name of the collation.
    -> (Text -> Text -> Ordering) -- ^ Comparison function.
    -> IO ()
createCollation db name cmp =
    Direct.createCollation db (toUtf8 name) cmp'
        >>= checkError (DetailDatabase db) ("createCollation " `appendShow` name)
  where
    cmp' (Utf8 s1) (Utf8 s2) = cmp (fromUtf8'' s1) (fromUtf8'' s2)
    -- avoid throwing exceptions as much as possible
    fromUtf8'' = decodeUtf8With lenientDecode

-- | Delete a collation.
deleteCollation :: Database -> Text -> IO ()
deleteCollation db name =
    Direct.deleteCollation db (toUtf8 name)
        >>= checkError (DetailDatabase db) ("deleteCollation " `appendShow` name)

-- | <https://www.sqlite.org/c3ref/blob_open.html>
--
-- Open a blob for incremental I/O.
blobOpen
    :: Database
    -> Text   -- ^ The symbolic name of the database (e.g. "main").
    -> Text   -- ^ The table name.
    -> Text   -- ^ The column name.
    -> Int64  -- ^ The @ROWID@ of the row.
    -> Bool   -- ^ Open the blob for read-write.
    -> IO Blob
blobOpen db zDb zTable zColumn rowid rw =
    Direct.blobOpen db (toUtf8 zDb) (toUtf8 zTable) (toUtf8 zColumn) rowid rw
        >>= checkError (DetailDatabase db) "blobOpen"

-- | <https://www.sqlite.org/c3ref/blob_close.html>
blobClose :: Blob -> IO ()
blobClose blob@(Direct.Blob db _) =
    Direct.blobClose blob
        >>= checkError (DetailDatabase db) "blobClose"

-- | <https://www.sqlite.org/c3ref/blob_reopen.html>
blobReopen
    :: Blob
    -> Int64 -- ^ The @ROWID@ of the row.
    -> IO ()
blobReopen blob@(Direct.Blob db _) rowid =
    Direct.blobReopen blob rowid
        >>= checkError (DetailDatabase db) "blobReopen"

-- | <https://www.sqlite.org/c3ref/blob_read.html>
blobRead
    :: Blob
    -> Int -- ^ Number of bytes to read.
    -> Int -- ^ Offset within the blob.
    -> IO ByteString
blobRead blob@(Direct.Blob db _) len offset =
    Direct.blobRead blob len offset
        >>= checkError (DetailDatabase db) "blobRead"

blobReadBuf :: Blob -> Ptr a -> Int -> Int -> IO ()
blobReadBuf blob@(Direct.Blob db _) buf len offset =
    Direct.blobReadBuf blob buf len offset
        >>= checkError (DetailDatabase db) "blobReadBuf"

-- | <https://www.sqlite.org/c3ref/blob_write.html>
blobWrite
    :: Blob
    -> ByteString
    -> Int -- ^ Offset within the blob.
    -> IO ()
blobWrite blob@(Direct.Blob db _) bs offset =
    Direct.blobWrite blob bs offset
        >>= checkError (DetailDatabase db) "blobWrite"

backupInit
    :: Database  -- ^ Destination database handle.
    -> Text      -- ^ Destination database name.
    -> Database  -- ^ Source database handle.
    -> Text      -- ^ Source database name.
    -> IO Backup
backupInit dstDb dstName srcDb srcName =
    Direct.backupInit dstDb (toUtf8 dstName) srcDb (toUtf8 srcName)
        >>= checkError (DetailDatabase dstDb) "backupInit"

backupFinish :: Backup -> IO ()
backupFinish backup@(Direct.Backup dstDb _) =
    Direct.backupFinish backup
        >>= checkError (DetailDatabase dstDb) "backupFinish"

backupStep :: Backup -> Int -> IO BackupStepResult
backupStep backup pages =
    Direct.backupStep backup pages
        -- it appears that sqlite does not generate an
        -- error message when sqlite3_backup_step fails
        >>= checkError (DetailMessage "failed") "backupStep"


text:
import path from 'path'

export const cli = 'tailwind'
export const defaultConfigFile = './tailwind.config.js'
export const defaultPostCssConfigFile = './postcss.config.js'
export const cjsConfigFile = './tailwind.config.cjs'
export const cjsPostCssConfigFile = './postcss.config.cjs'

export const supportedConfigFiles = [cjsConfigFile, defaultConfigFile]
export const supportedPostCssConfigFile = [cjsPostCssConfigFile, defaultPostCssConfigFile]

export const defaultConfigStubFile = path.resolve(__dirname, '../stubs/defaultConfig.stub.js')
export const simpleConfigStubFile = path.resolve(__dirname, '../stubs/simpleConfig.stub.js')
export const defaultPostCssConfigStubFile = path.resolve(
  __dirname,
  '../stubs/defaultPostCssConfig.stub.js'
)


text:
package org.aludratest.data;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.List;

import org.aludratest.AludraTest;
import org.aludratest.testcase.AludraTestCase;
import org.aludratest.testcase.Offset;
import org.aludratest.testcase.data.Source;

/**
 * Tests the @Offset annotation.
 * @author Volker Bergmann
 */
@SuppressWarnings("javadoc")
public class OffsetTest {

    static List<PersonBean> data0 = new ArrayList<PersonBean>();
    static List<PersonBean> data1 = new ArrayList<PersonBean>();

    @org.junit.Test
    public void test() {
        AludraTest aludraTest = AludraTest.startFramework();
        aludraTest.run(OffsetTestClass.class);
        assertEquals(2, data0.size());
        assertEquals(1, data1.size());
        aludraTest.stopFramework();
    }

    public static class OffsetTestClass extends AludraTestCase {

        @org.aludratest.testcase.Test
        @Offset(0)
        public void testOffset0(@Source(uri = "persons.xls", segment = "persons") PersonBean person) {
            System.out.println("Test invoked with: " + person);
            data0.add(person);
        }

        @org.aludratest.testcase.Test
        @Offset(1)
        public void testOffset1(@Source(uri = "persons.xls", segment = "persons") PersonBean person) {
            System.out.println("Test invoked with: " + person);
            data1.add(person);
        }
    }

}


text:
// Title=Maximum Depth of Binary Tree
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxDepth(struct TreeNode* root) {
    if (!root) {
        return 0;
    }
    int leftDepth, rightDepth;
    leftDepth = maxDepth(root->left);
    rightDepth = maxDepth(root->right);
    if (leftDepth > rightDepth) {
        return leftDepth + 1;
    } else {
        return rightDepth + 1;
    }
}