text:
package org.hisp.dhis.android.sdk.core.controllers;

import com.fasterxml.jackson.databind.JsonNode;

import org.hisp.dhis.android.sdk.core.controllers.common.ResourceController;
import org.hisp.dhis.android.sdk.core.controllers.common.StringConverter;
import org.hisp.dhis.android.sdk.core.network.APIException;
import org.hisp.dhis.android.sdk.core.network.IDhisApi;
import org.hisp.dhis.android.sdk.core.preferences.DateTimeManager;
import org.hisp.dhis.android.sdk.core.models.ResourceType;
import org.hisp.dhis.android.sdk.core.providers.ObjectMapperProvider;
import org.hisp.dhis.android.sdk.models.organisationunit.IOrganisationUnitStore;
import org.hisp.dhis.android.sdk.models.organisationunit.OrganisationUnit;
import org.hisp.dhis.android.sdk.models.program.IProgramStore;
import org.hisp.dhis.android.sdk.models.program.Program;
import org.joda.time.DateTime;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import retrofit.client.Response;
import retrofit.converter.ConversionException;

import static org.hisp.dhis.android.sdk.models.common.base.BaseIdentifiableObject.toMap;

public final class AssignedProgramsController extends ResourceController<Program> {

    private final static String ORGANISATIONUNITS = "organisationUnits";
    private final static String PROGRAMS = "programs";
    private final static String ID = "id";

    private final IDhisApi mDhisApi;
    private final IProgramController programController;
    private final IOrganisationUnitController organisationUnitController;

    private final IOrganisationUnitStore organisationUnitStore;
    private final IProgramStore programStore;

    public AssignedProgramsController(IDhisApi dhisApi, IProgramController programController,
                                      IOrganisationUnitController organisationUnitController,
                                      IOrganisationUnitStore organisationUnitStore, IProgramStore programStore) {
        mDhisApi = dhisApi;
        this.programController = programController;
        this.organisationUnitController = organisationUnitController;
        this.organisationUnitStore = organisationUnitStore;
        this.programStore = programStore;
    }

    private void getAssignedProgramsDataFromServer() throws APIException {
        DateTime serverTime = mDhisApi.getSystemInfo().getServerDate();
        DateTime lastUpdated = DateTimeManager.getInstance()
                .getLastUpdated(ResourceType.ASSIGNEDPROGRAMS);
        Response response = mDhisApi.getAssignedPrograms(getAllFieldsQueryMap(lastUpdated));

        List<OrganisationUnit> organisationUnits = new ArrayList<>();
        Map<OrganisationUnit, List<String>> organisationUnitPrograms = new HashMap<>();
        Map<String, List<String>> programOrganisationUnits = new HashMap<>();
        String responseBodyString = "";
        try {
            responseBodyString = new StringConverter().fromBody(response.getBody(), String.class);
        } catch (ConversionException e) {
            e.printStackTrace();
            return; //todo: handle
        }

        JsonNode node;
        try {
            node = ObjectMapperProvider.getInstance().
                    readTree(responseBodyString);
        } catch (IOException e) {
            node = null;
        }

        //manual deserialization of the /me/programs node for organisationUnits with programAssignments
        if (node != null) {
            JsonNode organisationUnitsNode = node.get(ORGANISATIONUNITS);
            if (organisationUnitsNode != null) { //may be null if there are no org units.
                Iterator<JsonNode> nodes = organisationUnitsNode.elements();
                List<String> programsToLoad = new ArrayList<>();
                while (nodes.hasNext()) {
                    JsonNode organisationUnitNode = nodes.next();
                    OrganisationUnit item;
                    try {
                        item = ObjectMapperProvider.getInstance().
                                readValue(organisationUnitNode.toString(), OrganisationUnit.class);
                    } catch (IOException e) {
                        item = null;
                    }
                    if (item != null) {
                        organisationUnits.add(item);
                        organisationUnitPrograms.put(item, new ArrayList<String>());
                        JsonNode programsNode = organisationUnitNode.get(PROGRAMS);

                        //Getting the program assignments for the current organisation unit
                        if (programsNode != null) {
                            Iterator<JsonNode> programsNodeIterator = programsNode.elements();
                            while (programsNodeIterator.hasNext()) {
                                JsonNode programNode = programsNodeIterator.next();
                                String programUid = programNode.get(ID).textValue();
                                List<String> organisationUnitsForProgram = programOrganisationUnits.get(programUid);
                                if (organisationUnitsForProgram == null) {
                                    organisationUnitsForProgram = new ArrayList<>();
                                    programOrganisationUnits.put(programUid, organisationUnitsForProgram);
                                }
                                organisationUnitsForProgram.add(item.getUId());

                                if (!programsToLoad.contains(programUid)) {
                                    programsToLoad.add(programUid);
                                }
                            }
                        }
                    }
                }
                //Load the programs and organisation units from server with full data
                programController.sync(programsToLoad);
                organisationUnitController.sync(organisationUnits);
            }
        }
        organisationUnits = organisationUnitStore.queryAll();
        List<Program> programs = programStore.queryAll();
        Map<String, OrganisationUnit> organisationUnitMap = toMap(organisationUnits);
        for (Program program : programs) {
            List<OrganisationUnit> organisationUnitsAssigned = new ArrayList<>();
            for (String organisationUnitId : programOrganisationUnits.get(program.getUId())) {
                organisationUnitsAssigned.add(organisationUnitMap.get(organisationUnitId));
            }
            programStore.assign(program, organisationUnitsAssigned);
        }

        DateTimeManager.getInstance()
                .setLastUpdated(ResourceType.ASSIGNEDPROGRAMS, serverTime);
    }

    @Override
    public void sync() throws APIException {
        getAssignedProgramsDataFromServer();
    }
}


text:
cmake_policy(SET CMP0007 NEW)

# arguments checking
if (NOT TEST_PROGRAM)
  message (FATAL_ERROR "Require TEST_PROGRAM to be defined")
endif (NOT TEST_PROGRAM)
#if (NOT TEST_ARGS)
#  message (STATUS "Require TEST_ARGS to be defined")
#endif (NOT TEST_ARGS)
if (NOT TEST_FOLDER)
  message ( FATAL_ERROR "Require TEST_FOLDER to be defined")
endif (NOT TEST_FOLDER)
if (NOT TEST_OUTPUT)
  message (FATAL_ERROR "Require TEST_OUTPUT to be defined")
endif (NOT TEST_OUTPUT)
if (NOT TEST_EXPECT)
  message (STATUS "Require TEST_EXPECT to be defined")
endif (NOT TEST_EXPECT)
#if (NOT TEST_FILTER)
#  message (STATUS "Require TEST_FILTER to be defined")
#endif (NOT TEST_FILTER)
if (NOT TEST_SKIP_COMPARE AND NOT TEST_REFERENCE)
  message (FATAL_ERROR "Require TEST_REFERENCE to be defined")
endif (NOT TEST_SKIP_COMPARE AND NOT TEST_REFERENCE)

# if there is not an error reference file add the error output to the stdout file
if (NOT TEST_ERRREF)
  set (ERROR_APPEND 1)
endif (NOT TEST_ERRREF)

message (STATUS "COMMAND: ${TEST_PROGRAM} ${TEST_ARGS}")

if (TEST_ENV_VAR)
  set (ENV{${TEST_ENV_VAR}} "${TEST_ENV_VALUE}")
endif (TEST_ENV_VAR)

if (NOT TEST_INPUT)
  # run the test program, capture the stdout/stderr and the result var
  execute_process (
      COMMAND ${TEST_PROGRAM} ${TEST_ARGS}
      WORKING_DIRECTORY ${TEST_FOLDER}
      RESULT_VARIABLE TEST_RESULT
      OUTPUT_FILE ${TEST_OUTPUT}
      ERROR_FILE ${TEST_OUTPUT}.err
      OUTPUT_VARIABLE TEST_OUT
      ERROR_VARIABLE TEST_ERROR
  )
else (NOT TEST_INPUT)
  # run the test program with stdin, capture the stdout/stderr and the result var
  execute_process (
      COMMAND ${TEST_PROGRAM} ${TEST_ARGS}
      WORKING_DIRECTORY ${TEST_FOLDER}
      RESULT_VARIABLE TEST_RESULT
      INPUT_FILE ${TEST_INPUT}
      OUTPUT_FILE ${TEST_OUTPUT}
      ERROR_FILE ${TEST_OUTPUT}.err
      OUTPUT_VARIABLE TEST_OUT
      ERROR_VARIABLE TEST_ERROR
  )
endif (NOT TEST_INPUT)

message (STATUS "COMMAND Result: ${TEST_RESULT}")

# if the .err file exists and ERRROR_APPEND is enabled
if (ERROR_APPEND AND EXISTS ${TEST_FOLDER}/${TEST_OUTPUT}.err)
  file (READ ${TEST_FOLDER}/${TEST_OUTPUT}.err TEST_STREAM)
  file (APPEND ${TEST_FOLDER}/${TEST_OUTPUT} "${TEST_STREAM}")
endif (ERROR_APPEND AND EXISTS ${TEST_FOLDER}/${TEST_OUTPUT}.err)

# append the test result status with a predefined text
if (TEST_APPEND)
  file (APPEND ${TEST_FOLDER}/${TEST_OUTPUT} "${TEST_APPEND} ${TEST_RESULT}\n")
endif (TEST_APPEND)

# if the return value is !=${TEST_EXPECT} bail out
if (NOT ${TEST_RESULT} STREQUAL ${TEST_EXPECT})
  message ( FATAL_ERROR "Failed: Test program ${TEST_PROGRAM} exited != ${TEST_EXPECT}.\n${TEST_ERROR}")
endif (NOT ${TEST_RESULT} STREQUAL ${TEST_EXPECT})

message (STATUS "COMMAND Error: ${TEST_ERROR}")

# if the output file needs Storage text removed
if (TEST_MASK)
  file (READ ${TEST_FOLDER}/${TEST_OUTPUT} TEST_STREAM)
   string (REGEX REPLACE "Storage:[^\n]+\n" "Storage:   <details removed for portability>\n" TEST_STREAM "${TEST_STREAM}")
  file (WRITE ${TEST_FOLDER}/${TEST_OUTPUT} "${TEST_STREAM}")
endif (TEST_MASK)

# if the output file needs Modified text removed
if (TEST_MASK_MOD)
  file (READ ${TEST_FOLDER}/${TEST_OUTPUT} TEST_STREAM)
   string (REGEX REPLACE "Modified:[^\n]+\n" "Modified:  XXXX-XX-XX XX:XX:XX XXX\n" TEST_STREAM "${TEST_STREAM}")
  file (WRITE ${TEST_FOLDER}/${TEST_OUTPUT} "${TEST_STREAM}")
