text:
/*
 * This file contains most of the code located in the demo application in the
 * upstream FreeRTOS repository. It is put here so that IDF applications can
 * seamlessly switch between Linux and chip targets without the need to provide
 * or implement additional functionality if the target is the Linux target.
 */

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <unistd.h>

/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "utils/wait_for_event.h"
#include "esp_log.h"

static const char *TAG = "port";

static volatile UBaseType_t uxInterruptNesting = 0;

/* When configSUPPORT_STATIC_ALLOCATION is set to 1 the application writer can
 * use a callback function to optionally provide the memory required by the idle
 * and timer tasks.  This is the stack that will be used by the timer task.  It is
 * declared here, as a global, so it can be checked by a test that is implemented
 * in a different file. */
StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ];

BaseType_t xPortCheckIfInISR(void)
{
    return uxInterruptNesting;
}

void app_main(void);

static void main_task(void* args)
{
    app_main();
    vTaskDelete(NULL);
}

int main(int argc, const char **argv)
{
    // This makes sure that stdio is flushed after each '\n' so that idf.py monitor
    // reads the program output on time.
    setvbuf(stdout, NULL, _IOLBF, 0);

    usleep(1000);
    portBASE_TYPE res = xTaskCreatePinnedToCore(&main_task, "main",
                                                ESP_TASK_MAIN_STACK, NULL,
                                                ESP_TASK_MAIN_PRIO, NULL, ESP_TASK_MAIN_CORE);
    assert(res == pdTRUE);
    (void)res;

    ESP_LOGI(TAG, "Starting scheduler.");
    vTaskStartScheduler();

    // This line should never be reached
    assert(false);
}

void esp_vApplicationIdleHook(void)
{
    /* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
     * to 1 in FreeRTOSConfig.h.  It will be called on each iteration of the idle
     * task.  It is essential that code added to this hook function never attempts
     * to block in any way (for example, call xQueueReceive() with a block time
     * specified, or call vTaskDelay()).  If application tasks make use of the
     * vTaskDelete() API function to delete themselves then it is also important
     * that vApplicationIdleHook() is permitted to return to its calling function,
     * because it is the responsibility of the idle task to clean up memory
     * allocated by the kernel to any task that has since deleted itself. */

    usleep( 15000 );
}

void esp_vApplicationTickHook( void ) { }

#if  (  configUSE_TICK_HOOK > 0 )
void vApplicationTickHook( void )
{
    esp_vApplicationTickHook();
}
#endif

void vPortYieldOtherCore( BaseType_t coreid ) { } // trying to skip for now

/* configUSE_STATIC_ALLOCATION is set to 1, so the application must provide an
 * implementation of vApplicationGetIdleTaskMemory() to provide the memory that is
 * used by the Idle task. */
void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer,
                                    StackType_t ** ppxIdleTaskStackBuffer,
                                    uint32_t * pulIdleTaskStackSize )
{
/* If the buffers to be provided to the Idle task are declared inside this
 * function then they must be declared static - otherwise they will be allocated on
 * the stack and so not exists after this function exits. */
    static StaticTask_t xIdleTaskTCB;
    static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ];

    /* Pass out a pointer to the StaticTask_t structure in which the Idle task's
     * state will be stored. */
    *ppxIdleTaskTCBBuffer = &xIdleTaskTCB;

    /* Pass out the array that will be used as the Idle task's stack. */
    *ppxIdleTaskStackBuffer = uxIdleTaskStack;

    /* Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer.
     * Note that, as the array is necessarily of type StackType_t,
     * configMINIMAL_STACK_SIZE is specified in words, not bytes. */
    *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
}
/*-----------------------------------------------------------*/

/* configUSE_STATIC_ALLOCATION and configUSE_TIMERS are both set to 1, so the
 * application must provide an implementation of vApplicationGetTimerTaskMemory()
 * to provide the memory that is used by the Timer service task. */
void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer,
                                     StackType_t ** ppxTimerTaskStackBuffer,
                                     uint32_t * pulTimerTaskStackSize )
{
/* If the buffers to be provided to the Timer task are declared inside this
 * function then they must be declared static - otherwise they will be allocated on
 * the stack and so not exists after this function exits. */
    static StaticTask_t xTimerTaskTCB;

    /* Pass out a pointer to the StaticTask_t structure in which the Timer
     * task's state will be stored. */
    *ppxTimerTaskTCBBuffer = &xTimerTaskTCB;

    /* Pass out the array that will be used as the Timer task's stack. */
    *ppxTimerTaskStackBuffer = uxTimerTaskStack;

    /* Pass out the size of the array pointed to by *ppxTimerTaskStackBuffer.
     * Note that, as the array is necessarily of type StackType_t,
     * configMINIMAL_STACK_SIZE is specified in words, not bytes. */
    *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH;
}

void __attribute__((weak)) vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName)
{
#define ERR_STR1 "***ERROR*** A stack overflow in task "
#define ERR_STR2 " has been detected."
    const char *str[] = {ERR_STR1, pcTaskName, ERR_STR2};

    char buf[sizeof(ERR_STR1) + CONFIG_FREERTOS_MAX_TASK_NAME_LEN + sizeof(ERR_STR2) + 1 /* null char */] = {0};

    char *dest = buf;
    for (int i = 0; i < sizeof(str) / sizeof(str[0]); i++) {
        dest = strcat(dest, str[i]);
    }
	printf("%s\n", buf);
    abort();
}


text:
<?php
	// Load Initialization File
	require_once 'core/init.php';
	// Load CSS Name
	$cssFileName = Config::get('links/css_root') . basename(__FILE__, '.php') . '.css';
	// Load User
	$user = new User;

	// If User Tried to Register
	if(Input::exists()) {
		if(Token::check(Input::get('token'))) {

			$validate = new Validate();
			$validation = $validate->check($_POST, array(
				'username' => array(
					'min' => 2,
					'max' => 20,
					'unique' => 'users',
					'numeric' => false
				),
				'email' => array(
					'min' => 6,
					'max' => 255,
					'unique' => 'users',
				),
				'password' => array(
					'min' => 6,
				),
				'password_again' => array(
					'matches' => 'password'
				),
				'name' => array(
					'min' => 2,
					'max' => 50
				),

			));

			if($validation->passed()) {
				$user = new User();

				$salt = Hash::salt(32);

				try {

					$user->create(array(
						'email' => Input::get('email'),
						'username' => Input::get('username'),
						'password' => Hash::make(Input::get('password'), $salt),
						'salt' => $salt,
						'name' => Input::get('name'),
						'joined' => date('Y-m-d H:i:s'),
						'groups' => 1
					));

					// Flash Message
					Session::flash('login', 'You have been registered and can now log in!', 'success');
					// Redirect User
					Redirect::to('login.php');

				} catch(Exception $e) {
					die($e->getMessage());
				}

			} else {
				// Define registrationErrors
				$registrationErrors = 'Some errors occured when registering:
';
				// Output Errors
				foreach($validation->errors() as $error) {
					// Add to registrationErrors, then display array as session flash on register
					$registrationErrors .= $error . "
";
				}
				Session::flash('register', $registrationErrors, 'danger');
			}
		}

	}

?>

<!DOCTYPE html>

	<title>Register - Makoto</title>

	<?php include(Config::get('file/head_contents')); ?>

	<link rel="stylesheet" type="text/css" href="<?php echo $cssFileName; ?>">

	<?php include(Config::get('file/navbar/default')); ?>
	<?php
		// Session Flash Message
		if(Session::exists('register')) {
			echo Session::flash('register');
		}
	?>

<a href="<?php echo Config::get('links/app_root'); ?>">Home

New User Registration

Sign Up

		<form action="" method="post">

				Username
				<input type="text" class="form-control" placeholder="Username" name="username" id="username" value="<?php  echo escape(Input::get('username')); ?>" autocomplete="off" required>

				Choose a Password
				<input type="password" placeholder="Choose a password..." class="form-control" name="password" id="password" required>

				Enter your password again
				<input type="password" placeholder="Enter the password again..." class="form-control" name="password_again" id="password_again" required>

				Email

If you want to link your account with Google, enter your gMail address below. Once registered, login via the "Log in with Google" button.

				<input type="email" placeholder="E-mail" class="form-control" name="email" id="email" required>

				Your Name
				<input type="text" placeholder="Your First Name" class="form-control" name="name" id="name" value="<?php echo escape(Input::get('name')); ?>" required>

			<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
			<button type="submit" class="btn btn-primary hvr-float-shadow">Register</button>
		</form>

redpajama_set_name: RedPajamaGithub


text:
import io
import json
from datetime import datetime

import pytest
from dateparser import parse

import TaniumThreatResponseV2

def util_load_json(path):
    with io.open(path, mode='r', encoding='utf-8') as f:
        return json.loads(f.read())

def mock_client():
    client = TaniumThreatResponseV2.Client(base_url=BASE_URL, password='TEST', username='TEST')
    return client

BASE_URL = 'https://test.com'
MOCK_CLIENT = mock_client()

FILTER_FILE_DOWNLOADS_ARGS = [
    ({'offset': '0', 'limit': '50', 'hostname': 'host1'}, 3),
    ({'offset': '0', 'limit': '50', 'hostname': 'host2'}, 2),
    ({'offset': '0', 'limit': '50', 'hostname': 'host3'}, 2),
    ({'offset': '0', 'limit': '50', 'hostname': 'host2,host3'}, 4),
    (
        {
            'offset': '0',
            'limit': '50',
            'hash': '123',
        },
        2,
    ),
    (
        {
            'offset': '0',
            'limit': '50',
            'hash': '123,1234',
        },
        3,
    ),
]

