text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sam.reading.spring.integration</groupId>
  <artifactId>FullRestService</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>
		<java-version>1.8</java-version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<org.springframework-version>4.1.7.RELEASE</org.springframework-version>
		<org.springframework.test-version>4.2.2.RELEASE</org.springframework.test-version>

		<spring.data.version>1.9.0.RELEASE</spring.data.version>
		<org.aspectj-version>1.7.4</org.aspectj-version>
		<org.slf4j-version>1.7.5</org.slf4j-version>
		<jackson.databind-version>2.5.3</jackson.databind-version>

		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<hibernate.core.verion>4.3.2.Final</hibernate.core.verion>
		<hibernate.entitymanager.verion>4.3.10.Final</hibernate.entitymanager.verion>
		<hibernate.annotation.verion>4.0.5.Final</hibernate.annotation.verion>
		<querydsl.version>3.6.9</querydsl.version>
	</properties>

	<dependencies>
		<!-- Jackson -->
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.1-api</artifactId>
			<version>1.0.0.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.core.verion}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.entitymanager.verion}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>${hibernate.core.verion}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate.common</groupId>
			<artifactId>hibernate-commons-annotations</artifactId>
			<version>${hibernate.annotation.verion}</version>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0</version>
		</dependency>

		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>${spring.data.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-envers</artifactId>
			<version>4.3.2.Final</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.databind-version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.databind-version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${jackson.databind-version}</version>
		</dependency>

		<dependency>
			<groupId>com.mysema.querydsl</groupId>
			<artifactId>querydsl-core</artifactId>
			<version>${querydsl.version}</version>
		</dependency>
		<dependency>
			<groupId>com.mysema.querydsl</groupId>
			<artifactId>querydsl-apt</artifactId>
			<version>${querydsl.version}</version>
		</dependency>
		<dependency>
			<groupId>com.mysema.querydsl</groupId>
			<artifactId>querydsl-jpa</artifactId>
			<version>${querydsl.version}</version>
		</dependency>

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons</artifactId>
			<version>1.11.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-collections4</artifactId>
			<version>4.0</version>
		</dependency>
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
			<scope>provided</scope>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
			<version>2.6.10</version>
		</dependency>

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>

		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<warName>pay</warName>
					<archive>
						<manifestEntries>

							<Title>${project.description}</Title>
							<Revision>${manifest.svnrevision}</Revision>
							<Label>${manifest.label}</Label>
							<Date>${maven.build.timestamp}</Date>
							<Branch>${manifest.branch}</Branch>
							<Build>${manifest.build.number}</Build>

							<Implementation-Title>${project.name}</Implementation-Title>
							<Implementation-Version>${manifest.svnrevision}</Implementation-Version>
							<addClasspath>true</addClasspath>
						</manifestEntries>
					</archive>

				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>

		</plugins>
	</build>

</project>


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* FbDocument.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

using AM;
using AM.Logging;
using AM.Text;
using AM.Xml;
using CodeJam;

using JetBrains.Annotations;

using ManagedIrbis.Infrastructure;
using ManagedIrbis.Pft.Infrastructure.Ast;

#endregion

namespace ManagedIrbis.FictionBook
{
    //
    // https://ru.wikipedia.org/wiki/FictionBook
    //
    // FictionBook (также FeedBook) - формат представления электронных
    // версий книг в виде XML-документов, где каждый элемент книги
    // описывается своими тегами. Стандарт призван обеспечить
    // совместимость с любыми устройствами и форматами. XML позволяет
    // легко создавать документы, готовые к непосредственному использованию
    // и программной обработке (преобразованию, хранению, управлению)
    // в любой среде. Документы, обычно имеющие расширение .fb2,
    // могут содержать структурную разметку основных элементов текста,
    // некоторое количество информации о книге, а также вложения
    // с двоичными файлами, в которых могут храниться иллюстрации,
    // например обложка.
    //
    // Стандарт был разработан группой разработчиков во главе
    // с Дмитрием Грибовым и Михаилом Мацневым.
    //
    // Каждая электронная книга в формате FictionBook представлена
    // в виде одного файла формата XML. Иллюстрации (PNG и JPEG)
    // встраиваются прямо в XML, будучи представленными в кодировке
    // Base64. FictionBook часто сжимают в ZIP (получается файл .fb2.zip
    // или .fbz), многие программы чтения поддерживают и FB2 со сжатием.
    //
    // FictionBook похож идеологией на первые версии HTML: все теги
    // относятся к логическому форматированию, а не к визуальному.
    // Нет привязки ни к какому аппаратному обеспечению и ни к какому
    // формату бумаги, нигде в FB2 не указана какая бы то ни была
    // единица измерения — пиксель, пункт или кегль. Как будет выглядеть
    // текст, полученный из формата .fb2, зависит либо от настроек
    // программы-просмотрщика этого формата, либо от параметров,
    // заданных при конвертации файла в другой формат. К примеру,
    // тег заголовка в программе просмотра можно вывести крупным шрифтом,
    // другим цветом или как-то иначе. А при конвертации в формат HTML
    // каждому заголовку может быть сопоставлен определённый HTML-тег,
    // например, <H4> или <B>. Поэтому FB2 претендует на роль
    // универсального формата хранения книг, который можно автоматически
    // переводить в HTML, PDF и другие форматы.
    //
    // Многие из возможностей FB2 специфичны для электронных книг.
    // В метаданных хранится название книги, ISBN, информация об авторе
    // и жанре книги. Поддерживаются сноски, оглавление, стихи, цитаты.
    // Для переводных книг предусмотрена информация об исходной книге.
    //
    // Проработанные метаданные дают широкое поле для автоматической
    // обработки книг. К примеру, в электронную библиотеку поступила
    // книга в формате .fb2. Эта книга может быть автоматически помещена
    // в раздел автора книги, а название книги и аннотация могут
    // автоматически отобразиться в колонке новостей библиотеки.
    // Таким образом, намного упрощается процесс помещения в библиотеку
    // новых книг. У документа и авторов есть идентификаторы свободной
    // формы: писателей «Kipling, Rudyard» и «Киплинг, Редьярд» может
    // объединить по совпадению идентификаторов; старая версия книги
    // будет автоматически замещена исправленной. Впрочем, метаданные
    // оказались несколько «СССР-центричными»: были отдельные жанры
    // «русская литература» и «советская литература».
    //
    // Защита от копирования не предусмотрена. Однако, начиная
    // с версии 2.1, добавлены специальные инструкции для библиотеки,
    // позволяющие выдавать тексты за деньги.
    //
    // Формат недостаточно выразителен для учебников, справочников
    // и научных публикаций (о чём говорит даже название — «художественная
    // книга»). В формате нет сложной вёрстки текста, нет поддержки
    // нумерованных и маркированных списков, разрядки текста, средств
    // формирования «замечаний на полях», авторского форматирования стихов
    // и векторной графики. Чтобы отобразить минимальную информацию
    // о книге - название, автора и обложку - программе требуется прочитать
    // и разобрать почти весь XML.
    //
    // Ссылки через XPath, заявленные в стандарте, на поверку реализует
    // мало кто, ограничиваясь обычно формой #id.
    //
    // История
    //
    // В середине 1990-х годов энтузиасты начали оцифровывать советские книги
    // (за этим в те времена никто не следил). Форматы были самые разные.
    // Текстовый файл можно читать любой программой, однако он не особо
    // удобен в чтении (текст обычно форматируется моноширинным шрифтом).
    // Библиотека Максима Мошкова использовала форматированный TXT,
    // что отлично работает в текстовом режиме, но совершенно неудобно
    // в оконных интерфейсах и на мобильных устройствах, да и обработку
    // затрудняет. Microsoft Word и TeX крайне сложны в обработке.
    // PDF приспособлен только для бумажных копий, чтение PDF с экрана
    // затруднено. DocBook рассчитан на технические книги: вся мощь
    // формата избыточна для художественных книг, а стихи не поддерживаются.
    // Немногочисленные карманные устройства, появившиеся в начале 2000-х,
    // имели свои книжные форматы и зачастую некачественное ПО для их чтения.
    // Врéменным решением было использовать подмножество HTML, так как
    // полный HTML крайне сложен в реализации. По такому пути пошёл,
    // например, Open eBook (ныне декларирующий полное соответствие
    // HTML/CSS ePub).
    //
    // В условиях такого «вакуума» Грибов и предложил свой формат, задумывавшийся не как формат для чтения электронных книг, а как формат для их хранения[9] с целью конечной конвертации для пользователя. Однако, наглядность и простота изменения книги «даже руками» и возможность конвертировать при необходимости книгу в другие форматы придало FB2 популярность в Рунете, он стал стандартом де-факто в русских, украинских и белорусских сетевых библиотеках. В последние годы возросла популярность формата в нерусскоязычных странах: Болгарии[10], Латвии[11][12]. Некоторые электронные библиотеки перешли на формат FictionBook полностью, и не принимают книги, подготовленные в других форматах. Однако на страницах этих библиотек можно скачать одну и ту же книгу в виде файлов других распространённых форматов (текстовый файл, RTF, HTML, rb, .doc, PRC[en], ePub, PDF), полученных из .fb2 путём автоматической конвертации.
    //
    // FictionBook 3 должен был быть ZIP-контейнером, в котором хранятся
    // XML и дополнительные файлы (метаданные, рисунки). Жанры предлагалось
    // классифицировать по шести разным «осям» (государственная принадлежность
    // автора, возраст аудитории, описанная историческая эпоха, литературная
    // форма, сюжет и стиль повествования). Разработка fb3 «заглохла» ещё
    // в 2008 году, однако продолжена автором fb2 в 2013.
    //

    //
    // https://en.wikipedia.org/wiki/FictionBook
    //
    // FictionBook is an open XML-based e-book format which originated
    // and gained popularity in Russia. FictionBook files have the .fb2
    // filename extension. Some readers also support ZIP-compressed
    // FictionBook files (.fb2.zip or .fbz)
    //
    // The FictionBook format does not specify the appearance of a document;
    // instead, it describes its structure. For example, there are special
    // tags for epigraphs, verses and quotations. All ebook metadata,
    // such as author name, title, and publisher, is also present in the
    // ebook file. This makes the format convenient for automatic processing,
    // indexing, and ebook collection management, and allows automatic
    // conversion into other formats.
    //
    // Features of FictionBook
    //
    // * Free and open format with multiple hardware and software implementations
    // * DRM-free
    // * Supports reflow by design
    // * Simple semantic markup
    // * Optimized for narrative literature
    // * Embeds metadata, proposes its own scheme for genre description
    // * Supports Unicode
    // * Documents may contain:
    //   * Structured text organized in nested sections (optionally titled)
    //   * Subtitles (which do not appear in the table of contents)
    //   * Epigraphs
    //   * Poetry
    //   * Quotations
    //   * References and footnotes
    //   * Tables (but not all readers support them)
    //   * Raster images (PNG or JPEG)
    // * Inline formatting:
    //   * Strong (usually bold)
    //   * Emphasized (usually slanted or italic)
    //   * Strikethrough
    //   * Superscript
    //   * Subscript
    //   * Source code (usually in monospace font)
    //
    // Differences from other ebook formats
    //
    // In contrast to other eBook formats (e.g. ePub), a FictionBook document
    // consists of a single XML file. Images are converted to Base64 and reside
    // inside the <binary> tag, so the size of the embedded images is increased
    // by approximately 37%. FictionBook files are often distributed inside Zip
    // archives, and most of hardware and software readers can work with
    // compressed FictionBook files (*.fb2.zip) directly. The metadata
    // and the plain text data are always placed in the beginning of the
    // FictionBook file, while more heavyweight binary images are placed
    // in the end. This allows software to start rendering or processing
    // FictionBook before the file is available entirely.
    //
    // FictionBook is the format of choice of some community-driven
    // online electronic libraries. It does not allow for digital rights
    // management of any kind.
    //
    // Software and hardware support
    //
    // The format is supported by e-book readers such as FBReader, AlReader,
    // Haali Reader, STDU Viewer, CoolReader, Fly Reader, Okular, Ectaco
    // jetBooks, Documents for iOS, and some others. Firefox can read
    // FictionBook by installing an extension: FB2 Reader. Many hardware
    // vendors support FictionBook in their firmware: BeBook One, BeBook
    // Mini and BeBook Club in Europe (and other Hanlin V3 and V5 based
    // devices), all PocketBook Readers, COOL-ER devices, Cybook Opus
    // and Cybook Gen3, and ASUS Eee Reader DR900. Devices based on the
    // Hanvon N516 design can read FictionBook if custom OpenInkpot firmware
    // is installed; it is factory default for Azbooka 516. Amazon's Kindle,
    // Barnes & Noble's Nook, and Sony devices do not support FictionBook directly.
    //
    // Conversion to and from FictionBook2 files (.fb2 and .fbz) is possible
    // via the cross-platform ebook management software Calibre. Conversion to,
    // but not from, FictionBook2 format is also available via Pandoc.
    //

    //
    // http://www.fictionbook.org/index.php/FictionBook
    //
    // Формат FictionBook - это xml формат хранения книг, где каждый
    // элемент книги описывается своими тегами.
    //
    // Главная цель сторонников хранения книг в формате FictionBook
    // - четкое хранение структуры книги с возможностью без труда
    // сконвертировать (в том числе и автоматизированно) файл формата
    // FictionBook в другие популярные форматы: txt, doc, rtf, html и пр.
    // Кроме того многие программы чтения книг позволяют читать книги
    // в формате FictionBook без конвертации.
    //
    // Все это служит удобству чтения.
    //
    // Решаемые задачи:
    //
    // * Описание формата.
    // * Разработка технического задания для программного обеспечения:
    //   редакторов, ридеров, конверторов.
    // * Разработка программного обеспечения.
    // * Изготовление качественных по структуре и содержанию книг.
    //
    // Попутно одним махом достигается и еще одна цель: на основе данных,
    // хранящихся внутри файла FictionBook, с необычайной легкостью можно
    // построить хранилище книг любого масштаба как у себя дома, так
    // и публичное (сетевая библиотека). Это хранилище в обработке
    // требует значительно меньше времени и усилий, чем хранение книг
    // в любом другом виде. Более всего формат FictionBook подходит
    // для художественной литературы. Специальную литературу: научную,
    // техническую, - описать в терминах формата пока затруднительно.
    //
    // Основная информация о формате расположена в секциях навигатора
    // Статьи и Документы. В секции Программы описаны различные программы,
    // используемые для чтения и подготовки книг в формате FictionBook,
    // библиотекари и различные утилиты. На Тестовой площадке происходит
    // тестирование программ, сообщения об ошибках.
    //
    // Если вы желаете написать комментарий или статью, но не знаете
    // как - вам поможет раздел Справка. Если вы желаете помочь перевести
    // статью на английский язык прочтите в Справке статью Переводчикам
    // и смело переходите в раздел English.
    //

    /// <summary>
    /// Корневой элемент.
    /// </summary>
    [XmlRoot("FictionBook", Namespace = "http://www.gribuser.ru/xml/fictionbook/2.0")]
    public sealed class FbDocument
    {
        #region Properties

        /// <summary>
        /// Стили.
        /// </summary>
        [XmlElement("stylesheet")]
        public string Stylesheet { get; set; }

        /// <summary>
        /// Описание.
        /// </summary>
        [XmlElement("description")]
        public FbDescription Description { get; set; }

        /// <summary>
        /// Тело.
        /// </summary>
        [XmlElement("body")]
        public FbBody[] Body { get; set; }

        /// <summary>
        /// Двоичные данные (рисунки).
        /// </summary>
        [XmlElement("binary")]
        public FbBinary[] Binary { get; set; }

        #endregion

        #region Public methods

        /// <summary>
        /// Загрузка книги из указанного sфайла.
        /// </summary>
        [NotNull]
        public static FbDocument LoadBook
            (
                [NotNull] string fileName
            )
        {
            Code.NotNullNorEmpty(fileName, "fileName");

            FbDocument result = XmlUtility.Deserialize<FbDocument>(fileName);

            return result;
        }

        #endregion

        #region Object members

        /// <inheritdoc cref="object.ToString" />
        public override string ToString()
        {
            return Description.ToVisibleString();
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <SearchResponse xmlns="http://www.digimap.gg/CAF/2.0">
      <SearchResult>
        <ResultCount>0</ResultCount>
        <AddressList/>
      </SearchResult>
    </SearchResponse>
  </soap:Body>
</soap:Envelope>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/darkgrey">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="5dp"
            android:background="@drawable/editshoppinglist_listviewelement_bg"
            android:layout_gravity="center_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Produktname"
                android:id="@+id/ProdName"
                android:layout_weight="90"
                android:layout_marginLeft="15dp"
                android:textSize="15dp"
                android:layout_gravity="center_vertical" />

            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/delBtn"
                android:background="@drawable/del_btn"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="10dp"
                android:layout_gravity="center_vertical" />

        </LinearLayout>
    </LinearLayout>
</LinearLayout>


text:
package org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties;

import java.util.Collections;
import java.util.UUID;

import org.eclipse.bpmn2.CallActivity;
import org.eclipse.bpmn2.Definitions;
import org.eclipse.bpmn2.di.BPMNDiagram;
import org.junit.Before;
import org.junit.Test;
import org.kie.workbench.common.stunner.bpmn.backend.converters.customproperties.CustomElement;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.DefinitionResolver;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.Factories.bpmn2;
import static org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.Factories.di;

public class CallActivityPropertyReaderTest {

    private DefinitionResolver definitionResolver;

    private CallActivityPropertyReader tested;

    @Before
    public void setUp() {
        Definitions definitions = bpmn2.createDefinitions();
        definitions.getRootElements().add(bpmn2.createProcess());
        BPMNDiagram bpmnDiagram = di.createBPMNDiagram();
        bpmnDiagram.setPlane(di.createBPMNPlane());
        definitions.getDiagrams().add(bpmnDiagram);

        definitionResolver = new DefinitionResolver(definitions, Collections.emptyList());
    }

    @Test
    public void testIsCase_true() {
        String id = UUID.randomUUID().toString();

        CallActivity callActivity = bpmn2.createCallActivity();
        callActivity.setId(id);
        CustomElement.isCase.of(callActivity).set(Boolean.TRUE);

        tested = new CallActivityPropertyReader(callActivity,
                                                definitionResolver.getDiagram(),
                                                definitionResolver);

        assertTrue(tested.isCase());
    }

    @Test
    public void testIsCase_false() {
        String id = UUID.randomUUID().toString();

        CallActivity callActivity = bpmn2.createCallActivity();
        callActivity.setId(id);
        CustomElement.isCase.of(callActivity).set(Boolean.FALSE);

        tested = new CallActivityPropertyReader(callActivity,
                                                definitionResolver.getDiagram(),
                                                definitionResolver);

        assertFalse(tested.isCase());
    }

    @Test
    public void testIsAdHocAutostart_true() {
        String id = UUID.randomUUID().toString();

        CallActivity callActivity = bpmn2.createCallActivity();
        callActivity.setId(id);
        CustomElement.autoStart.of(callActivity).set(Boolean.TRUE);

        tested = new CallActivityPropertyReader(callActivity,
                                                definitionResolver.getDiagram(),
                                                definitionResolver);

        assertTrue(tested.isAdHocAutostart());
    }

    @Test
    public void testIsAdHocAutostart_false() {
        String id = UUID.randomUUID().toString();

        CallActivity callActivity = bpmn2.createCallActivity();
        callActivity.setId(id);
        CustomElement.autoStart.of(callActivity).set(Boolean.FALSE);

        tested = new CallActivityPropertyReader(callActivity,
                                                definitionResolver.getDiagram(),
                                                definitionResolver);

        assertFalse(tested.isAdHocAutostart());
    }

    @Test
    public void testAbortParentTrue() {
        testAbortParent(true);
    }

    @Test
    public void testAbortParentFalse() {
        testAbortParent(false);
    }

    private void testAbortParent(boolean value) {
        CallActivity callActivity = bpmn2.createCallActivity();
        CustomElement.abortParent.of(callActivity).set(value);

        tested = new CallActivityPropertyReader(callActivity,
                                                definitionResolver.getDiagram(),
                                                definitionResolver);
        assertEquals(value, tested.isAbortParent());
    }

    @Test
    public void testIsAsync() {
        CallActivity callActivity = bpmn2.createCallActivity();
        CustomElement.async.of(callActivity).set(Boolean.TRUE);

        tested = new CallActivityPropertyReader(callActivity,
                                                definitionResolver.getDiagram(),
                                                definitionResolver);

        assertTrue(tested.isAsync());
    }

    @Test
    public void testGetSlaDueDate() {
        String rawSlaDueDate = "12/25/1983";

        CallActivity callActivity = bpmn2.createCallActivity();
        CustomElement.slaDueDate.of(callActivity).set(rawSlaDueDate);

        tested = new CallActivityPropertyReader(callActivity,
                                                definitionResolver.getDiagram(),
                                                definitionResolver);

        assertTrue(tested.getSlaDueDate().contains(rawSlaDueDate));
    }
}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :rentee

  def is_admin?
    current_user.email == 'morne.luus@gmail.com' unless current_user.blank?
  end

end


text:
const spawn = require('child_process').spawn

const ownExitCode = 123
const SERVICE_NAME = 'tester'
process.env.SERVICE_NAME = SERVICE_NAME

/**
 * Setup test to run library as intended by external applications.
 * This function spawns a new node process, pipes in code to be executed (log test),
 * and then exits with the global 'ownExitCode' exit code.
 *
 * If the log library exists with a different code than the above, the asserts
 * in this test helper will catch this.
 *
 * @param {string}   logLevel         Log level to test
 * @param {int}      expectedExitCode Which exit code is expected from the spawned process
 * @param            expect           Jest 'expect' assertion function
 * @param            done             'test is done' indicator function
 */
function testLoggingSpawn(logLevel, expectedExitCode, expect, done) {
  const node = spawn('node', { cwd: __dirname })
  const logInput = `
    const log = require('./index');
    log.${logLevel}('hej');

    // Exit with this exit code to indicate library did not exit the process
    process.exit(${ownExitCode});
  `
  let logOutput = ''

  node.stdin.write(logInput)
  node.stdin.end()

  node.stdout.on('data', (data) => { logOutput += data })

  node.on('close', (code) => {
    const logJSON = JSON.parse(logOutput)

    expect(code).toBe(expectedExitCode)
    expect(logJSON).toHaveProperty('level', logLevel)
    expect(logJSON).toHaveProperty('msg', 'hej')
    expect(logJSON).toHaveProperty('service', SERVICE_NAME)
    expect(logJSON).toHaveProperty('timestamp')

    done()
  })
}

/* eslint-disable no-multi-spaces */
/* eslint-env jest/globals */
describe('log output', () => {
  test('debug',   (done) => { testLoggingSpawn('debug',   ownExitCode, expect, done) })
  test('info',    (done) => { testLoggingSpawn('info',    ownExitCode, expect, done) })
  test('warning', (done) => { testLoggingSpawn('warning', ownExitCode, expect, done) })
  test('error',   (done) => { testLoggingSpawn('error',   ownExitCode, expect, done) })
  test('panic',   (done) => { testLoggingSpawn('panic',   1,           expect, done) })
})
/* eslint-enable */


text:
typedef unsigned long long OSMid;

//class
//{
//public:
//	const OSMDatabase& osmDatabase() const { return osmdb_; }
//}

//std::map<std::string,std::string> getAllNodeTagKeys();
//std::map<std::string,std::string> getAllWayTagKeys();
//std::map<std::string,std::string> getAllRelationTagKeys();
//
//std::vector<std::string> getAllTagValuesForKey(std::string);
//
//std::map<std::string,std::string> getAllTagsForObject(OSMid id);

// aggregate queries
unsigned long long getNumberOfStreets();
unsigned long long getNumberOfStreetSegments();
unsigned long long getNumberOfIntersections();
unsigned long long getNumberOfPointsOfInterest();

// load the database
bool loadStreetDatabaseBIN(const std::string&);
void closeStreetDatabase();

//------------------------------------------------
// Intersection information

std::string getIntersectionName(unsigned intersectionID);
LatLon getIntersectionPosition(unsigned intersectionID);
//number of street segments at an intersection
unsigned getIntersectionStreetSegmentCount(unsigned intersectionID);
// find the street segments at an intersection. idx is from
// 0..streetSegmentCount-1 (at this intersection)
unsigned getIntersectionStreetSegment(unsigned intersectionID,unsigned idx);

//------------------------------------------------
// Street segment information

//find the street to which this segment belongs
unsigned getStreetSegmentStreetID(unsigned streetSegmentID);
//find the from/to intersections for this street segment
StreetSegmentEnds getStreetSegmentEnds(unsigned streetSegmentID);
//find the number of curve points at a street segment
unsigned getStreetSegmentCurvePointCount(unsigned streetSegmentID);
//fetch the latlon of the idx'th curve point
LatLon getStreetSegmentCurvePoint(unsigned streetSegmentID,unsigned idx);
double getStreetSegmentSpeedLimit(unsigned streetSegmentID);
bool getStreetSegmentOneWay(unsigned streetSegmentID);

//street information
std::string getStreetName(unsigned streetID);

// points of interest
std::string getPointOfInterestName(unsigned pointOfInterestID);
LatLon getPointOfInterestPosition(unsigned pointOfInterestID);

// natural features
unsigned getFeatureCount();
std::string getFeatureAttribute(unsigned feature_id ,const std::string&);
unsigned getFeaturePointCount(unsigned feature_id);
LatLon getFeaturePoint(unsigned feature_id, unsigned idx);


text:
import { AlloyComponent, Composing, MementoRecord } from '@ephox/alloy';
import { Optional } from '@ephox/katamari';
import { Traverse } from '@ephox/sugar';

type ComposingBehaviour = ReturnType<typeof Composing['config']>;

// TODO: Move this to alloy if the concept works out
const self = (): ComposingBehaviour => Composing.config({
  find: Optional.some
});

const memento = (mem: MementoRecord): ComposingBehaviour => Composing.config({
  find: mem.getOpt
});

const childAt = (index: number): ComposingBehaviour => Composing.config({
  find: (comp: AlloyComponent) => Traverse.child(comp.element, index)
    .bind((element) => comp.getSystem().getByDom(element).toOptional())
});

export const ComposingConfigs = {
  self,
  memento,
  childAt
};


text:
#ifndef STMTDDLDROPSQL_H
#define STMTDDLDROPSQL_H
/* -*-C++-*-
 *****************************************************************************
 *
 * File:         StmtDDLDropSQL.h
 * Description:  class for parse node representing Drop SQL statements
 *
 *
 * Created:      03/29/96
 * Language:     C++
 *
 *
 *
 *
 *****************************************************************************
 */

#include "ComSmallDefs.h"
#include "StmtDDLNode.h"

// -----------------------------------------------------------------------
// contents of this file
// -----------------------------------------------------------------------
class StmtDDLDropSQL;

// -----------------------------------------------------------------------
// forward references
// -----------------------------------------------------------------------
// None

// -----------------------------------------------------------------------
// Drop SQL  statement
// -----------------------------------------------------------------------
class StmtDDLDropSQL : public StmtDDLNode
{

public:

  // constructor
  StmtDDLDropSQL(ComDropBehavior dropBehavior);

  // virtual destructor
  virtual ~StmtDDLDropSQL();

  // cast
  virtual StmtDDLDropSQL * castToStmtDDLDropSQL();

  // accessor
  inline ComDropBehavior getDropBehavior() const;

  // for tracing
  virtual const NAString getText() const;

private:

  ComDropBehavior dropBehavior_;

}; // class StmtDDLDropSQL

// -----------------------------------------------------------------------
// definitions of inline methods for class StmtDDLDropSQL
// -----------------------------------------------------------------------
inline ComDropBehavior
StmtDDLDropSQL::getDropBehavior() const
{
  return dropBehavior_;
}

#endif // STMTDDLDROPSQL_H


text:
  <md-tab-group md-dynamic-height md-border-bottom disableRipple="true" [(selectedIndex)]="selectedIndex" (selectedIndexChange)="onSelectionChange($event)">
    <md-tab *ngFor="let tab of tabs; let i = index">
      <ng-template md-tab-label #closable>

{{tab.name}}

      </ng-template>
    </md-tab>
  </md-tab-group>

      <app-workbench-dynamic class="flex-1" *ngFor="let tab of tabs; let i = index" [componentData]="tabs[i]" [context]="tabs[i].context" [hidden]="!isSelected(tab)"></app-workbench-dynamic>


text:
static logger::LogChannel sopnetlog("sopnetlog", "[Sopnet] ");

util::ProgramOption optionLinearCostFunction(
		util::_module           = "sopnet.inference",
		util::_long_name        = "linearCostFunction",
		util::_description_text = "Use the linear cost function for segments.",
		util::_default_value    = true);

util::ProgramOption optionRandomForestCostFunction(
		util::_module           = "sopnet.inference",
		util::_long_name        = "rfCostFunction",
		util::_description_text = "Use the random forest cost function for segments.",
		util::_default_value    = true);

util::ProgramOption optionSegmentationCostFunction(
		util::_module           = "sopnet.inference",
		util::_long_name        = "segmentationCostFunction",
		util::_description_text = "Use the segmentation cost function (based on membrane probabilites) for segments.");

util::ProgramOption optionPriorCostFunction(
		util::_module           = "sopnet.inference",
		util::_long_name        = "priorCostFunction",
		util::_description_text = "Use the prior cost function for segments (only really makes sense for gridSearch, since linearCostFunction provides the same).",
		util::_default_value    = false);

util::ProgramOption optionRandomForestFile(
		util::_module           = "sopnet.inference",
		util::_long_name        = "segmentRandomForest",
		util::_description_text = "Path to an HDF5 file containing the segment random forest.",
		util::_default_value    = "segment_rf.hdf");

util::ProgramOption optionLinearCostFunctionParametersFile(
		util::_module           = "sopnet.inference",
		util::_long_name        = "linearCostFunctionParameters",
		util::_description_text = "Path to a file containing the weights for the linear cost function.",
		util::_default_value    = "./feature_weights.dat");

util::ProgramOption optionDecomposeProblem(
		util::_module           = "sopnet.inference",
		util::_long_name        = "decomposeProblem",
		util::_description_text = "Decompose the problem into overlapping subproblems and solve them using SCALAR.",
		util::_default_value    = false);

util::ProgramOption optionReadGoldStandardFromFile(
		util::_module           = "sopnet.training",
		util::_long_name        = "readGoldStandardFromFile",
		util::_description_text = "Instead of looking at the ground truth, read the gold standard from a file with segment hashes, where each line is of the form: [0 or 1 (part of GS or not)] # [hash].");

Sopnet::Sopnet(
		const std::string& projectDirectory,
		boost::shared_ptr<ProcessNode> problemWriter) :
	_problemAssembler(boost::make_shared<ProblemAssembler>()),
	_segmentFeaturesExtractor(boost::make_shared<SegmentFeaturesExtractor>()),
	_randomForestReader(boost::make_shared<RandomForestHdf5Reader>(optionRandomForestFile.as<std::string>())),
	_objectiveGenerator(boost::make_shared<ObjectiveGenerator>()),
	_linearSolver(boost::make_shared<LinearSolver>()),
	_reconstructor(boost::make_shared<Reconstructor>()),
	_groundTruthExtractor(boost::make_shared<GroundTruthExtractor>()),
	_segmentRfTrainer(boost::make_shared<SegmentRandomForestTrainer>()),
	_spWriter(boost::make_shared<StructuredProblemWriter>()),
	_mitWriter(boost::make_shared<MinimalImpactTEDWriter>()),
	_projectDirectory(projectDirectory),
	_problemWriter(problemWriter),
	_pipelineCreated(false) {

	// tell the outside world what we need
	registerInput(_rawSections, "raw sections");
	registerInput(_membranes, "membranes");
	registerInput(_neuronSlices, "neuron slices", pipeline::Optional);
	registerInput(_neuronSliceStackDirectories, "neuron slice stack directories", pipeline::Optional);
	registerInput(_mitochondriaSlices, "mitochondria slices", pipeline::Optional);
	registerInput(_mitochondriaSliceStackDirectories, "mitochondria slice stack directories", pipeline::Optional);
	registerInput(_synapseSlices, "synapse slices", pipeline::Optional);
	registerInput(_synapseSliceStackDirectories, "synapse slice stack directories", pipeline::Optional);
	registerInput(_groundTruth, "ground truth", pipeline::Optional);
	registerInput(_segmentationCostFunctionParameters, "segmentation cost parameters");
	registerInput(_priorCostFunctionParameters, "prior cost parameters");
	registerInput(_forceExplanation, "force explanation");

	if (optionReadGoldStandardFromFile) {

		LOG_USER(sopnetlog) << "reading gold standard from file " << optionReadGoldStandardFromFile.as<std::string>() << std::endl;

		_goldStandardProvider = boost::make_shared<GoldStandardFileReader>(optionReadGoldStandardFromFile.as<std::string>());

	} else {

		LOG_USER(sopnetlog) << "extract gold standard from ground truth" << std::endl;

		_goldStandardProvider = boost::make_shared<GoldStandardExtractor>();
	}

	// tell the outside world what we've got
	registerOutput(_reconstructor->getOutput(), "solution");
	registerOutput(_problemAssembler->getOutput("segments"), "segments");
	registerOutput(_problemAssembler->getOutput("problem configuration"), "problem configuration");
	registerOutput(_objectiveGenerator->getOutput("objective"), "objective");
	registerOutput(_groundTruthExtractor->getOutput("ground truth segments"), "ground truth segments");
	registerOutput(_goldStandardProvider->getOutput("gold standard"), "gold standard");
	registerOutput(_goldStandardProvider->getOutput("negative samples"), "negative samples");
	if (!optionReadGoldStandardFromFile) registerOutput(_goldStandardProvider->getOutput("gold standard objective"), "gold standard objective");
	registerOutput(_segmentRfTrainer->getOutput("random forest"), "random forest");
	registerOutput(_segmentFeaturesExtractor->getOutput("all features"), "all features");

	// set input-output dependencies
	setDependency(_rawSections, _reconstructor->getOutput());
	setDependency(_rawSections, _objectiveGenerator->getOutput("objective"));
	setDependency(_rawSections, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_rawSections, _segmentFeaturesExtractor->getOutput("all features"));

	setDependency(_membranes, _reconstructor->getOutput());
	setDependency(_membranes, _objectiveGenerator->getOutput("objective"));
	setDependency(_membranes, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_membranes, _segmentFeaturesExtractor->getOutput("all features"));

	setDependency(_neuronSlices, _reconstructor->getOutput());
	setDependency(_neuronSlices, _problemAssembler->getOutput("segments"));
	setDependency(_neuronSlices, _problemAssembler->getOutput("problem configuration"));
	setDependency(_neuronSlices, _objectiveGenerator->getOutput("objective"));
	setDependency(_neuronSlices, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_neuronSlices, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_neuronSlices, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_neuronSlices, _segmentFeaturesExtractor->getOutput("all features"));
	setDependency(_neuronSliceStackDirectories, _reconstructor->getOutput());
	setDependency(_neuronSliceStackDirectories, _problemAssembler->getOutput("segments"));
	setDependency(_neuronSliceStackDirectories, _problemAssembler->getOutput("problem configuration"));
	setDependency(_neuronSliceStackDirectories, _objectiveGenerator->getOutput("objective"));
	setDependency(_neuronSliceStackDirectories, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_neuronSliceStackDirectories, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_neuronSliceStackDirectories, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_neuronSliceStackDirectories, _segmentFeaturesExtractor->getOutput("all features"));
	setDependency(_mitochondriaSlices, _reconstructor->getOutput());
	setDependency(_mitochondriaSlices, _problemAssembler->getOutput("segments"));
	setDependency(_mitochondriaSlices, _problemAssembler->getOutput("problem configuration"));
	setDependency(_mitochondriaSlices, _objectiveGenerator->getOutput("objective"));
	setDependency(_mitochondriaSlices, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_mitochondriaSlices, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_mitochondriaSlices, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_mitochondriaSlices, _segmentFeaturesExtractor->getOutput("all features"));
	setDependency(_mitochondriaSliceStackDirectories, _reconstructor->getOutput());
	setDependency(_mitochondriaSliceStackDirectories, _problemAssembler->getOutput("segments"));
	setDependency(_mitochondriaSliceStackDirectories, _problemAssembler->getOutput("problem configuration"));
	setDependency(_mitochondriaSliceStackDirectories, _objectiveGenerator->getOutput("objective"));
	setDependency(_mitochondriaSliceStackDirectories, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_mitochondriaSliceStackDirectories, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_mitochondriaSliceStackDirectories, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_mitochondriaSliceStackDirectories, _segmentFeaturesExtractor->getOutput("all features"));
	setDependency(_synapseSlices, _reconstructor->getOutput());
	setDependency(_synapseSlices, _problemAssembler->getOutput("segments"));
	setDependency(_synapseSlices, _problemAssembler->getOutput("problem configuration"));
	setDependency(_synapseSlices, _objectiveGenerator->getOutput("objective"));
	setDependency(_synapseSlices, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_synapseSlices, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_synapseSlices, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_synapseSlices, _segmentFeaturesExtractor->getOutput("all features"));
	setDependency(_synapseSliceStackDirectories, _reconstructor->getOutput());
	setDependency(_synapseSliceStackDirectories, _problemAssembler->getOutput("segments"));
	setDependency(_synapseSliceStackDirectories, _problemAssembler->getOutput("problem configuration"));
	setDependency(_synapseSliceStackDirectories, _objectiveGenerator->getOutput("objective"));
	setDependency(_synapseSliceStackDirectories, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_synapseSliceStackDirectories, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_synapseSliceStackDirectories, _segmentRfTrainer->getOutput("random forest"));
	setDependency(_synapseSliceStackDirectories, _segmentFeaturesExtractor->getOutput("all features"));

	setDependency(_groundTruth, _groundTruthExtractor->getOutput("ground truth segments"));
	setDependency(_groundTruth, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_groundTruth, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_groundTruth, _segmentRfTrainer->getOutput("random forest"));

	setDependency(_segmentationCostFunctionParameters, _reconstructor->getOutput());
	setDependency(_segmentationCostFunctionParameters, _objectiveGenerator->getOutput("objective"));

	setDependency(_priorCostFunctionParameters, _reconstructor->getOutput());
	setDependency(_priorCostFunctionParameters, _objectiveGenerator->getOutput("objective"));

	setDependency(_forceExplanation, _reconstructor->getOutput());
	setDependency(_forceExplanation, _goldStandardProvider->getOutput("gold standard"));
	setDependency(_forceExplanation, _goldStandardProvider->getOutput("negative samples"));
	setDependency(_forceExplanation, _segmentRfTrainer->getOutput("random forest"));
}

void
Sopnet::updateOutputs() {

	LOG_DEBUG(sopnetlog) << "update requested" << std::endl;

	createPipeline();
}

void
Sopnet::createPipeline() {

	if (_pipelineCreated) {

		LOG_DEBUG(sopnetlog) << "pipeline has been created already, skipping" << std::endl;
		return;
	}

	LOG_DEBUG(sopnetlog) << "creating pipeline" << std::endl;

	if (!_neuronSlices.isSet() && !_neuronSliceStackDirectories.isSet())
		UTIL_THROW_EXCEPTION(
				UsageError,
				"either an image stack of slices or a list of directory names has to be set as 'neuron slices' or 'neuron slice stack directories'");

	createBasicPipeline();
	createInferencePipeline();
	if (_groundTruth.isSet()) {

		createTrainingPipeline();
		createStructuredProblemPipeline();
		createMinimalImpactTEDPipeline();
	}

	_pipelineCreated = true;
}

void
Sopnet::createBasicPipeline() {

	LOG_DEBUG(sopnetlog) << "re-creating basic part..." << std::endl;

	// clear previous pipeline
	_problemAssembler->clearInputs("neuron segments");
	_problemAssembler->clearInputs("neuron linear constraints");
	_problemAssembler->clearInputs("mitochondria segments");
	_problemAssembler->clearInputs("mitochondria linear constraints");
	_problemAssembler->clearInputs("synapse segments");
	_problemAssembler->clearInputs("synapse linear constraints");

	bool finishLastSection = !_problemWriter;

	LOG_DEBUG(sopnetlog) << "creating neuron segment part..." << std::endl;

	if (_neuronSliceStackDirectories.isSet())
		_neuronSegmentExtractorPipeline = boost::make_shared<SegmentExtractionPipeline>(_neuronSliceStackDirectories.getSharedPointer(), finishLastSection);
	else
		_neuronSegmentExtractorPipeline = boost::make_shared<SegmentExtractionPipeline>(_neuronSlices.getSharedPointer(), _forceExplanation, finishLastSection);

	LOG_DEBUG(sopnetlog) << "creating mitochondria segment part..." << std::endl;

	_mitochondriaSegmentExtractorPipeline.reset();
	if (_mitochondriaSliceStackDirectories.isSet())
		_mitochondriaSegmentExtractorPipeline = boost::make_shared<SegmentExtractionPipeline>(_mitochondriaSliceStackDirectories.getSharedPointer(), finishLastSection);
	else if (_mitochondriaSlices.isSet())
		_mitochondriaSegmentExtractorPipeline = boost::make_shared<SegmentExtractionPipeline>(_mitochondriaSlices.getSharedPointer(), false, finishLastSection);

	LOG_DEBUG(sopnetlog) << "creating synapse segment part..." << std::endl;

	_synapseSegmentExtractorPipeline.reset();
	if (_synapseSliceStackDirectories.isSet())
		_synapseSegmentExtractorPipeline = boost::make_shared<SegmentExtractionPipeline>(_synapseSliceStackDirectories.getSharedPointer(), finishLastSection);
	else if (_synapseSlices.isSet())
		_synapseSegmentExtractorPipeline = boost::make_shared<SegmentExtractionPipeline>(_synapseSlices.getSharedPointer(), false, finishLastSection);

	LOG_DEBUG(sopnetlog) << "feeding output into problem assembler..." << std::endl;

	for (unsigned int i = 0; i < _neuronSegmentExtractorPipeline->numIntervals(); i++) {

		// add segments and linear constraints to problem assembler
		_problemAssembler->addInput("neuron segments", _neuronSegmentExtractorPipeline->getSegments(i));
		_problemAssembler->addInput("neuron linear constraints", _neuronSegmentExtractorPipeline->getConstraints(i));

		if (_mitochondriaSegmentExtractorPipeline) {

			_problemAssembler->addInput("mitochondria segments", _mitochondriaSegmentExtractorPipeline->getSegments(i));
			_problemAssembler->addInput("mitochondria linear constraints", _mitochondriaSegmentExtractorPipeline->getConstraints(i));
		}

		if (_synapseSegmentExtractorPipeline) {

			_problemAssembler->addInput("synapse segments", _synapseSegmentExtractorPipeline->getSegments(i));
			_problemAssembler->addInput("synapse linear constraints", _synapseSegmentExtractorPipeline->getConstraints(i));
		}
	}

	if (_groundTruth.isSet())
		_groundTruthExtractor->setInput(_groundTruth);
}

void
Sopnet::createInferencePipeline() {

	LOG_DEBUG(sopnetlog) << "re-creating inference part..." << std::endl;

	// setup the segment feature extractor
	_segmentFeaturesExtractor->setInput("segments", _problemAssembler->getOutput("segments"));
	_segmentFeaturesExtractor->setInput("raw sections", _rawSections.getAssignedOutput());

	boost::shared_ptr<LinearCostFunction>       linearCostFunction;
	boost::shared_ptr<RandomForestCostFunction> rfCostFunction;
	boost::shared_ptr<SegmentationCostFunction> segmentationCostFunction;
	boost::shared_ptr<PriorCostFunction>        priorCostFunction;

	// setup the segment evaluation functions
	if (optionLinearCostFunction) {

		LOG_DEBUG(sopnetlog) << "creating linear segment cost function" << std::endl;

		linearCostFunction = boost::make_shared<LinearCostFunction>();
		boost::shared_ptr<LinearCostFunctionParametersReader> reader
				= boost::make_shared<LinearCostFunctionParametersReader>();
		boost::shared_ptr<FileContentProvider> contentProvider
				= boost::make_shared<FileContentProvider>(optionLinearCostFunctionParametersFile.as<std::string>());
		reader->setInput(contentProvider->getOutput());
		linearCostFunction->setInput("features", _segmentFeaturesExtractor->getOutput("all features"));
		linearCostFunction->setInput("parameters", reader->getOutput());

	}

	if (optionRandomForestCostFunction) {

		LOG_DEBUG(sopnetlog) << "creating random forest segment cost function" << std::endl;

		rfCostFunction = boost::make_shared<RandomForestCostFunction>();
		rfCostFunction->setInput("features", _segmentFeaturesExtractor->getOutput("all features"));
		rfCostFunction->setInput("random forest", _randomForestReader->getOutput("random forest"));
	}

	if (optionSegmentationCostFunction) {

		segmentationCostFunction = boost::make_shared<SegmentationCostFunction>();
		segmentationCostFunction->setInput("membranes", _membranes);
		segmentationCostFunction->setInput("parameters", _segmentationCostFunctionParameters);
	}

	if (optionPriorCostFunction) {

		priorCostFunction = boost::make_shared<PriorCostFunction>();
		priorCostFunction->setInput("parameters", _priorCostFunctionParameters);
	}

	if (_problemWriter) {

		_problemWriter->setInput("segments", _problemAssembler->getOutput("segments"));
		_problemWriter->setInput("problem configuration", _problemAssembler->getOutput("problem configuration"));
		_problemWriter->setInput("features", _segmentFeaturesExtractor->getOutput("all features"));

		// assuming one of the two was selected
		if (rfCostFunction)
			_problemWriter->setInput("segment cost function", rfCostFunction->getOutput("cost function"));
		else
			_problemWriter->setInput("segment cost function", linearCostFunction->getOutput("cost function"));

		_problemWriter->setInput("segmentation cost function", segmentationCostFunction->getOutput("cost function"));
		_problemWriter->addInput("linear constraints", _problemAssembler->getOutput("linear constraints"));

	} else {

		// feed all segments to objective generator
		_objectiveGenerator->setInput("segments", _problemAssembler->getOutput("segments"));
		if (rfCostFunction)
			_objectiveGenerator->addInput("cost functions", rfCostFunction->getOutput("cost function"));
		if (linearCostFunction)
			_objectiveGenerator->addInput("cost functions", linearCostFunction->getOutput("cost function"));
		if (segmentationCostFunction)
			_objectiveGenerator->addInput("cost functions", segmentationCostFunction->getOutput("cost function"));
		if (priorCostFunction)
			_objectiveGenerator->addInput("cost functions", priorCostFunction->getOutput("cost function"));

		if (optionDecomposeProblem) {

			pipeline::Process<SubproblemsExtractor> subproblemsExtractor;
			pipeline::Process<SubproblemsSolver>    subproblemsSolver;

			subproblemsExtractor->setInput("objective", _objectiveGenerator->getOutput());
			subproblemsExtractor->setInput("linear constraints", _problemAssembler->getOutput("linear constraints"));
			subproblemsExtractor->setInput("problem configuration", _problemAssembler->getOutput("problem configuration"));

			subproblemsSolver->setInput(subproblemsExtractor->getOutput());

			// feed solution and segments to reconstructor
			_reconstructor->setInput("solution", subproblemsSolver->getOutput("solution"));
			_reconstructor->setInput("segments", _problemAssembler->getOutput("segments"));

		} else {

			// feed objective and linear constraints to ilp creator
			_linearSolver->setInput("objective", _objectiveGenerator->getOutput());
			_linearSolver->setInput("linear constraints", _problemAssembler->getOutput("linear constraints"));
			_linearSolver->setInput("parameters", boost::make_shared<LinearSolverParameters>(Binary));

			// feed solution and segments to reconstructor
			_reconstructor->setInput("solution", _linearSolver->getOutput("solution"));
			_reconstructor->setInput("segments", _problemAssembler->getOutput("segments"));
		}
	}

}

void
Sopnet::createTrainingPipeline() {

	LOG_DEBUG(sopnetlog) << "re-creating training part..." << std::endl;

	if (optionReadGoldStandardFromFile) {

		_goldStandardProvider->setInput("all segments", _problemAssembler->getOutput("segments"));

	} else {

		_goldStandardProvider->setInput("ground truth", _groundTruth);
		_goldStandardProvider->setInput("ground truth segments", _groundTruthExtractor->getOutput());
		_goldStandardProvider->setInput("all segments", _problemAssembler->getOutput("segments"));
		_goldStandardProvider->setInput("all linear constraints", _problemAssembler->getOutput("linear constraints"));
	}

	_segmentRfTrainer->setInput("positive samples", _goldStandardProvider->getOutput("gold standard"));
	_segmentRfTrainer->setInput("negative samples", _goldStandardProvider->getOutput("negative samples"));
	_segmentRfTrainer->setInput("features", _segmentFeaturesExtractor->getOutput("all features"));
}

void
Sopnet::createStructuredProblemPipeline() {

	LOG_DEBUG(sopnetlog) << "re-creating structured problem part..." << std::endl;

	_spWriter->setInput("linear constraints", _problemAssembler->getOutput("linear constraints"));
	_spWriter->setInput("problem configuration", _problemAssembler->getOutput("problem configuration"));
	_spWriter->setInput("features", _segmentFeaturesExtractor->getOutput("all features"));
	_spWriter->setInput("segments", _problemAssembler->getOutput("segments"));
	_spWriter->setInput("gold standard", _goldStandardProvider->getOutput("gold standard"));
	if (!optionReadGoldStandardFromFile) _spWriter->setInput("gold standard objective", _goldStandardProvider->getOutput("gold standard objective"));
}

void
Sopnet::writeStructuredProblem(std::string filename_labels, std::string filename_features, std::string filename_constraints) {

	LOG_DEBUG(sopnetlog) << "requested to write structured problem, updating inputs" << std::endl;

	updateInputs();

	LOG_DEBUG(sopnetlog) << "creating internal pipeline, if not created yet" << std::endl;

	createPipeline();

	LOG_DEBUG(sopnetlog) << "writing structured learning files" << std::endl;

	_spWriter->write(filename_labels, filename_features, filename_constraints);
}

void
Sopnet::createMinimalImpactTEDPipeline() {

	LOG_DEBUG(sopnetlog) << "re-creating minimal impact TED part..." << std::endl;

	// Set inputs to MinimalImpactTEDWriter
	_mitWriter->setInput("gold standard", _goldStandardProvider->getOutput("gold standard"));
	_mitWriter->setInput("ground truth", _groundTruth);
	_mitWriter->setInput("segments", _problemAssembler->getOutput("segments"));
	_mitWriter->setInput("linear constraints", _problemAssembler->getOutput("linear constraints"));
	_mitWriter->setInput("reference", _rawSections);
	_mitWriter->setInput("problem configuration", _problemAssembler->getOutput("problem configuration"));

}

void
Sopnet::writeMinimalImpactTEDCoefficients(std::string filename) {

	LOG_DEBUG(sopnetlog) << "requested to write minimal impact TED coefficients, updating inputs" << std::endl;

	updateInputs();

	LOG_DEBUG(sopnetlog) << "creating internal pipeline, if not created yet" << std::endl;

	createPipeline();

	LOG_DEBUG(sopnetlog) << "writing minimal impact TED coefficient files..." << std::endl;

	_mitWriter->write(filename);
}


text:
$(document).ready(function() {

	$('#agree-checkbox').change(function() {
		if($(this).is(':checked')) {
			$("#btn-create-paper").removeClass('disabled');
		} else {
			$("#btn-create-paper").addClass('disabled');
		}
	});
});


text:
//
//  PYCardViewController.m
//  Gank
//
//  Created by 谢培艺 on 2017/2/27.
//  Copyright © 2017年 CoderKo1o. All rights reserved.
//
#import "PYCardViewController.h"
#import "CardLayout.h"
#import "CardSelectedLayout.h"
#import "CardCellCollectionViewCell.h"
#import <MJRefresh/MJRefresh.h>
#import "PYRefreshHeader.h"
#import <AFNetworking/AFHTTPSessionManager.h>
#import "PYResource.h"
#import <MJExtension/MJExtension.h>
#import "CardCellCollectionViewCell.h"
#import "UIView+PYExtension.h"
#import "PYRefreshHeader.h"
#import "PYImage.h"
#import "PYHUD.h"
#import <AFNetworkReachabilityManager.h>

#define RGBAColor(r,g,b,a)  [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#define RGBColor(r,g,b)     RGBAColor(r,g,b,1.0)
#define RGBColorC(c)        RGBColor((((int)c) >> 16),((((int)c) >> 8) & 0xff),(((int)c) & 0xff))

static CGFloat collectionHeight;

@interface PYCardViewController ()<UICollectionViewDelegate,UICollectionViewDataSource, UIGestureRecognizerDelegate>

@property(nonatomic, strong)UICollectionView* cardCollectionView;
@property(nonatomic, strong)UICollectionViewLayout* cardLayout;
@property(nonatomic, strong)UICollectionViewLayout* cardLayoutStyle1;
@property(nonatomic, strong)UICollectionViewLayout* cardLayoutStyle2;
@property(nonatomic, strong)UITapGestureRecognizer* tapGesCollectionView;
@property (nonatomic, weak) CardCellCollectionViewCell *selectedCell;

/** 数组资源数组 */
@property (nonatomic, strong) NSMutableArray<NSArray *> *rescouceGroups;
/** 原数组的所有资源 */
@property (nonatomic, strong) NSMutableArray<PYResource *> *resources;
/** 当前页数 */
@property (nonatomic, assign) NSInteger currentPage;
/** 每次加载个数 */
@property (nonatomic, assign) NSInteger earchCount;

/** 网络加载失败提示 */
@property (nonatomic, strong) PYHUD *loadFailView;
/** 网络加载提示 */
@property (nonatomic, strong) PYHUD *loadingView;
/** 记录当前网络状态 */
@property (nonatomic, assign) AFNetworkReachabilityStatus currentNetworkStatus;

@end

@implementation PYCardViewController

- (NSMutableArray<NSArray *> *)rescouceGroups
{
    if (!_rescouceGroups) {
        _rescouceGroups = [NSMutableArray array];
        // 加载数据
        [self loadData:YES];
    }
    return _rescouceGroups;
}

- (PYHUD *)loadFailView
{
    if (!_loadFailView) {
        PYHUD *loadFailView = [[PYHUD alloc]initWithFrame:CGRectMake(15, 5, self.view.bounds.size.width - 10, self.view.bounds.size.height)];
        loadFailView.indicatorBackGroundColor = [UIColor clearColor];
        loadFailView.indicatorForegroundColor = self.typeColor;
        loadFailView.messageLabel.text = @"网络迷路了...\n快点我刷新下";
        loadFailView.backgroundColor = [UIColor whiteColor];
        loadFailView.customImage = [UIImage imageNamed:@"networkError"];
        __weak typeof(self) weakSelf = self;

        [loadFailView refreshWhenNwrworkError:^(PYHUD *hud) {
            [weakSelf loadData:self.resources.count == 0];
        }];
        _loadFailView = loadFailView;
    }
    return _loadFailView;
}

- (PYHUD *)loadingView
{
    if (!_loadingView) {
        PYHUD *loadingView = [[PYHUD alloc]initWithFrame:CGRectMake(15, 5, self.view.bounds.size.width - 10, self.view.bounds.size.height)];
        loadingView.indicatorBackGroundColor = [UIColor clearColor];
        loadingView.indicatorForegroundColor = self.typeColor;
        loadingView.messageLabel.text = nil;
        loadingView.backgroundColor = [UIColor whiteColor];
        _loadingView = loadingView;
    }
    return _loadingView;
}

- (NSInteger)earchCount
{
    if (_earchCount == 0) {
        if ([self.resourceType isEqualToString:@"iOS"]) { // 加载25条数据
            _earchCount = 25;
        } else if ([self.resourceType isEqualToString:@"Android"]) { // 加载40条
            _earchCount = 40;
        } else { // 加载15条
            _earchCount = 15;
        }
    }
    return _earchCount;
}

/** 加载数据 */
- (void)loadData:(BOOL)refresh
{
    [self.loadingView showAtView:self.view hudType:JHUDLoadingTypeDot];
    self.currentPage = refresh ? 1 : self.currentPage + 1;
    // 请求数据
    AFHTTPSessionManager *HTTPManager = [AFHTTPSessionManager manager];
    NSString *urlStr = [NSString stringWithFormat:@"http://gank.io/api/data/%@/%zd/%zd", self.resourceType, self.earchCount, self.currentPage];
    NSString *encodedString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 显示加载
    if (self.resources.count == 0) {
        self.resources = [NSMutableArray array];
    }
    [self.loadFailView hide];
    [HTTPManager GET:encodedString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) { // 请求成功
        // 取出数组
        NSArray *results = responseObject[@"results"];
        if (results.count == 0) return;
        // 转化成模型
        NSArray *resources = [PYResource mj_objectArrayWithKeyValuesArray:results];
        [self.resources addObjectsFromArray:resources];
        NSInteger originalDays = self.rescouceGroups.count;
        self.rescouceGroups = [NSMutableArray arrayWithArray:[self resourceByDay:self.resources]];

        // 根据原图获取其他信息
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        __block NSInteger imageCount = 0;
        for (PYResource *resource in self.resources) {
            if (resource.images.count == 0) continue;
            imageCount++;
            NSMutableArray *tempM = [NSMutableArray array];
            for (NSString *imageUrl in resource.images) {
                PYImage *imageModel = [[PYImage alloc] init];
                [mgr GET:[NSString stringWithFormat:@"%@?imageInfo", imageUrl] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
                    imageCount--;
                    // 缩略图地址
                    imageModel.thumbUrl = [NSString stringWithFormat:@"%@?imageView2/0/w/400/format/png", imageUrl];
                    // 获取其他图片信息
                    imageModel.width = [responseObject[@"width"] floatValue];
                    imageModel.height = [responseObject[@"height"] floatValue];
                    imageModel.url = [NSString stringWithFormat:@"%@?imageView2/0/w/%d", imageUrl, (int)(PYScreenW * [[UIScreen mainScreen] scale] * 1.5)];
                    [tempM addObject:imageModel];
                    resource.imageModels = [tempM copy];
                    if (imageCount == 0) { // 所有图片加载完成
                        if (_rescouceGroups.count > 0) {
                            [self.loadingView hide];
                            [self.loadFailView hide];
                            [self.cardCollectionView reloadData];
                            CGFloat offsetY = refresh ? _rescouceGroups.count * 140 : ((_rescouceGroups.count - originalDays)) * 140;
                            [self.cardCollectionView setContentOffset:CGPointMake(0, offsetY)];
                        }
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                }];
            }
        }
        if (_rescouceGroups.count > 0 && imageCount == 0) { // 没有图片
            [self.loadFailView hide];
            [self.loadingView hide];
            [self.cardCollectionView reloadData];
            CGFloat offsetY = refresh ? _rescouceGroups.count * 140 : ((_rescouceGroups.count - originalDays)) * 140;
            [self.cardCollectionView setContentOffset:CGPointMake(0, offsetY)];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        self.currentPage --;
        [self.loadingView hide];
        [self.loadFailView showAtView:self.view hudType:JHUDLoadingTypeCustomAnimations];
    }];
}

- (NSArray *)resourceByDay:(NSArray *)resourceArray
{
    //首先把原数组中数据的日期取出来放入timeArr
    NSMutableArray *timeArr = [NSMutableArray array];
    for (PYResource *resource in resourceArray) {
        [timeArr addObject:[resource.publishedAt substringToIndex:@"yyyy-MM-dd".length]];
    }
    //使用asset把timeArr的日期去重
    NSSet *set = [NSSet setWithArray:timeArr];
    NSArray *userArray = [set allObjects];
    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO]; // yes升序排列,no,降序排列
    //按日期降序排列的日期数组
    NSArray *myary = [userArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
    //此时得到的myary就是按照时间降序排列拍好的数组
    NSMutableArray *resultArray = [NSMutableArray array];
    int currentIndex = 0;
    for (int i = 0; i < myary.count; i++) {
        // 取出日期
        NSString *dateStr = myary[i];
        // 临时数组
        NSMutableArray *tempArr = [NSMutableArray array];
        for (int j = currentIndex; j < resourceArray.count; j++) {
            // 取出日期
            PYResource *resource = resourceArray[j];
            NSString *originalDateStr = resource.publishedAt;
            if ([originalDateStr containsString:dateStr]) { // 同一天
                [tempArr addObject:resource];
            } else { // 进到下一天
                currentIndex = j;
                break; // 跳出循环
            }
        }
        // 保存数组
        [resultArray addObject:[tempArr copy]];
    }
    // 遍历后的数组
    return resultArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    collectionHeight = self.view.bounds.size.height;
    self.cardLayoutStyle1 =  [[CardLayout alloc] initWithOffsetY:collectionHeight * 15];
    self.cardLayout = self.cardLayoutStyle1;
    [self.view addSubview:self.cardCollectionView];
    self.cardCollectionView.contentInset = UIEdgeInsetsMake(-350, 0, 0, 0);
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.rescouceGroups.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CardCellCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];
    cell.resouces = self.rescouceGroups[self.rescouceGroups.count - 1 - indexPath.row];
    // 设置背景色
    cell.bgColor = [self getGameColor:self.rescouceGroups.count - 1 - indexPath.row];
    return cell;
}

-(UIColor*)getGameColor:(NSInteger)index
{
    NSArray* colorList = @[RGBColorC(0xfb742a),RGBColorC(0xfcc42d),RGBColorC(0x29c26d),RGBColorC(0xfaa20a),RGBColorC(0x5e64d9),RGBColorC(0x6d7482),RGBColorC(0x54b1ff),RGBColorC(0xe2c179),RGBColorC(0x9973e5),RGBColorC(0x61d4ff)];
    UIColor* color = [colorList objectAtIndex:(index%10)];
    return color;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CardCellCollectionViewCell *selectedCell = (CardCellCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    self.selectedCell = selectedCell;

    selectedCell.tableView.userInteractionEnabled = YES;
    CGFloat offsetY = self.cardCollectionView.contentOffset.y;
    if ([self.cardLayout isKindOfClass:[CardLayout class]]) {
        if (!self.cardLayoutStyle2) {
            self.cardLayoutStyle2 =  [[CardSelectedLayout alloc]initWithIndexPath:indexPath offsetY:offsetY ContentSizeHeight:((CardLayout*)self.cardLayout).contentSizeHeight];
            self.cardLayout = self.cardLayoutStyle2;
        }
        else
        {
            ((CardSelectedLayout*)self.cardLayoutStyle2).contentOffsetY = offsetY;
            ((CardSelectedLayout*)self.cardLayoutStyle2).contentSizeHeight = ((CardLayout*)self.cardLayout).contentSizeHeight;
            ((CardSelectedLayout*)self.cardLayoutStyle2).selectedIndexPath = indexPath;
            self.cardLayout = self.cardLayoutStyle2;
        }
        self.cardCollectionView.scrollEnabled = NO;
        [self showMaskView]; //显示背景浮层
    }
    else
    {
        if (!self.cardLayoutStyle1) {
            self.cardLayoutStyle1 =  [[CardLayout alloc]initWithOffsetY:offsetY];
            self.cardLayout = self.cardLayoutStyle1;
        }
        else
        {
            ((CardLayout*)self.cardLayoutStyle1).offsetY = offsetY;
            self.cardLayout = self.cardLayoutStyle1;
        }
        self.cardCollectionView.scrollEnabled = YES;
        [self hideMaskView];
    }
    [self.cardCollectionView setCollectionViewLayout:self.cardLayout animated:YES];
}

-(void)showMaskView
{
    self.cardCollectionView.backgroundColor = [UIColor whiteColor];
    [self.cardCollectionView addGestureRecognizer:self.tapGesCollectionView];
}

-(void)hideMaskView
{
    self.cardCollectionView.backgroundColor = [UIColor whiteColor];
    [self.cardCollectionView removeGestureRecognizer:self.tapGesCollectionView];
}

-(void)tapOnBackGround
{
    self.selectedCell.tableView.userInteractionEnabled = NO;
    self.selectedCell.tableView.contentOffset = CGPointZero;
    CGFloat offsetY = self.cardCollectionView.contentOffset.y;

    if ([self.cardLayout isKindOfClass:[CardLayout class]]) {

    } else {
        if (!self.cardLayoutStyle1) {
            self.cardLayoutStyle1 =  [[CardLayout alloc]initWithOffsetY:offsetY];
            self.cardLayout = self.cardLayoutStyle1;
        } else {
            ((CardLayout*)self.cardLayoutStyle1).offsetY = offsetY;
            self.cardLayout = self.cardLayoutStyle1;
        }
        self.cardCollectionView.scrollEnabled = YES;
        [self.cardCollectionView removeGestureRecognizer:self.tapGesCollectionView];
    }
    [self.cardCollectionView setCollectionViewLayout:self.cardLayout animated:YES];
}

-(UITapGestureRecognizer*)tapGesCollectionView
{
    if (!_tapGesCollectionView) {
        _tapGesCollectionView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapOnBackGround)];
        _tapGesCollectionView.delegate = self;
    }
    return _tapGesCollectionView;
}

-(UICollectionView*)cardCollectionView
{
    if (!_cardCollectionView) {
        _cardCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, 0 , self.view.bounds.size.width - 10, self.view.bounds.size.height) collectionViewLayout:self.cardLayout];
        _cardCollectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _cardCollectionView.layer.cornerRadius = 5;
        [_cardCollectionView registerClass:[CardCellCollectionViewCell class] forCellWithReuseIdentifier:@"cardCell"];
        _cardCollectionView.delegate = self;
        _cardCollectionView.dataSource = self;
        _cardCollectionView.backgroundColor = [UIColor whiteColor];
        _cardCollectionView.showsVerticalScrollIndicator = NO;
        _cardCollectionView.showsHorizontalScrollIndicator = NO;
    }
    return _cardCollectionView;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if ((*targetContentOffset).y == -scrollView.contentInset.top && scrollView.contentOffset.y + 50 < (*targetContentOffset).y) { // 进入刷新状态
        [self loadData:self.resources.count == 0];
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    // 若为UITableViewCellContentView(即点击了tableViewCell),则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}

@end


text:
{{extend 'layout_admin.html'}}
{{block conteudo}}

Sobre Projeto:

    {{=form}}

{{end}}


text:
/* Generated By:JJTree: Do not edit this line. ASTTriplesSameSubject.java */

package org.eclipse.rdf4j.query.parser.sparql.ast;

public class ASTTriplesSameSubject extends SimpleNode {

	public ASTTriplesSameSubject(int id) {
		super(id);
	}

	public ASTTriplesSameSubject(SyntaxTreeBuilder p, int id) {
		super(p, id);
	}

	@Override
	public Object jjtAccept(SyntaxTreeBuilderVisitor visitor, Object data) throws VisitorException {
		return visitor.visit(this, data);
	}
}


text:
Thneed *g_thneed = NULL;
int g_fd = -1;

void hexdump(uint8_t *d, int len) {
  assert((len%4) == 0);
  printf("  dumping %p len 0x%x\n", d, len);
  for (int i = 0; i < len/4; i++) {
    if (i != 0 && (i%0x10) == 0) printf("\n");
    printf("%8x ", d[i]);
  }
  printf("\n");
}

// *********** ioctl interceptor ***********

extern "C" {

int (*my_ioctl)(int filedes, unsigned long request, void *argp) = NULL;
#undef ioctl
int ioctl(int filedes, unsigned long request, void *argp) {
  request &= 0xFFFFFFFF;  // needed on QCOM2
  if (my_ioctl == NULL) my_ioctl = reinterpret_cast<decltype(my_ioctl)>(dlsym(RTLD_NEXT, "ioctl"));
  Thneed *thneed = g_thneed;

  // save the fd
  if (request == IOCTL_KGSL_GPUOBJ_ALLOC) g_fd = filedes;

  // note that this runs always, even without a thneed object
  if (request == IOCTL_KGSL_DRAWCTXT_CREATE) {
    struct kgsl_drawctxt_create *create = (struct kgsl_drawctxt_create *)argp;
    create->flags &= ~KGSL_CONTEXT_PRIORITY_MASK;
    create->flags |= 1 << KGSL_CONTEXT_PRIORITY_SHIFT;   // priority from 1-15, 1 is max priority
    printf("IOCTL_KGSL_DRAWCTXT_CREATE: creating context with flags 0x%x\n", create->flags);
  }

  if (thneed != NULL) {
    if (request == IOCTL_KGSL_GPU_COMMAND) {
      struct kgsl_gpu_command *cmd = (struct kgsl_gpu_command *)argp;
      if (thneed->record) {
        thneed->timestamp = cmd->timestamp;
        thneed->context_id = cmd->context_id;
        thneed->cmds.push_back(unique_ptr<CachedCommand>(new CachedCommand(thneed, cmd)));
      }
      if (thneed->debug >= 1) {
        printf("IOCTL_KGSL_GPU_COMMAND(%2zu): flags: 0x%lx    context_id: %u  timestamp: %u  numcmds: %d  numobjs: %d\n",
            thneed->cmds.size(),
            cmd->flags,
            cmd->context_id, cmd->timestamp, cmd->numcmds, cmd->numobjs);
      }
    } else if (request == IOCTL_KGSL_GPUOBJ_SYNC) {
      struct kgsl_gpuobj_sync *cmd = (struct kgsl_gpuobj_sync *)argp;
      struct kgsl_gpuobj_sync_obj *objs = (struct kgsl_gpuobj_sync_obj *)(cmd->objs);

      if (thneed->debug >= 2) {
        printf("IOCTL_KGSL_GPUOBJ_SYNC count:%d ", cmd->count);
        for (int i = 0; i < cmd->count; i++) {
          printf(" -- offset:0x%lx len:0x%lx id:%d op:%d  ", objs[i].offset, objs[i].length, objs[i].id, objs[i].op);
        }
        printf("\n");
      }

      if (thneed->record) {
        thneed->cmds.push_back(unique_ptr<CachedSync>(new
              CachedSync(thneed, string((char *)objs, sizeof(struct kgsl_gpuobj_sync_obj)*cmd->count))));
      }
    } else if (request == IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID) {
      struct kgsl_device_waittimestamp_ctxtid *cmd = (struct kgsl_device_waittimestamp_ctxtid *)argp;
      if (thneed->debug >= 1) {
        printf("IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: context_id: %d  timestamp: %d  timeout: %d\n",
            cmd->context_id, cmd->timestamp, cmd->timeout);
      }
    } else if (request == IOCTL_KGSL_SETPROPERTY) {
      if (thneed->debug >= 1) {
        struct kgsl_device_getproperty *prop = (struct kgsl_device_getproperty *)argp;
        printf("IOCTL_KGSL_SETPROPERTY: 0x%x sizebytes:%zu\n", prop->type, prop->sizebytes);
        if (thneed->debug >= 2) {
          hexdump((uint8_t *)prop->value, prop->sizebytes);
          if (prop->type == KGSL_PROP_PWR_CONSTRAINT) {
            struct kgsl_device_constraint *constraint = (struct kgsl_device_constraint *)prop->value;
            hexdump((uint8_t *)constraint->data, constraint->size);
          }
        }
      }
    } else if (request == IOCTL_KGSL_DRAWCTXT_CREATE || request == IOCTL_KGSL_DRAWCTXT_DESTROY) {
      // this happens
    } else if (request == IOCTL_KGSL_GPUOBJ_ALLOC || request == IOCTL_KGSL_GPUOBJ_FREE) {
      // this happens
    } else {
      if (thneed->debug >= 1) {
        printf("other ioctl %lx\n", request);
      }
    }
  }

  int ret = my_ioctl(filedes, request, argp);
  if (ret != 0) printf("ioctl returned %d with errno %d\n", ret, errno);
  return ret;
}

}

// *********** GPUMalloc ***********

GPUMalloc::GPUMalloc(int size, int fd) {
  struct kgsl_gpuobj_alloc alloc;
  memset(&alloc, 0, sizeof(alloc));
  alloc.size = size;
  alloc.flags = 0x10000a00;
  ioctl(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc);
  void *addr = mmap64(NULL, alloc.mmapsize, 0x3, 0x1, fd, alloc.id*0x1000);
  assert(addr != MAP_FAILED);

  base = (uint64_t)addr;
  remaining = size;
}

GPUMalloc::~GPUMalloc() {
  // TODO: free the GPU malloced area
}

void *GPUMalloc::alloc(int size) {
  void *ret = (void*)base;
  size = (size+0xff) & (~0xFF);
  assert(size <= remaining);
  remaining -= size;
  base += size;
  return ret;
}

// *********** CachedSync, at the ioctl layer ***********

void CachedSync::exec() {
  struct kgsl_gpuobj_sync cmd;

  cmd.objs = (uint64_t)data.data();
  cmd.obj_len = data.length();
  cmd.count = data.length() / sizeof(struct kgsl_gpuobj_sync_obj);

  int ret = ioctl(thneed->fd, IOCTL_KGSL_GPUOBJ_SYNC, &cmd);
  assert(ret == 0);
}

// *********** CachedCommand, at the ioctl layer ***********

CachedCommand::CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd) {
  thneed = lthneed;
  assert(cmd->numsyncs == 0);

  memcpy(&cache, cmd, sizeof(cache));

  if (cmd->numcmds > 0) {
    cmds = make_unique<struct kgsl_command_object[]>(cmd->numcmds);
    memcpy(cmds.get(), (void *)cmd->cmdlist, sizeof(struct kgsl_command_object)*cmd->numcmds);
    cache.cmdlist = (uint64_t)cmds.get();
    for (int i = 0; i < cmd->numcmds; i++) {
      void *nn = thneed->ram->alloc(cmds[i].size);
      memcpy(nn, (void*)cmds[i].gpuaddr, cmds[i].size);
      cmds[i].gpuaddr = (uint64_t)nn;
    }
  }

  if (cmd->numobjs > 0) {
    objs = make_unique<struct kgsl_command_object[]>(cmd->numobjs);
    memcpy(objs.get(), (void *)cmd->objlist, sizeof(struct kgsl_command_object)*cmd->numobjs);
    cache.objlist = (uint64_t)objs.get();
    for (int i = 0; i < cmd->numobjs; i++) {
      void *nn = thneed->ram->alloc(objs[i].size);
      memset(nn, 0, objs[i].size);
      objs[i].gpuaddr = (uint64_t)nn;
    }
  }

  kq = thneed->ckq;
  thneed->ckq.clear();
}

void CachedCommand::exec() {
  cache.timestamp = ++thneed->timestamp;
  int ret = ioctl(thneed->fd, IOCTL_KGSL_GPU_COMMAND, &cache);

  if (thneed->debug >= 1) printf("CachedCommand::exec got %d\n", ret);

  if (thneed->debug >= 2) {
    for (auto &it : kq) {
      it->debug_print(false);
    }
  }

  assert(ret == 0);
}

// *********** Thneed ***********

Thneed::Thneed(bool do_clinit, cl_context _context) {
  // TODO: QCOM2 actually requires a different context
  //context = _context;
  if (do_clinit) clinit();
  assert(g_fd != -1);
  fd = g_fd;
  ram = make_unique<GPUMalloc>(0x80000, fd);
  timestamp = -1;
  g_thneed = this;
  char *thneed_debug_env = getenv("THNEED_DEBUG");
  debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0;
}

void Thneed::wait() {
  struct kgsl_device_waittimestamp_ctxtid wait;
  wait.context_id = context_id;
  wait.timestamp = timestamp;
  wait.timeout = -1;

  uint64_t tb = nanos_since_boot();
  int wret = ioctl(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait);
  uint64_t te = nanos_since_boot();

  if (debug >= 1) printf("wait %d after %lu us\n", wret, (te-tb)/1000);
}

void Thneed::execute(float **finputs, float *foutput, bool slow) {
  uint64_t tb, te;
  if (debug >= 1) tb = nanos_since_boot();

  // ****** copy inputs
  copy_inputs(finputs, true);

  // ****** set power constraint
  int ret;
  struct kgsl_device_constraint_pwrlevel pwrlevel;
  pwrlevel.level = KGSL_CONSTRAINT_PWR_MAX;

  struct kgsl_device_constraint constraint;
  constraint.type = KGSL_CONSTRAINT_PWRLEVEL;
  constraint.context_id = context_id;
  constraint.data = (void*)&pwrlevel;
  constraint.size = sizeof(pwrlevel);

  struct kgsl_device_getproperty prop;
  prop.type = KGSL_PROP_PWR_CONSTRAINT;
  prop.value = (void*)&constraint;
  prop.sizebytes = sizeof(constraint);
  ret = ioctl(fd, IOCTL_KGSL_SETPROPERTY, &prop);
  assert(ret == 0);

  // ****** run commands
  int i = 0;
  for (auto &it : cmds) {
    ++i;
    if (debug >= 1) printf("run %2d @ %7lu us: ", i, (nanos_since_boot()-tb)/1000);
    it->exec();
    if ((i == cmds.size()) || slow) wait();
  }

  // ****** copy outputs
  copy_output(foutput);

  // ****** unset power constraint
  constraint.type = KGSL_CONSTRAINT_NONE;
  constraint.data = NULL;
  constraint.size = 0;

  ret = ioctl(fd, IOCTL_KGSL_SETPROPERTY, &prop);
  assert(ret == 0);

  if (debug >= 1) {
    te = nanos_since_boot();
    printf("model exec in %lu us\n", (te-tb)/1000);
  }
}