endif (TEST_MASK_MOD)

# if the output file or the .err file needs to mask out error stack info
if (TEST_MASK_ERROR)
  if (NOT TEST_ERRREF)
    # the error stack has been appended to the output file
    file (READ ${TEST_FOLDER}/${TEST_OUTPUT} TEST_STREAM)
  else ()
    # the error stack remains in the .err file
    file (READ ${TEST_FOLDER}/${TEST_OUTPUT}.err TEST_STREAM)
  endif ()
  string (REGEX REPLACE "thread [0-9]*:" "thread (IDs):" TEST_STREAM "${TEST_STREAM}")
  string (REGEX REPLACE ": ([^\n]*)[.]c " ": (file name) " TEST_STREAM "${TEST_STREAM}")
  string (REGEX REPLACE " line [0-9]*" " line (number)" TEST_STREAM "${TEST_STREAM}")
  string (REGEX REPLACE "v[1-9]*[.][0-9]*[.]" "version (number)." TEST_STREAM "${TEST_STREAM}")
  string (REGEX REPLACE "[1-9]*[.][0-9]*[.][0-9]*[^)]*" "version (number)" TEST_STREAM "${TEST_STREAM}")
  string (REGEX REPLACE "H5Eget_auto[1-2]*" "H5Eget_auto(1 or 2)" TEST_STREAM "${TEST_STREAM}")
  string (REGEX REPLACE "H5Eset_auto[1-2]*" "H5Eset_auto(1 or 2)" TEST_STREAM "${TEST_STREAM}")
  # write back the changes to the original files
  if (NOT TEST_ERRREF)
    file (WRITE ${TEST_FOLDER}/${TEST_OUTPUT} "${TEST_STREAM}")
  else ()
    file (WRITE ${TEST_FOLDER}/${TEST_OUTPUT}.err "${TEST_STREAM}")
  endif ()
endif (TEST_MASK_ERROR)

# remove text from the output file
if (TEST_FILTER)
  file (READ ${TEST_FOLDER}/${TEST_OUTPUT} TEST_STREAM)
  string (REGEX REPLACE "${TEST_FILTER}" "" TEST_STREAM "${TEST_STREAM}")
  file (WRITE ${TEST_FOLDER}/${TEST_OUTPUT} "${TEST_STREAM}")
endif (TEST_FILTER)

# compare output files to references unless this must be skipped
if (NOT TEST_SKIP_COMPARE)
  if (WIN32 AND NOT MINGW)
    file (READ ${TEST_FOLDER}/${TEST_REFERENCE} TEST_STREAM)
    file (WRITE ${TEST_FOLDER}/${TEST_REFERENCE} "${TEST_STREAM}")
  endif (WIN32 AND NOT MINGW)

  # now compare the output with the reference
  execute_process (
      COMMAND ${CMAKE_COMMAND} -E compare_files ${TEST_FOLDER}/${TEST_OUTPUT} ${TEST_FOLDER}/${TEST_REFERENCE}
      RESULT_VARIABLE TEST_RESULT
  )
  if (NOT ${TEST_RESULT} STREQUAL 0)
  set (TEST_RESULT 0)
  file (STRINGS ${TEST_FOLDER}/${TEST_OUTPUT} test_act)
  list (LENGTH test_act len_act)
  file (STRINGS ${TEST_FOLDER}/${TEST_REFERENCE} test_ref)
  list (LENGTH test_ref len_ref)
  if (NOT ${len_act} STREQUAL "0")
    math (EXPR _FP_LEN "${len_ref} - 1")
    foreach (line RANGE 0 ${_FP_LEN})
      list (GET test_act ${line} str_act)
      list (GET test_ref ${line} str_ref)
      if (NOT "${str_act}" STREQUAL "${str_ref}")
        if (NOT "${str_act}" STREQUAL "")
          set (TEST_RESULT 1)
          message ("line = ${line}\n***ACTUAL: ${str_act}\n****REFER: ${str_ref}\n")
         endif (NOT "${str_act}" STREQUAL "")
      endif (NOT "${str_act}" STREQUAL "${str_ref}")
    endforeach (line RANGE 0 ${_FP_LEN})
  endif (NOT ${len_act} STREQUAL "0")
  if (NOT ${len_act} STREQUAL ${len_ref})
    set (TEST_RESULT 1)
  endif (NOT ${len_act} STREQUAL ${len_ref})
  endif (NOT ${TEST_RESULT} STREQUAL 0)

  message (STATUS "COMPARE Result: ${TEST_RESULT}")

  # again, if return value is !=0 scream and shout
  if (NOT ${TEST_RESULT} STREQUAL 0)
    message (FATAL_ERROR "Failed: The output of ${TEST_OUTPUT} did not match ${TEST_REFERENCE}")
  endif (NOT ${TEST_RESULT} STREQUAL 0)

  # now compare the .err file with the error reference, if supplied
  if (TEST_ERRREF)
    if (WIN32 AND NOT MINGW)
      file (READ ${TEST_FOLDER}/${TEST_ERRREF} TEST_STREAM)
      file (WRITE ${TEST_FOLDER}/${TEST_ERRREF} "${TEST_STREAM}")
    endif (WIN32 AND NOT MINGW)

    # now compare the error output with the error reference
    execute_process (
        COMMAND ${CMAKE_COMMAND} -E compare_files ${TEST_FOLDER}/${TEST_OUTPUT}.err ${TEST_FOLDER}/${TEST_ERRREF}
        RESULT_VARIABLE TEST_RESULT
    )
    if (NOT ${TEST_RESULT} STREQUAL 0)
    set (TEST_RESULT 0)
    file (STRINGS ${TEST_FOLDER}/${TEST_OUTPUT}.err test_act)
    list (LENGTH test_act len_act)
    file (STRINGS ${TEST_FOLDER}/${TEST_ERRREF} test_ref)
    list (LENGTH test_ref len_ref)
    math (EXPR _FP_LEN "${len_ref} - 1")
    if (NOT ${len_act} STREQUAL "0")
      math (EXPR _FP_LEN "${len_ref} - 1")
      foreach (line RANGE 0 ${_FP_LEN})
        list (GET test_act ${line} str_act)
        list (GET test_ref ${line} str_ref)
        if (NOT "${str_act}" STREQUAL "${str_ref}")
          if (NOT "${str_act}" STREQUAL "")
            set (TEST_RESULT 1)
            message ("line = ${line}\n***ACTUAL: ${str_act}\n****REFER: ${str_ref}\n")
           endif (NOT "${str_act}" STREQUAL "")
        endif (NOT "${str_act}" STREQUAL "${str_ref}")
      endforeach (line RANGE 0 ${_FP_LEN})
    endif (NOT ${len_act} STREQUAL "0")
    if (NOT ${len_act} STREQUAL ${len_ref})
      set (TEST_RESULT 1)
    endif (NOT ${len_act} STREQUAL ${len_ref})
    endif (NOT ${TEST_RESULT} STREQUAL 0)

    message (STATUS "COMPARE Result: ${TEST_RESULT}")

    # again, if return value is !=0 scream and shout
    if (NOT ${TEST_RESULT} STREQUAL 0)
      message (FATAL_ERROR "Failed: The error output of ${TEST_OUTPUT}.err did not match ${TEST_ERRREF}")
    endif (NOT ${TEST_RESULT} STREQUAL 0)
  endif (TEST_ERRREF)
endif (NOT TEST_SKIP_COMPARE)

# everything went fine...
message ("Passed: The output of ${TEST_PROGRAM} matches ${TEST_REFERENCE}")

redpajama_set_name: RedPajamaGithub


text:
use crate::errors::serialize::DeError;
use crate::escapei::_escape;
use crate::se::{Indent, QuoteLevel};
use serde::ser::{
    Impossible, Serialize, SerializeSeq, SerializeTuple, SerializeTupleStruct, Serializer,
};
use serde::serde_if_integer128;
use std::borrow::Cow;
use std::fmt::Write;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuoteTarget {
    /// Escape data for a text content. No additional escape symbols
    Text,
    /// Escape data for a double-quoted attribute. `"` always escaped
    DoubleQAttr,
    /// Escape data for a single-quoted attribute. `'` always escaped
    SingleQAttr,
}

/// Escapes atomic value that could be part of a `xs:list`. All whitespace characters
/// additionally escaped
fn escape_item(value: &str, target: QuoteTarget, level: QuoteLevel) -> Cow<str> {
    use QuoteLevel::*;
    use QuoteTarget::*;

    match (target, level) {
        (_, Full) => _escape(value, |ch| match ch {
            // Spaces used as delimiters of list items, cannot be used in the item
            b' ' | b'\r' | b'\n' | b'\t' => true,
            // Required characters to escape
            b'&' | b'<' | b'>' | b'\'' | b'\"' => true,
            _ => false,
        }),
        //----------------------------------------------------------------------
        (Text, Partial) => _escape(value, |ch| match ch {
            // Spaces used as delimiters of list items, cannot be used in the item
            b' ' | b'\r' | b'\n' | b'\t' => true,
            // Required characters to escape
            b'&' | b'<' | b'>' => true,
            _ => false,
        }),
        (Text, Minimal) => _escape(value, |ch| match ch {
            // Spaces used as delimiters of list items, cannot be used in the item
            b' ' | b'\r' | b'\n' | b'\t' => true,
            // Required characters to escape
            b'&' | b'<' => true,
            _ => false,
        }),
        //----------------------------------------------------------------------
        (DoubleQAttr, Partial) => _escape(value, |ch| match ch {
            // Spaces used as delimiters of list items, cannot be used in the item
            b' ' | b'\r' | b'\n' | b'\t' => true,
            // Required characters to escape
            b'&' | b'<' | b'>' => true,
            // Double quoted attribute should escape quote
            b'"' => true,
            _ => false,
        }),
        (DoubleQAttr, Minimal) => _escape(value, |ch| match ch {
            // Spaces used as delimiters of list items, cannot be used in the item
            b' ' | b'\r' | b'\n' | b'\t' => true,
            // Required characters to escape
            b'&' | b'<' => true,
            // Double quoted attribute should escape quote
            b'"' => true,
            _ => false,
        }),
        //----------------------------------------------------------------------
        (SingleQAttr, Partial) => _escape(value, |ch| match ch {
            // Spaces used as delimiters of list items
            b' ' | b'\r' | b'\n' | b'\t' => true,
            // Required characters to escape
            b'&' | b'<' | b'>' => true,
            // Single quoted attribute should escape quote
            b'\'' => true,
            _ => false,
        }),
        (SingleQAttr, Minimal) => _escape(value, |ch| match ch {
            // Spaces used as delimiters of list items
            b' ' | b'\r' | b'\n' | b'\t' => true,
            // Required characters to escape
            b'&' | b'<' => true,
            // Single quoted attribute should escape quote
            b'\'' => true,
            _ => false,
        }),
    }
}