FILTER_CONNECTIONS_LIST_ARGS = [
    ({'offset': '0', 'limit': '50', 'hostname': 'host1'}, 3),
    ({'offset': '0', 'limit': '50', 'hostname': 'host2'}, 2),
    ({'offset': '0', 'limit': '50', 'hostname': 'host3'}, 2),
    ({'offset': '0', 'limit': '50', 'hostname': 'host1,host2'}, 5),
    ({'offset': '0', 'limit': '50', 'platform': 'Linux'}, 3),
    ({'offset': '0', 'limit': '50', 'platform': 'Windows'}, 4),
    ({'offset': '0', 'limit': '50', 'status': 'connected'}, 2),
    ({'offset': '0', 'limit': '50', 'status': 'disconnected'}, 5),
    ({'offset': '0', 'limit': '50', 'ip': '3.3.3.3'}, 4),
    (
        {
            'offset': '0',
            'limit': '50',
            'ip': '3.3.3.3',
            'hostname': 'host2',
        },
        6
    ),
]

FILTER_EVIDENCE_LIST_ARGS = [
    ({'offset': '0', 'limit': '50', 'hostname': 'host1,host2'}, 6),
    ({'offset': '0', 'limit': '50', 'hostname': 'host1'}, 3),
    ({'offset': '0', 'limit': '50', 'hostname': 'host2'}, 3),
    ({'offset': '0', 'limit': '50', 'hostname': 'host3'}, 2),
    (
        {
            'offset': '0',
            'limit': '50',
            'hostname': 'host1,host3',
            'type': 'event',
        },
        5,
    ),
]

FILTER_GET_SYSTEM_STATUS_ARGS = [
    ({'offset': '0', 'limit': '50', 'status': 'Leader'}, 2),
    ({'offset': '0', 'limit': '50', 'status': 'Normal'}, 1),
    (
        {
            'offset': '0',
            'limit': '50',
            'status': 'Normal',
            'hostname': 'host1',
        },
        3,
    ),
    (
        {
            'offset': '0',
            'limit': '50',
            'hostname': 'host1',
            'ip_client': '3.3.3.3',
        },
        4,
    ),
    (
        {
            'offset': '0',
            'limit': '50',
            'hostname': 'host3',
            'ip_server': '1.1.1.1',
        },
        2,
    ),
    ({'offset': '0', 'limit': '50', 'hostname': 'host1,host2,host4'}, 4),
    ({'offset': '0', 'limit': '50', 'port': '8080'}, 2),
]

""" GENERAL HELPER FUNCTIONS TESTS"""

@pytest.mark.parametrize('test_input, expected_output', [('2', 2), (None, None), (2, 2), ('', None)])
def test_convert_to_int(test_input, expected_output):
    """
    Given -
        An object to convert to int.

    When -
        Running convert_to_int function.

    Then -
        If the object can be converted to int, the function returns the int, otherwise returns None.
    """

    res = TaniumThreatResponseV2.convert_to_int(test_input)
    assert res == expected_output

@pytest.mark.parametrize('test_input, expected_output', [({'testingFunctionFirst': 1, 'testingFunctionSecond': 2},
                                                          {'TestingFunctionFirst': 1, 'TestingFunctionSecond': 2}),

                                                         ([{'testingFunctionFirst': 1}, {'testingFunctionSecond': 2}],
                                                          [{'TestingFunctionFirst': 1}, {'TestingFunctionSecond': 2}])])
def test_format_context_data(test_input, expected_output):
    """
    Given -
        A dict or a list of dicts to format to standard context.

    When -
        Running format_context_data function.
        Running format_context_data function.

    Then -
        A formatted dict should be returned.
    """

    assert TaniumThreatResponseV2.format_context_data(test_input) == expected_output

''' INTEL DOCS FUNCTIONS TESTS'''

