text:
<?php
class ControllerExtensionInstaller extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('extension/installer');

		$this->document->setTitle($this->language->get('heading_title'));

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_loading'] = $this->language->get('text_loading');

		$data['entry_upload'] = $this->language->get('entry_upload');
		$data['entry_overwrite'] = $this->language->get('entry_overwrite');
		$data['entry_progress'] = $this->language->get('entry_progress');

		$data['help_upload'] = $this->language->get('help_upload');

		$data['button_upload'] = $this->language->get('button_upload');
		$data['button_clear'] = $this->language->get('button_clear');
		$data['button_continue'] = $this->language->get('button_continue');

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/installer', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['token'] = $this->session->data['token'];

		$directories = glob(DIR_UPLOAD . 'temp-*', GLOB_ONLYDIR);

		if ($directories) {
			$data['error_warning'] = $this->language->get('error_temporary');
		} else {
			$data['error_warning'] = '';
		}

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('extension/installer.tpl', $data));
	}

	public function upload() {
		$this->load->language('extension/installer');

		$json = array();

		// Check user has permission
		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		if (!$json) {
			if (!empty($this->request->files['file']['name'])) {
				if (substr($this->request->files['file']['name'], -10) != '.ocmod.zip' && substr($this->request->files['file']['name'], -10) != '.ocmod.xml') {
					$json['error'] = $this->language->get('error_filetype');
				}

				if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
					$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
				}
			} else {
				$json['error'] = $this->language->get('error_upload');
			}
		}

		if (!$json) {
			// If no temp directory exists create it
			$path = 'temp-' . md5(mt_rand());

			if (!is_dir(DIR_UPLOAD . $path)) {
				mkdir(DIR_UPLOAD . $path, 0777);
			}

			// Set the steps required for installation
			$json['step'] = array();
			$json['overwrite'] = array();

			if (strrchr($this->request->files['file']['name'], '.') == '.xml') {
				$file = DIR_UPLOAD . $path . '/install.xml';

				// If xml file copy it to the temporary directory
				move_uploaded_file($this->request->files['file']['tmp_name'], $file);

				if (file_exists($file)) {
					$json['step'][] = array(
						'text' => $this->language->get('text_xml'),
						'url'  => str_replace('&', '&', $this->url->link('extension/installer/xml', 'token=' . $this->session->data['token'], 'SSL')),
						'path' => $path
					);

					// Clear temporary files
					$json['step'][] = array(
						'text' => $this->language->get('text_remove'),
						'url'  => str_replace('&', '&', $this->url->link('extension/installer/remove', 'token=' . $this->session->data['token'], 'SSL')),
						'path' => $path
					);
				} else {
					$json['error'] = $this->language->get('error_file');
				}
			}

			// If zip file copy it to the temp directory
			if (strrchr($this->request->files['file']['name'], '.') == '.zip') {
				$file = DIR_UPLOAD . $path . '/upload.zip';

				move_uploaded_file($this->request->files['file']['tmp_name'], $file);

				if (file_exists($file)) {
					$zip = zip_open($file);

					if ($zip) {
						// Zip
						$json['step'][] = array(
							'text' => $this->language->get('text_unzip'),
							'url'  => str_replace('&', '&', $this->url->link('extension/installer/unzip', 'token=' . $this->session->data['token'], 'SSL')),
							'path' => $path
						);

						// FTP
						$json['step'][] = array(
							'text' => $this->language->get('text_ftp'),
							'url'  => str_replace('&', '&', $this->url->link('extension/installer/ftp', 'token=' . $this->session->data['token'], 'SSL')),
							'path' => $path
						);

						// Send make and array of actions to carry out
						while ($entry = zip_read($zip)) {
							$zip_name = zip_entry_name($entry);

							// SQL
							if (substr($zip_name, 0, 11) == 'install.sql') {
								$json['step'][] = array(
									'text' => $this->language->get('text_sql'),
									'url'  => str_replace('&', '&', $this->url->link('extension/installer/sql', 'token=' . $this->session->data['token'], 'SSL')),
									'path' => $path
								);
							}

							// XML
							if (substr($zip_name, 0, 11) == 'install.xml') {
								$json['step'][] = array(
									'text' => $this->language->get('text_xml'),
									'url'  => str_replace('&', '&', $this->url->link('extension/installer/xml', 'token=' . $this->session->data['token'], 'SSL')),
									'path' => $path
								);
							}

							// PHP
							if (substr($zip_name, 0, 11) == 'install.php') {
								$json['step'][] = array(
									'text' => $this->language->get('text_php'),
									'url'  => str_replace('&', '&', $this->url->link('extension/installer/php', 'token=' . $this->session->data['token'], 'SSL')),
									'path' => $path
								);
							}

							// Compare admin files
							$file = DIR_APPLICATION . substr($zip_name, 13);

							if (is_file($file) && substr($zip_name, 0, 13) == 'upload/admin/') {
								$json['overwrite'][] = substr($zip_name, 7);
							}

							// Compare catalog files
							$file = DIR_CATALOG . substr($zip_name, 15);

							if (is_file($file) && substr($zip_name, 0, 15) == 'upload/catalog/') {
								$json['overwrite'][] = substr($zip_name, 7);
							}

							// Compare image files
							$file = DIR_IMAGE . substr($zip_name, 13);

							if (is_file($file) && substr($zip_name, 0, 13) == 'upload/image/') {
								$json['overwrite'][] = substr($zip_name, 7);
							}

							// Compare system files
							$file = DIR_SYSTEM . substr($zip_name, 14);

							if (is_file($file) && substr($zip_name, 0, 14) == 'upload/system/') {
								$json['overwrite'][] = substr($zip_name, 7);
							}
						}

						// Clear temporary files
						$json['step'][] = array(
							'text' => $this->language->get('text_remove'),
							'url'  => str_replace('&', '&', $this->url->link('extension/installer/remove', 'token=' . $this->session->data['token'], 'SSL')),
							'path' => $path
						);

						zip_close($zip);
					} else {
						$json['error'] = $this->language->get('error_unzip');
					}
				} else {
					$json['error'] = $this->language->get('error_file');
				}
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function unzip() {
		$this->load->language('extension/installer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		// Sanitize the filename
		$file = DIR_UPLOAD . str_replace(array('../', '..\\', '..'), '', $this->request->post['path']) . '/upload.zip';

		if (!file_exists($file)) {
			$json['error'] = $this->language->get('error_file');
		}

		if (!$json) {
			// Unzip the files
			$zip = new ZipArchive();

			if ($zip->open($file)) {
				$zip->extractTo(DIR_UPLOAD . str_replace(array('../', '..\\', '..'), '', $this->request->post['path']));
				$zip->close();
			} else {
				$json['error'] = $this->language->get('error_unzip');
			}

			// Remove Zip
			unlink($file);
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function ftp() {
		$this->load->language('extension/installer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		// Check FTP status
		if (!$this->config->get('config_ftp_status')) {
			$json['error'] = $this->language->get('error_ftp_status');
		}

		$directory = DIR_UPLOAD . str_replace(array('../', '..\\', '..'), '', $this->request->post['path']) . '/upload/';

		if (!is_dir($directory)) {
			$json['error'] = $this->language->get('error_directory');
		}

		if (!$json) {
			// Get a list of files ready to upload
			$files = array();

			$path = array($directory . '*');

			while (count($path) != 0) {
				$next = array_shift($path);

				foreach (glob($next) as $file) {
					if (is_dir($file)) {
						$path[] = $file . '/*';
					}

					$files[] = $file;
				}
			}

			// Connect to the site via FTP
			$connection = ftp_connect($this->config->get('config_ftp_hostname'), $this->config->get('config_ftp_port'));

			if ($connection) {
				$login = ftp_login($connection, $this->config->get('config_ftp_username'), $this->config->get('config_ftp_password'));

				if ($login) {
					if ($this->config->get('config_ftp_root')) {
						$root = ftp_chdir($connection, $this->config->get('config_ftp_root'));
					} else {
						$root = ftp_chdir($connection, '/');
					}

					if ($root) {
						foreach ($files as $file) {
							$destination = substr($file, strlen($directory));

							// Upload everything in the upload directory
							// Many people rename their admin folder for security purposes which I believe should be an option during installation just like setting the db prefix.
							// the following code would allow you to change the name of the following directories and any extensions installed will still go to the right directory.
							if (substr($destination, 0, 5) == 'admin') {
								$destination = basename(DIR_APPLICATION) . substr($destination, 5);
							}

							if (substr($destination, 0, 7) == 'catalog') {
								$destination = basename(DIR_CATALOG) . substr($destination, 7);
							}

							if (substr($destination, 0, 5) == 'image') {
								$destination = basename(DIR_IMAGE) . substr($destination, 5);
							}

							if (substr($destination, 0, 6) == 'system') {
								$destination = basename(DIR_SYSTEM) . substr($destination, 6);
							}

							if (is_dir($file)) {
								$list = ftp_nlist($connection, substr($destination, 0, strrpos($destination, '/')));

								if (!in_array($destination, $list)) {
									if (!ftp_mkdir($connection, $destination)) {
										$json['error'] = sprintf($this->language->get('error_ftp_directory'), $destination);
									}
								}
							}

							if (is_file($file)) {
								if (!ftp_put($connection, $destination, $file, FTP_BINARY)) {
									$json['error'] = sprintf($this->language->get('error_ftp_file'), $file);
								}
							}
						}
					} else {
						$json['error'] = sprintf($this->language->get('error_ftp_root'), $root);
					}
				} else {
					$json['error'] = sprintf($this->language->get('error_ftp_login'), $this->config->get('config_ftp_username'));
				}

				ftp_close($connection);
			} else {
				$json['error'] = sprintf($this->language->get('error_ftp_connection'), $this->config->get('config_ftp_hostname'), $this->config->get('config_ftp_port'));
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function sql() {
		$this->load->language('extension/installer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		$file = DIR_UPLOAD . str_replace(array('../', '..\\', '..'), '', $this->request->post['path']) . '/install.sql';

		if (!file_exists($file)) {
			$json['error'] = $this->language->get('error_file');
		}

		if (!$json) {
			$lines = file($file);

			if ($lines) {
				try {
					$sql = '';

					foreach ($lines as $line) {
						if ($line && (substr($line, 0, 2) != '--') && (substr($line, 0, 1) != '#')) {
							$sql .= $line;

							if (preg_match('/;\s*$/', $line)) {
								$sql = str_replace(" `oc_", " `" . DB_PREFIX, $sql);

								$this->db->query($sql);

								$sql = '';
							}
						}
					}
				} catch(Exception $exception) {
					$json['error'] = sprintf($this->language->get('error_exception'), $exception->getCode(), $exception->getMessage(), $exception->getFile(), $exception->getLine());
				}
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function xml() {
		$this->load->language('extension/installer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		$file = DIR_UPLOAD . str_replace(array('../', '..\\', '..'), '', $this->request->post['path']) . '/install.xml';

		if (!file_exists($file)) {
			$json['error'] = $this->language->get('error_file');
		}

		if (!$json) {
			$this->load->model('extension/modification');

			// If xml file just put it straight into the DB
			$xml = file_get_contents($file);

			if ($xml) {
				try {
					$dom = new DOMDocument('1.0', 'UTF-8');
					$dom->loadXml($xml);

					$name = $dom->getElementsByTagName('name')->item(0);

					if ($name) {
						$name = $name->nodeValue;
					} else {
						$name = '';
					}

					$code = $dom->getElementsByTagName('code')->item(0);

					if ($code) {
						$code = $code->nodeValue;

						// Check to see if the modification is already installed or not.
						$modification_info = $this->model_extension_modification->getModificationByCode($code);

						if ($modification_info) {
							$json['error'] = sprintf($this->language->get('error_exists'), $modification_info['name']);
						}
					} else {
						$json['error'] = $this->language->get('error_code');
					}

					$author = $dom->getElementsByTagName('author')->item(0);

					if ($author) {
						$author = $author->nodeValue;
					} else {
						$author = '';
					}

					$version = $dom->getElementsByTagName('version')->item(0);

					if ($version) {
						$version = $version->nodeValue;
					} else {
						$version = '';
					}

					$link = $dom->getElementsByTagName('link')->item(0);

					if ($link) {
						$link = $link->nodeValue;
					} else {
						$link = '';
					}

					$modification_data = array(
						'name'    => $name,
						'code'    => $code,
						'author'  => $author,
						'version' => $version,
						'link'    => $link,
						'xml'     => $xml,
						'status'  => 1
					);

					if (!$json) {
						$this->model_extension_modification->addModification($modification_data);
					}
				} catch(Exception $exception) {
					$json['error'] = sprintf($this->language->get('error_exception'), $exception->getCode(), $exception->getMessage(), $exception->getFile(), $exception->getLine());
				}
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function php() {
		$this->load->language('extension/installer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		$file = DIR_UPLOAD . str_replace(array('../', '..\\', '..'), '', $this->request->post['path']) . '/install.php';

		if (!file_exists($file)) {
			$json['error'] = $this->language->get('error_file');
		}

		if (!$json) {
			try {
				include($file);
			} catch(Exception $exception) {
				$json['error'] = sprintf($this->language->get('error_exception'), $exception->getCode(), $exception->getMessage(), $exception->getFile(), $exception->getLine());
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function remove() {
		$this->load->language('extension/installer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		$directory = DIR_UPLOAD . str_replace(array('../', '..\\', '..'), '', $this->request->post['path']);

		if (!is_dir($directory)) {
			$json['error'] = $this->language->get('error_directory');
		}

		if (!$json) {
			// Get a list of files ready to upload
			$files = array();

			$path = array($directory);

			while (count($path) != 0) {
				$next = array_shift($path);

				// We have to use scandir function because glob will not pick up dot files.
				foreach (array_diff(scandir($next), array('.', '..')) as $file) {
					$file = $next . '/' . $file;

					if (is_dir($file)) {
						$path[] = $file;
					}

					$files[] = $file;
				}
			}

			rsort($files);

			foreach ($files as $file) {
				if (is_file($file)) {
					unlink($file);
				} elseif (is_dir($file)) {
					rmdir($file);
				}
			}

			if (file_exists($directory)) {
				rmdir($directory);
			}

			$json['success'] = $this->language->get('text_success');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function clear() {
		$this->load->language('extension/installer');

		$json = array();

		if (!$this->user->hasPermission('modify', 'extension/installer')) {
			$json['error'] = $this->language->get('error_permission');
		}

		if (!$json) {
			$directories = glob(DIR_UPLOAD . 'temp-*', GLOB_ONLYDIR);

			foreach ($directories as $directory) {
				// Get a list of files ready to upload
				$files = array();

				$path = array($directory);

				while (count($path) != 0) {
					$next = array_shift($path);

					// We have to use scandir function because glob will not pick up dot files.
					foreach (array_diff(scandir($next), array('.', '..')) as $file) {
						$file = $next . '/' . $file;

						if (is_dir($file)) {
							$path[] = $file;
						}

						$files[] = $file;
					}
				}

				rsort($files);

				foreach ($files as $file) {
					if (is_file($file)) {
						unlink($file);
					} elseif (is_dir($file)) {
						rmdir($file);
					}
				}

				if (file_exists($directory)) {
					rmdir($directory);
				}
			}

			$json['success'] = $this->language->get('text_clear');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}


text:
package uk.nhs.ciao.cda.builder.eastkent;

import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Predicate;
import org.apache.camel.Producer;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import uk.nhs.ciao.camel.CamelApplicationRunner;
import uk.nhs.ciao.camel.CamelApplicationRunner.AsyncExecution;
import uk.nhs.ciao.cda.builder.CDABuilderApplication;
import uk.nhs.ciao.configuration.CIAOConfig;
import uk.nhs.ciao.configuration.impl.MemoryCipProperties;
import uk.nhs.ciao.docs.parser.ParsedDocument;
import uk.nhs.interoperability.payloads.helpers.DocumentRenderer;
import uk.nhs.interoperability.payloads.toc_edischarge_draftB.ClinicalDocument;
import uk.nhs.interoperability.payloads.util.FileWriter;
import uk.nhs.interoperability.payloads.util.xml.SchemaValidator;

import com.google.common.base.Strings;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;

public class EastKentCDABuilderExample {
	private static final Logger LOGGER = LoggerFactory.getLogger(EastKentCDABuilderExample.class);
	private static final String CIP_NAME = "ciao-cda-builder";

	@Rule
	public Timeout globalTimeout = Timeout.seconds(30);

	private ExecutorService executorService;
	private CDABuilderApplication application;
	private AsyncExecution execution;

	public static void main(String[] args) throws Exception {
		EastKentCDABuilderExample builder = new EastKentCDABuilderExample();
		builder.setup();
		//for (final String name: Arrays.asList("Example6.htm", "Example7.htm", "Example8.htm", "Example9.htm", "Example10.htm")) {
		String name = "Example10.htm";
			System.out.println("##################################");
			System.out.println("#");
			System.out.println("# " + name);
			System.out.println("#");
			System.out.println("##################################");

			System.out.println();
			builder.buildCDA("/parsed-actual/" + name);
			System.out.println();
		//}
	}

	public void setup() throws IOException {
		final CIAOConfig ciaoConfig = setupCiaoConfig();
		application = new CDABuilderApplication(ciaoConfig);
		executorService = Executors.newSingleThreadExecutor();
	}

	public void buildCDA(final String name) throws Exception {

		runApplication();

		// Route the output to a mock
		final CamelContext camelContext = getCamelContext();
		camelContext.addRoutes(new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("jms:queue:cda-documents")
				.unmarshal().json(JsonLibrary.Jackson, ParsedDocument.class)
				.to("mock:output");
			}
		});

		final Producer producer = camelContext.getEndpoint("jms:queue:enriched-documents")
				.createProducer();
		final MockEndpoint endpoint = MockEndpoint.resolve(camelContext, "mock:output");
		endpoint.expectedMessageCount(1);
		endpoint.expectedMessagesMatches(new Predicate() {
			@Override
			public boolean matches(final Exchange exchange) {
				// For now just check that we get a ParsedDocument containing some key fields
				final ParsedDocument parsedDocument = exchange.getIn().getBody(ParsedDocument.class);
				assertNotNull("parsedDocument", parsedDocument);
				final InputStream xml = parsedDocument.getOriginalDocument().getContentStream();
				try {
					final ClinicalDocument template = new ClinicalDocument(xml);
					String serialised = template.serialise();
					// Write the results
					FileWriter.writeFile("src/test/resources/cda-actual/"+name+".xml", serialised.getBytes());
					String html = DocumentRenderer.generateHTMLDocument(serialised);
					FileWriter.writeFile("src/test/resources/cda-actual/"+name, html.getBytes());

					boolean hasData = (template.hasData() &&
							template.getPatient().hasData() &&
							!Strings.isNullOrEmpty(template.getDocumentId()));
					if (!hasData) {
						return false;
					} else {
						// Do a schema check to make sure this is a valid CDA document
						String schemaPath = "./XSD/Schemas/POCD_MT000002UK01.xsd";
						try {
							SchemaValidator.validate(serialised, new File(schemaPath));
						} catch (Exception e) {
							// Validation failed
							LOGGER.error("Schema validation failed", e);
							return false;
						}

						// Now, transform the document and to a schema check on the "templated" form
						String templatedSchemaPath = "./XSD/Schemas/POCD_MT000026GB01.xsd";
						String transformPath = "./XSD/Transform/TrueCDAToCDALike_v2.xsl";
						try {
							SchemaValidator.testAgainstTemplatedSchema(serialised,
											new File(templatedSchemaPath), new File(transformPath));
						} catch (Exception e) {
							// Validation failed
							LOGGER.error("Templated schema validation failed", e);
							return false;
						}
					}
					return true;
				} finally {
					Closeables.closeQuietly(xml);
				}
			}
		});

		String inputJSON = loadResource(name);
		LOGGER.info("Input contents: " + inputJSON);
		sendMessage(producer, inputJSON);

		MockEndpoint.assertIsSatisfied(10, TimeUnit.SECONDS, endpoint);

		try {
			stopApplication();
		} finally {
			// Always stop the executor service
			executorService.shutdownNow();
		}
	}

	private void sendMessage(final Producer producer, final Object body) throws Exception {
		final Exchange exchange = producer.createExchange();
		final Message message = exchange.getIn();
		message.setHeader(Exchange.CORRELATION_ID, "test-correlation-id");
		message.setBody(body);
		producer.process(exchange);
	}

	private String loadResource(String name) throws Exception {
		InputStream in = new ClassPathResource(name, getClass()).getInputStream();
		try {
			return new String(ByteStreams.toByteArray(in));
		} finally {
			Closeables.closeQuietly(in);
		}
	}

	/*** The below stuff boot-straps Camel to do the work for us ***/

	private void runApplication() throws Exception {
		LOGGER.info("About to start camel application");
		execution = CamelApplicationRunner.runApplication(application, executorService);
		LOGGER.info("Camel application has started");
	}

	private CamelContext getCamelContext() {
		if (execution == null) {
			return null;
		}
		final List<CamelContext> camelContexts = execution.getRunner().getCamelContexts();
		return camelContexts.isEmpty() ? null : camelContexts.get(0);
	}

	private CIAOConfig setupCiaoConfig() throws IOException {
		final MemoryCipProperties cipProperties = new MemoryCipProperties(CIP_NAME, "tests");
		addProperties(cipProperties, CIP_NAME + ".properties");
		addProperties(cipProperties, CIP_NAME + "-test.properties");
		return new CIAOConfig(cipProperties);
	}

	private void addProperties(final MemoryCipProperties cipProperties, final String resourcePath) throws IOException {
		final Resource resource = new ClassPathResource(resourcePath);
		final Properties properties = PropertiesLoaderUtils.loadProperties(resource);
		cipProperties.addConfigValues(properties);
	}

	private void stopApplication() {
		if (execution == null) {
			return;
		}

		final CamelContext context = getCamelContext();
		try {
			LOGGER.info("About to stop camel application");
			execution.getRunner().stop();
			execution.getFuture().get(); // wait for task to complete
			LOGGER.info("Camel application has stopped");
		} catch (Exception e) {
			LOGGER.warn("Exception while trying to stop camel application", e);
		} finally {
			if (context != null) {
				MockEndpoint.resetMocks(context);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace aura {
class WindowEventDispatcher;
class WindowTreeHost;
namespace client {
class DragDropClient;
class FocusClient;
class ScreenPositionClient;
class WindowParentingClient;
}
}

namespace wm {
class CompoundEventFilter;
class CursorManager;
class FocusController;
class ShadowController;
class VisibilityController;
class WindowModalityController;
}

namespace views {
namespace corewm {
class TooltipController;
}
class DesktopCaptureClient;
class DesktopEventClient;
class DesktopNativeCursorManager;
class DesktopWindowTreeHost;
class DropHelper;
class FocusManagerEventHandler;
class TooltipManagerAura;
class WindowReorderer;

class VIEWS_EXPORT DesktopNativeWidgetAura
    : public internal::NativeWidgetPrivate,
      public aura::WindowDelegate,
      public aura::client::ActivationDelegate,
      public aura::client::ActivationChangeObserver,
      public aura::client::FocusChangeObserver,
      public aura::client::DragDropDelegate,
      public aura::WindowTreeHostObserver {
 public:
  explicit DesktopNativeWidgetAura(internal::NativeWidgetDelegate* delegate);
  ~DesktopNativeWidgetAura() override;

  // Maps from window to DesktopNativeWidgetAura. |window| must be a root
  // window.
  static DesktopNativeWidgetAura* ForWindow(aura::Window* window);

  // Called by our DesktopWindowTreeHost after it has deleted native resources;
  // this is the signal that we should start our shutdown.
  virtual void OnHostClosed();

  // TODO(beng): remove this method and replace with an implementation of
  //             WindowDestroying() that takes the window being destroyed.
  // Called from ~DesktopWindowTreeHost. This takes the WindowEventDispatcher
  // as by the time we get here |dispatcher_| is NULL.
  virtual void OnDesktopWindowTreeHostDestroyed(aura::WindowTreeHost* host);

  wm::CompoundEventFilter* root_window_event_filter() {
    return root_window_event_filter_.get();
  }
  aura::WindowTreeHost* host() {
    return host_.get();
  }

  // Ensures that the correct window is activated/deactivated based on whether
  // we are being activated/deactivated.
  void HandleActivationChanged(bool active);

 protected:
  // Overridden from internal::NativeWidgetPrivate:
  void InitNativeWidget(const Widget::InitParams& params) override;
  void OnWidgetInitDone() override;
  NonClientFrameView* CreateNonClientFrameView() override;
  bool ShouldUseNativeFrame() const override;
  bool ShouldWindowContentsBeTransparent() const override;
  void FrameTypeChanged() override;
  Widget* GetWidget() override;
  const Widget* GetWidget() const override;
  gfx::NativeView GetNativeView() const override;
  gfx::NativeWindow GetNativeWindow() const override;
  Widget* GetTopLevelWidget() override;
  const ui::Compositor* GetCompositor() const override;
  const ui::Layer* GetLayer() const override;
  void ReorderNativeViews() override;
  void ViewRemoved(View* view) override;
  void SetNativeWindowProperty(const char* name, void* value) override;
  void* GetNativeWindowProperty(const char* name) const override;
  TooltipManager* GetTooltipManager() const override;
  void SetCapture() override;
  void ReleaseCapture() override;
  bool HasCapture() const override;
  ui::InputMethod* GetInputMethod() override;
  void CenterWindow(const gfx::Size& size) override;
  void GetWindowPlacement(gfx::Rect* bounds,
                          ui::WindowShowState* maximized) const override;
  bool SetWindowTitle(const base::string16& title) override;
  void SetWindowIcons(const gfx::ImageSkia& window_icon,
                      const gfx::ImageSkia& app_icon) override;
  void InitModalType(ui::ModalType modal_type) override;
  gfx::Rect GetWindowBoundsInScreen() const override;
  gfx::Rect GetClientAreaBoundsInScreen() const override;
  gfx::Rect GetRestoredBounds() const override;
  std::string GetWorkspace() const override;
  void SetBounds(const gfx::Rect& bounds) override;
  void SetSize(const gfx::Size& size) override;
  void StackAbove(gfx::NativeView native_view) override;
  void StackAtTop() override;
  void SetShape(std::unique_ptr<SkRegion> shape) override;
  void Close() override;
  void CloseNow() override;
  void Show() override;
  void Hide() override;
  void ShowMaximizedWithBounds(const gfx::Rect& restored_bounds) override;
  void ShowWithWindowState(ui::WindowShowState state) override;
  bool IsVisible() const override;
  void Activate() override;
  void Deactivate() override;
  bool IsActive() const override;
  void SetAlwaysOnTop(bool always_on_top) override;
  bool IsAlwaysOnTop() const override;
  void SetVisibleOnAllWorkspaces(bool always_visible) override;
  bool IsVisibleOnAllWorkspaces() const override;
  void Maximize() override;
  void Minimize() override;
  bool IsMaximized() const override;
  bool IsMinimized() const override;
  void Restore() override;
  void SetFullscreen(bool fullscreen) override;
  bool IsFullscreen() const override;
  void SetOpacity(float opacity) override;
  void FlashFrame(bool flash_frame) override;
  void RunShellDrag(View* view,
                    const ui::OSExchangeData& data,
                    const gfx::Point& location,
                    int operation,
                    ui::DragDropTypes::DragEventSource source) override;
  void SchedulePaintInRect(const gfx::Rect& rect) override;
  void SetCursor(gfx::NativeCursor cursor) override;
  bool IsMouseEventsEnabled() const override;
  void ClearNativeFocus() override;
  gfx::Rect GetWorkAreaBoundsInScreen() const override;
  Widget::MoveLoopResult RunMoveLoop(
      const gfx::Vector2d& drag_offset,
      Widget::MoveLoopSource source,
      Widget::MoveLoopEscapeBehavior escape_behavior) override;
  void EndMoveLoop() override;
  void SetVisibilityChangedAnimationsEnabled(bool value) override;
  void SetVisibilityAnimationDuration(const base::TimeDelta& duration) override;
  void SetVisibilityAnimationTransition(
      Widget::VisibilityTransition transition) override;
  ui::NativeTheme* GetNativeTheme() const override;
  void OnRootViewLayout() override;
  bool IsTranslucentWindowOpacitySupported() const override;
  void OnSizeConstraintsChanged() override;
  void RepostNativeEvent(gfx::NativeEvent native_event) override;
  std::string GetName() const override;

  // Overridden from aura::WindowDelegate:
  gfx::Size GetMinimumSize() const override;
  gfx::Size GetMaximumSize() const override;
  void OnBoundsChanged(const gfx::Rect& old_bounds,
                       const gfx::Rect& new_bounds) override {}
  gfx::NativeCursor GetCursor(const gfx::Point& point) override;
  int GetNonClientComponent(const gfx::Point& point) const override;
  bool ShouldDescendIntoChildForEventHandling(
      aura::Window* child,
      const gfx::Point& location) override;
  bool CanFocus() override;
  void OnCaptureLost() override;
  void OnPaint(const ui::PaintContext& context) override;
  void OnDeviceScaleFactorChanged(float device_scale_factor) override;
  void OnWindowDestroying(aura::Window* window) override;
  void OnWindowDestroyed(aura::Window* window) override;
  void OnWindowTargetVisibilityChanged(bool visible) override;
  bool HasHitTestMask() const override;
  void GetHitTestMask(gfx::Path* mask) const override;

  // Overridden from ui::EventHandler:
  void OnKeyEvent(ui::KeyEvent* event) override;
  void OnMouseEvent(ui::MouseEvent* event) override;
  void OnScrollEvent(ui::ScrollEvent* event) override;
  void OnGestureEvent(ui::GestureEvent* event) override;

  // Overridden from aura::client::ActivationDelegate:
  bool ShouldActivate() const override;

  // Overridden from aura::client::ActivationChangeObserver:
  void OnWindowActivated(
      aura::client::ActivationChangeObserver::ActivationReason reason,
      aura::Window* gained_active,
      aura::Window* lost_active) override;

  // Overridden from aura::client::FocusChangeObserver:
  void OnWindowFocused(aura::Window* gained_focus,
                       aura::Window* lost_focus) override;

  // Overridden from aura::client::DragDropDelegate:
  void OnDragEntered(const ui::DropTargetEvent& event) override;
  int OnDragUpdated(const ui::DropTargetEvent& event) override;
  void OnDragExited() override;
  int OnPerformDrop(const ui::DropTargetEvent& event) override;

  // Overridden from aura::WindowTreeHostObserver:
  void OnHostCloseRequested(const aura::WindowTreeHost* host) override;
  void OnHostResized(const aura::WindowTreeHost* host) override;
  void OnHostWorkspaceChanged(const aura::WindowTreeHost* host) override;
  void OnHostMoved(const aura::WindowTreeHost* host,
                   const gfx::Point& new_origin) override;

 private:
  friend class RootWindowDestructionObserver;

  // To save a clear on platforms where the window is never transparent, the
  // window is only set as transparent when the glass frame is in use.
  void UpdateWindowTransparency();

  void RootWindowDestroyed();

  std::unique_ptr<aura::WindowTreeHost> host_;
  DesktopWindowTreeHost* desktop_window_tree_host_;

  // See class documentation for Widget in widget.h for a note about ownership.
  Widget::InitParams::Ownership ownership_;

  // Internal name.
  std::string name_;

  std::unique_ptr<DesktopCaptureClient> capture_client_;

  // Child of the root, contains |content_window_|.
  aura::Window* content_window_container_;

  // Child of |content_window_container_|. This is the return value from
  // GetNativeView().
  // WARNING: this may be NULL, in particular during shutdown it becomes NULL.
  aura::Window* content_window_;

  internal::NativeWidgetDelegate* native_widget_delegate_;

  std::unique_ptr<wm::FocusController> focus_client_;
  std::unique_ptr<aura::client::ScreenPositionClient> position_client_;
  std::unique_ptr<aura::client::DragDropClient> drag_drop_client_;
  std::unique_ptr<aura::client::WindowParentingClient> window_parenting_client_;
  std::unique_ptr<DesktopEventClient> event_client_;
  std::unique_ptr<FocusManagerEventHandler> focus_manager_event_handler_;

  // Toplevel event filter which dispatches to other event filters.
  std::unique_ptr<wm::CompoundEventFilter> root_window_event_filter_;

  std::unique_ptr<DropHelper> drop_helper_;
  int last_drop_operation_;

  std::unique_ptr<corewm::TooltipController> tooltip_controller_;
  std::unique_ptr<TooltipManagerAura> tooltip_manager_;

  std::unique_ptr<wm::VisibilityController> visibility_controller_;

  std::unique_ptr<wm::WindowModalityController> window_modality_controller_;

  bool restore_focus_on_activate_;

  gfx::NativeCursor cursor_;
  // We must manually reference count the number of users of |cursor_manager_|
  // because the cursors created by |cursor_manager_| are shared among the
  // DNWAs. We can't just stuff this in a LazyInstance because we need to
  // destroy this as the last DNWA happens; we can't put it off until
  // (potentially) after we tear down the X11 connection because that's a
  // crash.
  static int cursor_reference_count_;
  static wm::CursorManager* cursor_manager_;
  static views::DesktopNativeCursorManager* native_cursor_manager_;

  std::unique_ptr<wm::ShadowController> shadow_controller_;

  // Reorders child windows of |window_| associated with a view based on the
  // order of the associated views in the widget's view hierarchy.
  std::unique_ptr<WindowReorderer> window_reorderer_;

  // See class documentation for Widget in widget.h for a note about type.
  Widget::InitParams::Type widget_type_;

  // The following factory is used for calls to close the NativeWidgetAura
  // instance.
  base::WeakPtrFactory<DesktopNativeWidgetAura> close_widget_factory_;

  DISALLOW_COPY_AND_ASSIGN(DesktopNativeWidgetAura);
};

}  // namespace views

#endif  // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_WIDGET_AURA_H_


text:
/*
 * Author Luke Campbell <LCampbell@asascience.com>
 * com.asascience.netcdf4.NcDim
 */

using System;
using System.Text;

namespace ASA.NetCDF4 {
    public class NcDim {
        public NcDim() {
            nullObject = true;
        }

        ~NcDim() {
        }

        public NcDim(NcGroup grp, Int32 dimId) {
            nullObject = false;
            groupId = grp.GetId();
            myId = dimId;
        }

        public NcDim(NcDim rhs) {
            nullObject = rhs.nullObject;
            myId = rhs.myId;
            groupId = rhs.groupId;
        }

        public string GetName() {
            CheckNull();
            StringBuilder dimName = new StringBuilder((int)NetCDF.netCDF_limits.NC_MAX_NAME);
            NcCheck.Check(NetCDF.nc_inq_dimname(groupId, myId, dimName));
            return dimName.ToString();
        }

        public Int32 GetId() {
            CheckNull();
            return myId;
        }

        public NcGroup GetParentGroup() {
            CheckNull();
            return new NcGroup(groupId);
        }

        public bool IsUnlimited() {
            CheckNull();
            Int32 numlimdims=0;
            Int32[] unlimdimidsp = null;
            NcCheck.Check(NetCDF.nc_inq_unlimdims(groupId, ref numlimdims, unlimdimidsp));
            unlimdimidsp = new Int32[numlimdims];
            NcCheck.Check(NetCDF.nc_inq_unlimdims(groupId, ref numlimdims, unlimdimidsp));
            for(int i=0;i<numlimdims;i++) {
                if(unlimdimidsp[i] == myId)
                    return true;
            }
            return false;
        }

        public Int32 GetSize() {
            CheckNull();
            Int32 dimSize=0;
            NcCheck.Check(NetCDF.nc_inq_dimlen(groupId, myId, ref dimSize));
            return dimSize;
        }

        public void Rename(string newName) {
            CheckNull();
            NcCheck.Check(NetCDF.nc_rename_dim(groupId, myId, newName));
        }

        public bool IsNull() {
            return nullObject;
        }
        protected void CheckNull() {
            if(IsNull()) {
                throw new exceptions.NcNullType("Attempt to invoke NcGroup.GetId on a Null group");
            }
        }

        private bool nullObject;
        private Int32 myId;
        private Int32 groupId;

    }
}


text:
package com.navercorp.pinpoint.profiler.monitor.collector.jvmgc;

import com.navercorp.pinpoint.profiler.monitor.metric.gc.DetailedGarbageCollectorMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.gc.DetailedGarbageCollectorMetricSnapshot;
import com.navercorp.pinpoint.profiler.monitor.metric.memory.DetailedMemoryMetric;
import com.navercorp.pinpoint.profiler.monitor.metric.memory.DetailedMemoryMetricSnapshot;
import com.navercorp.pinpoint.thrift.dto.TJvmGc;
import com.navercorp.pinpoint.thrift.dto.TJvmGcDetailed;

/**
 * @author dawidmalina
 * @author HyunGil Jeong
 */
public class DetailedJvmGcMetricCollector implements JvmGcMetricCollector {

    private final JvmGcMetricCollector jvmGcMetricCollector;
    private final DetailedMemoryMetric detailedMemoryMetric;
    private final DetailedGarbageCollectorMetric detailedGarbageCollectorMetric;

    public DetailedJvmGcMetricCollector(
            JvmGcMetricCollector jvmGcMetricCollector,
            DetailedMemoryMetric detailedMemoryMetric,
            DetailedGarbageCollectorMetric detailedGarbageCollectorMetric) {
        if (jvmGcMetricCollector == null) {
            throw new NullPointerException("jvmGcMetricCollector must not be null");
        }
        if (detailedMemoryMetric == null) {
            throw new NullPointerException("detailedMemoryMetric must not be null");
        }
        if (detailedGarbageCollectorMetric == null) {
            throw new NullPointerException("detailedGarbageCollectorMetric must not be null");
        }
        this.jvmGcMetricCollector = jvmGcMetricCollector;
        this.detailedMemoryMetric = detailedMemoryMetric;
        this.detailedGarbageCollectorMetric = detailedGarbageCollectorMetric;
    }

    @Override
    public TJvmGc collect() {
        TJvmGc jvmGc = jvmGcMetricCollector.collect();
        DetailedMemoryMetricSnapshot detailedMemoryMetricSnapshot = detailedMemoryMetric.getSnapshot();
        DetailedGarbageCollectorMetricSnapshot detailedGarbageCollectorMetricSnapshot = detailedGarbageCollectorMetric.getSnapshot();
        TJvmGcDetailed jvmGcDetailed = new TJvmGcDetailed();
        jvmGcDetailed.setJvmPoolNewGenUsed(detailedMemoryMetricSnapshot.getNewGenUsage());
        jvmGcDetailed.setJvmPoolOldGenUsed(detailedMemoryMetricSnapshot.getOldGenUsage());
        jvmGcDetailed.setJvmPoolSurvivorSpaceUsed(detailedMemoryMetricSnapshot.getSurvivorSpaceUsage());
        jvmGcDetailed.setJvmPoolCodeCacheUsed(detailedMemoryMetricSnapshot.getCodeCacheUsage());
        jvmGcDetailed.setJvmPoolPermGenUsed(detailedMemoryMetricSnapshot.getPermGenUsage());
        jvmGcDetailed.setJvmPoolMetaspaceUsed(detailedMemoryMetricSnapshot.getMetaspaceUsage());
        jvmGcDetailed.setJvmGcNewCount(detailedGarbageCollectorMetricSnapshot.getGcNewCount());
        jvmGcDetailed.setJvmGcNewTime(detailedGarbageCollectorMetricSnapshot.getGcNewTime());
        jvmGc.setJvmGcDetailed(jvmGcDetailed);
        return jvmGc;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("DetailedJvmGcMetricCollector{");
        sb.append("jvmGcMetricCollector=").append(jvmGcMetricCollector);
        sb.append(", detailedMemoryMetric=").append(detailedMemoryMetric);
        sb.append(", detailedGarbageCollectorMetric=").append(detailedGarbageCollectorMetric);
        sb.append('}');
        return sb.toString();
    }
}


text:
package com.microsoft.azure.management.compute.v2020_06_01.implementation;

import com.microsoft.azure.management.compute.v2020_06_01.VirtualMachineScaleSetVMInstanceView;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.compute.v2020_06_01.BootDiagnosticsInstanceView;
import java.util.List;
import com.microsoft.azure.management.compute.v2020_06_01.DiskInstanceView;
import com.microsoft.azure.management.compute.v2020_06_01.VirtualMachineExtensionInstanceView;
import com.microsoft.azure.management.compute.v2020_06_01.MaintenanceRedeployStatus;
import com.microsoft.azure.management.compute.v2020_06_01.InstanceViewStatus;
import com.microsoft.azure.management.compute.v2020_06_01.VirtualMachineAgentInstanceView;
import com.microsoft.azure.management.compute.v2020_06_01.VirtualMachineHealthStatus;

class VirtualMachineScaleSetVMInstanceViewImpl extends WrapperImpl<VirtualMachineScaleSetVMInstanceViewInner> implements VirtualMachineScaleSetVMInstanceView {
    private final ComputeManager manager;
    VirtualMachineScaleSetVMInstanceViewImpl(VirtualMachineScaleSetVMInstanceViewInner inner, ComputeManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public ComputeManager manager() {
        return this.manager;
    }

    @Override
    public String assignedHost() {
        return this.inner().assignedHost();
    }

    @Override
    public BootDiagnosticsInstanceView bootDiagnostics() {
        return this.inner().bootDiagnostics();
    }

    @Override
    public List<DiskInstanceView> disks() {
        return this.inner().disks();
    }

    @Override
    public List<VirtualMachineExtensionInstanceView> extensions() {
        return this.inner().extensions();
    }

    @Override
    public MaintenanceRedeployStatus maintenanceRedeployStatus() {
        return this.inner().maintenanceRedeployStatus();
    }

    @Override
    public String placementGroupId() {
        return this.inner().placementGroupId();
    }

    @Override
    public Integer platformFaultDomain() {
        return this.inner().platformFaultDomain();
    }

    @Override
    public Integer platformUpdateDomain() {
        return this.inner().platformUpdateDomain();
    }

    @Override
    public String rdpThumbPrint() {
        return this.inner().rdpThumbPrint();
    }

    @Override
    public List<InstanceViewStatus> statuses() {
        return this.inner().statuses();
    }

    @Override
    public VirtualMachineAgentInstanceView vmAgent() {
        return this.inner().vmAgent();
    }

    @Override
    public VirtualMachineHealthStatus vmHealth() {
        return this.inner().vmHealth();
    }

}


text:
<?php
namespace Janitor\Entities;

use Illuminate\Http\Request;
use Illuminate\Routing\Route as RouteInstance;
use Janitor\Abstracts\AbstractAnalyzedEntity;
use Janitor\UsageNeedle;

class Route extends AbstractAnalyzedEntity
{
    /**
     * @type RouteInstance
     */
    protected $route;

    //////////////////////////////////////////////////////////////////////
    /////////////////////////////// ROUTE ////////////////////////////////
    //////////////////////////////////////////////////////////////////////

    /**
     * @return RouteInstance
     */
    public function getRoute()
    {
        return $this->route;
    }

    /**
     * @param RouteInstance $route
     */
    public function setRoute(RouteInstance $route)
    {
        // Compile route
        $request = new Request();
        $route->matches($request);

        $this->route = $route;
    }

    //////////////////////////////////////////////////////////////////////
    //////////////////////////// USAGE MATRIX ////////////////////////////
    //////////////////////////////////////////////////////////////////////

    /**
     * Compute the usage matrix of the analyzed entity.
     *
     * @return UsageNeedle[]
     */
    public function computeUsageMatrix()
    {
        return [
            new UsageNeedle(1, $this->route->getActionName()),
            new UsageNeedle(0.5, $this->route->getName()),
            new UsageNeedle(0.25, $this->route->getCompiled()->getRegex(), true),
        ];
    }
}


text:
extern const NSString *FWErrorDomain = @"FWErrorDomain";
extern const NSString *FWNotImplementedException = @"NotImplementedException";


text:
The item is the basic building block for all of your operations on
Walmart. An item includes the product you are trying to sell as well as
the offer prices for this product across different Walmart properties.

Items have a fairly complex model and it is recommended that you read
through the overview and item object documentation linked to below.
You'll also likely want to reference the XSD schema for an Item to
ensure you use all appropriate properties of an item.

Official API Documentation: https://developer.walmartapis.com/#overview

## List Items
```php
<?php
use Walmart\Item;

$client = new Item([
    'consumerId' => getenv('CONSUMER_ID'),
    'privateKey' => getenv('PRIVATE_KEY'),
]);

$items = $client->list([
    'sku' => '123', // optional
    'limit' => 20, // optional, default is 20
    'offset' => 0, //optional, default is 0
]);
```

## Get a single Item
```php
<?php
use Walmart\Item;

$client = new Item([
    'consumerId' => getenv('CONSUMER_ID'),
    'privateKey' => getenv('PRIVATE_KEY'),
]);

$item = $client->get([
    'sku' => '123', // required
]);
```

## Retire an Item
```php
<?php
use Walmart\Item;

$client = new Item([
    'consumerId' => getenv('CONSUMER_ID'),
    'privateKey' => getenv('PRIVATE_KEY'),
]);

$item = $client->retire([
    'sku' => '123', // required
]);
```

## Bulk create/update Items
This API creates an Item Feed

```php
<?php
use Walmart\Item;

$client = new Item([
    'consumerId' => getenv('CONSUMER_ID'),
    'privateKey' => getenv('PRIVATE_KEY'),
]);

$feed = $client->bulk([
   'MPItemFeed' => [
       'MPItemFeedHeader' => [
           'version' => '2.1',
           'requestId' => $time,
           'requestBatchId' => $time,
       ],
       'MPItem' => [
           [
               'sku' => 'NO11140_7022363',
               'Product' => [
                   'productName' => 'Nourison Oasis Hand-Tufted Rectangle Rug',
                   'longDescription' => 'From its supremely plush pile to its satiny yarns and sublime patina, this sensational hand-tufted rug is truly an embarrassment of riches. This hibiscus floral print is certain to take center stage.',
                   'shelfDescription' => 'From its supremely plush pile to its satiny yarns and sublime patina, this sensational hand-tufted rug is truly an embarrassment of riches. This hibiscus floral print is certain to take center stage.',
                   'shortDescription' => 'From its supremely plush pile to its satiny yarns and sublime patina, this sensational hand-tufted rug is truly an embarrassment of riches.',
                   'mainImage' => ['mainImageUrl' => 'http://us-i5.tb.wal.co/dfw/dce07b8c-4239/k2-_b1ed5989-151a-4810-944b-35eee2c7b5b0.v1.jpg'],
                   'productIdentifiers' => [
                       [
                           'productIdType' => 'UPC',
                           'productId' => '06108-OAS02-CHA',
                       ],
                   ],
                   'productTaxCode' => '203030',
                   'Home' => ['brand' => 'Nourison'],
               ],
               'price' => [
                   'currency' => 'USD',
                   'amount' => 198.00,
               ],
               'shippingWeight' => [
                   'value' => 10,
                   'unit' => 'LB'
               ],
           ],
           [
               'sku' => 'NO11140_123123',
               'Product' => [
                   'productName' => 'Fancy Rug',
                   'longDescription' => 'From its supremely plush pile to its satiny yarns and sublime patina, this sensational hand-tufted rug is truly an embarrassment of riches. This hibiscus floral print is certain to take center stage.',
                   'shelfDescription' => 'From its supremely plush pile to its satiny yarns and sublime patina, this sensational hand-tufted rug is truly an embarrassment of riches. This hibiscus floral print is certain to take center stage.',
                   'shortDescription' => 'From its supremely plush pile to its satiny yarns and sublime patina, this sensational hand-tufted rug is truly an embarrassment of riches.',
                   'mainImage' => ['mainImageUrl' => 'http://us-i5.tb.wal.co/dfw/dce07b8c-4239/k2-_b1ed5989-151a-4810-944b-35eee2c7b5b0.v1.jpg'],
                   'productIdentifiers' => [
                       [
                           'productIdType' => 'UPC',
                           'productId' => '06108-OAS02-CHA',
                       ],
                   ],
                   'productTaxCode' => '203030',
                   'Home' => ['brand' => 'Nourison'],
               ],
               'price' => [
                   'currency' => 'USD',
                   'amount' => 198.00,
               ],
               'shippingWeight' => [
                   'value' => 10,
                   'unit' => 'LB'
               ],
           ],

       ],
   ],
]);
```


text:
package org.broadleafcommerce.core.order.service.call;

import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.domain.OrderItem;

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

public class ReconstructCartResponse {

    private Order order;

    private List<OrderItem> removedItems = new ArrayList<OrderItem>();

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public List<OrderItem> getRemovedItems() {
        return removedItems;
    }

    public void setRemovedItems(List<OrderItem> removedItems) {
        this.removedItems = removedItems;
    }
}


text:
package panda.interpreter.parser.expression;

import panda.interpreter.architecture.expression.Expression;
import panda.interpreter.parser.Contextual;
import panda.interpreter.parser.Parser;
import panda.interpreter.token.SourceStream;
import panda.interpreter.token.Streamable;
import panda.interpreter.token.SynchronizedSource;
import panda.std.Option;

/**
 * Expression parser
 */
public interface ExpressionParser extends Parser {

    /**
     * Parse expression
     *
     * @param context the current context
     * @param streamable the source with expression
     * @param settings the settings to use
     * @return the parsed expression wrapped into the transaction
     * @see panda.interpreter.architecture.expression.Expression
     */
    Expression parse(Contextual<?> context, Streamable streamable, ExpressionParserSettings settings);

    /**
     * Try to parse expression
     *
     * @param context the current context
     * @param streamable the source that may contain expression
     * @param settings the settings to use
     * @return the parsed expression wrapped into the transaction or nothing
     */
    Option<Expression> parseSilently(Contextual<?> context, Streamable streamable, ExpressionParserSettings settings);

    /**
     * Utility method to call
     * {@link #parseSilently(panda.interpreter.parser.Contextual, panda.interpreter.token.Streamable, ExpressionParserSettings)}
     * with the default settings ({@link ExpressionParserSettings#DEFAULT})
     *
     * @see #parseSilently(panda.interpreter.parser.Contextual, panda.interpreter.token.Streamable, ExpressionParserSettings)
     */
    default Option<Expression> parseSilently(Contextual<?> context, Streamable streamable) {
        return parseSilently(context, streamable, ExpressionParserSettings.DEFAULT);
    }

    /**
     * Utility method to parse expression from the synchronized source
     *
     * @param context the current context
     * @param source the synchronized source that contain
     * @return the parsed expression wrapped into the transaction
     */
    default Expression parse(Contextual<?> context, SynchronizedSource source) {
        return parse(context, source, ExpressionParserSettings.DEFAULT);
    }

    /**
     * Utility method to parse expression from the synchronized source using custom settings
     *
     * @param context the current context
     * @param source the synchronized source that contain
     * @param settings the settings to use
     * @return the parsed expression wrapped into the transaction
     */
    default Expression parse(Contextual<?> context, SynchronizedSource source, ExpressionParserSettings settings) {
        SourceStream stream = source.toStream();

        Expression expression = parse(context, stream, settings);
        source.setIndex(source.getIndex() + stream.getReadLength());

        return expression;
    }

    /**
     * Utility method to call
     * {@link #parse(panda.interpreter.parser.Contextual, panda.interpreter.token.Streamable, ExpressionParserSettings)}
     * with the default settings ({@link ExpressionParserSettings#DEFAULT})
     *
     * @see #parse(panda.interpreter.parser.Contextual, panda.interpreter.token.Streamable, ExpressionParserSettings)
     */
    default Expression parse(Contextual<?> context, Streamable streamable) {
        return parse(context, streamable, ExpressionParserSettings.DEFAULT);
    }

}


text:
(function($){

if (typeof PimpMyMatrix == 'undefined')
{
  PimpMyMatrix = {};
}

PimpMyMatrix.GroupsDesigner = Craft.FieldLayoutDesigner.extend(
{

  $form: null,
  $spinner: null,

  modal: null,

  initField: function($blockType)
  {
    var $editBtn = $blockType.find('.settings'),
        $menu = $('
').insertAfter($editBtn),
        $ul = $('
').appendTo($menu);

    $('
'+Craft.t('Edit field layout')+'
').appendTo($ul);

    $('
'+Craft.t('Remove')+'
').appendTo($ul);

    new Garnish.MenuBtn($editBtn, {
      onOptionSelect: $.proxy(this, 'onFieldOptionSelect')
    });
  },

  onFieldOptionSelect: function(option)
  {
    var $option = $(option),
        $blockType = $option.data('menu').$anchor.parent(),
        action = $option.data('action');

    switch (action)
    {
      case 'edit-field-layout':
      {
        this.onEditFieldLayout($blockType);
        break;
      }
      case 'remove':
      {
        this.removeField($blockType);
        break;
      }
    }
  },

  // cloned for language adjustments
  renameTab: function($tab)
  {
    if (!this.settings.customizableTabs)
    {
      return;
    }

    var $labelSpan = $tab.find('.tabs .tab span'),
      oldName = $labelSpan.text(),
      newName = prompt(Craft.t('Give your group a name.'), oldName);

    if (newName && newName != oldName)
    {
      $labelSpan.text(newName);
      $tab.find('.id-input').attr('name', this.getFieldInputName(newName));
    }
  },

  // cloned for language adjustments
  addTab: function()
  {
    if (!this.settings.customizableTabs)
    {
      return;
    }

    var $tab = $('
' +
            '
' +
              '
' +
                'Group '+(this.tabGrid.$items.length+1)+'' +
                '' +
              '
' +
            '
' +
            '

' +
          '
').appendTo(this.$tabContainer);

    this.tabGrid.addItems($tab);
    this.tabDrag.addItems($tab);

    this.initTab($tab);
  },

  /**
   * When trying to edit a field layout make sure the
   * block groups have saved first
   */
  onEditFieldLayout: function($blockType)
  {
    var $modalForm = $blockType.parents('.modal');
    $modalForm.one('blockTypesSaved', $.proxy(function()
    {
      this.editFieldLayout($blockType);
    }, this));

    $modalForm.trigger('submit');
  },

  /**
   * This pops open another modal with another fld in it to enable
   * the editing of fields and tabs to happen inside the block type
   */
  editFieldLayout: function($blockType)
  {

    // Build the markup
    this.$form = $('<form class="modal elementselectormodal pimpmymatrix-fields-configurator"/>');

    var $body = $('
').appendTo(this.$form),
        $body = $('
').appendTo($body),
        $bigSpinner = $('
').appendTo($body),
        $body = $('
').appendTo($body),
        $footer = $('
').appendTo(this.$form),
        $buttons = $('
').appendTo($footer);

    this.$spinner = $('
').appendTo($buttons);

    var $cancelBtn = $('
'+Craft.t('Cancel')+'
').appendTo($buttons),
        $submitBtn = $('<input type="submit" class="btn submit" value="'+Craft.t('Save')+'"/>').appendTo($buttons);

    this.modal = new Garnish.Modal(this.$form,
    {
      resizable: true,
      closeOtherModals: false,
      onFadeIn: $.proxy(function()
      {

        var data = {
          context : this.settings.context,
          blockTypeId : $blockType.data('id')
        };

        Craft.postActionRequest('pimpMyMatrix/getFieldsConfigurator', data, $.proxy(function(response, textStatus)
        {
          if (textStatus == 'success')
          {
            $(response.html).appendTo($body);
            $bigSpinner.addClass('hidden');
            var fld = new PimpMyMatrix.BlockTypeFieldLayoutDesigner('#pimpmymatrix-fields-configurator', {
              fieldInputName: 'blockTypeFieldLayouts[__TAB_NAME__][]'
            });
          }
        }, this));

      }, this),
      onHide: $.proxy(function()
      {
        this.modal.$container.remove();
        this.modal.$shade.remove();
        delete this;
      }, this)
    });

    this.addListener(this.$form, 'submit', '_handleSubmit');
    this.addListener($cancelBtn, 'click', $.proxy(function()
    {
      this.modal.hide();
    }, this));
  },

  _handleSubmit: function(ev)
  {
    ev.preventDefault();

    // Show spinner
    this.$spinner.removeClass('hidden');

    // Get the form data
    var data = this.$form.serialize();

    // Post it
    Craft.postActionRequest('pimpMyMatrix/blockTypes/saveFieldLayout', data, $.proxy(function(response, textStatus)
    {
      this.$spinner.addClass('hidden');
      if (textStatus == 'success' && response.success)
      {
        Craft.cp.displayNotice(Craft.t('Field layout saved.'));
        this.modal.hide();
      }
      else
      {
        if (textStatus == 'success')
        {
          Craft.cp.displayError(Craft.t('An unknown error occurred.'));
        }
      }
    }, this));
  }

});

})(jQuery);


text:
//-CRE-
using Glass.Mapper.Sc.Configuration.Attributes;

namespace Glass.Mapper.Sc.Razor.Model
{
    /// <summary>
    /// Class GlassTypedRazor
    /// </summary>
    [SitecoreType(TemplateId = "{7B10C01D-B0DF-4626-BE34-F48E38828FB7}")]
    public class GlassTypedRazor
    {
        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>The name.</value>
        [SitecoreInfo(Configuration.SitecoreInfoType.Name)]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the view.
        /// </summary>
        /// <value>The view.</value>
        [SitecoreField("Name")]
        public string View { get; set; }

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        /// <value>The code.</value>
        [SitecoreField]
        public string Code { get; set; }

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>The type.</value>
        [SitecoreField]
        public string Type { get; set; }

        /// <summary>
        /// Gets or sets the assembly.
        /// </summary>
        /// <value>The assembly.</value>
        [SitecoreField]
        public string Assembly { get; set; }
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>svnmailer.notifier.news</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css"></link>

news

Classes

NNTPSubmitter

Functions

getNotifier

[show private | hide private]


text:
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { Rooms, Messages } from '../../../models';
import { hasPermission } from '../../../authorization';

Meteor.methods({
	'livechat:getFirstRoomMessage'({ rid }) {
		if (!Meteor.userId() || !hasPermission(Meteor.userId(), 'view-l-room')) {
			throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'livechat:getFirstRoomMessage' });
		}

		check(rid, String);

		const room = Rooms.findOneById(rid);

		if (!room || room.t !== 'l') {
			throw new Meteor.Error('error-invalid-room', 'Invalid room');
		}

		return Messages.findOne({ rid }, { sort: { ts: 1 } });
	},
});


text:
static
NType _primitive_type;

static
NErrorType* ILLEGAL_ARGUMENT = NULL;

static
NErrorType* BAD_ALLOCATION = NULL;

void
ni_init_primitives(NError* error) {
#define EC ON_ERROR(error, return)
	n_construct_type(&_primitive_type, "nuvm.PrimitiveProcedure");
	n_register_type(&_primitive_type, error);                        EC;

	ILLEGAL_ARGUMENT = n_error_type("nuvm.IllegalArgument", error);  EC;
	BAD_ALLOCATION = n_error_type("nuvm.BadAllocation", error);      EC;
#undef EC
}

NValue
n_create_primitive(NPrimitiveFunc function, NError *error) {
    NPrimitive *primitive;
    if (function == NULL) {
        n_set_error(error, ILLEGAL_ARGUMENT, "Can't creat a NULL primitive.");
    }

    primitive = malloc(sizeof(NPrimitive));
    if (primitive == NULL) {
        n_set_error(error, BAD_ALLOCATION, "Unable to allocate primitive.");
    }

    primitive->object_header.type = &_primitive_type;
    primitive->func = function;
    return n_wrap_object((NObject*) primitive);
}

int
n_is_primitive(NValue value) {
    if (!n_is_immediate(value)) {
        return ((NObject*) n_unwrap_object(value))->type == &_primitive_type;
    }
    return 0;
}

NValue
n_call_primitive(NValue primitive, int n_args, NValue *args, NError *error) {
    NPrimitiveFunc func = ((NPrimitive*) n_unwrap_object(primitive))->func;

    return func(n_args, args, error);
}


text:
#pragma once
#include <aws/sagemaker-a2i-runtime/AugmentedAIRuntime_EXPORTS.h>
#include <aws/sagemaker-a2i-runtime/AugmentedAIRuntimeRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/sagemaker-a2i-runtime/model/HumanLoopInput.h>
#include <aws/sagemaker-a2i-runtime/model/HumanLoopDataAttributes.h>
#include <utility>

namespace Aws
{
namespace AugmentedAIRuntime
{
namespace Model
{

  /**
   */
  class AWS_AUGMENTEDAIRUNTIME_API StartHumanLoopRequest : public AugmentedAIRuntimeRequest
  {
  public:
    StartHumanLoopRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "StartHumanLoop"; }

    Aws::String SerializePayload() const override;

    /**
     *
The name of the human loop.

     */
    inline const Aws::String& GetHumanLoopName() const{ return m_humanLoopName; }

    /**
     *
The name of the human loop.

     */
    inline bool HumanLoopNameHasBeenSet() const { return m_humanLoopNameHasBeenSet; }

    /**
     *
The name of the human loop.

     */
    inline void SetHumanLoopName(const Aws::String& value) { m_humanLoopNameHasBeenSet = true; m_humanLoopName = value; }

    /**
     *
The name of the human loop.

     */
    inline void SetHumanLoopName(Aws::String&& value) { m_humanLoopNameHasBeenSet = true; m_humanLoopName = std::move(value); }

    /**
     *
The name of the human loop.

     */
    inline void SetHumanLoopName(const char* value) { m_humanLoopNameHasBeenSet = true; m_humanLoopName.assign(value); }

    /**
     *
The name of the human loop.

     */
    inline StartHumanLoopRequest& WithHumanLoopName(const Aws::String& value) { SetHumanLoopName(value); return *this;}

    /**
     *
The name of the human loop.

     */
    inline StartHumanLoopRequest& WithHumanLoopName(Aws::String&& value) { SetHumanLoopName(std::move(value)); return *this;}

    /**
     *
The name of the human loop.

     */
    inline StartHumanLoopRequest& WithHumanLoopName(const char* value) { SetHumanLoopName(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline const Aws::String& GetFlowDefinitionArn() const{ return m_flowDefinitionArn; }

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline bool FlowDefinitionArnHasBeenSet() const { return m_flowDefinitionArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline void SetFlowDefinitionArn(const Aws::String& value) { m_flowDefinitionArnHasBeenSet = true; m_flowDefinitionArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline void SetFlowDefinitionArn(Aws::String&& value) { m_flowDefinitionArnHasBeenSet = true; m_flowDefinitionArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline void SetFlowDefinitionArn(const char* value) { m_flowDefinitionArnHasBeenSet = true; m_flowDefinitionArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline StartHumanLoopRequest& WithFlowDefinitionArn(const Aws::String& value) { SetFlowDefinitionArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline StartHumanLoopRequest& WithFlowDefinitionArn(Aws::String&& value) { SetFlowDefinitionArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the flow definition associated with this
     * human loop.

     */
    inline StartHumanLoopRequest& WithFlowDefinitionArn(const char* value) { SetFlowDefinitionArn(value); return *this;}

    /**
     *
An object that contains information about the human loop.

     */
    inline const HumanLoopInput& GetHumanLoopInput() const{ return m_humanLoopInput; }

    /**
     *
An object that contains information about the human loop.

     */
    inline bool HumanLoopInputHasBeenSet() const { return m_humanLoopInputHasBeenSet; }

    /**
     *
An object that contains information about the human loop.

     */
    inline void SetHumanLoopInput(const HumanLoopInput& value) { m_humanLoopInputHasBeenSet = true; m_humanLoopInput = value; }

    /**
     *
An object that contains information about the human loop.

     */
    inline void SetHumanLoopInput(HumanLoopInput&& value) { m_humanLoopInputHasBeenSet = true; m_humanLoopInput = std::move(value); }

    /**
     *
An object that contains information about the human loop.

     */
    inline StartHumanLoopRequest& WithHumanLoopInput(const HumanLoopInput& value) { SetHumanLoopInput(value); return *this;}

    /**
     *
An object that contains information about the human loop.

     */
    inline StartHumanLoopRequest& WithHumanLoopInput(HumanLoopInput&& value) { SetHumanLoopInput(std::move(value)); return *this;}

    /**
     *
Attributes of the specified data. Use DataAttributes to specify
     * if your data is free of personally identifiable information and/or free of adult
     * content.

     */
    inline const HumanLoopDataAttributes& GetDataAttributes() const{ return m_dataAttributes; }

    /**
     *
Attributes of the specified data. Use DataAttributes to specify
     * if your data is free of personally identifiable information and/or free of adult
     * content.

     */
    inline bool DataAttributesHasBeenSet() const { return m_dataAttributesHasBeenSet; }

    /**
     *
Attributes of the specified data. Use DataAttributes to specify
     * if your data is free of personally identifiable information and/or free of adult
     * content.

     */
    inline void SetDataAttributes(const HumanLoopDataAttributes& value) { m_dataAttributesHasBeenSet = true; m_dataAttributes = value; }

    /**
     *
Attributes of the specified data. Use DataAttributes to specify
     * if your data is free of personally identifiable information and/or free of adult
     * content.

     */
    inline void SetDataAttributes(HumanLoopDataAttributes&& value) { m_dataAttributesHasBeenSet = true; m_dataAttributes = std::move(value); }

    /**
     *
Attributes of the specified data. Use DataAttributes to specify
     * if your data is free of personally identifiable information and/or free of adult
     * content.

     */
    inline StartHumanLoopRequest& WithDataAttributes(const HumanLoopDataAttributes& value) { SetDataAttributes(value); return *this;}

    /**
     *
Attributes of the specified data. Use DataAttributes to specify
     * if your data is free of personally identifiable information and/or free of adult
     * content.

     */
    inline StartHumanLoopRequest& WithDataAttributes(HumanLoopDataAttributes&& value) { SetDataAttributes(std::move(value)); return *this;}

  private:

    Aws::String m_humanLoopName;
    bool m_humanLoopNameHasBeenSet = false;

    Aws::String m_flowDefinitionArn;
    bool m_flowDefinitionArnHasBeenSet = false;

    HumanLoopInput m_humanLoopInput;
    bool m_humanLoopInputHasBeenSet = false;

    HumanLoopDataAttributes m_dataAttributes;
    bool m_dataAttributesHasBeenSet = false;
  };

} // namespace Model
} // namespace AugmentedAIRuntime
} // namespace Aws


text:
package com.formulasearchengine.mathmltools.converters.mathoid;

/**
 * @author Andre Greiner-Petter
 */
public enum MathoidEndpoints {
    SVG_ENDPOINT("svg", "image/svg+xml"),
    PNG_ENDPOINT("png", "image/png"),
    MML_ENDPOINT("mml", "application/mathml+xml"),
    INFO_ENDPOINT("texvcinfo", "application/json");

    private final String endpoint;
    private final String responseMediaType;

    MathoidEndpoints(String endpoint, String responseMediaType) {
        this.endpoint = endpoint;
        this.responseMediaType = responseMediaType;
    }

    public String getEndpoint(String host) {
        return host + "/" + endpoint;
    }

    public String getResponseMediaType() {
        return responseMediaType;
    }
}


text:
struct default_init_tag;

class poi::hssf::record::RecordInputStream_LeftoverDataException final
    : public ::java::lang::RuntimeException
{

public:
    typedef ::java::lang::RuntimeException super;
protected:
    void ctor(int32_t sid, int32_t remainingByteCount);

private:
    static ::java::lang::String* getRecordName(int32_t sid);

    // Generated

public:
    RecordInputStream_LeftoverDataException(int32_t sid, int32_t remainingByteCount);
protected:
    RecordInputStream_LeftoverDataException(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();

private:
    virtual ::java::lang::Class* getClass0();
    friend class RecordInputStream;
    friend class RecordInputStream_SimpleHeaderInput;
};


text:
+++
categories = ["", ""]
date = "2015-06-26T23:25:20+01:00"
description = "get_iplayer not working? Try these simple steps and make sure you follow this troubleshooting guide before you post in the forums."
draft = false
pageimage = ""
pagesubtitle = "COMPREHENSIVE GUIDES TO GET YOU STARTED QUICKLY"
pagetitle = "get_iplayer Guides and Tutorials"
slug = "get_iplayer-troubleshooting-guide"
title = "get_iplayer not working? • Troubleshooting Guide"
Type = "guides"
breadcrumb = "get_iplayer troubleshooting guide"
+++
# get_iplayer troubleshooting guide

Having problems or need help with get_iplayer? If get_iplayer is not working and you can't download programmes it might just be an error with your setup or it may be a wider issue with get_iplayer, or even with BBC iPlayer itself. Either way, it's a frustrating thing to try and remedy alone.

## get_iplayer Known Issues

The latest errors will be posted in the [Forums](/forums/) and in the [Known Issues](https://github.com/get-iplayer/get_iplayer/wiki/issues) pages. Make sure you check there for the latest errors to see if there is a simple fix for your problem.

## Check the latest Release Notes

The BBC is undertaking a series of alterations to how they deliver their digital content and this can often affect get_iplayer. It's essential that you read the latest release notes in order to understand how get_iplayer is dealing with these changes. The Release Notes for the latest version of get_iplayer are linked below:

[get_iplayer Release Notes](https://github.com/get-iplayer/get_iplayer/wiki/releasenotes/)

## Basic Troubleshooting Steps

If you find you can't download a programme with get_iplayer, first make sure you are issuing the correct commands. The [TV Download Guide](/guides/tv-download-guide/) or [Radio Download Guide](/guides/radio-download-guide/) have most of the detail you need to get up and running, complete with example commands, so make sure you check it to be sure you are using the correct commands.

Alternatively, you can view the complete get_iPlayer usage guide in the [Wiki section](https://github.com/get-iplayer/get_iplayer/wiki/) to check you are using the more advanced codes correctly.

If you have done that and are still having trouble, try each of these steps which have worked for other users:

1.  It's a cliche, but it works - restart your computer and try again. Amazingly, this still works most of the time.
2.  Make sure you have the latest version of get_iplayer for your platform. You can find an installation guide in the [downloads section](/downloads/) which will give you links to all the latest versions of the programme.
3.  Check you have a UK IP address. BBC iPlayer requires a UK IP address in order to connect, otherwise the BBC's servers will reject your connection. This means you need to be connecting from within the UK.
4.  Ensure your firewall is allowing get_iplayer to connect. If you are unsure how to do this, turn off your firewall temporarily and see if you can connect. If you can connect, you know your firewall is the problem. Armed with this knowledge, you can look up the instructions for allowing get_iplayer to connect through the firewall at all times.
5.  Restart your modem/router. This has worked for a couple of people so give it a shot and see if it resolves your connection issues.


text: echo "127.0.0.1 app.integration.simplytestable.com" | sudo tee --append /etc/hosts


text:
import org.junit.Test;

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

import static org.junit.Assert.assertArrayEquals;

/**
 * Given an array of words and a length L, format the text such that each line has exactly L
 * characters and is fully (left and right) justified.
 *

 * You should pack your words in a greedy approach; that is, pack as many words as you can in each
 * line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.
 *

 * Extra spaces between words should be distributed as evenly as possible. If the number of spaces
 * on a line do not divide evenly between words, the empty slots on the left will be assigned more
 * spaces than the slots on the right.
 *

 * For the last line of text, it should be left justified and no extra space is inserted between
 * words.
 *

 * For example, words: ["This", "is", "an", "example", "of", "text", "justification."] L: 16.
 */
public class L068 {
    @Test
    public void fullJustify() throws Exception {
        Solution solution = new Solution();

        String[] words = {"This", "is", "an", "example", "of", "text", "justification."};
        int length = 16;
        String[] ret = {"This    is    an", "example  of text", "justification.  "};
        assertArrayEquals(ret, solution.fullJustify(words, 16).toArray());
        String[] ret1 = {""};
        assertArrayEquals(ret1, solution.fullJustify(ret1, 0).toArray());

        String[] words2 = {"a", "b", "c", "d", "e"};
        assertArrayEquals(words2, solution.fullJustify(words2, 1).toArray());

        String[] words3 = {"Don't", "go", "around", "saying", "the", "world", "owes", "you", "a", "living;", "the", "world", "owes", "you", "nothing;", "it", "was", "here", "first."};
        String[] ret3 = {"Don't  go  around  saying  the", "world  owes  you a living; the", "world owes you nothing; it was", "here first.                   "};
        assertArrayEquals(ret3, solution.fullJustify(words3, 30).toArray());
    }

    @Test
    public void fullJustify2() throws Exception {
        Solution solution = new Solution();

        String[] words = {"This", "is", "an", "example", "of", "text", "justification."};
        int length = 16;
        String[] ret = {"This    is    an", "example  of text", "justification.  "};
        assertArrayEquals(ret, solution.fullJustify2(words, 16).toArray());
        String[] ret1 = {""};
        assertArrayEquals(ret1, solution.fullJustify2(ret1, 0).toArray());

        String[] words2 = {"a", "b", "c", "d", "e"};
        assertArrayEquals(words2, solution.fullJustify2(words2, 1).toArray());

        String[] words3 = {"Don't", "go", "around", "saying", "the", "world", "owes", "you", "a", "living;", "the", "world", "owes", "you", "nothing;", "it", "was", "here", "first."};
        String[] ret3 = {"Don't  go  around  saying  the", "world  owes  you a living; the", "world owes you nothing; it was", "here first.                   "};
        assertArrayEquals(ret3, solution.fullJustify2(words3, 30).toArray());
    }

    class Solution {
        /**
         * Intuitive solution. Spaghetti Code. Slow but not sure why.
         *
         * @param words    Array words to be justify.
         * @param maxWidth Maximum width of one line.
         * @return List of line (String) after justification.
         */
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> ret = new ArrayList<>();
            if (words.length == 1 && words[0].equals("")) {
                if (maxWidth != 0)
                    ret.add(String.format("%" + maxWidth + "s", " "));
                else
                    ret.add("");
                return ret;
            }

            List<String> line = new ArrayList<>();

            int wordsLengthWithoutBlank = 0;

            for (String word : words) {
            /* length of current words + new word length + number of blank <= maxWidth => add word */
                if (wordsLengthWithoutBlank + word.length() + line.size() <= maxWidth) {
                    wordsLengthWithoutBlank += word.length();
                    line.add(word);
                    continue;
                }
                if (line.size() == 1) {
                    ret.add(String.format("%-" + maxWidth + "s", line.get(0)));
                } else {
            /* Otherwise, add current words list to the new line, and start over. */
                    StringBuilder stringBuilder = new StringBuilder(maxWidth);
                    int blankCount = (maxWidth - wordsLengthWithoutBlank) / (line.size() - 1);
                    int restBlankCount = (maxWidth - wordsLengthWithoutBlank) % (line.size() - 1);
                    if (restBlankCount == 0) {
                        ret.add(String.join(String.format("%" + blankCount + "s", " "), line));
                    } else {
                        stringBuilder.append(String.join(String.format("%" + (blankCount + 1) + "s", ' '), line.subList(0, restBlankCount + 1)))
                                .append(String.format("%" + blankCount + "s", ' '))
                                .append(String.join(String.format("%" + blankCount + "s", ' '), line.subList(restBlankCount + 1, line.size())));
                        ret.add(stringBuilder.toString());
                    }
                }
                line = new ArrayList<>();
                line.add(word);
                wordsLengthWithoutBlank = word.length();
            }
            ret.add(String.format("%-" + maxWidth + "s", String.join(" ", line)));
            return ret;
        }

        /**
         * A modified version, though having little difference. Change [String.format("%" +
         * blankCount + "s", " ")] to for loop.
         */
        public List<String> fullJustify2(String[] words, int maxWidth) {
            List<String> ret = new ArrayList<>();
            if (words.length == 1 && words[0].equals("")) {
                if (maxWidth != 0)
                    ret.add(String.format("%" + maxWidth + "s", " "));
                else
                    ret.add("");
                return ret;
            }

            List<String> line = new ArrayList<>();

            int wordsLengthWithoutBlank = 0;

            for (String word : words) {
            /* length of current words + new word length + number of blank <= maxWidth => add word */
                if (wordsLengthWithoutBlank + word.length() + line.size() <= maxWidth) {
                    wordsLengthWithoutBlank += word.length();
                    line.add(word);
                    continue;
                }
                if (line.size() == 1) {
                    ret.add(String.format("%-" + maxWidth + "s", line.get(0)));
                } else {
            /* Otherwise, add current words list to the new line, and start over. */
                    StringBuilder stringBuilder = new StringBuilder(maxWidth);
                    int blankCount = (maxWidth - wordsLengthWithoutBlank) / (line.size() - 1);
                    int restBlankCount = (maxWidth - wordsLengthWithoutBlank) % (line.size() - 1);
                    if (restBlankCount == 0) {
                        ret.add(String.join(String.format("%" + blankCount + "s", " "), line));
                    } else {
                        int i;
                        for (i = 0; i < restBlankCount; i++) {
                            stringBuilder.append(line.get(i));
                            addBlank(stringBuilder, blankCount + 1);
                        }
                        for (; i < line.size(); i++) {
                            stringBuilder.append(line.get(i));
                            addBlank(stringBuilder, blankCount);
                        }
                        ret.add(stringBuilder.toString());
                    }
                }
                line = new ArrayList<>();
                line.add(word);
                wordsLengthWithoutBlank = word.length();
            }
            ret.add(String.format("%-" + maxWidth + "s", String.join(" ", line)));
            return ret;
        }

        private void addBlank(StringBuilder stringBuilder, int numberOfBlank) {
            for (int i = 0; i < numberOfBlank; i++)
                stringBuilder.append(" ");
        }
    }
}


text:
package com.cmlteam.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;

public class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = prepareObjectMapper();

    private static ObjectMapper prepareObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        objectMapper.setDateFormat(df);
        // exclude null and empty values from output XML/JSON
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        // allow reading of JSON values without quotes
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        // support both Jackson and JAXB annotations
        objectMapper.setAnnotationIntrospector(new AnnotationIntrospectorPair(new JacksonAnnotationIntrospector(), new JaxbAnnotationIntrospector()));
        return objectMapper;
    }

    public static String toJsonString(Object object) {
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<?> parseList(String json) {
        try {
            return OBJECT_MAPPER.readValue(json, List.class);
        } catch (IOException e) {
            throw new RuntimeException("Unable to parse json to list: " + Util.trim(json, 100), e);
        }
    }

    public static Map parseJson(String json) {
        try {
            return OBJECT_MAPPER.readValue(json, Map.class);
        } catch (IOException e) {
            throw new RuntimeException("Unable to parse json to map: " + Util.trim(json, 100), e);
        }
    }

    public static <T> T parseJson(String json, Class<T> clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            throw new RuntimeException("Unable to parse json to class: " + Util.trim(json, 100), e);
        }
    }

    /**
     * @param jsonString JSON string representation (quoted)
     * @return Java string
     */
    public static String parseJsonString(String jsonString) {
        try {
            return OBJECT_MAPPER.readValue(jsonString, String.class);
        } catch (IOException e) {
            throw new RuntimeException("Unable to parseJsonString: " + Util.trim(jsonString, 100), e);
        }
    }

    public static String unescapeJson(String jsonStringContents) {
        Objects.requireNonNull(jsonStringContents);

        return parseJsonString('"' + jsonStringContents + '"');
    }

    public static String escapeJson(String string) {
        Objects.requireNonNull(string);

        String jsonString = toJsonString(string);
        return jsonString.substring(1, jsonString.length() - 1);// unquote
    }

    public static String prettyPrintJson(String json) {
        if (json == null)
            return null;
        try {
            Object parsed = OBJECT_MAPPER.readValue(json, Object.class);
            return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(parsed);
        } catch (IOException ignore) {
            return json;
        }
    }
}


text:
from django.forms import ModelForm
from cyder.cydns.ptr.models import PTR

class PTRForm( ModelForm ):
    class Meta:
        model   = PTR
        exclude = ('ip','data_domain','reverse_domain', 'ip_upper', 'ip_lower')


text:
/* eslint-disable import/no-unresolved, import/extensions */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { View, Image, StyleSheet } from 'react-native';
/* eslint-enable import/no-unresolved, import/extensions */
import HeaderAccount from './HeaderAccount.react';
import { ViewPropTypes } from '../utils';
import withTheme from '../styles/withTheme';

const propTypes = {
  image: PropTypes.shape({ type: PropTypes.oneOf([Image]) }),
  backgroundColor: PropTypes.string,
  children: PropTypes.node,
  style: PropTypes.shape({
    contentContainer: ViewPropTypes.style,
    container: ViewPropTypes.style,
  }),
};
const defaultProps = {
  image: null,
  backgroundColor: null,
  children: null,
  style: {},
};

function getStyles(props) {
  const { image, theme } = props;
  const { drawerHeader } = theme;

  const local = {};

  if (image) {
    local.contentContainer = {
      backgroundColor: null,
    };
  }

  return {
    container: [drawerHeader.container, props.style.container],
    contentContainer: [
      drawerHeader.contentContainer,
      props.style.contentContainer,
      local.contentContainer,
    ],
  };
}

class Header extends PureComponent {
  render() {
    const { image, children } = this.props;

    const styles = getStyles(this.props);
    const flatten = StyleSheet.flatten(styles.contentContainer);

    const content = <View style={styles.contentContainer}>{children}</View>;

    if (image) {
      return (
        <View>
          {React.cloneElement(image, {
            style: [{ height: flatten.height }],
          })}
          <View style={[styles.container]}>{content}</View>
        </View>
      );
    }

    return content;
  }
}

Header.propTypes = propTypes;
Header.defaultProps = defaultProps;

Header.Account = HeaderAccount;

export default withTheme(Header);