/// Escapes XSD simple type value
fn escape_list(value: &str, target: QuoteTarget, level: QuoteLevel) -> Cow<str> {
    use QuoteLevel::*;
    use QuoteTarget::*;

    match (target, level) {
        (_, Full) => _escape(value, |ch| match ch {
            // Required characters to escape
            b'&' | b'<' | b'>' | b'\'' | b'\"' => true,
            _ => false,
        }),
        //----------------------------------------------------------------------
        (Text, Partial) => _escape(value, |ch| match ch {
            // Required characters to escape
            b'&' | b'<' | b'>' => true,
            _ => false,
        }),
        (Text, Minimal) => _escape(value, |ch| match ch {
            // Required characters to escape
            b'&' | b'<' => true,
            _ => false,
        }),
        //----------------------------------------------------------------------
        (DoubleQAttr, Partial) => _escape(value, |ch| match ch {
            // Required characters to escape
            b'&' | b'<' | b'>' => true,
            // Double quoted attribute should escape quote
            b'"' => true,
            _ => false,
        }),
        (DoubleQAttr, Minimal) => _escape(value, |ch| match ch {
            // Required characters to escape
            b'&' | b'<' => true,
            // Double quoted attribute should escape quote
            b'"' => true,
            _ => false,
        }),
        //----------------------------------------------------------------------
        (SingleQAttr, Partial) => _escape(value, |ch| match ch {
            // Required characters to escape
            b'&' | b'<' | b'>' => true,
            // Single quoted attribute should escape quote
            b'\'' => true,
            _ => false,
        }),
        (SingleQAttr, Minimal) => _escape(value, |ch| match ch {
            // Required characters to escape
            b'&' | b'<' => true,
            // Single quoted attribute should escape quote
            b'\'' => true,
            _ => false,
        }),
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////

/// A serializer that handles ordinary [simple type definition][item] with
/// `{variety} = atomic`, or an ordinary [simple type] definition with
/// `{variety} = union` whose basic members are all atomic.
///
/// This serializer can serialize only primitive types:
/// - numbers
/// - booleans
/// - strings
/// - units
/// - options
/// - unit variants of enums
///
/// Identifiers represented as strings and serialized accordingly.
///
/// Serialization of all other types returns [`Unsupported`][DeError::Unsupported] error.
///
/// [item]: https://www.w3.org/TR/xmlschema11-1/#std-item_type_definition
/// [simple type]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition
pub struct AtomicSerializer<W: Write> {
    pub writer: W,
    pub target: QuoteTarget,
    /// Defines which XML characters need to be escaped
    pub level: QuoteLevel,
}

impl<W: Write> AtomicSerializer<W> {
    fn write_str(&mut self, value: &str) -> Result<(), DeError> {
        Ok(self
            .writer
            .write_str(&escape_item(value, self.target, self.level))?)
    }
}

impl<W: Write> Serializer for AtomicSerializer<W> {
    type Ok = W;
    type Error = DeError;

    type SerializeSeq = Impossible<Self::Ok, Self::Error>;
    type SerializeTuple = Impossible<Self::Ok, Self::Error>;
    type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
    type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;
    type SerializeMap = Impossible<Self::Ok, Self::Error>;
    type SerializeStruct = Impossible<Self::Ok, Self::Error>;
    type SerializeStructVariant = Impossible<Self::Ok, Self::Error>;

    write_primitive!();

    fn serialize_str(mut self, value: &str) -> Result<Self::Ok, Self::Error> {
        self.write_str(value)?;
        Ok(self.writer)
    }

    /// We cannot store anything, so the absence of a unit and presence of it
    /// does not differ, so serialization of unit returns `Err(Unsupported)`
    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Err(DeError::Unsupported(
            "unit type `()` cannot be serialized as an `xs:list` item".into(),
        ))
    }

    /// We cannot store anything, so the absence of a unit and presence of it
    /// does not differ, so serialization of unit returns `Err(Unsupported)`
    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
        Err(DeError::Unsupported(
            format!(
                "unit struct `{}` cannot be serialized as an `xs:list` item",
                name
            )
            .into(),
        ))
    }

    /// We cannot store both a variant discriminant and a variant value,
    /// so serialization of enum newtype variant returns `Err(Unsupported)`
    fn serialize_newtype_variant<T: ?Sized + Serialize>(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _value: &T,
    ) -> Result<Self::Ok, DeError> {
        Err(DeError::Unsupported(
            format!(
                "enum newtype variant `{}::{}` cannot be serialized as an `xs:list` item",
                name, variant
            )
            .into(),
        ))
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Err(DeError::Unsupported(
            "sequence cannot be serialized as an `xs:list` item".into(),
        ))
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        Err(DeError::Unsupported(
            "tuple cannot be serialized as an `xs:list` item".into(),
        ))
    }

    fn serialize_tuple_struct(
        self,
        name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        Err(DeError::Unsupported(
            format!(
                "tuple struct `{}` cannot be serialized as an `xs:list` item",
                name
            )
            .into(),
        ))
    }

    fn serialize_tuple_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Err(DeError::Unsupported(
            format!(
                "enum tuple variant `{}::{}` cannot be serialized as an `xs:list` item",
                name, variant
            )
            .into(),
        ))
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Err(DeError::Unsupported(
            "map cannot be serialized as an `xs:list` item".into(),
        ))
    }

    fn serialize_struct(
        self,
        name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Err(DeError::Unsupported(
            format!(
                "struct `{}` cannot be serialized as an `xs:list` item",
                name
            )
            .into(),
        ))
    }

    fn serialize_struct_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Err(DeError::Unsupported(
            format!(
                "enum struct variant `{}::{}` cannot be serialized as an `xs:list` item",
                name, variant
            )
            .into(),
        ))
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////

/// A serializer for a values representing XSD [simple types], which used in:
/// - attribute values (`<... ...="value" ...>`)
/// - text content (`<...>text</...>`)
/// - CDATA content (`<...><![CDATA[cdata]]></...>`)
///
/// [simple types]: https://www.w3.org/TR/xmlschema11-1/#Simple_Type_Definition
pub struct SimpleTypeSerializer<'i, W: Write> {
    /// Writer to which this serializer writes content
    pub writer: W,
    /// Target for which element is serializing. Affects additional characters to escape.
    pub target: QuoteTarget,
    /// Defines which XML characters need to be escaped
    pub level: QuoteLevel,
    /// Indent that should be written before the content if content is not an empty string
    pub(crate) indent: Indent<'i>,
}

impl<'i, W: Write> SimpleTypeSerializer<'i, W> {
    fn write_str(&mut self, value: &str) -> Result<(), DeError> {
        self.indent.write_indent(&mut self.writer)?;
        Ok(self
            .writer
            .write_str(&escape_list(value, self.target, self.level))?)
    }
}

impl<'i, W: Write> Serializer for SimpleTypeSerializer<'i, W> {
    type Ok = W;
    type Error = DeError;

    type SerializeSeq = SimpleSeq<'i, W>;
    type SerializeTuple = SimpleSeq<'i, W>;
    type SerializeTupleStruct = SimpleSeq<'i, W>;
    type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;
    type SerializeMap = Impossible<Self::Ok, Self::Error>;
    type SerializeStruct = Impossible<Self::Ok, Self::Error>;
    type SerializeStructVariant = Impossible<Self::Ok, Self::Error>;

    write_primitive!();

    fn serialize_str(mut self, value: &str) -> Result<Self::Ok, Self::Error> {
        if value.is_empty() {
            self.indent = Indent::None;
        }
        self.write_str(value)?;
        Ok(self.writer)
    }

    /// Does not write anything
    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Ok(self.writer)
    }

    /// Does not write anything
    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        Ok(self.writer)
    }

    /// We cannot store both a variant discriminant and a variant value,
    /// so serialization of enum newtype variant returns `Err(Unsupported)`
    fn serialize_newtype_variant<T: ?Sized + Serialize>(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _value: &T,
    ) -> Result<Self::Ok, DeError> {
        Err(DeError::Unsupported(
            format!("enum newtype variant `{}::{}` cannot be serialized as an attribute or text content value", name, variant).into(),
        ))
    }

    #[inline]
    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Ok(SimpleSeq {
            writer: self.writer,
            target: self.target,
            level: self.level,
            first: true,
            indent: self.indent,
        })
    }

    #[inline]
    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        self.serialize_seq(None)
    }

    #[inline]
    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        self.serialize_seq(None)
    }

    fn serialize_tuple_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Err(DeError::Unsupported(
            format!("enum tuple variant `{}::{}` cannot be serialized as an attribute or text content value", name, variant).into(),
        ))
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Err(DeError::Unsupported(
            "map cannot be serialized as an attribute or text content value".into(),
        ))
    }

    fn serialize_struct(
        self,
        name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Err(DeError::Unsupported(
            format!(
                "struct `{}` cannot be serialized as an attribute or text content value",
                name
            )
            .into(),
        ))
    }

    fn serialize_struct_variant(
        self,
        name: &'static str,
        _variant_index: u32,
        variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Err(DeError::Unsupported(
            format!("enum struct variant `{}::{}` cannot be serialized as an attribute or text content value", name, variant).into(),
        ))
    }
}

/// Serializer for a sequence of atomic values delimited by space
pub struct SimpleSeq<'i, W: Write> {
    writer: W,
    target: QuoteTarget,
    level: QuoteLevel,
    /// If `true`, nothing was written yet
    first: bool,
    /// Indent that should be written before the content if content is not an empty string
    indent: Indent<'i>,
}

impl<'i, W: Write> SerializeSeq for SimpleSeq<'i, W> {
    type Ok = W;
    type Error = DeError;

    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + Serialize,
    {
        // Write indent for the first element and delimiter for others
        //FIXME: sequence with only empty strings will be serialized as indent only + delimiters
        if self.first {
            self.indent.write_indent(&mut self.writer)?;
        } else {
            self.writer.write_char(' ')?;
        }
        self.first = false;
        value.serialize(AtomicSerializer {
            writer: &mut self.writer,
            target: self.target,
            level: self.level,
        })?;
        Ok(())
    }

    #[inline]
    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(self.writer)
    }
}

impl<'i, W: Write> SerializeTuple for SimpleSeq<'i, W> {
    type Ok = W;
    type Error = DeError;

    #[inline]
    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + Serialize,
    {
        <Self as SerializeSeq>::serialize_element(self, value)
    }

    #[inline]
    fn end(self) -> Result<Self::Ok, Self::Error> {
        <Self as SerializeSeq>::end(self)
    }
}