def test_get_intel_doc(requests_mock):
    """
    Given -
        A specific intel doc id.

    When -
        Running get_intel_doc function.

    Then -
        The intel doc details should be returned.
    """

    api_expected_response = util_load_json('test_files/get_intel_doc_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/423', json=api_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.get_intel_doc(MOCK_CLIENT, {'intel_doc_id': '423'})
    assert '| 423 | get_doc_test |' in human_readable
    assert outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', {}).get('Name') == 'get_doc_test'
    assert outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', {}).get('ID') == 423

def test_get_intel_docs_single(requests_mock):
    """
    Given -
        A specific intel name to obtain.

    When -
        Running get_intel_docs function.

    Then -
        This intel doc details should be returned.
    """

    api_expected_response = util_load_json('test_files/get_intel_docs_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/?name=test2', json=api_expected_response[1])

    human_readable, outputs, raw_response = TaniumThreatResponseV2.get_intel_docs(MOCK_CLIENT, {'name': 'test2'})
    assert '| 430 | test2 |' in human_readable
    intel_docs = outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', [])
    assert intel_docs.get('Name') == 'test2'
    assert intel_docs.get('ID') == 430

def test_get_intel_docs_multiple(requests_mock):
    """
    Given -
        Some data args to filter.

    When -
        Running get_intel_docs function.

    Then -
        A list of all intel docs with their details should be returned.
    """

    api_expected_response = util_load_json('test_files/get_intel_docs_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/', json=api_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.get_intel_docs(MOCK_CLIENT, {})
    intel_docs = outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', [])
    assert len(intel_docs) == 3

def test_get_intel_docs_labels_list(requests_mock):
    """
    Given -
        A specific intel-doc ID.

    When -
        Running get_intel_docs_labels_list function.

    Then -
        A list of label IDs of this specific intel-doc.
    """

    intel_doc_id = 423
    api_expected_response = util_load_json('test_files/get_intel_docs_labels_list_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + f'/plugin/products/detect3/api/v1/intels/{intel_doc_id}/labels',
                      json=api_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.get_intel_docs_labels_list(MOCK_CLIENT, {
        'intel_doc_id': intel_doc_id})
    assert '| 8 | test3 |' in human_readable
    assert '| 9 | test4 |' in human_readable
    intel_docs = outputs.get('Tanium.IntelDocLabel(val.IntelDocID && val.IntelDocID === obj.IntelDocID)', {})
    assert intel_docs.get('IntelDocID') == 423
    labels = intel_docs.get('LabelsList')
    assert len(labels) == 5
    assert labels[1].get('Name') == 'test2'
    assert labels[3].get('ID') == 9

def test_add_intel_docs_label(requests_mock):
    """
    Given -
        A specific intel-doc ID.
        A specific label ID.

    When -
        Running add_intel_docs_label function.

    Then -
        A list of label IDs of this specific intel-doc with the label ID added.
    """

    intel_doc_id = 423
    label_id = 3
    api_expected_response = util_load_json('test_files/add_intel_docs_labels_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    req = requests_mock.put(BASE_URL + f'/plugin/products/detect3/api/v1/intels/{intel_doc_id}/labels',
                            json=api_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.add_intel_docs_label(MOCK_CLIENT,
                                                                                {'intel_doc_id': intel_doc_id,
                                                                                'label_id': label_id})
    assert 'Successfully created a new label (3) association for the identified intel document (423).' in human_readable
    assert '| 3 | test6 |' in human_readable
    assert json.loads(req.last_request.text) == {'id': label_id}
    intel_docs = outputs.get('Tanium.IntelDocLabel(val.IntelDocID && val.IntelDocID === obj.IntelDocID)', {})
    assert intel_docs.get('IntelDocID') == 423
    labels = intel_docs.get('LabelsList')
    assert len(labels) == 6
    assert labels[1].get('Name') == 'test2'
    assert labels[3].get('ID') == 9

def test_remove_intel_docs_label(requests_mock):
    """
    Given -
        A specific intel-doc ID.
        A specific label ID.

    When -
        Running remove_intel_docs_label function.

    Then -
        A list of label IDs of this specific intel-doc with the label ID removed.
    """

    intel_doc_id = 423
    label_id = 3
    api_expected_response = util_load_json('test_files/get_intel_docs_labels_list_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + f'/plugin/products/detect3/api/v1/intels/{intel_doc_id}/labels/{label_id}',
                         json=api_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.remove_intel_docs_label(MOCK_CLIENT, {
        'intel_doc_id': intel_doc_id,
        'label_id': label_id})
    assert 'Successfully removed the label (3)' in human_readable
    intel_docs = outputs.get('Tanium.IntelDocLabel(val.IntelDocID && val.IntelDocID === obj.IntelDocID)', {})
    labels = intel_docs.get('LabelsList')
    for item in labels:
        assert item.get('ID') != 3

def test_create_intel_doc(mocker, requests_mock):
    """
    Given -
        An ioc file content.

    When -
        Running create_intel_doc function.

    Then -
        A new intel-doc should be created with that specific file content.
    """

    with open('test_files/test.ioc') as f:
        file_content = f.read()
    entry_id = 'Test'
    file_extension = 'ioc'
    api_expected_response = util_load_json('test_files/create_intel_docs_raw_response.json')
    mocker.patch('TaniumThreatResponseV2.get_file_data',
                 return_value=("test_name", "test_files/test.ioc", file_content))
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.post(BASE_URL + '/plugin/products/detect3/api/v1/intels', json=api_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.create_intel_doc(MOCK_CLIENT, {
        'entry_id': entry_id,
        'file_extension': file_extension})
    assert 'Intel Doc information' in human_readable
    assert outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', {}).get('Name') == 'VIRUS TEST'

def test_update_intel_doc_ioc(mocker, requests_mock):
    intel_doc_id = 423
    with open('test_files/test.ioc') as f:
        file_content = f.read()
    entry_id = 'Test'
    file_extension = 'ioc'
    api_update_expected_response = util_load_json('test_files/update_intel_docs_raw_response.json')
    api_get_expected_response = util_load_json('test_files/get_intel_doc_raw_response.json')
    mocker.patch('TaniumThreatResponseV2.get_file_data',
                 return_value=("test_name", 'test_files/test.ioc', file_content))
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/423', json=api_get_expected_response)
    requests_mock.put(BASE_URL + f'/plugin/products/detect3/api/v1/intels/{str(intel_doc_id)}',
                      json=api_update_expected_response,
                      request_headers={'Content-Disposition': 'filename=file.ioc',
                                       'Content-Type': 'application/xml'})

    human_readable, outputs, raw_response = TaniumThreatResponseV2.update_intel_doc(MOCK_CLIENT, {
        'intel_doc_id': intel_doc_id,
        'entry_id': entry_id,
        'file_extension': file_extension})
    assert outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', {}).get('IntrinsicId') == 'test123456'
    assert outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', {}).get('RevisionId') == 2

def test_update_intel_doc_yara(mocker, requests_mock):
    intel_doc_id = 423
    with open('test_files/test.yara') as f:
        file_content = f.read()
    entry_id = 'Test'
    file_extension = 'yara'
    api_update_expected_response = util_load_json('test_files/update_intel_docs_raw_response.json')
    api_get_expected_response = util_load_json('test_files/get_intel_doc_raw_response.json')
    mocker.patch('TaniumThreatResponseV2.get_file_data',
                 return_value=("test_name", 'test_files/test.yara', file_content))
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/423', json=api_get_expected_response)
    requests_mock.put(BASE_URL + f'/plugin/products/detect3/api/v1/intels/{str(intel_doc_id)}',
                      request_headers={'Content-Disposition': 'filename=test123456',
                                       'Content-Type': 'application/xml'}, json=api_update_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.update_intel_doc(MOCK_CLIENT, {
        'intel_doc_id': intel_doc_id,
        'entry_id': entry_id,
        'file_extension': file_extension})
    assert outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', {}).get('IntrinsicId') == 'test123456'
    assert outputs.get('Tanium.IntelDoc(val.ID && val.ID === obj.ID)', {}).get('RevisionId') == 2

def test_delete_intel_doc(mocker, requests_mock):
    """
    Given -
        A specific intel-doc ID.

    When -
        Running delete_intel_doc function.

    Then -
        Specified intel-doc is deleted.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + '/plugin/products/detect3/api/v1/intels/?id=431', json={})

    human_readable, outputs, raw_response = TaniumThreatResponseV2.delete_intel_doc(MOCK_CLIENT, {'intel_doc_id': 431})
    assert 'Intel Doc deleted' in human_readable

def test_start_quick_scan(mocker, requests_mock):
    """
    Given -
        A specific intel-doc ID.
        A Tanium Computer Group Name

    When -
        Running start_quick_scan function.

    Then -
        A quick scan is started.
    """

    api_get_expected_response = util_load_json('test_files/get_computer_group_name_raw_response.json')
    api_post_expected_response = util_load_json('test_files/start_quick_scan_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/api/v2/groups/by-name/All%20Computers', json=api_get_expected_response)
    requests_mock.post(BASE_URL + '/plugin/products/detect3/api/v1/quick-scans/', json=api_post_expected_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.start_quick_scan(MOCK_CLIENT, {
        'intel_doc_id': 431, 'computer_group_name': 'All Computers'})
    assert 'Quick Scan started' in human_readable
    assert outputs.get('Tanium.QuickScan(val.ID && val.ID === obj.ID)', {}).get('IntelDocId') == 431
    assert outputs.get('Tanium.QuickScan(val.ID && val.ID === obj.ID)', {}).get('ComputerGroupId') == 1
    assert outputs.get('Tanium.QuickScan(val.ID && val.ID === obj.ID)', {}).get('ID') == 1000239
    assert outputs.get('Tanium.QuickScan(val.ID && val.ID === obj.ID)', {}).get('AlertCount') == 0
    assert outputs.get('Tanium.QuickScan(val.ID && val.ID === obj.ID)', {}).get('CreatedAt') == "2022-01-05T19:53:43.049Z"
    assert outputs.get('Tanium.QuickScan(val.ID && val.ID === obj.ID)', {}).get('UserId') == 64
    assert outputs.get('Tanium.QuickScan(val.ID && val.ID === obj.ID)', {}).get('QuestionId') == 2025697

def test_deploy_intel(requests_mock):
    """
    Given -
        We want to deploy the intels.

    When -
        Running deploy_intel function.

    Then -
        The deploy process should begin.
    """

    api_raw_response = {
        'data': {
            'taskId': 750
        }
    }
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.post(BASE_URL + '/plugin/products/threat-response/api/v1/intel/deploy',
                       json=api_raw_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.deploy_intel(MOCK_CLIENT, {})
    assert 'Successfully deployed intel.' == human_readable
    assert api_raw_response == raw_response

def test_get_deploy_status(requests_mock):
    """
    Given -
        We want to get the last deploy status.

    When -
        Running get_deploy_status function.

    Then -
        The deploy status details should be returned.
    """

    api_raw_response = {
        'data': {
            'createdAt': '2021-05-02T19:18:00.685Z',
            'modifiedAt': '2021-07-14T10:17:13.050Z',
            'currentRevision': 10,
            'currentSize': 2000,
            'pendingRevision': None,
            'pendingSize': None
        }
    }
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/intel/status',
                      json=api_raw_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.get_deploy_status(MOCK_CLIENT, {})
    assert 'Intel deploy status' in human_readable
    assert outputs.get('Tanium.IntelDeployStatus', {}).get('CurrentRevision') == 10

def test_get_alerts(requests_mock):
    """
    Given -
        We want to get alerts list.

    When -
        Running get_alerts function.

    Then -
        The alerts list should be returned.
    """

    api_raw_response = util_load_json('test_files/get_alerts_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/alerts/',
                      json=api_raw_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.get_alerts(MOCK_CLIENT, {})
    assert 'Alerts' in human_readable
    assert len(outputs.get('Tanium.Alert(val.ID && val.ID === obj.ID)', [])) == 2

def test_get_alert(requests_mock):
    """
    Given -
        We want to get alerts by id.

    When -
        Running get_alert function.

    Then -
        The alert should be returned.
    """

    api_raw_response = util_load_json('test_files/get_alert_raw_response.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/alerts/1',
                      json=api_raw_response)

    human_readable, outputs, raw_response = TaniumThreatResponseV2.get_alert(MOCK_CLIENT, {'alert_id': 1})
    assert 'Alert information' in human_readable
    assert outputs.get('Tanium.Alert(val.ID && val.ID === obj.ID)', {}).get('ID') == 1

def test_alert_update_state(requests_mock):
    """
    Given -
        We want to update alert status.

    When -
        Running get_alert function.

    Then -
        The alert should be returned.
    """
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.put(BASE_URL + '/plugin/products/detect3/api/v1/alerts/', json={})

    args = {'alert_ids': '1,2',
            'state': 'unresolved'}
    human_readable, outputs, _ = TaniumThreatResponseV2.alert_update_state(MOCK_CLIENT, args)
    assert 'Alert state updated to unresolved' in human_readable
    assert outputs == {}

def test_create_snapshot(requests_mock):
    """
    Given - connection to snapshot.

    When -
        Running create_snapshot function.

    Then -
        The Task_id should be returned.
    """

    api_raw_response = util_load_json('test_files/create_snapshot.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.post(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/snapshot',
                       json=api_raw_response)

    args = {'connection_id': 'remote:host:123:'}
    human_readable, outputs, _ = TaniumThreatResponseV2.create_snapshot(MOCK_CLIENT, args)
    assert 'Initiated snapshot creation request for' in human_readable
    assert 'Task id: 1' in human_readable
    assert outputs.get('Tanium.SnapshotTask(val.taskId === obj.taskId && val.connection === obj.connection)',
                       {}).get('taskId') == 1
    assert outputs.get('Tanium.SnapshotTask(val.taskId === obj.taskId && val.connection === obj.connection)',
                       {}).get('connection') == 'remote:host:123:'

def test_delete_snapshot(requests_mock):
    """
    Given - snapshot ids to delete

    When -
        Running delete_snapshot function.

    Then -
        The human_readable should be returned.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + '/plugin/products/threat-response/api/v1/snapshot',
                         json={})

    args = {'snapshot_ids': '1,2,3'}
    human_readable, outputs, _ = TaniumThreatResponseV2.delete_snapshot(MOCK_CLIENT, args)
    assert 'deleted successfully.' in human_readable
    assert outputs == {}

def test_list_snapshots(requests_mock):
    """
    Given - list_snapshots command, with limit 2.

    When -
        Running list_snapshots function.

    Then -
        The 2 snapshots should be returned.
    """

    api_raw_response = util_load_json('test_files/list_snapshots.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/snapshot',
                      json=api_raw_response)

    args = {'limit': 2, 'offset': 0}
    human_readable, outputs, _ = TaniumThreatResponseV2.list_snapshots(MOCK_CLIENT, args)
    assert 'Snapshots:' in human_readable
    assert outputs.get('Tanium.Snapshot(val.uuid === obj.uuid)', [{}])[0].get('uuid') == '1234567890'

def test_delete_local_snapshot(requests_mock):
    """
    Given - connection id to delete its local snapshot

    When -
        Running delete_local_snapshot function.

    Then -
        The human_readable should be returned.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:',
                         json={})

    args = {'connection_id': 'remote:host:123:'}
    human_readable, outputs, _ = TaniumThreatResponseV2.delete_local_snapshot(MOCK_CLIENT, args)
    assert ' was deleted successfully.' in human_readable
    assert outputs == {}

def test_get_connections(requests_mock):
    """
    Given - get_connections command and limit=2.

    When -
        Running get_connections function.

    Then -
        2 connections should be returned.
    """

    api_raw_response = util_load_json('test_files/get_connections.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/conns',
                      json=api_raw_response)

    args = {'limit': '2', 'offset': '0'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_connections(MOCK_CLIENT, args)
    assert 'Connections' in human_readable
    assert outputs.get('Tanium.Connection(val.id === obj.id)', [{}])[0].get('hostname') == 'hostname'
    assert len(outputs.get('Tanium.Connection(val.id === obj.id)')) == 2

@pytest.mark.parametrize(
    'command_args, expected_output_len', FILTER_CONNECTIONS_LIST_ARGS
)
def test_filter_get_connections(
        requests_mock, command_args, expected_output_len
):
    """
    Given -
        offset, limit, hostname/platform/status/ip as filter parameters to 'get_connections' function

    When -
        Running 'get_connections' function

    Then -
        'get_connections' function will filter and return response output length the same as expected_output_len
    """
    api_raw_response = util_load_json('test_files/filter_get_connections.json')
    requests_mock.get(
        BASE_URL + '/api/v2/session/login',
        json={'data': {'session': 'session-id'}},
    )
    requests_mock.get(
        BASE_URL + '/plugin/products/threat-response/api/v1/conns',
        json=api_raw_response,
    )

    _, outputs, _ = TaniumThreatResponseV2.get_connections(
        client=MOCK_CLIENT, command_args=command_args
    )
    response = outputs.get('Tanium.Connection(val.id === obj.id)', {})
    full_response_len = len(response)
    assert full_response_len == expected_output_len, f'Actual: {full_response_len}, Expected: {expected_output_len}'

def test_create_connection(requests_mock):
    """
    Given - ip, client_id, hostname to create new connection.

    When -
        Running create_connection function.

    Then -
        The connection_id should be returned.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.post(BASE_URL + '/plugin/products/threat-response/api/v1/conns/connect',
                       content=b'remote:hostname:123:')

    args = {'ip': '1.1.1.1',
            'client_id': '123',
            'hostname': 'hostname'}
    human_readable, outputs, _ = TaniumThreatResponseV2.create_connection(MOCK_CLIENT, args)
    assert 'Initiated connection request to ' in human_readable
    assert outputs.get('Tanium.Connection(val.id === obj.id)', {}).get('id') == 'remote:hostname:123:'

def test_delete_connection(requests_mock):
    """
    Given - connection_id to delete

    When -
        Running delete_connection function.

    Then -
        The connection should be deleted without errors.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + '/plugin/products/threat-response/api/v1/conns/delete/remote:host:123:', json={})

    args = {'connection_id': 'remote:host:123:'}
    human_readable, outputs, _ = TaniumThreatResponseV2.delete_connection(MOCK_CLIENT, args)
    assert 'Connection `remote:host:123:` deleted successfully.' in human_readable
    assert outputs == {}

def test_close_connection(requests_mock):
    """
    Given - connection_id to close

    When -
        Running close_connection function.

    Then -
        The connection should be closed without errors.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + '/plugin/products/threat-response/api/v1/conns/close/remote:host:123:', json={})

    args = {'connection_id': 'remote:host:123:'}
    human_readable, outputs, _ = TaniumThreatResponseV2.close_connection(MOCK_CLIENT, args)
    assert 'Connection `remote:host:123:` closed successfully.' in human_readable
    assert outputs == {}

def test_get_events_by_connection(requests_mock):
    """
    Given -connection_id and type of events to return in this connection.

    When -
        Running get_events_by_connection function.

    Then -
        The list of events in connection should be returned.
    """

    api_raw_response = util_load_json('test_files/get_events_by_connection.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(
        BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:hostname:123:/views/process/events',
        json=api_raw_response)

    args = {'limit': '2',
            'offset': '0',
            'connection_id': 'remote:hostname:123:',
            'type': 'process'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_events_by_connection(MOCK_CLIENT, args)
    assert 'Events for remote:hostname:123:' in human_readable
    assert outputs.get('TaniumEvent(val.id === obj.id)', [{}])[0].get('pid') == 1

def test_get_labels(requests_mock):
    """
    Given - limit 2 labels.

    When -
        Running get_labels function.

    Then -
        two labels should be returned.
    """

    api_raw_response = util_load_json('test_files/get_labels.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/labels/',
                      json=api_raw_response)

    args = {'limit': '2', 'offset': '0'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_labels(MOCK_CLIENT, args)
    assert 'Labels' in human_readable
    assert outputs.get('Tanium.Label(val.id === obj.id)', [{}])[0].get('id') == 1
    assert len(outputs.get('Tanium.Label(val.id === obj.id)')) == 2

def test_get_label(requests_mock):
    """
    Given - label id to get.

    When -
        Running get_label function.

    Then -
        The label info should be returned.
    """

    api_raw_response = util_load_json('test_files/get_label.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/labels/1',
                      json=api_raw_response)

    args = {'label_id': 1}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_label(MOCK_CLIENT, args)
    assert 'Label information' in human_readable
    assert outputs.get('Tanium.Label(val.id && val.id === obj.id)', {}).get('id') == 1

def test_get_events_by_process(requests_mock):
    """
    Given - connection id, process id anf type of events to get.

    When -
        Running get_events_by_process function.

    Then -
        Two pocess events related to connection id and ptid 1 should be returned.
    """

    api_raw_response = util_load_json('test_files/get_events_by_process.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(
        BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/processevents/1/process?limit=2&offset=0',
        json=api_raw_response)

    args = {'connection_id': 'remote:host:123:',
            'limit': '2',
            'offset': '0',
            'ptid': '1',
            'type': 'Process'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_events_by_process(MOCK_CLIENT, args)
    assert 'Events for process 1' in human_readable
    assert outputs.get('Tanium.ProcessEvent(val.id && val.id === obj.id)', [{}])[0].get('id') == '1'

def test_get_process_info(requests_mock):
    """
    Given - connection id and ptid to get its info.

    When -
        Running get_process_info function.

    Then -
        The process info should be returned.
    """

    api_raw_response = util_load_json('test_files/get_process_info.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/processtrees/1',
                      json=api_raw_response)

    args = {'connection_id': 'remote:host:123:',
            'ptid': '1'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_process_info(MOCK_CLIENT, args)
    assert 'Process information for process with PTID 1' in human_readable
    assert outputs.get('Tanium.ProcessInfo(val.id === obj.id)', [{}])[0].get('id') == "1"

def test_get_process_children(requests_mock):
    """
    Given - connection id and ptid to get its children.

    When -
        Running get_process_children function.

    Then -
        The process children should be returned.
    """

    api_raw_response = util_load_json('test_files/get_process_children.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/processtrees/1',
                      json=api_raw_response)

    args = {'connection_id': 'remote:host:123:',
            'ptid': '1'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_process_children(MOCK_CLIENT, args)
    assert 'Children for process with PTID 1' in human_readable
    assert outputs.get('Tanium.ProcessChildren(val.id === obj.id)', [{}])[0].get('id') == "2"

def test_get_parent_process(requests_mock):
    """
    Given - connection id and ptid to get its parent.

    When -
        Running get_parent_process function.

    Then -
        The process parent should be returned.
    """

    api_raw_response = util_load_json('test_files/get_parent_process.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/processtrees/2',
                      json=api_raw_response)

    args = {'connection_id': 'remote:host:123:',
            'ptid': '2'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_parent_process(MOCK_CLIENT, args)
    assert 'Parent process for process with PTID 2' in human_readable
    assert outputs.get('Tanium.ProcessParent(val.id === obj.id)', [{}])[0].get('id') == "1"

def test_get_process_tree(requests_mock):
    """
    Given - connection id and ptid to get its process tree.

    When -
        Running get_process_tree function.

    Then -
        The process tree should be returned.
    """

    api_raw_response = util_load_json('test_files/get_process_tree.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/processtrees/2',
                      json=api_raw_response)

    args = {'connection_id': 'remote:host:123:',
            'ptid': '2'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_process_tree(MOCK_CLIENT, args)
    assert 'Process information for process with PTID 2' in human_readable
    assert outputs.get('Tanium.ProcessTree(val.id && val.id === obj.id)', [{}])[0].get('id') == "1"

def test_list_evidence(requests_mock):
    """
    Given - limit and offset for evidenced to get

    When -
        Running list_evidence function.

    Then -
        Two evidences should be returned.
    """

    api_raw_response = util_load_json('test_files/list_evidence.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/evidence',
                      json=api_raw_response)

    args = {'limit': '2',
            'offset': '0'}
    human_readable, outputs, _ = TaniumThreatResponseV2.list_evidence(MOCK_CLIENT, args)
    assert 'Evidence list' in human_readable
    assert outputs.get('Tanium.Evidence(val.uuid && val.uuid === obj.uuid)', [{}])[0].get('uuid') == '123abc'
    assert len(outputs.get('Tanium.Evidence(val.uuid && val.uuid === obj.uuid)')) == 2

@pytest.mark.parametrize(
    'command_args, expected_output_len', FILTER_EVIDENCE_LIST_ARGS
)
def test_filter_list_evidence(requests_mock, command_args, expected_output_len):
    """
    Given -
        offset, limit, hash/hostname as filter arguments for 'get_file_downloads_function'

    When -
        Running 'get_file_downloads' function

    Then -
        'get_file_downloads' function will filter and return response in the same length as expected_output_len.
    """
    api_raw_response = util_load_json('test_files/filter_list_evidence.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/evidence',
                      json=api_raw_response)

    _, outputs, _ = TaniumThreatResponseV2.list_evidence(MOCK_CLIENT, command_args)
    response = outputs.get('Tanium.Evidence(val.uuid && val.uuid === obj.uuid)', {})
    assert (len(
        response) == expected_output_len), f'Actual length: {len(response)}, Expected length: {expected_output_len}'

def test_event_evidence_get_properties(requests_mock):
    """
    Given - event_evidence_get_properties command.

    When -
        Running event_evidence_get_properties function.

    Then -
        The properties list should be returned should be returned.
    """

    api_raw_response = util_load_json('test_files/event_evidence_get_properties.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/event-evidence/properties',
                      json=api_raw_response)

    args = {}
    human_readable, outputs, _ = TaniumThreatResponseV2.event_evidence_get_properties(MOCK_CLIENT, args)
    assert 'Evidence Properties' in human_readable
    assert outputs.get('Tanium.EvidenceProperties(val.value === obj.value)', [{}])[0].get('type') == 'ProcessId'

def test_get_evidence_by_id(requests_mock):
    """
    Given - evidence id to get its info.

    When -
        Running get_evidence_by_id function.

    Then -
        The evidence with given id should be returned.
    """

    api_raw_response = util_load_json('test_files/get_evidence_by_id.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/event-evidence/1',
                      json=api_raw_response)

    args = {'evidence_id': '1'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_evidence_by_id(MOCK_CLIENT, args)
    assert 'Evidence information' in human_readable
    assert outputs.get('Tanium.Evidence(val.uuid && val.uuid === obj.uuid)', {}).get('uuid') == '1'

def test_create_evidence(requests_mock):
    """
    Given - hostname, connection_id and ptid to create event evidence with this data.

    When -
        Running create_evidence function.

    Then -
        Human readable should be returned.
    """
    api_raw_response = util_load_json('test_files/create_evidence.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/views/process/events',
                      json=api_raw_response)
    requests_mock.post(BASE_URL + '/plugin/products/threat-response/api/v1/event-evidence',
                       json={})

    args = {'connection_id': 'remote:host:123:',
            'hostname': 'host',
            'ptid': '1'}
    human_readable, _, _ = TaniumThreatResponseV2.create_evidence(MOCK_CLIENT, args)
    assert 'Evidence have been created.' in human_readable

def test_delete_evidence(requests_mock):
    """
    Given - evidence_ids to delete

    When -
        Running delete_evidence? function.

    Then -
        The evidence ids should be deleted.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + '/plugin/products/threat-response/api/v1/event-evidence',
                         json={})

    args = {'evidence_ids': '1,2,3'}
    human_readable, _, _ = TaniumThreatResponseV2.delete_evidence(MOCK_CLIENT, args)
    assert 'Evidence 1,2,3 has been deleted successfully.' in human_readable

def test_get_file_downloads(requests_mock):
    """
    Given - get_file_downloads command

    When -
        Running get_file_downloads function.

    Then -
        The file dowloads list should be returned.
    """

    api_raw_response = util_load_json('test_files/get_file_downloads.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/filedownload',
                      json=api_raw_response)

    args = {'limit': '2'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_file_downloads(MOCK_CLIENT, args)
    assert 'File downloads' in human_readable
    assert outputs.get('Tanium.FileDownload(val.uuid === obj.uuid)', [{}])[0].get('uuid') == '1'
    assert outputs.get('Tanium.FileDownload(val.uuid === obj.uuid)', [{}])[0].get('evidenceType') == 'file'

@pytest.mark.parametrize(
    'command_args, expected_output_len', FILTER_FILE_DOWNLOADS_ARGS
)
def test_filter_get_file_downloads(requests_mock, command_args, expected_output_len):
    """
    Given -
        offset, limit, hash/hostname as filter arguments for 'get_file_downloads_function'

    When -
        Running 'get_file_downloads' function

    Then -
        'get_file_downloads' function will filter and return response in the same length as expected_output_len.
    """
    api_raw_response = util_load_json('test_files/filter_get_file_downloads.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/filedownload',
                      json=api_raw_response)

    _, outputs, _ = TaniumThreatResponseV2.get_file_downloads(MOCK_CLIENT, command_args)
    response = outputs.get('Tanium.FileDownload(val.uuid === obj.uuid)', {})
    assert len(response) == expected_output_len, f"Expected length: {expected_output_len}, actual: {len(response)}"

def test_get_file_download_info(requests_mock):
    """
    Given - file id to get its info

    When -
        Running get_file_download_info function.

    Then -
        The file download info should be returned.
    """

    api_raw_response = util_load_json('test_files/get_file_download_info.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/filedownload/1',
                      json=api_raw_response)

    args = {'file_id': '1'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_file_download_info(MOCK_CLIENT, args)
    assert 'File download' in human_readable
    assert outputs.get('Tanium.FileDownload(val.uuid === obj.uuid)', {}).get('uuid') == '1'

def test_request_file_download(requests_mock):
    """
    Given - path, connection id to request file download from there.

    When -
        Running request_file_download function.

    Then -
        The Task info should be returned.
    """

    api_raw_response = util_load_json('test_files/request_file_download.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.post(BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/file',
                       json=api_raw_response)

    args = {'connection_id': 'remote:host:123:', 'path': 'C:\\file.txt'}
    human_readable, outputs, _ = TaniumThreatResponseV2.request_file_download(MOCK_CLIENT, args)
    assert 'Task id: 1' in human_readable
    assert outputs.get('Tanium.FileDownloadTask(val.taskId === obj.taskId && val.connection === obj.connection)',
                       {}).get('taskId') == 1
    assert outputs.get('Tanium.FileDownloadTask(val.taskId === obj.taskId && val.connection === obj.connection)',
                       {}).get('connection') == 'remote:host:123:'

def test_delete_file_download(requests_mock):
    """
    Given - file id to delete

    When -
        Running delete_file_download function.

    Then -
        The file download should be deleted.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(BASE_URL + '/plugin/products/threat-response/api/v1/filedownload/1',
                         json={})

    args = {'file_id': '1'}
    human_readable, outputs, _ = TaniumThreatResponseV2.delete_file_download(MOCK_CLIENT, args)
    assert 'Delete request of file with ID 1 has been sent successfully' in human_readable

def test_list_files_in_dir(requests_mock):
    """
    Given - path in connection to get its files.

    When -
        Running list_files_in_dir function.

    Then -
        The list of files in path should be returned.
    """

    api_raw_response = util_load_json('test_files/list_files_in_dir.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(
        BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/file/list/C%3A%5CDir%5C',
        json=api_raw_response)

    args = {'connection_id': 'remote:host:123:',
            'path': 'C:\\Dir\\',
            'limit': '2', 'offset': '0'}
    human_readable, outputs, _ = TaniumThreatResponseV2.list_files_in_dir(MOCK_CLIENT, args)
    assert 'Files in directory' in human_readable
    assert outputs.get('Tanium.File(val.name === obj.name && val.connectionId === obj.connectionId)', [{}])[0].get(
        'name') == 'file1.exe'
    assert outputs.get('Tanium.File(val.name === obj.name && val.connectionId === obj.connectionId)', [{}])[0].get(
        'connectionId') == 'remote:host:123:'

def test_get_file_info(requests_mock):
    """
    Given -

    When -
        Running get_file_info function.

    Then -
        The file info should be returned.
    """

    api_raw_response = util_load_json('test_files/get_file_info.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(
        BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/file/info/C%3A%5Cfile1.txt',
        json=api_raw_response)

    args = {'path': "C:\\file1.txt",
            'connection_id': "remote:host:123:"}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_file_info(MOCK_CLIENT, args)
    assert 'Information for file' in human_readable
    assert outputs.get('Tanium.File(val.path === obj.path && val.connectionId === obj.connectionId)', {}).get(
        'connectionId') == 'remote:host:123:'
    assert outputs.get('Tanium.File(val.path === obj.path && val.connectionId === obj.connectionId)', {}).get(
        'path') == "C:\\file1.txt"

def test_delete_file_from_endpoint(requests_mock):
    """
    Given - connection id and path of file to delete.

    When -
        Running delete_file_from_endpoint function.

    Then -
        The file should be deleted.
    """

    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.delete(
        BASE_URL + '/plugin/products/threat-response/api/v1/conns/remote:host:123:/file/delete/C%3A%5Cfile1.txt',
        json={})

    args = {'path': "C:\\file1.txt",
            'connection_id': "remote:host:123:"}
    human_readable, outputs, _ = TaniumThreatResponseV2.delete_file_from_endpoint(MOCK_CLIENT, args)
    assert 'Delete request of file C:\\file1.txt' in human_readable

def test_get_task_by_id(requests_mock):
    """
    Given - task id to get its status and info

    When -
        Running get_task_by_id function.

    Then -
        The task info should be returned.
    """

    api_raw_response = util_load_json('test_files/get_task_by_id.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/threat-response/api/v1/tasks/1',
                      json=api_raw_response)

    args = {'task_id': '1'}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_task_by_id(MOCK_CLIENT, args)
    assert 'Task information' in human_readable
    assert outputs.get('Tanium.Task(val.id === obj.id)', {}).get('id') == 1

def test_get_system_status(requests_mock):
    """
    Given - tanium system

    When -
        Running get_system_status function.

    Then -
        The connected computers should be returned.
    """

    api_raw_response = util_load_json('test_files/get_system_status.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/api/v2/system_status',
                      json=api_raw_response)

    args = {'limit': 2, 'offset': 0}
    human_readable, outputs, _ = TaniumThreatResponseV2.get_system_status(MOCK_CLIENT, args)
    assert 'Reporting clients' in human_readable
    assert outputs.get('Tanium.SystemStatus(val.clientId === obj.clientId)', {})[0].get('clientId') == 1

@pytest.mark.parametrize(
    'command_args, expected_output_len', FILTER_GET_SYSTEM_STATUS_ARGS
)
def test_filter_get_system_status(
        requests_mock, command_args, expected_output_len
):
    """
    Given -
        offset, limit, status/hostname/ip_server/ip_client/port as filter arguments for 'get_system_status' function

    When -
        Running 'get_system_status' function

    Then -
        'get_system_status' function will filter and return response in the same length as expected_output_len.
    """
    api_raw_response = util_load_json(
        'test_files/filter_get_system_status.json'
    )

    requests_mock.get(
        BASE_URL + '/api/v2/session/login',
        json={'data': {'session': 'session-id'}},
    )
    requests_mock.get(
        BASE_URL + '/api/v2/system_status', json=api_raw_response
    )

    _, outputs, _ = TaniumThreatResponseV2.get_system_status(
        MOCK_CLIENT, command_args
    )
    response = outputs.get(
        'Tanium.SystemStatus(val.clientId === obj.clientId)', {}
    )
    assert (len(
        response) == expected_output_len), f'Actual length: {len(response)}, Expected length: {expected_output_len}'

def test_fetch_all_incidents(requests_mock):
    """
        Given
            fetch incidents command running for the first time.
        When
            mock the Client's http_request.
        Then
            validate fetch incidents command using the Client gets all 2 relevant incidents
    """

    test_incidents = util_load_json('test_files/fetch_incidents.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/alerts?'
                                 '&state=unresolved&sort=-createdAt&limit=500&offset=0',
                      json=test_incidents)
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/alerts?'
                                 '&state=unresolved&sort=-createdAt&limit=500&offset=500',
                      json=[])
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/11', json={'name': 'test'})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/11/labels', json=[{'name': 'test'}])

    alerts_states_to_retrieve = 'unresolved'
    last_run = {}
    fetch_time = '10 years'
    max_fetch = 2

    incidents, next_run = TaniumThreatResponseV2.fetch_incidents(
        MOCK_CLIENT,
        alerts_states_to_retrieve,
        '',
        last_run,
        fetch_time,
        max_fetch
    )

    assert len(incidents) == 2
    assert incidents[0].get(
        'name') == 'hostname found test'
    assert incidents[0].get(
        'occurred') == "2021-09-26T14:01:31.000Z"
    assert next_run.get('id') == "2"
    assert next_run.get('time') == datetime.strftime(parse("2021-09-26T14:02:59.000Z"),
                                                     TaniumThreatResponseV2.DATE_FORMAT)

def test_fetch_new_incidents(requests_mock):
    """
        Given
            fetch incidents command running for the first time.
        When
            mock the Client's http_request.
        Then
            validate fetch incidents command using the Client gets new 2 relevant incidents
    """

    test_incidents = util_load_json('test_files/fetch_incidents_new.json')
    requests_mock.post(BASE_URL + '/api/v2/session/login', json={'data': {'session': 'session-id'}})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/alerts?'
                                 '&state=unresolved&sort=-createdAt&limit=500&offset=0',
                      json=test_incidents)
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/alerts?'
                                 '&state=unresolved&sort=-createdAt&limit=500&offset=500',
                      json=[])
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/11', json={'name': 'test'})
    requests_mock.get(BASE_URL + '/plugin/products/detect3/api/v1/intels/11/labels', json=[{'name': 'test'}])

    alerts_states_to_retrieve = 'unresolved'
    last_run = {'time': '2021-09-26T14:02:59.000000Z', 'id': '2'}
    fetch_time = '3 days'
    max_fetch = 2

    incidents, next_run = TaniumThreatResponseV2.fetch_incidents(
        MOCK_CLIENT,
        alerts_states_to_retrieve,
        '',
        last_run,
        fetch_time,
        max_fetch
    )

    assert len(incidents) == 2
    assert incidents[0].get(
        'name') == 'hostname found test'
    assert incidents[0].get(
        'occurred') == "2021-09-26T14:01:31.000Z"
    assert next_run.get('id') == "4"
    assert next_run.get('time') == datetime.strftime(parse("2021-09-26T14:04:59.000Z"),
                                                     TaniumThreatResponseV2.DATE_FORMAT)


text:
package com.amazonaws.services.iot.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * AttributePayload JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AttributePayloadJsonUnmarshaller implements Unmarshaller<AttributePayload, JsonUnmarshallerContext> {

    public AttributePayload unmarshall(JsonUnmarshallerContext context) throws Exception {
        AttributePayload attributePayload = new AttributePayload();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("attributes", targetDepth)) {
                    context.nextToken();
                    attributePayload.setAttributes(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
                            .getUnmarshaller(String.class)).unmarshall(context));
                }
                if (context.testExpression("merge", targetDepth)) {
                    context.nextToken();
                    attributePayload.setMerge(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return attributePayload;
    }

    private static AttributePayloadJsonUnmarshaller instance;

    public static AttributePayloadJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new AttributePayloadJsonUnmarshaller();
        return instance;
    }
}


text:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace WebsitePanel.EnterpriseServer.Code.MailServers
{
    public class QuotaLimit
    {
        private bool isExceeded;
        private string message;

        public bool IsExceeded
        {
            get { return this.isExceeded; }
            set { isExceeded = value; }
        }

        public string Message
        {
            get { return this.message;}
            set { message = value; }
        }
    }
}


text:
<?php
/**
 * The template for displaying search results
 *
 * @package Start Here
 * @since Start Here 1.0.0
 */

get_header(); ?>

            <?php
                if( have_posts() ) : ?>

<?php printf( __( 'Search Results for: %s', 'twentyfourteen' ), get_search_query() ); ?>

                <?php
                    while( have_posts() ) : the_post();

                        get_template_part( 'templates/content', get_post_format() );

                    endwhile;

                    sh_page_nav();

                else:

                    get_template_part( 'templates/content', 'nope' );

                endif;

            ?>

<?php
get_sidebar();
get_footer();


text:
ChangePassword - change password with correct timeout

--SKIPIF--
<?php include('skip_enterprise.inc'); ?>
--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("ChangePassword", "testChangePasswordCorrectTimeout");
--EXPECT--
OK


text:
#include "CTiglInterpolatePointsWithKinks.h"

#include "CTiglBSplineAlgorithms.h"
#include "CTiglPointsToBSplineInterpolation.h"
#include "tiglmathfunctions.h"

#include <iterator>

namespace
{
    template <typename ArrayLike>
    inline bool in(unsigned int key, const ArrayLike& array)
    {
        return std::find(std::begin(array), std::end(array), key) != array.end();
    }

    template <>
    inline bool in(unsigned int key, const tigl::ParamMap& map)
    {
        return map.find(key) != map.end();
    }

    template <typename ArrayLike>
    ArrayLike slice(const ArrayLike& array, size_t imin, size_t imax)
    {
        size_t len = imax - imin + 1;
        ArrayLike result(len);
        for (size_t i = 0; i < len; ++i) {
            result[i] = array[i + imin];
        }

        return result;
    }

    template <>
    Handle(TColgp_HArray1OfPnt) slice(const Handle(TColgp_HArray1OfPnt) & pnts, size_t imin, size_t imax)
    {
        int len = static_cast<int>(imax - imin + 1);
        Handle(TColgp_HArray1OfPnt) result = new TColgp_HArray1OfPnt(1, len);
        for (int i = 0; i < len; ++i) {
            result->SetValue(i+1, pnts->Value(i + static_cast<int>(imin)));
        }

        return result;
    }

    template <typename ArrayLike>
    ArrayLike stack(const ArrayLike& arr1, const ArrayLike& arr2)
    {
        auto result = arr1;
        for (const auto& v : arr2) {
            result.push_back(v);
        }

        return result;
    }

    template <>
    Handle(TColgp_HArray1OfPnt) stack(const Handle(TColgp_HArray1OfPnt) & pnts1, const Handle(TColgp_HArray1OfPnt) & pnts2)
    {
        const int len1 = pnts1->Length();
        const int len2 = pnts2->Length();

        Handle(TColgp_HArray1OfPnt) result = new TColgp_HArray1OfPnt(1, len1 + len2);
        for (int i = 0; i < len1; ++i) {
            result->SetValue(i+1, pnts1->Value(i+1));
        }

        for (int i = 0; i < len2; ++i) {
            result->SetValue(len1 + i + 1, pnts2->Value(i+1));
        }

        return result;
    }

    std::vector<double> computeParams(const Handle(TColgp_HArray1OfPnt)& pnts, tigl::ParamMap& params, double alpha)
    {
        auto initial_params = tigl::CTiglBSplineAlgorithms::computeParamsBSplineCurve(pnts, alpha);

        unsigned int n_pnts = static_cast<unsigned int>(pnts->Length());

        if (!in(0, params)) {
            params[0] = 0.;
        }
        if (!in(n_pnts - 1, params)) {
            params[n_pnts - 1] = 1.;
        }

        std::vector<double> kink_params_new;
        std::vector<double> kink_params_old;

        for (const auto& p : params) {
            kink_params_new.push_back(p.second);
            kink_params_old.push_back(initial_params[p.first]);
        }

        // Perform linear interpolation to get the new parameters
        std::vector<double> new_params;
        std::transform(std::begin(initial_params), std::end(initial_params),
                       std::back_inserter(new_params), [&](double p) {
           return  tigl::Interpolate(kink_params_old, kink_params_new, p);
        });

        return new_params;
    }

} // namespace

namespace tigl
{

CTiglInterpolatePointsWithKinks::CTiglInterpolatePointsWithKinks(const Handle(TColgp_HArray1OfPnt) & points,
                                                                const std::vector<unsigned int>& kinkIndices,
                                                                const ParamMap& parameters,
                                                                double alpha,
                                                                unsigned int maxDegree)
    : m_pnts(points)
    , m_kinks(kinkIndices)
    , m_params(parameters)
    , m_alpha(alpha)
    , m_maxDegree(maxDegree)
    , m_result(*this, &CTiglInterpolatePointsWithKinks::ComputeResult)
{
}

Handle(Geom_BSplineCurve) CTiglInterpolatePointsWithKinks::Curve() const
{
    return m_result->curve;
}

std::vector<double> CTiglInterpolatePointsWithKinks::Parameters() const
{
    return m_result->parameters;
}

void CTiglInterpolatePointsWithKinks::ComputeResult(Result& result) const
{
    auto params = m_params;

    // assuming iterating over parameters is sorted in keys
    auto new_params = computeParams(m_pnts, params, m_alpha);

    unsigned int n_pnts = static_cast<unsigned int>(m_pnts->Length());

    // make a sorted copy of the kinks array
    auto kinks = m_kinks;
    std::sort(std::begin(kinks), std::end(kinks));

    bool make_continuous = false;
    if (m_pnts->Value(m_pnts->Lower()).IsEqual(m_pnts->Value(m_pnts->Upper()), 1e-6)) {
        if (!in(0, kinks) && ! in(n_pnts - 1, kinks)) {
            make_continuous = true;
        }
    }

    // make sure, that first and last points are in kink list
    if (!make_continuous) {
        if (!in(0, kinks)) {
            kinks.insert(kinks.begin(), 0);
        }
        if (!in(n_pnts - 1, kinks)) {
            kinks.push_back(n_pnts - 1);
        }
    }

    std::vector<Handle(Geom_BSplineCurve)> curve_segments;

    for (size_t i=1; i < kinks.size(); ++i) {
        auto start_idx = kinks[i-1];
        auto end_idx   = kinks[i];

        auto current_pnts = slice(m_pnts, start_idx + 1, end_idx + 1);
        auto the_pars = slice(new_params, start_idx, end_idx);

        auto segment_curve = CTiglPointsToBSplineInterpolation(current_pnts, the_pars, m_maxDegree, false).Curve();
        curve_segments.push_back(segment_curve);
    }

    // create a continuous spline from the last to the first kink
    if (make_continuous && kinks.size() > 0) {
        double offset = new_params.front() - new_params.back();

        auto last_kink_idx = kinks.back();
        auto first_kink_idx = kinks.front();

        auto pnts = stack(slice(m_pnts, last_kink_idx + 1, static_cast<size_t>(m_pnts->Length())),
                          slice(m_pnts, 2, first_kink_idx + 1));

        auto left_parms = slice(new_params, last_kink_idx,  new_params.size()-1);
        std::transform(std::begin(left_parms), std::end(left_parms), std::begin(left_parms), [offset](double p) {
            return p + offset;
        });
        auto right_parms = slice(new_params, 1, first_kink_idx);
        auto the_pars = stack(std::move(left_parms), std::move(right_parms));

        auto lower_curve = CTiglPointsToBSplineInterpolation(pnts, the_pars, m_maxDegree, false).Curve();

        double param_to_split = new_params.front();
        auto last = CTiglBSplineAlgorithms::trimCurve(lower_curve, lower_curve->FirstParameter(), param_to_split);
        auto first = CTiglBSplineAlgorithms::trimCurve(lower_curve, param_to_split, lower_curve->LastParameter());
        // shift parametrization of the last curve to the end of the parameter range
        CTiglBSplineAlgorithms::reparametrizeBSpline(*last, the_pars.front() - offset, param_to_split - offset);

        curve_segments.insert(curve_segments.begin(), first);
        curve_segments.push_back(last);
    }
    else if (make_continuous && kinks.empty()) {
        auto curve = CTiglPointsToBSplineInterpolation(m_pnts, new_params, m_maxDegree, true).Curve();
        curve_segments.push_back(curve);
    }

    result.curve = CTiglBSplineAlgorithms::concatCurves(curve_segments, false);
    result.parameters = new_params;
}

} // namespace tigl


text:
[![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/)
Twitter Bootstrap Ajax Typeahead Plugin
============

Modifications to the Bootstrap Typeahead plugin to give it ajax capabilities.
[See Demo](http://plugins.upbootstrap.com/bootstrap-ajax-typeahead)

How to Use
----------

To make a regular typeahead plugin query a server for the source, just specify an ajax member when initializing.

Feature
-----------------
- A callback function is available for when an item is selected
- Ability to specify data source properties
- Ability to use a local or remote (AJAX) data source
- Most original methods are overridable so you can customize without changing the source code

Required
-----------------
* Twitter Bootstrap 2.0+
* jQuery 1.8+

Installation
-----------------
#### Download [jQuery](http://docs.jquery.com/Downloading_jQuery)
* [Download the latest release](http://docs.jquery.com/Downloading_jQuery)
* [Clone in Windows](github-windows://openRepo/https://github.com/jquery/jquery)
* Clone the repo: `git clone git://github.com/jquery/jquery.git`.

#### Download [Bootstrap](https://github.com/twitter/bootstrap)
* [Download the latest release](https://github.com/twitter/bootstrap/zipball/master).
* [Clone in Windows](github-windows://openRepo/https://github.com/twitter/bootstrap)
* Clone the repo: `git clone git://github.com/twitter/bootstrap.git`.
* Install with Twitter's [Bower](http://twitter.github.com/bower): `bower install bootstrap`.

#### Download this plugin.
* [Download the latest release](https://github.com/biggora/bootstrap-ajax-typeahead/zipball/master)
* [Clone in Windows](github-windows://openRepo/https://github.com/biggora/bootstrap-ajax-typeahead)
* Clone the repo: `git clone git://github.com/biggora/bootstrap-ajax-typeahead.git`
* Install with Bower: `bower install bs-typeahead`.

#### Include files in your HTML. The minimum required for this plugin are:

#### Execute the plugin:
```javascript
    $('input.typeahead').typeahead(options);
```

Events
-----------------

				Event

				Description

            grepper

            Filters relevant results from the source.

            highlighter

            Highlights any matching results in the list.

            onSelect

            The callback function that is invoked when an item is chosen.

{
   item : {
    value: "",
    text: ""
   }
}

            lookup

            Determines if source is remote or local and initializes the search.

            matcher

            Looks for a match between the query and a source item.

            render

            Renders the list of results.

            select

            Selects an item from the results list.

            sorter

            Sorts the results.

Options
-----------------

			Name

			Type

			Default

			Description

            ajax

            object

            null

            The object required to use a remote datasource.

See also: ajax as a string (below)

            ajax

            string

            null

            Optionally, a simple URL may be used instead of the AJAX object.

            See also: ajax as an object

            displayField

            string

            'name'

            The object property to match the query against and highlight in the results.

            item

            string

            '<li><a href="#"></a></li>'

			The HTML rendering for a result item.

            items

            integer

            10

	    The maximum number of items to show in the results.

            menu

            string

            '<ul class="typeahead dropdown-menu"></ul>'

			The HTML rendering for the results list.

     scrollBar
     boolean
     false

       Used to show scrollBar when there are too many match records and it's set to True.

	   If this option is set to true,the items value will be 100 and the HTML render menu will be set to:

		'<ul
			class="typeahead dropdown-menu"
			style="max-height:220px;overflow:auto;"
		></ul>'

                alignWidth

                boolean

                true

    			The align dropdown width by input field width.

            source

            object

           []

			The source to search against.

            valueField

            string

            'id'

            The object property that is returned when an item is selected.

Ajax Options
-----------------

			Name

			Type

			Default

			Description

            url

            string

            null

            timeout

            integer

            300

            Specify the amount of time to wait for keyboard input to stop until you send the query to the server.
            Default is at 300ms.

            method

            string

            'get'

            The method to use, either "post" or "get".

            triggerLength

            integer

            1

	    This is the minimum length of text to take action on. Default is at 1.

            loadingClass

            string

            null

            preDispatch

            function

            null

	This function will be run prior to any call. It is used to fashion a custom parameter
	object to send to the server. Its only argument is the query text. It must return an
	object that jQuery's post() function will use as its second argument. There's no default for this.
	If not specified, the parameters send to the server are:

            { query: "some text" }

            preProcess

            function

           null

	This function will be run right after a call and before the typeahead list is populated.
	It is used to pre process the data returned from the server. Its only argument is the data
	from the server. Returning false from this method will hide the typeahead list.
	If not specified, the data will be passed to the typeahead mechanism as is.

            displayField

            string

            'name'

        If the data returned from the server is a list of objects (as opposed to an array of strings),
        set this member to the name for the field to use for display.

            valueField

            string

            'id'

          If the data returned from the server is a list of objects (as opposed to an array of strings),
          set this member to the id data for the item into list (*required* for a list of objects).

Basic Usage
-----------------
The plugin in its simplest (realistic) form.

#### Example 1

```js
var typeaheadSource = ['John', 'Alex', 'Terry'];

$('input.typeahead').typeahead({
	source: typeaheadSource
});
```

#### Example 2

```js
var typeaheadSource = [{ id: 1, name: 'John'}, { id: 2, name: 'Alex'}, { id: 3, name: 'Terry'}];

$('input.typeahead').typeahead({
	source: typeaheadSource
});
```
#### Example 3

```js
var typeaheadSource = [{
         id: 1, firstName: 'John'}, {
         id: 2, firstName: 'Alex'}, {
         id: 3, firstName: 'Terry'
    }];

$('input.typeahead').typeahead({
        source: typeaheadSource,
        displayField: 'firstName'
});
```
#### Example 4
For a quick setup, specify a source url to pull data from:

```js
$('input.typeahead').typeahead({
        ajax: '/path/to/typeahead/source'
});
```

Extended Usage
-----------------

```javascript
$("input.typeahead").typeahead({
	onSelect: function(item) {
		console.log(item);
	},
	ajax: {
		url: "/path/to/source",
		timeout: 500,
		displayField: "title",
		triggerLength: 1,
		method: "get",
		loadingClass: "loading-circle",
		preDispatch: function (query) {
			showLoadingMask(true);
			return {
				search: query
			}
		},
		preProcess: function (data) {
			showLoadingMask(false);
			if (data.success === false) {
				// Hide the list, there was some error
				return false;
			}
			// We good!
			return data.mylist;
		}
	}
});
```

Bootstrap Integration
---------------------

For simple autocomplete use cases, the typeahead component [Bootstrap][bootstrap] provides should suffice. However, if you'd prefer to take advantage of some of the advance features typeahead.js provides, here's what you'll need to do to integrate typeahead.js with Bootstrap:

* If you're customizing Bootstrap, exclude the typeahead component. If you're depending on the standard *bootstrap.js*, ensure *bootstrap-typeahead.js* is loaded after it.
* The DOM structure of the dropdown menu used by typeahead.js differs from the DOM structure of the Bootstrap dropdown menu. You'll need to load some [additional CSS][typeahead-bootstrap.css] in order to get the bootstrap-typeahead.js dropdown menu to fit the default Bootstrap theme.

Browser Support
---------------

* Chrome
* Firefox 3.5+
* Safari 4+
* Internet Explorer 7+
* Opera 11+

### Recommend extensions

- [Bootstrap Fancy File Plugin](https://github.com/biggora/bootstrap-fancyfile/)
- [Bootstrap Select Plugin](https://github.com/biggora/bootstrap-select/)
- [TrinteJS - Javascrpt MVC Framework for Node.JS](http://www.trintejs.com/)
- [CaminteJS - Cross-db ORM for NodeJS](http://www.camintejs.com/)
- [MongoDB Session Storage for ExpressJS](https://github.com/biggora/express-mongodb)
- [Middleware exposing user-agent for NodeJS](https://github.com/biggora/express-useragent)
- [2CO NodeJS adapter for 2checkout API payment gateway](https://github.com/biggora/2co)

Copyright and license
-------

The MIT License (MIT)

Copyright (c) 2011-2014 Twitter, Inc

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

## Resources

- Visit the [author website](http://www.gordejev.lv).
- Follow [@biggora](https://twitter.com/#!/biggora) on Twitter for updates.
- Report issues on the [github issues](https://github.com/biggora/bootstrap-ajax-typeahead/issues) page.

[![Analytics](https://ga-beacon.appspot.com/UA-22788134-5/ajax-typeahead/readme)](https://github.com/igrigorik/ga-beacon)

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/biggora/bootstrap-ajax-typeahead/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
import translator

class XorTranslator(translator.Translator):
	"""One time pad translator"""
	def translate(self, cipher):
		if len(cipher) > len(self.key):
			return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(cipher[:len(self.key)], self.key)])
		else:
			return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(cipher, self.key[:len(cipher)])])

	def encode(self, cipher):
		return self.translate(cipher)


text:
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Cms.Core.Configuration;

namespace Umbraco.Cms.Core.Configuration
{
    public class JsonConfigManipulator : IConfigManipulator
    {
        private readonly IConfiguration _configuration;
        private readonly object _locker = new object();

        public JsonConfigManipulator(IConfiguration configuration) => _configuration = configuration;

        public string UmbracoConnectionPath { get; } = $"ConnectionStrings:{ Cms.Core.Constants.System.UmbracoConnectionName}";
        public void RemoveConnectionString()
        {
            var provider = GetJsonConfigurationProvider(UmbracoConnectionPath);

            var json = GetJson(provider);

            RemoveJsonKey(json, UmbracoConnectionPath);

            SaveJson(provider, json);
        }

        public void SaveConnectionString(string connectionString, string providerName)
        {
            var provider = GetJsonConfigurationProvider();

            var json = GetJson(provider);

            var item = GetConnectionItem(connectionString, providerName);

            json.Merge(item, new JsonMergeSettings());

            SaveJson(provider, json);
        }

        public void SaveConfigValue(string key, object value)
        {
            var provider = GetJsonConfigurationProvider();

            var json = GetJson(provider);

            JToken token = json;
            foreach (var propertyName in key.Split(new[] { ':' }))
            {
                if (token is null)
                    break;
                token = CaseSelectPropertyValues(token, propertyName);
            }

            if (token is null)
                return;

            var writer = new JTokenWriter();
            writer.WriteValue(value);

            token.Replace(writer.Token);

            SaveJson(provider, json);

        }

        public void SaveDisableRedirectUrlTracking(bool disable)
        {
            var provider = GetJsonConfigurationProvider();

            var json = GetJson(provider);

            var item = GetDisableRedirectUrlItem(disable);

            json.Merge(item, new JsonMergeSettings());

            SaveJson(provider, json);
        }

        public void SetGlobalId(string id)
        {
            var provider = GetJsonConfigurationProvider();

            var json = GetJson(provider);

            var item = GetGlobalIdItem(id);

            json.Merge(item, new JsonMergeSettings());

            SaveJson(provider, json);
        }

        private object GetGlobalIdItem(string id)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("Umbraco");
            writer.WriteStartObject();
            writer.WritePropertyName("CMS");
            writer.WriteStartObject();
            writer.WritePropertyName("Global");
            writer.WriteStartObject();
            writer.WritePropertyName("Id");
            writer.WriteValue(id);
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();

            return writer.Token;
        }

        private JToken GetDisableRedirectUrlItem(bool value)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("Umbraco");
            writer.WriteStartObject();
            writer.WritePropertyName("CMS");
            writer.WriteStartObject();
            writer.WritePropertyName("WebRouting");
            writer.WriteStartObject();
            writer.WritePropertyName("DisableRedirectUrlTracking");
            writer.WriteValue(value);
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();
            writer.WriteEndObject();

            return writer.Token;
        }

        private JToken GetConnectionItem(string connectionString, string providerName)
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();
            writer.WritePropertyName("ConnectionStrings");
            writer.WriteStartObject();
            writer.WritePropertyName(Cms.Core.Constants.System.UmbracoConnectionName);
            writer.WriteValue(connectionString);
            writer.WriteEndObject();
            writer.WriteEndObject();

            return writer.Token;
        }

        private static void RemoveJsonKey(JObject json, string key)
        {
            JToken token = json;
            foreach (var propertyName in key.Split(new[] { ':' }))
            {
                token = CaseSelectPropertyValues(token, propertyName);
            }

            token?.Parent?.Remove();
        }

        private void SaveJson(JsonConfigurationProvider provider, JObject json)
        {
            lock (_locker)
            {
                if (provider.Source.FileProvider is PhysicalFileProvider physicalFileProvider)
                {
                    var jsonFilePath = Path.Combine(physicalFileProvider.Root, provider.Source.Path);

                    using (var sw = new StreamWriter(jsonFilePath, false))
                    using (var jsonTextWriter = new JsonTextWriter(sw)
                    {
                        Formatting = Formatting.Indented,
                    })
                    {
                        json?.WriteTo(jsonTextWriter);
                    }
                }
            }
        }

        private JObject GetJson(JsonConfigurationProvider provider)
        {
            lock (_locker)
            {
                if (provider.Source.FileProvider is PhysicalFileProvider physicalFileProvider)
                {
                    var jsonFilePath = Path.Combine(physicalFileProvider.Root, provider.Source.Path);

                    var serializer = new JsonSerializer();
                    using (var sr = new StreamReader(jsonFilePath))
                    using (var jsonTextReader = new JsonTextReader(sr))
                    {
                        return serializer.Deserialize<JObject>(jsonTextReader);
                    }
                }

                return null;
            }
        }

        private JsonConfigurationProvider GetJsonConfigurationProvider(string requiredKey = null)
        {
            if (_configuration is IConfigurationRoot configurationRoot)
            {
                foreach (var provider in configurationRoot.Providers)
                {
                    if (provider is JsonConfigurationProvider jsonConfigurationProvider)
                    {
                        if (requiredKey is null || provider.TryGet(requiredKey, out _))
                        {
                            return jsonConfigurationProvider;
                        }
                    }
                }
            }
            throw new InvalidOperationException("Could not find a writable json config source");
        }

        /// <summary>
        /// Returns the property value when case insensative
        /// </summary>
        /// <remarks>
        /// This method is required because keys are case insensative in IConfiguration.
        /// JObject[..] do not support case insensative and JObject.Property(...) do not return a new JObject.
        /// </remarks>
        private static JToken CaseSelectPropertyValues(JToken token, string name)
        {
            if (token is JObject obj)
            {

                foreach (var property in obj.Properties())
                {
                    if (name is null)
                        return property.Value;
                    if (string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase))
                        return property.Value;
                }
            }
            return null;
        }

    }
}


text:
#ifndef _SKINNEDRENDEROBJECT_H_
#define _SKINNEDRENDEROBJECT_H_
#include "app/graphicfeature/components/meshrenderobject.h"
#include "app/graphicfeature/components/skinnedrenderable.h"

namespace App
{
	class SkinnedMeshRenderComponent;

	class SkinnedRenderObject : public MeshRenderObject
	{
		__DeclareSubClass(SkinnedRenderObject, MeshRenderObject)
	public:
		typedef SkinnedRenderable RenderableType;
		typedef SkinnedMeshRenderComponent Owner;
		SkinnedRenderObject();
		~SkinnedRenderObject();
		virtual void AddToCollection(Graphic::RenderDataCollection* collection);
		virtual void Render(const Graphic::Renderable* renderable, Graphic::RenderPassType passType, const Graphic::Material* customizedMaterial);
	protected:
		void render(const RenderableType* renderable, Graphic::RenderPassType passType, const Graphic::Material* customizedMat, const Math::matrix44& _matrix);
	private:
		Owner* getOwner() const;
	};
	inline SkinnedRenderObject::Owner* SkinnedRenderObject::getOwner() const
	{
		return GetOwner<Owner>();
	}
}

#endif //_SKINNEDRENDEROBJECT_H_


text:
@implementation LQSubscriptionRecord

- (instancetype)initWithQuery:(PFQuery *)query requestId:(LQRequestId *)requestId handler:(id)handler {
    self = [super init];
    if (self) {
        self.query               = query;
        self.requestId           = requestId;
        self.subscriptionHandler = handler;

        __weak LQSubscriptionRecord *weakSelf = self;

        self.eventHandlerClosure = ^(LQEvent *event, LQClient *client) {
            if (!weakSelf || !weakSelf.subscriptionHandler) {
                return;
            }

            // [weakSelf.subscriptionHandler didReceiveEvent: event forQuery:query inClient:client];
        };

        self.errorHandlerClosure = ^(LQErrorType *error, LQClient *client) {
            if (!weakSelf || !weakSelf.subscriptionHandler) {
                return;
            }

            // [weakSelf.subscriptionHandler didEncounterError:error forQuery: query inClient:client];
        };

        self.subscribeHandlerClosure = ^(LQClient *client) {
            if (!weakSelf || !weakSelf.subscriptionHandler) {
                return;
            }

            //[weakSelf.subscriptionHandler didSubscribeToQuery:query inClient:client];
        };

        self.unsubscribeHandlerClosure = ^(LQClient *client) {
            if (!weakSelf || !weakSelf.subscriptionHandler) {
                return;
            }

            //[weakSelf.subscriptionHandler didUnsubscribeFromQuery:query inClient:client];
        };
    }

    return self;
}

@end


text:
require('stratum/stratum')

-- https://github.com/kikito/middleclass/blob/master/performance/time.lua

function time(title, f)

	collectgarbage()

	local startTime = os.clock()

	for i=0,10000 do f() end

	local endTime = os.clock()

	print( title, endTime - startTime )

end

-- Class creation

time('Class creation', function()
	class 'A' is { }
end)

-- Instance creation

class 'A'

time('Instance creation', function()
	local a = new 'A'
end)

-- Instance method invocation

class 'A' is {

	foo = function()
		return 1
	end
}

local a = new 'A'

time('Instance method invocation', function()
	a:foo()
end)

-- Inherited method invocation

class 'B' extends 'A' is  { }

local b = new 'B'

time('Inherited method invocation', function()
	b:foo()
end)

-- Static calls

local A = class 'A' is {

	bar = function()
		return 2
	end

}

time('class method invocation', function()
	A.bar()
end)

local B = class 'B' extends 'A' is { }

time('inherited class method invocation', function()
	B.bar()
end)