impl<'i, W: Write> SerializeTupleStruct for SimpleSeq<'i, W> {
    type Ok = W;
    type Error = DeError;

    #[inline]
    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: ?Sized + Serialize,
    {
        <Self as SerializeSeq>::serialize_element(self, value)
    }

    #[inline]
    fn end(self) -> Result<Self::Ok, Self::Error> {
        <Self as SerializeSeq>::end(self)
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::Bytes;
    use serde::Serialize;
    use std::collections::BTreeMap;

    #[derive(Debug, Serialize, PartialEq)]
    struct Unit;

    #[derive(Debug, Serialize, PartialEq)]
    struct Newtype(usize);

    #[derive(Debug, Serialize, PartialEq)]
    struct Tuple(&'static str, usize);

    #[derive(Debug, Serialize, PartialEq)]
    struct Struct {
        key: &'static str,
        val: usize,
    }

    #[derive(Debug, Serialize, PartialEq)]
    enum Enum {
        Unit,
        #[serde(rename = "<\"&'>")]
        UnitEscaped,
        Newtype(usize),
        Tuple(&'static str, usize),
        Struct {
            key: &'static str,
            val: usize,
        },
    }

    mod escape_item {
        use super::*;

        mod full {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn text() {
                assert_eq!(
                    escape_item("text<\"'&> \t\r\ntext", QuoteTarget::Text, QuoteLevel::Full),
                    "text<"'&>

text"
                );
            }

            #[test]
            fn double_quote_attr() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::DoubleQAttr,
                        QuoteLevel::Full
                    ),
                    "text<"'&>

text"
                );
            }

            #[test]
            fn single_quote_attr() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::SingleQAttr,
                        QuoteLevel::Full
                    ),
                    "text<"'&>

text"
                );
            }
        }

        mod partial {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn text() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::Text,
                        QuoteLevel::Partial
                    ),
                    "text<\"'&>

text"
                );
            }

            #[test]
            fn double_quote_attr() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::DoubleQAttr,
                        QuoteLevel::Partial
                    ),
                    "text<"'&>

text"
                );
            }

            #[test]
            fn single_quote_attr() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::SingleQAttr,
                        QuoteLevel::Partial
                    ),
                    "text<\"'&>

text"
                );
            }
        }

        mod minimal {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn text() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::Text,
                        QuoteLevel::Minimal
                    ),
                    "text<\"'&>

text"
                );
            }

            #[test]
            fn double_quote_attr() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::DoubleQAttr,
                        QuoteLevel::Minimal
                    ),
                    "text<"'&>

text"
                );
            }

            #[test]
            fn single_quote_attr() {
                assert_eq!(
                    escape_item(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::SingleQAttr,
                        QuoteLevel::Minimal
                    ),
                    "text<\"'&>

text"
                );
            }
        }
    }

    mod escape_list {
        use super::*;

        mod full {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn text() {
                assert_eq!(
                    escape_list("text<\"'&> \t\r\ntext", QuoteTarget::Text, QuoteLevel::Full),
                    "text<"'&> \t\r\ntext"
                );
            }

            #[test]
            fn double_quote_attr() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::DoubleQAttr,
                        QuoteLevel::Full
                    ),
                    "text<"'&> \t\r\ntext"
                );
            }

            #[test]
            fn single_quote_attr() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::SingleQAttr,
                        QuoteLevel::Full
                    ),
                    "text<"'&> \t\r\ntext"
                );
            }
        }

        mod partial {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn text() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::Text,
                        QuoteLevel::Partial
                    ),
                    "text<\"'&> \t\r\ntext"
                );
            }

            #[test]
            fn double_quote_attr() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::DoubleQAttr,
                        QuoteLevel::Partial
                    ),
                    "text<"'&> \t\r\ntext"
                );
            }

            #[test]
            fn single_quote_attr() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::SingleQAttr,
                        QuoteLevel::Partial
                    ),
                    "text<\"'&> \t\r\ntext"
                );
            }
        }

        mod minimal {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn text() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::Text,
                        QuoteLevel::Minimal
                    ),
                    "text<\"'&> \t\r\ntext"
                );
            }

            #[test]
            fn double_quote_attr() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::DoubleQAttr,
                        QuoteLevel::Minimal
                    ),
                    "text<"'&> \t\r\ntext"
                );
            }

            #[test]
            fn single_quote_attr() {
                assert_eq!(
                    escape_list(
                        "text<\"'&> \t\r\ntext",
                        QuoteTarget::SingleQAttr,
                        QuoteLevel::Minimal
                    ),
                    "text<\"'&> \t\r\ntext"
                );
            }
        }
    }

    /// Tests for serialize atomic and union values, as defined in XSD specification
    mod atomic {
        use super::*;
        use pretty_assertions::assert_eq;

        /// Checks that given `$data` successfully serialized as `$expected`
        macro_rules! serialize_as {
            ($name:ident: $data:expr => $expected:literal) => {
                #[test]
                fn $name() {
                    let ser = AtomicSerializer {
                        writer: String::new(),
                        target: QuoteTarget::Text,
                        level: QuoteLevel::Full,
                    };

                    let buffer = $data.serialize(ser).unwrap();
                    assert_eq!(buffer, $expected);
                }
            };
        }

        /// Checks that attempt to serialize given `$data` results to a
        /// serialization error `$kind` with `$reason`
        macro_rules! err {
            ($name:ident: $data:expr => $kind:ident($reason:literal)) => {
                #[test]
                fn $name() {
                    let mut buffer = String::new();
                    let ser = AtomicSerializer {
                        writer: &mut buffer,
                        target: QuoteTarget::Text,
                        level: QuoteLevel::Full,
                    };

                    match $data.serialize(ser).unwrap_err() {
                        DeError::$kind(e) => assert_eq!(e, $reason),
                        e => panic!(
                            "Expected `{}({})`, found `{:?}`",
                            stringify!($kind),
                            $reason,
                            e
                        ),
                    }
                    assert_eq!(buffer, "");
                }
            };
        }

        serialize_as!(false_: false => "false");
        serialize_as!(true_:  true  => "true");

        serialize_as!(i8_:    -42i8                => "-42");
        serialize_as!(i16_:   -4200i16             => "-4200");
        serialize_as!(i32_:   -42000000i32         => "-42000000");
        serialize_as!(i64_:   -42000000000000i64   => "-42000000000000");
        serialize_as!(isize_: -42000000000000isize => "-42000000000000");

        serialize_as!(u8_:    42u8                => "42");
        serialize_as!(u16_:   4200u16             => "4200");
        serialize_as!(u32_:   42000000u32         => "42000000");
        serialize_as!(u64_:   42000000000000u64   => "42000000000000");
        serialize_as!(usize_: 42000000000000usize => "42000000000000");

        serde_if_integer128! {
            serialize_as!(i128_: -420000000000000000000000000000i128 => "-420000000000000000000000000000");
            serialize_as!(u128_:  420000000000000000000000000000u128 => "420000000000000000000000000000");
        }

        serialize_as!(f32_: 4.2f32 => "4.2");
        serialize_as!(f64_: 4.2f64 => "4.2");

        serialize_as!(char_non_escaped: 'h' => "h");
        serialize_as!(char_lt:   '<' => "<");
        serialize_as!(char_gt:   '>' => ">");
        serialize_as!(char_amp:  '&' => "&");
        serialize_as!(char_apos: '\'' => "'");
        serialize_as!(char_quot: '"' => """);

        serialize_as!(str_non_escaped: "non-escaped-string" => "non-escaped-string");
        serialize_as!(str_escaped: "<\"escaped & string'>" => "<"escaped & string'>");

        err!(bytes: Bytes(b"<\"escaped & bytes'>")
            => Unsupported("`serialize_bytes` not supported yet"));

        serialize_as!(option_none: Option::<&str>::None => "");
        serialize_as!(option_some: Some("non-escaped-string") => "non-escaped-string");

        err!(unit: ()
            => Unsupported("unit type `()` cannot be serialized as an `xs:list` item"));
        err!(unit_struct: Unit
            => Unsupported("unit struct `Unit` cannot be serialized as an `xs:list` item"));

        serialize_as!(enum_unit: Enum::Unit => "Unit");
        serialize_as!(enum_unit_escaped: Enum::UnitEscaped => "<"&'>");

        serialize_as!(newtype: Newtype(42) => "42");
        err!(enum_newtype: Enum::Newtype(42)
            => Unsupported("enum newtype variant `Enum::Newtype` cannot be serialized as an `xs:list` item"));

        err!(seq: vec![1, 2, 3]
            => Unsupported("sequence cannot be serialized as an `xs:list` item"));
        err!(tuple: ("<\"&'>", "with\t\r\n spaces", 3usize)
            => Unsupported("tuple cannot be serialized as an `xs:list` item"));
        err!(tuple_struct: Tuple("first", 42)
            => Unsupported("tuple struct `Tuple` cannot be serialized as an `xs:list` item"));
        err!(enum_tuple: Enum::Tuple("first", 42)
            => Unsupported("enum tuple variant `Enum::Tuple` cannot be serialized as an `xs:list` item"));

        err!(map: BTreeMap::from([(1, 2), (3, 4)])
            => Unsupported("map cannot be serialized as an `xs:list` item"));
        err!(struct_: Struct { key: "answer", val: 42 }
            => Unsupported("struct `Struct` cannot be serialized as an `xs:list` item"));
        err!(enum_struct: Enum::Struct { key: "answer", val: 42 }
            => Unsupported("enum struct variant `Enum::Struct` cannot be serialized as an `xs:list` item"));
    }

    mod simple_type {
        use super::*;
        use pretty_assertions::assert_eq;

        /// Checks that given `$data` successfully serialized as `$expected`
        macro_rules! serialize_as {
            ($name:ident: $data:expr => $expected:literal) => {
                #[test]
                fn $name() {
                    let ser = SimpleTypeSerializer {
                        writer: String::new(),
                        target: QuoteTarget::Text,
                        level: QuoteLevel::Full,
                        indent: Indent::None,
                    };

                    let buffer = $data.serialize(ser).unwrap();
                    assert_eq!(buffer, $expected);
                }
            };
        }

        /// Checks that attempt to serialize given `$data` results to a
        /// serialization error `$kind` with `$reason`
        macro_rules! err {
            ($name:ident: $data:expr => $kind:ident($reason:literal)) => {
                #[test]
                fn $name() {
                    let mut buffer = String::new();
                    let ser = SimpleTypeSerializer {
                        writer: &mut buffer,
                        target: QuoteTarget::Text,
                        level: QuoteLevel::Full,
                        indent: Indent::None,
                    };

                    match $data.serialize(ser).unwrap_err() {
                        DeError::$kind(e) => assert_eq!(e, $reason),
                        e => panic!(
                            "Expected `{}({})`, found `{:?}`",
                            stringify!($kind),
                            $reason,
                            e
                        ),
                    }
                    assert_eq!(buffer, "");
                }
            };
        }

        serialize_as!(false_: false => "false");
        serialize_as!(true_:  true  => "true");

        serialize_as!(i8_:    -42i8                => "-42");
        serialize_as!(i16_:   -4200i16             => "-4200");
        serialize_as!(i32_:   -42000000i32         => "-42000000");
        serialize_as!(i64_:   -42000000000000i64   => "-42000000000000");
        serialize_as!(isize_: -42000000000000isize => "-42000000000000");

        serialize_as!(u8_:    42u8                => "42");
        serialize_as!(u16_:   4200u16             => "4200");
        serialize_as!(u32_:   42000000u32         => "42000000");
        serialize_as!(u64_:   42000000000000u64   => "42000000000000");
        serialize_as!(usize_: 42000000000000usize => "42000000000000");

        serde_if_integer128! {
            serialize_as!(i128_: -420000000000000000000000000000i128 => "-420000000000000000000000000000");
            serialize_as!(u128_:  420000000000000000000000000000u128 => "420000000000000000000000000000");
        }

        serialize_as!(f32_: 4.2f32 => "4.2");
        serialize_as!(f64_: 4.2f64 => "4.2");

        serialize_as!(char_non_escaped: 'h' => "h");
        serialize_as!(char_lt:   '<' => "<");
        serialize_as!(char_gt:   '>' => ">");
        serialize_as!(char_amp:  '&' => "&");
        serialize_as!(char_apos: '\'' => "'");
        serialize_as!(char_quot: '"' => """);

        serialize_as!(str_non_escaped: "non-escaped string" => "non-escaped string");
        serialize_as!(str_escaped: "<\"escaped & string'>" => "<"escaped & string'>");

        err!(bytes: Bytes(b"<\"escaped & bytes'>")
            => Unsupported("`serialize_bytes` not supported yet"));

        serialize_as!(option_none: Option::<&str>::None => "");
        serialize_as!(option_some: Some("non-escaped string") => "non-escaped string");

        serialize_as!(unit: () => "");
        serialize_as!(unit_struct: Unit => "");

        serialize_as!(enum_unit: Enum::Unit => "Unit");
        serialize_as!(enum_unit_escaped: Enum::UnitEscaped => "<"&'>");

        serialize_as!(newtype: Newtype(42) => "42");
        err!(enum_newtype: Enum::Newtype(42)
            => Unsupported("enum newtype variant `Enum::Newtype` cannot be serialized as an attribute or text content value"));

        serialize_as!(seq: vec![1, 2, 3] => "1 2 3");
        serialize_as!(seq_empty: Vec::<usize>::new() => "");
        serialize_as!(seq_with_1_empty_str: vec![""] => "");
        serialize_as!(seq_with_2_empty_strs: vec!["", ""] => " ");
        serialize_as!(tuple: ("<\"&'>", "with\t\r\n spaces", 3usize)
            => "<"&'> with

 spaces 3");
        serialize_as!(tuple_struct: Tuple("first", 42) => "first 42");
        err!(enum_tuple: Enum::Tuple("first", 42)
            => Unsupported("enum tuple variant `Enum::Tuple` cannot be serialized as an attribute or text content value"));

        err!(map: BTreeMap::from([(1, 2), (3, 4)])
            => Unsupported("map cannot be serialized as an attribute or text content value"));
        err!(struct_: Struct { key: "answer", val: 42 }
            => Unsupported("struct `Struct` cannot be serialized as an attribute or text content value"));
        err!(enum_struct: Enum::Struct { key: "answer", val: 42 }
            => Unsupported("enum struct variant `Enum::Struct` cannot be serialized as an attribute or text content value"));
    }
}


text:
{% extends "base.html" %}
{% load i18n %}

{% block content %}

<form method="post" action=".">
{% csrf_token %}

{{form.username.label_tag}}
{{form.username}}

{{form.password.label_tag}}
{{form.password}}

{% if form.errors %}
   {% trans "Try again, username and password don't match." %}
{% endif %}

<input type="submit" value="login">
<input type="hidden" value="{{next}}" name="next">
</form>
{% trans "register" %}
{% trans "reset password" %}

{% endblock %}


text:
<?php

namespace Shopline\Bundle\PDFDesignerBundle\Composer;

use Symfony\Component\ClassLoader\ClassCollectionLoader;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\PhpExecutableFinder;
use Composer\Script\CommandEvent;
use Symfony\Component\Console\Output\OutputInterface;

class DesignerHandler
{
    /**
     * Clears the Symfony cache.
     *
     * @param $event CommandEvent A instance
     */
    public static function InstallDesigner(CommandEvent $event)
    {
	$output=new OutputInterface;
         $output->writeln('<comment>Install Designer</comment>');
        $options = self::getOptions($event);
        $appDir = $options['symfony-app-dir'];

        if (!is_dir($appDir)) {
            echo 'The symfony-app-dir ('.$appDir.') specified in composer.json was not found in '.getcwd().', can not clear the cache.'.PHP_EOL;

            return;
        }
        $commands = array('cache:clear --no-warmup --no-debug','doctrine:schema:update --force', 'oro:translation:dump', 'oro:entity-config:update');
        foreach($commands as $command)
            self::executeCommand($event, $appDir, $command, $options['process-timeout']);
    }

    protected static function executeCommand(CommandEvent $event, $appDir, $cmd, $timeout = 300)
    {
        $php = escapeshellarg(self::getPhp());
        $console = escapeshellarg($appDir.'/console');
        if ($event->getIO()->isDecorated()) {
            $console .= ' --ansi';
        }

        $process = new Process($php.' '.$console.' '.$cmd, null, null, null, $timeout);
        $process->run(function ($type, $buffer) { echo $buffer; });
        if (!$process->isSuccessful()) {
            throw new \RuntimeException(sprintf('An error occurred when executing the "%s" command.', escapeshellarg($cmd)));
        }
    }
    protected static function getOptions(CommandEvent $event)
    {
        $options = array_merge(array(
            'symfony-app-dir' => 'app',
            'symfony-web-dir' => 'web',
            'symfony-assets-install' => 'hard'
        ), $event->getComposer()->getPackage()->getExtra());

        $options['symfony-assets-install'] = getenv('SYMFONY_ASSETS_INSTALL') ?: $options['symfony-assets-install'];

        $options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');

        return $options;
    }
    protected static function getPhp()
    {
        $phpFinder = new PhpExecutableFinder;
        if (!$phpPath = $phpFinder->find()) {
            throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
        }

        return $phpPath;
    }
}


text:
fiberassign
==============

This repository contains code to plan the location of DESI fiber positioners.  Given information about the instrument, a list of pointings (tiles), and catalogs of prioritized targets, fiber assignment computes the best positioner locations for each tile.

For full documentation, please visit  `fiberassign on Read the Docs`_

.. image:: https://readthedocs.org/projects/fiberassign/badge/?version=latest
    :target: http://fiberassign.readthedocs.org/en/latest/
    :alt: Documentation Status

.. _`fiberassign on Read the Docs`: http://fiberassign.readthedocs.org/en/latest/


text:
namespace boxer
{
    extern pthread_mutex_t gAudioMutex;
    extern control jControl;
}

extern boxer::audioParam* jAudioParam;

JavaVM* jVM = NULL;
jclass jBoxerEngine = NULL;
jmethodID jShowStage = NULL;
char androidData[PATH_MAX];

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
    jVM = vm;
    JNIEnv* env;
    if(vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)
    {
        return -1;
    }

    return JNI_VERSION_1_6;
}

extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_preload(JNIEnv* env, jobject obj, jstring pathString)
{
    const char* path = env->GetStringUTFChars(pathString, NULL);

    boxer::preload(path);

    memset(androidData, '\0', PATH_MAX);
    const char* finalSlash = strrchr(path, '/');
    memcpy(androidData, path, (finalSlash - path) + 1);

    env->ReleaseStringUTFChars(pathString, path);
}

extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_boxerMain(JNIEnv* env, jobject obj)
{
    jBoxerEngine = env->FindClass("org/starlo/boxer/BoxerEngine");
    jShowStage = env->GetStaticMethodID(jBoxerEngine, "showStage", "([B)V");
    boxerMain();
}

extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_audioResourceThread(JNIEnv* env, jobject obj)
{
    jclass engine = env->FindClass("org/starlo/boxer/BoxerEngine");
    jmethodID audioWrite = env->GetStaticMethodID(engine, "audioWrite", "([S)V");
    while(true)
    {
        if(jAudioParam != NULL)
        {
            int32_t i = 0;
            const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(jAudioParam->id);
            const uint8_t* data = (const uint8_t*)(boxer::getResource(jAudioParam->id) + WAV_HEADER_SIZE);
            jshortArray jData = env->NewShortArray(AUDIO_BUFFER_SIZE/sizeof(short));
            while(i+AUDIO_BUFFER_SIZE < stat->size && jAudioParam->keepGoing)
            {
                env->SetShortArrayRegion(jData, 0, AUDIO_BUFFER_SIZE/sizeof(short), (const short*)&data[i]);
                env->CallStaticVoidMethod(engine, audioWrite, jData);
                i+=AUDIO_BUFFER_SIZE;
            }
            env->DeleteLocalRef(jData);
            pthread_mutex_lock(&boxer::gAudioMutex);
            delete jAudioParam;
            jAudioParam = NULL;
            pthread_mutex_unlock(&boxer::gAudioMutex);
        }
        sched_yield();
    }
}

extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_triggerControl(JNIEnv* env, jobject obj, jint control)
{
    static bool first = true;
    if(first)
    {
        BOXER_LOG("Input Initialized\n");
        boxer::initializeInput();
        first = false;
    }

    while(boxer::jControl != boxer::UNKNOWN)
        usleep(1);

    boxer::jControl = (boxer::control)control;
}


text:
package com.capitalone.dashboard.common;

import com.capitalone.dashboard.ApiSettings;
import com.capitalone.dashboard.model.Commit;
import com.capitalone.dashboard.model.CommitStatus;
import com.capitalone.dashboard.model.GitRequest;
import com.capitalone.dashboard.model.Review;
import com.capitalone.dashboard.model.ServiceAccount;
import com.capitalone.dashboard.repository.CommitRepository;
import com.capitalone.dashboard.repository.ServiceAccountRepository;
import com.capitalone.dashboard.response.AuditReviewResponse;
import com.capitalone.dashboard.status.CodeReviewAuditStatus;
import org.bson.types.ObjectId;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RunWith(MockitoJUnitRunner.class)
public class CommonCodeReviewTest {

    private ApiSettings apiSettings = new ApiSettings();
    @Mock
    private CommitRepository commitRepository;
    @Mock
    private ServiceAccountRepository serviceAccountRepository;
    @Test
    public void testCheckForServiceAccount() {

        apiSettings.setServiceAccountOU(TestConstants.SERVICE_ACCOUNTS);
        Assert.assertEquals(true, CommonCodeReview.checkForServiceAccount("CN=hygieiaUser,OU=Service Accounts,DC=basic,DC=ds,DC=industry,DC=com", apiSettings,null,null,null,false,new AuditReviewResponse()));
    }

    @Test
    public void testCheckForServiceAccountForAllUsers() {
        apiSettings.setServiceAccountOU(TestConstants.SERVICE_ACCOUNTS);
        Assert.assertEquals(false, CommonCodeReview.checkForServiceAccount("CN=hygieiaUser,OU=Developers,OU=All Users,DC=basic,DC=ds,DC=industry,DC=com", apiSettings,null,null,null,false,new AuditReviewResponse()));
    }

    @Test
    public void testCheckForServiceAccountForAllowedServiceAccountsMatch() {
        apiSettings.setServiceAccountOU(TestConstants.SERVICE_ACCOUNTS);
        Map<String,String> allowedUsers =  Collections.unmodifiableMap(Stream.of(
                new AbstractMap.SimpleEntry<>("allowedUser1", "pom.xml,test.json"),
                new AbstractMap.SimpleEntry<>("allowedUser2", "test.java"))
                .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
        Assert.assertEquals(true, CommonCodeReview.checkForServiceAccount("CN=hygieiaUser,OU=Developers,OU=All Users,DC=basic,DC=ds,DC=industry,DC=com", apiSettings,allowedUsers,"allowedUser1",Stream.of("test.json").collect(Collectors.toList()), true,new AuditReviewResponse()));
    }

    @Test
    public void testCheckForServiceAccountForAllowedServiceAccountsWildcardMatch() {
        AuditReviewResponse<CodeReviewAuditStatus> auditStatusAuditReviewResponse = new AuditReviewResponse();
        apiSettings.setServiceAccountOU(TestConstants.SERVICE_ACCOUNTS);
        Map<String,String> allowedUsers =  Collections.unmodifiableMap(Stream.of(
                new AbstractMap.SimpleEntry<>("allowedUser1", "pom.xml,test.json"),
                new AbstractMap.SimpleEntry<>("allowedUser2", "*.java"))
                .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
        Assert.assertEquals(true, CommonCodeReview.checkForServiceAccount("CN=hygieiaUser,OU=Developers,OU=All Users,DC=basic,DC=ds,DC=industry,DC=com", apiSettings,allowedUsers,"allowedUser2",Stream.of("test.java").collect(Collectors.toList()), true,auditStatusAuditReviewResponse));
        Assert.assertEquals(true, auditStatusAuditReviewResponse.getAuditStatuses().toString().contains("DIRECT_COMMIT_CHANGE_WHITELISTED_ACCOUNT"));
    }

    @Test
    public void testCheckForServiceAccountForAllowedServiceAccountsNonMatch() {
        AuditReviewResponse<CodeReviewAuditStatus> auditStatusAuditReviewResponse = new AuditReviewResponse();
        apiSettings.setServiceAccountOU(TestConstants.SERVICE_ACCOUNTS);
        Map<String,String> allowedUsers =  Collections.unmodifiableMap(Stream.of(
                new AbstractMap.SimpleEntry<>("allowedUser1", "pom.xml,test.json"),
                new AbstractMap.SimpleEntry<>("allowedUser2", "*.java"))
                .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue())));
        Assert.assertEquals(false, auditStatusAuditReviewResponse.getAuditStatuses().toString().contains("DIRECT_COMMIT_CHANGE_WHITELISTED_ACCOUNT"));
        Assert.assertEquals(false, CommonCodeReview.checkForServiceAccount("CN=hygieiaUser,OU=Developers,OU=All Users,DC=basic,DC=ds,DC=industry,DC=com", apiSettings,allowedUsers,"allowedUser2",Stream.of("test.md").collect(Collectors.toList()), true,auditStatusAuditReviewResponse));
    }

    @Test
    public void testComputePeerReviewStatusForServiceAccount() {
        apiSettings.setServiceAccountOU(TestConstants.SERVICE_ACCOUNTS);
        apiSettings.setPeerReviewContexts("context");
        apiSettings.setPeerReviewApprovalText("approved by");
        Mockito.when(serviceAccountRepository.findAll()).thenReturn(Stream.of(makeServiceAccount()).collect(Collectors.toList()));
        AuditReviewResponse<CodeReviewAuditStatus> codeReviewAuditRequestAuditReviewResponse = new AuditReviewResponse<>();
        Assert.assertEquals(false, CommonCodeReview.computePeerReviewStatus(makeGitRequest("Service Accounts"), apiSettings, codeReviewAuditRequestAuditReviewResponse, Stream.of(makeCommit()).collect(Collectors.toList()),commitRepository,serviceAccountRepository));
        Assert.assertEquals(true, codeReviewAuditRequestAuditReviewResponse.getAuditStatuses().toString().contains("PEER_REVIEW_BY_SERVICEACCOUNT"));
    }

    @Test
    public void testComputePeerReviewStatusForAllUsers() {
        apiSettings.setServiceAccountOU(TestConstants.SERVICE_ACCOUNTS);
        apiSettings.setPeerReviewContexts("context");
        apiSettings.setPeerReviewApprovalText("approved by");
        Mockito.when(serviceAccountRepository.findAll()).thenReturn(Stream.of(makeServiceAccount()).collect(Collectors.toList()));
        AuditReviewResponse<CodeReviewAuditStatus> codeReviewAuditRequestAuditReviewResponse = new AuditReviewResponse<>();
        Assert.assertEquals(false, CommonCodeReview.computePeerReviewStatus(makeGitRequest("All Users"), apiSettings, codeReviewAuditRequestAuditReviewResponse, Stream.of(makeCommit()).collect(Collectors.toList()),commitRepository,serviceAccountRepository));
        Assert.assertEquals(Boolean.TRUE,codeReviewAuditRequestAuditReviewResponse.getAuditStatuses().contains(CodeReviewAuditStatus.PEER_REVIEW_GHR));
        Assert.assertEquals(Boolean.TRUE,codeReviewAuditRequestAuditReviewResponse.getAuditStatuses().contains(CodeReviewAuditStatus.PEER_REVIEW_BY_SERVICEACCOUNT));
        Assert.assertEquals(Boolean.TRUE,codeReviewAuditRequestAuditReviewResponse.getAuditStatuses().contains(CodeReviewAuditStatus.PEER_REVIEW_GHR_SELF_APPROVAL));
    }

    private GitRequest makeGitRequest(String userAccount) {
        GitRequest pr = new GitRequest();
        pr.setCommitStatuses(Stream.of(makeCommitStatus()).collect(Collectors.toList()));
        pr.setReviews(Stream.of(makeReview()).collect(Collectors.toList()));
        pr.setMergeAuthor("hygieiaUser");
        pr.setMergeAuthorLDAPDN("CN=hygieiaUser,OU=" + userAccount + ",DC=basic,DC=ds,DC=industry,DC=com");
        pr.setCommits(Stream.of(makeCommit()).collect(Collectors.toList()));
        pr.setScmBranch("master");
        pr.setSourceBranch("branch");

        return pr;
    }

    private Commit makeCommit() {
        Commit c = new Commit();
        c.setId(ObjectId.get());
        c.setScmCommitLog("Merge branch master into branch");
        c.setScmAuthorLDAPDN("CN=hygieiaUser,OU=Service Accounts,DC=basic,DC=ds,DC=industry,DC=com");
        return c;
    }

    private CommitStatus makeCommitStatus() {
        CommitStatus cs = new CommitStatus();
        cs.setState("success");
        cs.setContext("context");
        cs.setDescription("approved by hygieiaUser");
        return cs;
    }

    private Review makeReview() {
        Review r = new Review();
        r.setState("approved");
        r.setAuthorLDAPDN("CN=hygieiaUser,OU=Service Accounts,DC=basic,DC=ds,DC=industry,DC=com");
        return r;
    }

    private ServiceAccount makeServiceAccount(){
        return new ServiceAccount("servUserName","pom.xml,test.json");
    }
}


text:
package org.jboss.resteasy.plugins.providers.multipart;

import org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Providers;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.bind.attachment.AttachmentUnmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * A special JAXB Provider. It is not a real provider, it is only used as a
 * helper class inside {@link XopWithMultipartRelatedReader} and
 * {@link XopWithMultipartRelatedWriter}.
 *
 * @author Attila Kiraly
 * @version $Revision: 1 $
 */
public class XopWithMultipartRelatedJAXBProvider extends
		AbstractJAXBProvider<Object> {

	private static class XopAttachmentMarshaller extends AttachmentMarshaller {
		private final MultipartRelatedOutput xopPackage;

		private XopAttachmentMarshaller(MultipartRelatedOutput xopPackage) {
			this.xopPackage = xopPackage;
		}

		@Override
		public String addMtomAttachment(DataHandler data,
				String elementNamespace, String elementLocalName) {
			return addBinary(data.getDataSource(), data.getContentType());
		}

		@Override
		public String addMtomAttachment(byte[] data, int offset, int length,
				String mimeType, String elementNamespace,
				String elementLocalName) {
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
					data, offset, length);
			return addBinary(byteArrayInputStream, mimeType);
		}

		protected String addBinary(Object object, String mimeType) {
			String addrSpec = ContentIDUtils.generateRFC822AddrSpec();
			String contentID = ContentIDUtils
					.generateContentIDFromAddrSpec(addrSpec);
			xopPackage.addPart(object, MediaType.valueOf(mimeType), contentID,
					"binary");
			return ContentIDUtils.generateCidFromAddrSpec(addrSpec);
		}

		@Override
		public String addSwaRefAttachment(DataHandler data) {
			throw new UnsupportedOperationException(
					"SwaRefs are not supported in xop creation.");
		}

		@Override
		public boolean isXOPPackage() {
			return true;
		}
	}

	private static class InputPartBackedDataSource implements DataSource {
		private final String cid;
		private final InputPart inputPart;

		private InputPartBackedDataSource(String cid, InputPart inputPart) {
			this.cid = cid;
			this.inputPart = inputPart;
		}

		public String getContentType() {
			return inputPart.getMediaType().toString();
		}

		public String getName() {
			return cid;
		}

		public InputStream getInputStream() throws IOException {
			return inputPart.getBody(InputStream.class, null);
		}

		public OutputStream getOutputStream() throws IOException {
			throw new IOException(
					"This DataSource represents an incoming xop message part. Getting an OutputStream on it is not allowed.");
		}
	}

	private static class XopAttachmentUnmarshaller extends
			AttachmentUnmarshaller {

		private final MultipartRelatedInput xopPackage;

		private XopAttachmentUnmarshaller(MultipartRelatedInput xopPackage) {
			this.xopPackage = xopPackage;
		}

		@Override
		public byte[] getAttachmentAsByteArray(String cid) {
			InputPart inputPart = getInputPart(cid);
			try {
				return inputPart.getBody(byte[].class, null);
			} catch (IOException e) {
				throw new IllegalArgumentException(
						"Exception while extracting attachment with cid = "
								+ cid + " from xop message to a byte[].", e);
			}
		}

		@Override
		public DataHandler getAttachmentAsDataHandler(final String cid) {
			final InputPart inputPart = getInputPart(cid);
			return new DataHandler(
					new InputPartBackedDataSource(cid, inputPart));
		}

		protected InputPart getInputPart(String cid) {
			String contentID = ContentIDUtils.convertCidToContentID(cid);
			InputPart inputPart = xopPackage.getRelatedMap().get(contentID);
			if (inputPart == null)
				throw new IllegalArgumentException("No attachment with cid = "
						+ cid + " (Content-ID = " + contentID
						+ ") found in xop message.");
			return inputPart;
		}

		@Override
		public boolean isXOPPackage() {
			return true;
		}
	}

	public XopWithMultipartRelatedJAXBProvider(Providers providers) {
		super();
		this.providers = providers;
	}

	@Override
	protected boolean isReadWritable(Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType) {
		throw new UnsupportedOperationException(
				"This provider and this method are not ment for stand alone usage.");
	}

	public Object readFrom(Class<Object> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, String> httpHeaders,
			InputStream entityStream, final MultipartRelatedInput xopPackage)
			throws IOException {
		try {
			InputPart rootPart = xopPackage.getRootPart();
			JAXBContext jaxb = findJAXBContext(type, annotations, rootPart
					.getMediaType(), true);
			Unmarshaller unmarshaller = jaxb.createUnmarshaller();
			unmarshaller
					.setAttachmentUnmarshaller(new XopAttachmentUnmarshaller(
							xopPackage));
			return unmarshaller.unmarshal(new StreamSource(rootPart.getBody(
					InputStream.class, null)));
		} catch (JAXBException e) {
			Response response = Response.serverError().build();
			throw new WebApplicationException(e, response);
		}
	}

	public void writeTo(Object t, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, Object> httpHeaders,
			final MultipartRelatedOutput xopPackage) throws IOException {
		try {
			Map<String, String> mediaTypeParameters = new LinkedHashMap<String, String>();
			mediaTypeParameters.put("charset", "UTF-8");
			mediaTypeParameters.put("type", "text/xml");

			MediaType xopRootMediaType = new MediaType("application",
					"xop+xml", mediaTypeParameters);

			Marshaller marshaller = getMarshaller(type, annotations,
					xopRootMediaType);
			marshaller.setAttachmentMarshaller(new XopAttachmentMarshaller(
					xopPackage));
			ByteArrayOutputStream xml = new ByteArrayOutputStream();
			marshaller.marshal(t, xml);

			OutputPart outputPart = xopPackage.addPart(xml.toByteArray(),
					xopRootMediaType, ContentIDUtils.generateContentID(), null);
			List<OutputPart> outputParts = xopPackage.getParts();
			outputParts.remove(outputPart);
			outputParts.add(0, outputPart);
		} catch (JAXBException e) {
			Response response = Response.serverError().build();
			throw new WebApplicationException(e, response);
		}
	}

}


text:
import { useEffect } from 'react'
import { pick } from 'ramda'

import type { TEditValue } from '@/spec'
import { EVENT, ERR } from '@/constant'
import { asyncSuit, buildLog, errRescue, updateEditing } from '@/utils'

import type { TStore } from './store'
import type { TCommunityType } from './spec'
import { COMMUNITY_TYPE, STEP } from './constant'

import S from './schema'

/* eslint-disable-next-line */
const log = buildLog('L:ExploreContent')

const { SR71, $solver, asyncRes, asyncErr } = asyncSuit
const sr71$ = new SR71({
  // @ts-ignore
  receive: [EVENT.LOGOUT, EVENT.LOGIN],
})

let store: TStore | undefined
let sub$ = null

/**
 * pervious step based on current step
 * 当前流程的上一步流程
 * @public
 */
export const pervStep = (): void => {
  const { step } = store

  if (step === STEP.SETUP_DOMAIN) store.mark({ step: STEP.SELECT_TYPE })
  if (step === STEP.SETUP_INFO) store.mark({ step: STEP.SETUP_DOMAIN })
  if (step === STEP.MORE_INFO) store.mark({ step: STEP.SETUP_INFO })
}

/**
 * next step based on current step
 * 当前流程的下一步流程
 * @public
 */
export const nextStep = (): void => {
  const { step } = store

  if (step === STEP.SELECT_TYPE) store.mark({ step: STEP.SETUP_DOMAIN })
  if (step === STEP.SETUP_DOMAIN) {
    checkIfCommunityExist()
  }
  if (step === STEP.SETUP_INFO) {
    store.mark({ step: STEP.MORE_INFO })
  }
}

const checkIfCommunityExist = () => {
  const { raw } = store

  store.mark({ checking: true, communityExist: false })
  sr71$.query(S.isCommunityExist, { raw })
}

const checkPendingApply = () => {
  sr71$.query(S.hasPendingCommunityApply, {})
}

/**
 * change the type of the creating community
 * 改变创建社区类型
 * @public
 */
export const communityTypeOnChange = (communityType: TCommunityType): void => {
  store.mark({ communityType })
}

export const applyCommunity = (): void => {
  const args = pick(['title', 'logo', 'desc', 'raw', 'applyMsg'], store)

  store.mark({ submitting: true })
  sr71$.mutate(S.applyCommunity, {
    applyCategory: store.communityType,
    ...args,
  })
}

/**
 * handle input field change
 * @param {part} string field name
 * @param {e} htmlEvent
 * @public
 */
export const inputOnChange = (e: TEditValue, part: string): void => {
  if (part === 'raw') {
    store.mark({ communityExist: false })
  }
  updateEditing(store, part, e)
}

/* when error occured cancel all the loading state */
const cancelLoading = () =>
  store.mark({
    subscribing: false,
    searching: false,
  })

const DataSolver = [
  {
    match: asyncRes('searchCommunities'),
    action: ({ searchCommunities: pagedCommunities }) =>
      store.mark({ pagedCommunities, searching: false }),
  },
  {
    match: asyncRes('isCommunityExist'),
    action: ({ isCommunityExist }) => {
      store.mark({ checking: false, communityExist: isCommunityExist.exist })

      if (!isCommunityExist.exist) {
        store.mark({ step: STEP.SETUP_INFO })
      }
    },
  },
  {
    match: asyncRes('hasPendingCommunityApply'),
    action: ({ hasPendingCommunityApply }) => {
      store.mark({ hasPendingApply: hasPendingCommunityApply.exist })
    },
  },
  {
    match: asyncRes('applyCommunity'),
    action: () => store.mark({ step: STEP.FINISHED }),
  },
]

const ErrSolver = [
  {
    match: asyncErr(ERR.GRAPHQL),
    action: () => cancelLoading(),
  },
  {
    match: asyncErr(ERR.TIMEOUT),
    action: ({ details }) => {
      errRescue({ type: ERR.TIMEOUT, details, path: 'ExploreContent' })
      cancelLoading()
    },
  },
  {
    match: asyncErr(ERR.NETWORK),
    action: () => {
      cancelLoading()
      errRescue({ type: ERR.NETWORK, path: 'ExploreContent' })
    },
  },
]

// ###############################
// init & uninit
// ###############################
export const useInit = (_store: TStore): void => {
  useEffect(() => {
    store = _store
    // log('effect init')
    sub$ = sr71$.data().subscribe($solver(DataSolver, ErrSolver))

    if (store.isLogin) {
      checkPendingApply()
    }

    return () => {
      // log('effect uninit')
      if (!sub$) return
      // log('===== do uninit')
      sub$.unsubscribe()
    }
  }, [_store])
}


text:
curl --location --request POST 'https://localhost/pdf/find' \
--header 'x-api-key: {{x-api-key}}' \
--form 'url=https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-to-text/sample.pdf' \
--form 'searchString=Invoice Date \d+/\d+/\d+' \
--form 'pages=' \
--form 'password=' \
--form 'regexSearch=true'


text:
sudo yum -y install git

# Install Maven
wget http://apache.claz.org/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz
tar xvzf apache-maven-3.3.9-bin.tar.gz
export PATH=/home/hadoop/apache-maven-3.3.9/bin:$PATH

# Install ADAM
git clone https://github.com/bigdatagenomics/adam.git
cd adam
sed -i 's/2.6.0/2.7.2/' pom.xml
./scripts/move_to_spark_2.sh
export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256m"
mvn clean package -DskipTests

export PATH=/home/hadoop/adam/bin:$PATH

cd ~/


text:
package com.iluwatar.registry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class CustomerRegistry {

  private static final CustomerRegistry instance = new CustomerRegistry();

  public static CustomerRegistry getInstance() {
    return instance;
  }

  private final Map<String, Customer> customerMap;

  private CustomerRegistry() {
    customerMap = new ConcurrentHashMap<>();
  }

  public Customer addCustomer(Customer customer) {
    return customerMap.put(customer.getId(), customer);
  }

  public Customer getCustomer(String id) {
    return customerMap.get(id);
  }

}


text:
require 'stick/frame'
require 'stick/type'
require 'stick/prefix'
require 'stick/measure'

module Stick

  # Alawys use :au as fallback system.
  def self.use(*system_names)
    @use ||= []

    return @use if system_names.empty?

    system_names.each do |name|
      name = name.to_sym
      next if @use.include?(name)
      sys = Stick.systems[name]
      raise "unknown system -- #{name}" unless sys
      ::Numeric.class_eval do
        include sys.numeric_module
      end
      @use << name
    end

    return @use
  end

  #
  def self.systems
    @systems ||= {}
  end

  #
  def self.system(name, *frame, &block)
    sys = System.new(name, *frame, &block)
    systems[name.to_sym] = sys
    (class << self ; self ; end).class_eval do
      define_method(name){ sys }
    end
  end

  #
  #def self.method_missing(system_name)
  #  systems[system_name]
  #end

  #def self.convert(from, goal, &block)
  #  if String == from
  #    system, type = *from.split(':')
  #    from = @systems[system.to_sym].types[type.to_sym]
  #  end
  #  from.conversion(goal, &block)
  #end

  # = System
  #
  # A system defines a set of unit types, prefix factors that can be used with
  # them and conversions to unit types in the system and without.
  #
  # All the systems defined via Stick utilize the AU system as a basis for
  # fallback conversion. By ensuring that the unit types can be converted to
  # and from AU units, then they can be converted to and form any other unit
  # system as well. See Frame class for more information.
  #
  class System

    # Name of system. This should be a short, two or three letter
    # abbreviated name, eg. 'si'.
    attr :name

    # Unit types in the system.
    attr :types

    # Prefixes recognized by the system.
    attr :prefixes

    #
    def initialize(name, *frame) #:yield:
      @name  = name.to_sym
      @frame = Frame.new(*frame.flatten) unless frame.empty?
      @types    = {}
      @prefixes = []

      # used to track universal conversions
      @universal_conversions = {}

      yield(self) if block_given?
    end

    #

    def frame
      @frame
    end

    # Define a prefix multiplier for this system.

    def prefix(name, symbol, factor)
      prefixes << Prefix.new(self, name, symbol, factor)
    end

    # Define a unit type for this system.

    def unit(name, symbol, quantity, options={})
      type = UnitType.new(self, name, symbol, quantity, options)
      type.terms.each do |key|
        next if /\W/ =~ key.to_s   # can't use non-words characters
        types[key.to_sym] = type
      end

      # define au conversions
      au_conversion(type)
    end

    # Used to access types by term and to assign conversions.

    def method_missing(name, *args)
      case name.to_s
      when /\=$/
        name = name.to_s.chomp('=').to_sym
        type = types.key?(name) ? types[name] : super
        type.conversion(*args)
      else
        name = name.to_sym
        types.key?(name) ? types[name] : super
      end
    end

    #

    def [](conversion)
      parse(conversion)
    end

    #

    def inspect
      "#<System:#{name}>"
    end

    #

    def to_s
      "#{name}"
    end

    # Returns a module to be included into Numeric.

    def numeric_module
      methods = {}
      prefix_types, bare_types = *types.values.uniq.partition{ |t| t.prefix? }

      prefix_types.each do |type|
        prefixes.each do |prefix|
          name = "#{prefix.symbol}#{type.symbol}".to_sym
          methods[name]  = Unit.new(type, 1, prefix)
        end
        type.terms.each do |name|
          next if /\W/ =~ name.to_s   # can't use non-words characters
          methods[name] = Unit.new(type, 1)
        end
      end

      bare_types.each do |type|
        type.terms.each do |name|
          next if /\W/ =~ name.to_s   # can't use non-words characters
          methods[name] = Unit.new(type, 1)
        end
      end

      mod = Module.new

      mod.module_eval do
        methods.each do |name, unit|
          define_method(name) do
            Measure.new(self, unit)
          end
        end
      end

      prefixes.each do |prefix|
        mod.module_eval do
          define_method(prefix.name) do
            prefix
          end
        end
      end

      mod
    end

    # The @universal_conversions hash is used to prevent
    # secondary unit types of like quantities from replacing
    # the conical types. When defining conversions, always put
    # the concical types first.
    #
    # TODO: Add concical option to UnitType class, so they can be skipped.

    def au_conversion(type)
      return nil if type.system == :au
      return nil if @universal_conversions[type.quantity]
      au_system = Stick.systems[:au]
      au_type   = au_system.types.values.find{ |u| u.quantity == type.quantity }
      return nil unless au_type
      au_measure = au_type.base
      #au_measure = au_type.measure
      f = 1
      au_measure.units.each do |u|
        f *= (frame.A(u.symbol) ** u.power)
      end
      au_type * f

      this_to_au = type.conversion(au_type * f)
      au_to_this = au_type.conversion(type / f)

      @universal_conversions[type.quantity] = [this_to_au, au_to_this]
    end

    #

    def ==(other)
      case other
      when Symbol
        name == other
      else
        super
      end
    end

    private

    # Parse a conversion string. This method makes it possible
    # to define conversions using a concise string-based notation.
    # Simply separate units by name or symbol and optionally suffix
    # them with a power. A single division ("/") can also be used.
    #
    #   si.N = "kg m / s2"
    #
    # If the unit is from another unit system, prefix the unit
    # with the systems name and a colon.
    #
    #   us.nmi = "si:nmi"
    #
    # Currently this does not support prefixes or plain numbers.
    #--
    # TODO: Support prefixes in string conversions.
    # TODO: Support numbers in string conversions.
    #++
    def parse(conversion)
      numerator, denominator = *conversion.split('/')
      numerator = numerator.strip.split(/\s+/)
      numerator = numerator.inject(1) do |c, n|
        c * parse_segment(n)
      end

      if denominator
        denominator = denominator.strip.split(/\s+/)
        denominator = denominator.inject(1) do |c, d|
          c * parse_segment(d)
        end
        result = numerator / denominator
      else
        result = numerator
      end
      result
    end

    # Parse a conversion string segment.
    def parse_segment(segment)
      case segment
      when /(\w+):(\w+)(\d+)/
        systems[$1.to_sym].types[$2.to_sym] ** $3.to_i
      when /(\w+):(\w+)[-](\d+)/
        systems[$1.to_sym].types[$2.to_sym] ** -($3.to_i)
      when /(\w+):(\w+)/
        systems[$1.to_sym].types[$2.to_sym]
      when /(\w+)(\d+)/
        types[$1.to_sym] ** $2.to_i
      when /(\w+)[-](\d+)/
        types[$1.to_sym] ** -($2.to_i)
      when /(\w+)/
        types[$1.to_sym]
      when /(\d+)/
        ($1.to_i)
      when /[-](\d+)/
        -($1.to_i)
      end
    end

  end

end


text:
CREATE TABLE `order_change_set` (
  `id_order_change_set` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_order` int(11) unsigned DEFAULT NULL,
  `timestamp` timestamp NULL DEFAULT NULL,
  `id_admin` int(11) unsigned DEFAULT NULL,
  `id_user` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id_order_change_set`),
  KEY `id_order` (`id_order`),
  KEY `id_admin` (`id_admin`),
  KEY `id_user` (`id_user`),
  CONSTRAINT `order_change_set_ibfk_3` FOREIGN KEY (`id_user`) REFERENCES `user` (`id_user`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `order_change_set_ibfk_1` FOREIGN KEY (`id_order`) REFERENCES `order` (`id_order`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `order_change_set_ibfk_2` FOREIGN KEY (`id_admin`) REFERENCES `admin` (`id_admin`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `order_change` (
  `id_order_change` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_order_change_set` int(11) unsigned DEFAULT NULL,
  `field` varchar(255) DEFAULT NULL,
  `old_value` varchar(255) DEFAULT NULL,
  `new_value` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id_order_change`),
  KEY `id_order_change_set` (`id_order_change_set`),
  CONSTRAINT `order_change_ibfk_1` FOREIGN KEY (`id_order_change_set`) REFERENCES `order_change_set` (`id_order_change_set`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
package gitlab

import (
	"bytes"
	"encoding/json"
	"gopkg.in/yaml.v2"
	"io"
)

type Renderable interface {
	RenderJson(w io.Writer) error
	RenderYaml(w io.Writer) error
}

func renderJson(w io.Writer, v interface{}) error {
	j, err := json.Marshal(v)
	if err != nil {
		return err
	}

	var indented bytes.Buffer
	err = json.Indent(&indented, j, "", "  ")
	if err != nil {
		return err
	}

	_, err = indented.WriteTo(w)

	return err
}

func renderYaml(w io.Writer, v interface{}) error {
	j, err := yaml.Marshal(v)
	if err != nil {
		return err
	}

	w.Write(j)

	return nil
}


text:
package threewks.framework.cloudstorage.attachment.transformer;

import threewks.framework.cloudstorage.attachment.AttachmentDto;
import threewks.framework.cloudstorage.attachment.model.Attachment;
import threewks.framework.transformer.NullSafeTransformer;
import threewks.framework.usermanager.controller.dto.transformer.ToUserDto;

public class ToAttachmentDto extends NullSafeTransformer<Attachment, AttachmentDto> {
    @Override
    public AttachmentDto transform(Attachment input) {
        return new AttachmentDto()
            .setBucket(input.getBucket())
            .setContentType(input.getContentType())
            .setFilename(input.getFilename())
            .setGcsObjectName(input.getGcsObjectName())
            .setId(input.getId())
            .setName(input.getName())
            .setSize(input.getSize())
            .setCreated(input.getCreated())
            .setUploadedBy(ToUserDto.INSTANCE.apply(input.getUploadedBy()));
    }
}


text:
cask 'ipe' do
  version '7.2.6'
  sha256 '35e90434d635bb0c085c4447767ad746e61fc276b1f1dbe43a9d671327d5cfa1'

  # bintray.com/otfried was verified as official when first introduced to the cask
  url "https://dl.bintray.com/otfried/generic/ipe/#{version.major_minor}/ipe-#{version}-mac.dmg"
  name 'Ipe'
  homepage 'http://ipe.otfried.org/'

  app 'Ipe.app'

  zap delete: [
                '~/.ipe',
                '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.otfried.ipe.ipe.sfl',
                '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.otfried.ipe.sfl',
                '~/Library/Preferences/org.otfried.ipe.Ipe.plist',
                '~/Library/Saved Application State/org.otfried.ipe.savedState',
              ]
end


text:
package cn.coolspan.open.android_increment_update;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * To work on unit tests, switch the Test Artifact in the Build Variants view.
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}


text:
/* Mark tidy up Nov 2005 */
/* General purpose header file - rf 12/90 */

#ifndef _H_general
    #define _H_general

namespace clustalw
{

    /* Macintosh specific rf 12/9/94 */
    #ifdef OS_MAC

        //#define const           /* THINK C doesn't know about these identifiers */
        //#define signed
        //#define volatile
        //#define int long
        //#define pint short            /* cast ints in printf statements as pint*/
        //#define int int            /* cast ints for sequence lengths */
        //#define lint int            /* cast ints for profile scores */

    #else

        //#define pint int            /* cast ints in printf statements as pint */
        //#define int int            /* cast ints for sequence lengths */
        //#define lint int             /* cast ints for profile scores */

    #endif

    /* definitions for all machines */

    #define EOS '\0'                /* End-Of-String */
    #define MAXLINE 5000            /* Max. line length */

}
#endif /* ifndef _H_general */


text:
include $(TOPDIR)/config.mk

LIB	= libpostdrivers.o

COBJS-$(CONFIG_HAS_POST)	+= flash.o i2c.o memory.o rtc.o

include $(TOPDIR)/post/rules.mk