text:
This project contains code to parse `cron` expressions and build corresponding Java objects. It provides a small
interface for checking whether a `cron` expression matches a `java.time.ZonedDateTime` object. It provides code for
integrating with `java.util.concurrent`, though using this is optional and it might be more straightforward to roll
your own.

It might come in handy if you're already using (or don't mind using) Java8, [Guava](http://code.google.com/p/guava-libraries/),
want to handle `cron` expressions, and don't want a full-blown scheduling library like [Quartz](http://quartz-scheduler.org).

## Motivation

* support POSIX cron syntax
    * day of week 0-6 (with 0=Sunday)
    * both day of week and day of month may be specified in a single expression
    * etc.
* support syntax of other common implementations
    * ranges, e.g. `1-10` which is equivalent to `1,2,3,4,5,6,7,8,9,10`
    * ranges with skipped numbers, e.g. `1-10/2` which is equivalent to `1,3,5,7,9`
    * wildcard ranges, e.g. `*/5`
    * aliases:

Alias     | Description                                                           | Equivalent
----------|-----------------------------------------------------------------------|-------------
@reboot   | Run at startup                                                        |
@yearly   | Run once a year at midnight in the morning of January 1               | `0 0 1 1 *`
@annually | (same as @yearly)                                                     |
@monthly  | Run once a month at midnight in the morning of the first of the month | `0 0 1 * *`
@weekly   | Run once a week at midnight in the morning of Sunday                  | `0 0 * * 0`
@daily    | Run once a day at midnight                                            | `0 0 * * *`
@midnight | (same as @daily)                                                      |
@hourly   | Run once an hour at the beginning of the hour                         | `0 * * * *`

* support [Quartz](http://quartz-scheduler.org) syntax
    * day of week 1-7 (with 1=Sunday)
    * either day of month or day of week but not both
    * nth day of week of month
    * last day of week of month
    * last day of month
    * nearest weekday of month
    * etc.
* support scenarios that [Quartz](http://quartz-scheduler.org) doesn't
    * multiple nth day of week of month, for example:
        * `0 0 * * 1#2,5#3` (at midnight on the second Monday and third Friday of every month)
    * multiple last day of week of month, for example:
        * `0 0 * * 1L,5L` (at midnight on the last Friday and last Monday of every month)
* minimal support for `java.util.concurrent`
* represent `cron` expressions as immutable objects
* be as fast or faster than other implementations, such as [Quartz](http://quartz-scheduler.org)
* use less memory than other implementations, such as [Quartz](http://quartz-scheduler.org)

## Requirements

* Java 8
* [Guava](http://code.google.com/p/guava-libraries/)

## Examples

### Normal

```java
ZonedDateTime time = ZonedDateTime.now().withDayOfYear(1).truncatedTo(ChronoUnit.DAYS);
assertTrue(CronExpression.parse("0 0 1 1 *").matches(time));
assertTrue(CronExpression.parse("@yearly").matches(time));
assertTrue(CronExpression.parse("@annually").matches(time));
assertTrue(CronExpression.yearly().matches(time));
```

### Quartz-like

```java
CronExpression expression = CronExpression.parser()
    .withSecondsField(true)
    .withOneBasedDayOfWeek(true)
    .allowBothDayFields(false)
    .parse("0 15 10 L * ?");
ZonedDateTime time = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS)
    .withYear(2013)
    .withMonth(1)
    .withDayOfMonth(31)
    .withHour(10)
    .withMinute(15);
assertTrue(expression.matches(time));
```

You can find more examples in the unit tests.

redpajama_set_name: RedPajamaGithub


text:
:mod:`libtaxii.taxii_default_query` Module
==========================================
.. automodule:: libtaxii.taxii_default_query

Classes
-------

Default Query
*************

.. autoclass:: DefaultQuery
	:show-inheritance:
	:members:

**Example**

.. code-block:: python

	import libtaxii.taxii_default_query as tdq
	from libtaxii.taxii_default_query import Test
	from libtaxii.taxii_default_query import Criterion
	from libtaxii.taxii_default_query import Criteria
	from libtaxii.constants import *
	import datetime

	##############################################################################
	# A Taxii Default Query *Test* gives the consumer granular control over the
	# Target of a Query by applying unambiguos relationship requirements specified
	# using a standardized vocabulary.

	# Each Relationship (e.g. equals, matches, greater_than, etc.) in a Capability
	# Module defines a set of paramater fields, capable of expressing that
	# relation.

	# The *equals* relationship, of the Core Capability Module,  returns True if
	# the target matches the value exactly. If the target merely contains the
	# value (but does not match exactly) the relationship Test returns False.
	test_equals = Test(capability_id=CM_CORE,
	                   relationship='equals',
	                   parameters={'value': 'Test value',
	                               'match_type': 'case_sensitive_string'})

	# The *matches* relationship, in the context of the Regular Expression
	# Capability Module, returns true if the target matches the regular expression
	# contained in the value.
	test_matches = Test(capability_id=CM_REGEX,
	                    relationship='matches',
	                    parameters={'value': '[A-Z]*',
	                                'case_sensitive': True})

	# The *greater than* relationship, in the context of the Timestamp Capability
	# Module returns True if the target's timestamp indicates a later time than
	# that specified by this value. This relationship is only valid for timestamp
	# comparisons.
	test_timestamp = Test(capability_id=CM_TIMESTAMP,
	                      relationship='greater_than',
	                      parameters={'value': datetime.datetime.now()})

	##############################################################################
	# A *Criterion* specifies how a Target is evaluated against a Test. Within a
	# Criterion, the Target is used to identify a specific region of a record to
	# which the Test should be applied. Slash Notation Targeting Expression syntax,
	# in conjunction with a Targeting Expression Vocabulary, are used to form a
	# Targeting Expression

	# A Multi-field Wildcard (**). This indicates any Node or series of Nodes,
	# specified by double asterisks.
	criterion1 = Criterion(target='**',
	                       test=test_equals)

	# Indicates that *id* fields in the STIX Indicator construct are in scope
	criterion2 = Criterion(target='STIX_Package/Indicators/Indicator/@id',
	                       test=test_matches)

	# Indicates that all STIX Description fields are in scope
	criterion3 = Criterion(target='**/Description',
	                       test=test_timestamp)

	##############################################################################
	# *Criteria* consist of a logical operator (and/or) that should be applied to
	# child Criteria and Criterion to determine whether content matches this query.

	criteria1 = Criteria(operator=OP_AND,
	                     criterion=[criterion1])

	criteria2 = Criteria(operator=OP_OR,
	                     criterion=[criterion1, criterion2, criterion3])

	criteria3 = Criteria(operator=OP_AND,
	                     criterion=[criterion1, criterion3],
	                     criteria=[criteria2])

	##############################################################################
	# query1, query2 and query3 would be able to be used in TAXII requests that
	# contain queries (e.g., PollRequest Messages)
	query1 = tdq.DefaultQuery(targeting_expression_id=CB_STIX_XML_111,
	                          criteria=criteria1)

	query2 = tdq.DefaultQuery(targeting_expression_id=CB_STIX_XML_111,
	                          criteria=criteria3)

	query3 = tdq.DefaultQuery(targeting_expression_id=CB_STIX_XML_111,
	                          criteria=criteria2)

Default Query Info
******************

.. autoclass:: DefaultQueryInfo
	:show-inheritance:
	:members:

**Example**

.. code-block:: python

	import libtaxii.taxii_default_query as tdq
	from libtaxii.taxii_default_query import TargetingExpressionInfo
	from libtaxii.constants import *

	##############################################################################
	# *TargetingExpressionInfo* describes which expressions are available to
	# a consumer when submitting a query to a taxii service. A
	# `targetting_expression_id` indicates a suppoted targetting vocabulary
	# TargetingExpressionInfo also contains the permissible scope of queries.

	# This example has no preferred scope, and allows any scope
	tei_01 = TargetingExpressionInfo(
	    targeting_expression_id=CB_STIX_XML_111,
	    preferred_scope=[],
	    allowed_scope=['**'])

	# This example prefers the Indicator scope and allows no other scope
	tei_02 = TargetingExpressionInfo(
	    targeting_expression_id=CB_STIX_XML_111,
	    preferred_scope=['STIX_Package/Indicators/Indicator/**'],
	    allowed_scope=[])

	##############################################################################
	# *DefaultQueryInfo* describes the TAXII Default Queries that are supported
	# using a list of TargetExpressionInfo objects, and a list of capability
	# module identifiers.
	tdqi1 = tdq.DefaultQueryInfo(
	    targeting_expression_infos=[tei_01, tei_02],
	    capability_modules=[CM_CORE])


text:
<?php

namespace NetSuite\Classes;

class SerializedAssemblyItemHierarchyVersionsList {
    /**
     * @var \NetSuite\Classes\SerializedAssemblyItemHierarchyVersions[]
     */
    public $serializedAssemblyItemHierarchyVersions;
    /**
     * @var boolean
     */
    public $replaceAll;
    static $paramtypesmap = array(
        "serializedAssemblyItemHierarchyVersions" => "SerializedAssemblyItemHierarchyVersions[]",
        "replaceAll" => "boolean",
    );
}


text:
package net.sourceforge.plantuml;

import java.io.IOException;
import java.io.OutputStream;

// Modified by Maxime Sinclair
public class NullOutputStream extends OutputStream {

    /**
     * Writes to nowhere
     */
    @Override
    public void write(int b) throws IOException {
        // Do nothing silently
    }

    /**
     * Overridden for performance reason
     */
    @Override
    public void write(byte b[]) throws IOException {
        // Do nothing silently
    }

    /**
     * Overridden for performance reason
     */
    @Override
    public void write(byte b[], int off, int len) throws IOException {
        // Do nothing silently
    }

}


text:
<!DOCTYPE animal [
<!ELEMENT animal ANY>
<?஘ an only legal per 5th edition char #x0b98
 in PITarget ?>
]>
<animal/>


text:
package llsm.io.metadata

import java.util.UUID

import org.scalatest.Matchers._
import org.scalacheck.Gen

class MetadataParserSpec extends MetadataSuite {

  "A Parser[String]" should " simply return the string" in {
    val in: String = "Hellow"

    assert(Parser[String](in) == Either.right("Hellow"))
  }
  it should "parse all strings" in forAll { (s: String) =>
    assert(Parser[String](s) == Either.right(s))
  }

  "A Parser[Int]" should "parse an int from a string" in {
    val in: String = "1"

    assertResult(Right(1))(Parser[Int](in))
  }
  it should "fail with an Error when the string cannont be cast to an integer" in {
    val hello: String = "hello"

    Parser[Int](hello) should be('left)
  }

  "A Parser[Waveform]" should "parse LLSM waveform metadata from a block of text" in {
    val wave =
      """Waveform type :	Linear

X Galvo Offset, Interval (um), # of Pixels for Excitation (0) :	0	0.1	101
X Galvo Offset, Interval (um), # of Pixels for Excitation (1) :	0	0.1	101

Z Galvo Offset, Interval (um), # of Pixels for Excitation (0) :	0.45	0	251
Z Galvo Offset, Interval (um), # of Pixels for Excitation (1) :	0.45	0	251

Z PZT Offset, Interval (um), # of Pixels for Excitation (0) :	12	0	251
Z PZT Offset, Interval (um), # of Pixels for Excitation (1) :	12	0	251

S PZT Offset, Interval (um), # of Pixels for Excitation (0) :	50	0.3	251
S PZT Offset, Interval (um), # of Pixels for Excitation (1) :	50	0.3	251

# of stacks (0) :	20
# of stacks (1) :	20

Excitation Filter, Laser, Power (%), Exp(ms) (0) :	N/A	561	2	3
Excitation Filter, Laser, Power (%), Exp(ms) (1) :	N/A	488	20	3

Cycle lasers :	per Z

Z motion :	Sample piezo"""
    val wf = Parser[WaveformMetadata](wave)

    wf match {
      case Right(
          WaveformMetadata(wt,
                           nSlices,
                           zPZTOffset,
                           sPZTOffset,
                           channels,
                           nFrames,
                           cyc,
                           zm)) => {
        assertResult("Linear")(wt)
        assertResult("Sample piezo")(zm)
        assertResult("per Z")(cyc)
        assertResult(251)(nSlices)
        assertResult(0)(zPZTOffset)
        assertResult(0.3)(sPZTOffset)
        assertResult(20)(nFrames)
        assertResult(2)(channels.size)
        assertResult(0)(channels(0).id)
      }
      case Left(ParsingFailure(m, e)) => fail(s"$m:\n$e")
    }
  }

  "A Parser[CameraMetadata]" should "parse CameraMetadata from a block of text" in {
    val text: String =
      """Model :	C11440-22C
Serial :	3296
Frame Transfer :	OFF
Trigger :	External
Exp(s) :	0.00101
Cycle(s) :	0.00226
Cycle(Hz) :	442.34 Hz
Frame Mode :	Run Till Abort
Readout Mode :	Image
ROI :	Left=897 Top=897 Right=1152 Bot=1152
Binning :	X=1 Y=1
# of Pixels :	X=2048 Y=2048
VSSspeed :	-1.0000
HSSspeed :	0.0000
VSSAmplitude :	Normal
Output Amplifier :	EM Amp
Temp(C) :	0.00000
AD Channel :	0
EM Gain :	0
HS Speed index :	0
Preamp Gain :	0
Bit depth :	0
Baseline Clamp :	Yes
Spool :	Enabled?=No File stem=Unknown type # buffs=10 Method=16-buit TIFF
# of Exps :	10040 exp(s)
Cropped :	On?=No # of pix=X=2048 Y=2048  Bin=X=1 Y=1
L ROI :	Left=897 Top=897 Right=0 Bot=1152
R ROI :	Left=0 Top=897 Right=1152 Bot=1152
FOV ROI :	Left=897 Top=897 Right=1152 Bot=1152
# of Imgs :	10040 img(s)
subROIs :	Unknown type
"""

    val cam = Parser[CameraMetadata](text)

    cam match {
      case Right(c: CameraMetadata) => {
        assertResult("C11440-22C")(c.model)
        assertResult(CameraMetadata.ROI(897L, 897L, 1152L, 1152L))(c.roi)
        assertResult(10040)(c.imgNumber)
        assertResult(0)(c.bitDepth)
      }
      case Left(ParsingFailure(m, e)) => fail(s"$m:\n$e")
    }

  }

  "A Parser[SampleStage]" should "parse the angle between the stage and bessel as a Double" in forAll("ang") {
    (ang: Double) =>
      val str: String = s"Angle between stage and bessel beam (deg) = $ang"

      Parser[SampleStage](str) match {
        case Right(SampleStage(a)) => a should equal (ang)
        case Left(ParsingFailure(m, e)) => fail(s"$m:\n$e")
      }
  }

  "A Parser[FilenameMetadata]" should "parse LLSM Metadata from a list of LLSM data files" in {
    val file: String =
      "Resolution test 4_ch1_stack0001_488nm_0007480msec_0008884606msecAbs.tif"

    Parser[FilenameMetadata](file) match {
      case Right(FilenameMetadata(id, n, c, tidx, wl, ts, ats)) => {
        assertResult(UUID.nameUUIDFromBytes(file.getBytes))(id)
        assertResult("Resolution test 4")(n)
        assertResult(1)(c)
        assertResult(1)(tidx)
        assertResult(488)(wl)
        assertResult(7480L)(ts)
        assertResult(8884606L)(ats)
      }
      case Left(ParsingFailure(m, e)) => fail(s"$m:\n$e")
    }
  }
  it should "parse any channel and stack number >= 0" in forAll(
    Gen.choose(0, Integer.MAX_VALUE),
    Gen.choose(0, 9999)) { (c: Int, s: Int) =>
    whenever(c >= 0 && s >= 0 && s <= 9999) {
      val paddedS = "%04d".format(s)

      val fn: String =
        s"Resolution test 4_ch${c}_stack${paddedS}_488nm_0007480msec_0008884606msecAbs.tif"
      val pfn: Parser.Result[FilenameMetadata] = Parser[FilenameMetadata](fn)
      pfn should be('right)
      pfn should be(
        Either.right(
          FilenameMetadata(UUID.nameUUIDFromBytes(fn.getBytes), "Resolution test 4", c, s, 488, 7480L, 8884606L)))
    }
  }
  it should "parse any wavelength 0 <= wl <= 9999" in forAll(
    Gen.choose(0, 9999)) { (w: Int) =>
    whenever(w >= 0 && w <= 9999) {
      val fn: String =
        s"Resolution test 4_ch1_stack0001_${w}nm_0007480msec_0008884606msecAbs.tif"

      val pfn: Parser.Result[FilenameMetadata] = Parser[FilenameMetadata](fn)

      pfn should be('right)
      pfn should be(
        Either.right(
          FilenameMetadata(UUID.nameUUIDFromBytes(fn.getBytes), "Resolution test 4", 1, 1, w, 7480L, 8884606L)))
    }
  }
  it should "successly parse when the name has underscores in it" in {
    val fn: String =
      s"Resolution_test_4_ch1_stack0001_488nm_0007480msec_0008884606msecAbs.tif"

    val pfn: Parser.Result[FilenameMetadata] = Parser[FilenameMetadata](fn)

    pfn should be('right)
    pfn should be(
      Either.right(
        FilenameMetadata(UUID.nameUUIDFromBytes(fn.getBytes), "Resolution_test_4", 1, 1, 488, 7480L, 8884606L)))
  }
  it should "fail when passed a malformed file name" in {
    val file: String = "Test_hello.txt"

    Parser[FilenameMetadata](file) should be('left)
  }
  it should "fail when the channel number isn't an Int" in {
    val file: String =
      "Resolution test 4_chh_stack0001_488nm_0007480msec_0008884606msecAbs.tif"

    Parser[FilenameMetadata](file) should be('left)
  }
  a[NumberFormatException] should be thrownBy {
    val file: String =
      "Resolution test 4_ch1_stack000b_488nm_0007480msec_0008884606msecAbs.tif"

    Parser[FilenameMetadata](file) match {
      case Left(ParsingFailure(_, e)) => throw e
      case _ =>
        fail("Expected a Either.Left with ParsingFailure but got Either.Right")
    }
  }
}


text:
#ifndef GrMtlPipelineState_DEFINED
#define GrMtlPipelineState_DEFINED

#include "include/private/GrTypesPriv.h"
#include "src/gpu/GrStencilSettings.h"
#include "src/gpu/glsl/GrGLSLProgramBuilder.h"
#include "src/gpu/mtl/GrMtlBuffer.h"
#include "src/gpu/mtl/GrMtlPipelineStateDataManager.h"

#import <Metal/Metal.h>

class GrMtlGpu;
class GrMtlPipelineStateDataManager;
class GrMtlSampler;
class GrMtlTexture;
class GrPipeline;

/**
 * Wraps a MTLRenderPipelineState object and also contains more info about the pipeline as needed
 * by Ganesh
 */
class GrMtlPipelineState {
public:
    using UniformInfoArray = GrMtlPipelineStateDataManager::UniformInfoArray;
    using UniformHandle = GrGLSLProgramDataManager::UniformHandle;

    GrMtlPipelineState(
            GrMtlGpu* gpu,
            id<MTLRenderPipelineState> pipelineState,
            MTLPixelFormat pixelFormat,
            const GrGLSLBuiltinUniformHandles& builtinUniformHandles,
            const UniformInfoArray& uniforms,
            uint32_t uniformBufferSize,
            uint32_t numSamplers,
            std::unique_ptr<GrGLSLPrimitiveProcessor> geometryProcessor,
            std::unique_ptr<GrGLSLXferProcessor> xferPRocessor,
            std::unique_ptr<std::unique_ptr<GrGLSLFragmentProcessor>[]> fragmentProcessors,
            int fFragmentProcessorCnt);

    id<MTLRenderPipelineState> mtlPipelineState() { return fPipelineState; }

    void setData(const GrRenderTarget*, GrSurfaceOrigin,
                 const GrPrimitiveProcessor& primPRoc, const GrPipeline& pipeline,
                 const GrTextureProxy* const primProcTextures[]);

    void setDrawState(id<MTLRenderCommandEncoder>, const GrSwizzle& outputSwizzle,
                      const GrXferProcessor&);

    static void SetDynamicScissorRectState(id<MTLRenderCommandEncoder> renderCmdEncoder,
                                           const GrRenderTarget* renderTarget,
                                           GrSurfaceOrigin rtOrigin,
                                           SkIRect scissorRect);

    bool doesntSampleAttachment(const MTLRenderPassAttachmentDescriptor*) const;

private:
    /**
    * We use the RT's size and origin to adjust from Skia device space to Metal normalized device
    * space and to make device space positions have the correct origin for processors that require
    * them.
    */
    struct RenderTargetState {
        SkISize         fRenderTargetSize;
        GrSurfaceOrigin fRenderTargetOrigin;

        RenderTargetState() { this->invalidate(); }
        void invalidate() {
            fRenderTargetSize.fWidth = -1;
            fRenderTargetSize.fHeight = -1;
            fRenderTargetOrigin = (GrSurfaceOrigin)-1;
        }

        /**
        * Gets a float4 that adjusts the position from Skia device coords to Metals normalized
        * device coords. Assuming the transformed position, pos, is a homogeneous float3, the vec,
        * v, is applied as such:
        * pos.x = dot(v.xy, pos.xz)
        * pos.y = dot(v.zw, pos.yz)
        */
        void getRTAdjustmentVec(float* destVec) {
            destVec[0] = 2.f / fRenderTargetSize.fWidth;
            destVec[1] = -1.f;
            if (kBottomLeft_GrSurfaceOrigin == fRenderTargetOrigin) {
                destVec[2] = -2.f / fRenderTargetSize.fHeight;
                destVec[3] = 1.f;
            } else {
                destVec[2] = 2.f / fRenderTargetSize.fHeight;
                destVec[3] = -1.f;
            }
        }
    };

    void setRenderTargetState(const GrRenderTarget*, GrSurfaceOrigin);

    void bind(id<MTLRenderCommandEncoder>);

    void setBlendConstants(id<MTLRenderCommandEncoder>, const GrSwizzle&, const GrXferProcessor&);

    void setDepthStencilState(id<MTLRenderCommandEncoder> renderCmdEncoder);

    struct SamplerBindings {
        GrMtlSampler*  fSampler;
        id<MTLTexture> fTexture;

        SamplerBindings(const GrSamplerState& state, GrTexture* texture, GrMtlGpu*);
    };

    GrMtlGpu* fGpu;
    id<MTLRenderPipelineState> fPipelineState;
    MTLPixelFormat             fPixelFormat;

    RenderTargetState fRenderTargetState;
    GrGLSLBuiltinUniformHandles fBuiltinUniformHandles;

    GrStencilSettings fStencil;

    int fNumSamplers;
    SkTArray<SamplerBindings> fSamplerBindings;

    std::unique_ptr<GrGLSLPrimitiveProcessor> fGeometryProcessor;
    std::unique_ptr<GrGLSLXferProcessor> fXferProcessor;
    std::unique_ptr<std::unique_ptr<GrGLSLFragmentProcessor>[]> fFragmentProcessors;
    int fFragmentProcessorCnt;

    GrMtlPipelineStateDataManager fDataManager;
};

#endif


text:
<?php

namespace Webit\DataSelection\Tests\Filter;

use Webit\DataSelection\Filter\Model\FilterDateTime;
use Webit\DataSelection\Filter\Model\FilterDateTimeComparatorModes;
use Webit\DataSelection\Filter\Model\FilterDateTimeComparators;
use Webit\DataSelection\Filter\Model\FilterTypes;

/**
 * Class FilterDateTimeTest
 * @package Webit\DataSelection\Tests\Filter
 */
class FilterDateTimeTest extends AbstractFilterTest
{
    public function setUp()
    {
        $this->class = 'Webit\\DataSelection\\Filter\\Model\\FilterDateTime';
        $this->filterType = FilterTypes::TYPE_DATETIME;

        $this->defaultData = array(
            'property' => null,
            'value' => null,
            'comparator' => FilterDateTimeComparators::EQUAL,
            'comparatorMode' => FilterDateTimeComparatorModes::MODE_DATE_TIME
        );

        $this->expectedData = array(
            'property' => 'test-property',
            'value' => new \DateTime(),
            'comparator' => FilterDateTimeComparators::GREATER_THAN,
            'comparatorMode' => FilterDateTimeComparatorModes::MODE_DATE
        );
    }

    /**
     * @expectedException \Webit\DataSelection\Filter\Model\Exception\InvalidFilterComparatorException
     */
    public function testInvalidComparator()
    {
        $filter = new FilterDateTime();
        $filter->setComparator('invalid-comparator');
    }

    /**
     * @expectedException \Webit\DataSelection\Filter\Model\Exception\InvalidFilterDateTimeComparatorModeException
     */
    public function testInvalidComparatorMode()
    {
        $filter = new FilterDateTime();
        $filter->setComparatorMode('invalid-comparator-mode');
    }
}


text:
function [L,H,I] = csdCalculate(X,gridloc,delta,channel_order,sync_channel_position,above_sync,below_sync)
%super_csd_interp
%To output the CSD array for a specified electrode and grid.
%
%Example:
%[L,H,I] = super_csd(X,coordinates_to_grid(15,7,15),100,[9 8 10 7 13 4 12 5 15 2 16 1 14 3 11 6])
%[L,H,I] = super_csd(X,coordinates_to_grid(1,1,10),25,[23 10 24 9 25 8 26 7 27 6 28 5 29 4 30 3 31 2 32 1 22 11 21 12 20 13 19 14 18 15 17 16])
%[L,H,I] = super_csd(X,coordinates_to_grid(1,1,10),25,[23 10 24 9 25 8 26 7 27 6 28 5 29 4 30 3 31 2 1 22 11 21 12 20 13 19 14 18 15 17 16])
%[L,H,I] = super_csd(X,217,100,[9 8 10 7 13 4 12 5 15 2 16 1 14 3 11 6])
%[L,H,I] = super_csd(X,1,100,[9 8 10 7 13 4 12 5 15 2 16 1 14 3 11 6])
%T = GetSGStimTriggers('/Users/dennisou/Desktop','t00022',179);
%
%
%myheader = readvhlvheaderfile([path filesep tfile filesep header])
%myheader = readvhlvheaderfile(['/Users/dennisou/Desktop/' filesep 't00001' filesep 'vhlvanaloginput.vlh']);
%
%[L,H,I] = super_csd_interp(Xw2b,coordinates_to_grid(9,1,10),25,[23 10 24 9 25 8 26 7 27 6 28 5 29 4 30 3 31 2 1 22 11 21 12 20 13 19 14 18 15 17 16],sync_channel_position,above_sync,below_sync)
%
%NOTE:
%The If Statement on Line 77 has to be eliminated for exceptions.

%% Creating the LFP Array L
%gridloc = coordinates(x,y,rows);

%Isolating the relevant matrix
matrix = X(:,gridloc);  %This should output a 16 by 1 cell. Each element within this cell should be ~620 by 31.

%Converting to suitable format
matrix2 = [];

%NOTE: Could potentially take in num_triggers for all grids so the most
%complete data could be outputted.
s = size(matrix{1});    %[~620 31]
num_triggers = s(1);    %~620

channels = length(matrix);    %16 channels

%Converts matrix1 (16 by 1 cell with ~620 by 31 elements) into matrix2 (16 by 31 by ~620)
for i = 1:num_triggers  %iterates ~620 times
    temp = [];
    for j = 1:channels  %iterates 16 times
        temp(j,:) = matrix{j,1}(i,:);
    end
    matrix2(:,:,i) = temp;  %matrix2 will be a 16 by 31 by ~620 array.
end

%Need to convert columns to rows and rows to columns
s1 = size(matrix2); %[16 31 ~620]
depth = s1(3); %depth = ~620
matrix3 = [];

for i = 1:depth     %iterates ~620 times
    matrix3(:,:,i) = matrix2(:,:,i)';   %matrix3 will be a 31 by 16 by ~620 array.
end

matrix4 = mean(matrix3,3);  %averages matrix3 along the depth axis which results in matrix4 being a 31 by 16 array
L = matrix4';   %L is a 16 by 31 array

size_L = size(L);
rows_L = size_L(1);
columns_L = size_L(2);

%% Taking care of the offset
%L is either 16 or 31 rows
for i = 1:rows_L
    relevant_offset = L(i,1);
    for j = 1:columns_L
        L(i,j) = L(i,j) - relevant_offset;
    end
end

%% Creating the CSD array, H
%Note: The reason why the above was inverted and uninverted was because the
%31 by 16 format of matrix4 was compatible for the CSD code below; however,
%the 16 by 31 format of L has time as the x-axis which makes more sense for
%viewing. L will also be called out via the function superCSD and that is
%why this confusing step is necessary.

%T = GetSGStimTriggers(dirname,tfile,gridloc);   %a 1 by 620 array
%containing all triggers within the ~20min of training session. This is
%already accounted for in matrix X.

F = [];

%Accounting for the offset for all LFP values used in the CSD generating
%code after this
size_matrix3 = size(matrix3);
rows_matrix3 = size_matrix3(1);
cols_matrix3 = size_matrix3(2);
depth_matrix3 = size_matrix3(3);

for i = 1:depth_matrix3
    for j = 1:cols_matrix3
        relevant_offset = matrix3(1,j,i);
        for k = 1:rows_matrix3
            matrix3(k,j,i) = matrix3(k,j,i) - relevant_offset;
        end
    end
end

for i = 1:num_triggers %iterates ~620 times
    deltaX = delta*10^-6;     %Converting the delta[um] to deltaX[m]
    %channel_order = [9 8 10 7 13 4 12 5 15 2 16 1 14 3 11 6]; % 16 channel order
    %channel_order = [23 10 24 9 25 8 26 7 27 6 28 5 29 4 30 3 31 2 "32" 1 22 11 21 12 20 13 19 14 18 15 17 16]
    %above length = 31
    LFP = matrix3(:,:,i);
    CSD = [];

    %real function:
    for j = 2:(length(channel_order)-1) %2:15 or 2:30
        if (channel_order(j) == above_sync) && (sync_channel_position ~= 0)
            CSD(:,channel_order(j)) = (LFP(:,channel_order(j-2)) + LFP(:,channel_order(j+1)) ...   % CSD equation
             - 2*LFP(:,channel_order(j))) / ((deltaX*2)^2);
        elseif (channel_order(j) == below_sync) && (sync_channel_position ~= 0)
            CSD(:,channel_order(j)) = (LFP(:,channel_order(j-1)) + LFP(:,channel_order(j+2)) ...   % CSD equation
             - 2*LFP(:,channel_order(j))) / ((deltaX*2)^2);
        else
            CSD(:,channel_order(j)) = (LFP(:,channel_order(j-1)) + LFP(:,channel_order(j+1)) ...   % CSD equation
             - 2*LFP(:,channel_order(j))) / ((deltaX)^2);
        end
    end
    F(:,:,i) = CSD;
end

G = mean(F,3);  %Collapsing the array by averaging it.
H = G'; %Inverting the array so that the pcolor graph is easier to interpret

%% Removing (snipping) empty channels --- these empty channels are due to a discrepancy of not taking into account the first
%and last of the channel_order array

bad_rows = [channel_order(1) channel_order(end)];   %[23 16] in the case of the 31-channel electrode
for i = 1:length(bad_rows)
    H(bad_rows(i),:) = [];
end

%% Modifying the array L into a surf-friendly format I
I = pcolordummyrowcolumn(H);
end

%To do list:
%1. How about accounting only for 1 triggers or fewer grids? Might accounting
%for all triggers by averaging the corresponding LFP values lower the
%significance?


text:
"""
Utility functions to return a formatted name and description for a given view.
"""
from django.utils.html import escape
from django.utils.safestring import mark_safe

from taiga.base.api.settings import api_settings

from textwrap import dedent
import re

# Markdown is optional
try:
    import markdown

    def apply_markdown(text):
        """
        Simple wrapper around :func:`markdown.markdown` to set the base level
        of '#' style headers to <h2>.
        """
        extensions = ["headerid(level=2)"]
        safe_mode = False
        md = markdown.Markdown(extensions=extensions, safe_mode=safe_mode)
        return md.convert(text)

except ImportError:
    apply_markdown = None

def remove_trailing_string(content, trailing):
    """
    Strip trailing component `trailing` from `content` if it exists.
    Used when generating names from view classes.
    """
    if content.endswith(trailing) and content != trailing:
        return content[:-len(trailing)]
    return content

def dedent(content):
    """
    Remove leading indent from a block of text.
    Used when generating descriptions from docstrings.

    Note that python's `textwrap.dedent` doesn't quite cut it,
    as it fails to dedent multiline docstrings that include
    unindented text on the initial line.
    """
    whitespace_counts = [len(line) - len(line.lstrip(" "))
                         for line in content.splitlines()[1:] if line.lstrip()]

    # unindent the content if needed
    if whitespace_counts:
        whitespace_pattern = "^" + (" " * min(whitespace_counts))
        content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), "", content)

    return content.strip()

def camelcase_to_spaces(content):
    """
    Translate 'CamelCaseNames' to 'Camel Case Names'.
    Used when generating names from view classes.
    """
    camelcase_boundry = "(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))"
    content = re.sub(camelcase_boundry, " \\1", content).strip()
    return " ".join(content.split("_")).title()

def markup_description(description):
    """
    Apply HTML markup to the given description.
    """
    if apply_markdown:
        description = apply_markdown(description)
    else:
        description = escape(description).replace("\n", "<br />")
    return mark_safe(description)


text:
namespace chrono {

using namespace fea;
using namespace collision;
using namespace geometry;

// Register into the object factory, to enable run-time dynamic creation and persistence
CH_FACTORY_REGISTER(ChAssembly)

ChAssembly::ChAssembly()
    : nbodies(0),
      nlinks(0),
      nmeshes(0),
      nphysicsitems(0),
      ndof(0),
      ndoc(0),
      ndoc_w(0),
      ndoc_w_C(0),
      ndoc_w_D(0),
      ncoords(0),
      ncoords_w(0),
      nsysvars(0),
      nsysvars_w(0),
      nbodies_sleep(0),
      nbodies_fixed(0) {}

ChAssembly::ChAssembly(const ChAssembly& other) : ChPhysicsItem(other) {
    nbodies = other.nbodies;
    nlinks = other.nlinks;
    nmeshes = other.nmeshes;
    nphysicsitems = other.nphysicsitems;
    ncoords = other.ncoords;
    ncoords_w = other.ncoords_w;
    ndoc = other.ndoc;
    ndoc_w = other.ndoc_w;
    ndoc_w_C = other.ndoc_w_C;
    ndoc_w_D = other.ndoc_w_D;
    ndof = other.ndof;
    nsysvars = other.nsysvars;
    nsysvars_w = other.nsysvars_w;
    nbodies_sleep = other.nbodies_sleep;
    nbodies_fixed = other.nbodies_fixed;

    //// RADU
    //// TODO:  deep copy of the object lists (bodylist, linklist, meshlist,  otherphysicslist)
}

ChAssembly::~ChAssembly() {
    RemoveAllBodies();
    RemoveAllLinks();
    RemoveAllMeshes();
    RemoveAllOtherPhysicsItems();
}

void ChAssembly::Clear() {
    RemoveAllLinks();
    RemoveAllBodies();
    RemoveAllMeshes();
    RemoveAllOtherPhysicsItems();

    nbodies = 0;
    nlinks = 0;
    nmeshes = 0;
    nphysicsitems = 0;
    ndof = 0;
    ndoc = 0;
    ndoc_w = 0;
    ndoc_w_C = 0;
    ndoc_w_D = 0;
    nsysvars_w = 0;
    ncoords = 0;
    ncoords_w = 0;
    nsysvars = 0;
    ncoords_w = 0;
    nbodies_sleep = 0;
    nbodies_fixed = 0;
}

// Note: removing items from the assembly incurs linear time cost

void ChAssembly::AddBody(std::shared_ptr<ChBody> body) {
    assert(std::find(std::begin(bodylist), std::end(bodylist), body) == bodylist.end());
    assert(body->GetSystem() == nullptr);  // should remove from other system before adding here

    // set system and also add collision models to system
    body->SetSystem(system);
    bodylist.push_back(body);
}

void ChAssembly::RemoveBody(std::shared_ptr<ChBody> body) {
    auto itr = std::find(std::begin(bodylist), std::end(bodylist), body);
    assert(itr != bodylist.end());

    bodylist.erase(itr);
    body->SetSystem(nullptr);
}

void ChAssembly::AddLink(std::shared_ptr<ChLink> link) {
    assert(std::find(std::begin(linklist), std::end(linklist), link) == linklist.end());

    link->SetSystem(system);
    linklist.push_back(link);
}

void ChAssembly::RemoveLink(std::shared_ptr<ChLink> link) {
    auto itr = std::find(std::begin(linklist), std::end(linklist), link);
    assert(itr != linklist.end());

    linklist.erase(itr);
    link->SetSystem(nullptr);
}

void ChAssembly::AddMesh(std::shared_ptr<fea::ChMesh> mesh) {
    assert(std::find(std::begin(meshlist), std::end(meshlist), mesh) == meshlist.end());

    mesh->SetSystem(system);
    meshlist.push_back(mesh);
}

void ChAssembly::RemoveMesh(std::shared_ptr<fea::ChMesh> mesh) {
    auto itr = std::find(std::begin(meshlist), std::end(meshlist), mesh);
    assert(itr != meshlist.end());

    meshlist.erase(itr);
    mesh->SetSystem(nullptr);
}

void ChAssembly::AddOtherPhysicsItem(std::shared_ptr<ChPhysicsItem> item) {
    assert(!std::dynamic_pointer_cast<ChBody>(item));
    assert(!std::dynamic_pointer_cast<ChLink>(item));
    assert(!std::dynamic_pointer_cast<ChMesh>(item));
    assert(std::find(std::begin(otherphysicslist), std::end(otherphysicslist), item) == otherphysicslist.end());
    // assert(item->GetSystem()==nullptr); // should remove from other system before adding here

    // set system and also add collision models to system
    item->SetSystem(system);
    otherphysicslist.push_back(item);
}

void ChAssembly::RemoveOtherPhysicsItem(std::shared_ptr<ChPhysicsItem> item) {
    auto itr = std::find(std::begin(otherphysicslist), std::end(otherphysicslist), item);
    assert(itr != otherphysicslist.end());

    otherphysicslist.erase(itr);
    item->SetSystem(nullptr);
}

void ChAssembly::Add(std::shared_ptr<ChPhysicsItem> item) {
    if (auto body = std::dynamic_pointer_cast<ChBody>(item)) {
        AddBody(body);
        return;
    }

    if (auto link = std::dynamic_pointer_cast<ChLink>(item)) {
        AddLink(link);
        return;
    }

    if (auto mesh = std::dynamic_pointer_cast<fea::ChMesh>(item)) {
        AddMesh(mesh);
        return;
    }

    AddOtherPhysicsItem(item);
}

void ChAssembly::AddBatch(std::shared_ptr<ChPhysicsItem> item) {
    batch_to_insert.push_back(item);
}

void ChAssembly::FlushBatch() {
    for (auto& item : batch_to_insert) {
        Add(item);
    }
    batch_to_insert.clear();
}

void ChAssembly::Remove(std::shared_ptr<ChPhysicsItem> item) {
    if (auto body = std::dynamic_pointer_cast<ChBody>(item)) {
        RemoveBody(body);
        return;
    }

    if (auto link = std::dynamic_pointer_cast<ChLink>(item)) {
        RemoveLink(link);
        return;
    }

    if (auto mesh = std::dynamic_pointer_cast<fea::ChMesh>(item)) {
        RemoveMesh(mesh);
        return;
    }

    RemoveOtherPhysicsItem(item);
}

void ChAssembly::RemoveAllBodies() {
    for (auto& body : bodylist) {
        body->SetSystem(nullptr);
    }
    bodylist.clear();
}

void ChAssembly::RemoveAllLinks() {
    for (auto& link : linklist) {
        link->SetSystem(nullptr);
    }
    linklist.clear();
}

void ChAssembly::RemoveAllMeshes() {
    for (auto& mesh : meshlist) {
        mesh->SetSystem(nullptr);
    }
    meshlist.clear();
}

void ChAssembly::RemoveAllOtherPhysicsItems() {
    for (auto& item : otherphysicslist) {
        item->SetSystem(nullptr);
    }
    otherphysicslist.clear();
}

std::shared_ptr<ChBody> ChAssembly::SearchBody(const char* name) {
    return ChContainerSearchFromName<std::shared_ptr<ChBody>, std::vector<std::shared_ptr<ChBody>>::iterator>(
        name, bodylist.begin(), bodylist.end());
}

std::shared_ptr<ChLink> ChAssembly::SearchLink(const char* name) {
    return ChContainerSearchFromName<std::shared_ptr<ChLink>, std::vector<std::shared_ptr<ChLink>>::iterator>(
        name, linklist.begin(), linklist.end());
}

std::shared_ptr<fea::ChMesh> ChAssembly::SearchMesh(const char* name) {
    return ChContainerSearchFromName<std::shared_ptr<fea::ChMesh>, std::vector<std::shared_ptr<fea::ChMesh>>::iterator>(
        name, meshlist.begin(), meshlist.end());
}

std::shared_ptr<ChPhysicsItem> ChAssembly::SearchOtherPhysicsItem(const char* name) {
    return ChContainerSearchFromName<std::shared_ptr<ChPhysicsItem>,
                                     std::vector<std::shared_ptr<ChPhysicsItem>>::iterator>(
        name, otherphysicslist.begin(), otherphysicslist.end());
}

std::shared_ptr<ChPhysicsItem> ChAssembly::Search(const char* name) {
    if (auto mbo = SearchBody(name))
        return mbo;

    if (auto mli = SearchLink(name))
        return mli;

    if (auto mesh = SearchMesh(name))
        return mesh;

    if (auto mph = SearchOtherPhysicsItem(name))
        return mph;

    return std::shared_ptr<ChPhysicsItem>();  // not found; return an empty shared_ptr
}

std::shared_ptr<ChMarker> ChAssembly::SearchMarker(const char* name) {
    // Iterate over all bodies and search in the body's marker list
    for (auto& body : bodylist) {
        if (auto mmark = body->SearchMarker(name))
            return mmark;
    }

    return (std::shared_ptr<ChMarker>());  // not found; return an empty shared_ptr
}

std::shared_ptr<ChMarker> ChAssembly::SearchMarker(int markID) {
    // Iterate over all bodies and search in the body's marker list
    for (auto& body : bodylist) {
        if (auto res = ChContainerSearchFromID<std::shared_ptr<ChMarker>,
                                               std::vector<std::shared_ptr<ChMarker>>::const_iterator>(
                markID, body->GetMarkerList().begin(), body->GetMarkerList().end()))
            return res;
    }

    return (std::shared_ptr<ChMarker>());  // not found; return an empty shared_ptr
}

// -----------------------------------------------------------------------------

void ChAssembly::SetSystem(ChSystem* m_system) {
    system = m_system;

    for (auto& body : bodylist) {
        body->SetSystem(m_system);
    }
    for (auto& link : linklist) {
        link->SetSystem(m_system);
    }
    for (auto& mesh : meshlist) {
        mesh->SetSystem(m_system);
    }
    for (auto& item : otherphysicslist) {
        item->SetSystem(m_system);
    }
}

void ChAssembly::SyncCollisionModels() {
    for (auto& body : bodylist) {
        body->SyncCollisionModels();
    }
    for (auto& link : linklist) {
        link->SyncCollisionModels();
    }
    for (auto& mesh : meshlist) {
        mesh->SyncCollisionModels();
    }
    for (auto& item : otherphysicslist) {
        item->SyncCollisionModels();
    }
}

// -----------------------------------------------------------------------------
// UPDATING ROUTINES

// Count all bodies, links, meshes, and other physics items.
// Set counters (DOF, num constraints, etc) and offsets.
void ChAssembly::Setup() {
    nbodies = 0;
    nbodies_sleep = 0;
    nbodies_fixed = 0;
    ncoords = 0;
    ncoords_w = 0;
    ndoc = 0;
    ndoc_w = 0;
    ndoc_w_C = 0;
    ndoc_w_D = 0;
    nlinks = 0;
    nmeshes = 0;
    nphysicsitems = 0;

    // Add any items queued for insertion in the assembly's lists.
    this->FlushBatch();

    for (auto& body : bodylist) {
        if (body->GetBodyFixed())
            nbodies_fixed++;
        else if (body->GetSleeping())
            nbodies_sleep++;
        else {
            nbodies++;

            body->SetOffset_x(this->offset_x + ncoords);
            body->SetOffset_w(this->offset_w + ncoords_w);
            body->SetOffset_L(this->offset_L + ndoc_w);

            // body->Setup(); // not needed since in bodies does nothing

            ncoords += body->GetDOF();
            ncoords_w += body->GetDOF_w();
            ndoc_w += body->GetDOC();      // not really needed since ChBody introduces no constraints
            ndoc_w_C += body->GetDOC_c();  // not really needed since ChBody introduces no constraints
            ndoc_w_D += body->GetDOC_d();  // not really needed since ChBody introduces no constraints
        }
    }

    for (auto& link : linklist) {
        if (link->IsActive()) {
            nlinks++;

            link->SetOffset_x(this->offset_x + ncoords);
            link->SetOffset_w(this->offset_w + ncoords_w);
            link->SetOffset_L(this->offset_L + ndoc_w);

            link->Setup();  // compute DOFs etc. and sets the offsets also in child items, if any

            ncoords += link->GetDOF();
            ncoords_w += link->GetDOF_w();
            ndoc_w += link->GetDOC();
            ndoc_w_C += link->GetDOC_c();
            ndoc_w_D += link->GetDOC_d();
        }
    }

    for (auto& mesh : meshlist) {
        nmeshes++;

        mesh->SetOffset_x(this->offset_x + ncoords);
        mesh->SetOffset_w(this->offset_w + ncoords_w);
        mesh->SetOffset_L(this->offset_L + ndoc_w);

        mesh->Setup();  // compute DOFs and iteratively call Setup for child items

        ncoords += mesh->GetDOF();
        ncoords_w += mesh->GetDOF_w();
        ndoc_w += mesh->GetDOC();
        ndoc_w_C += mesh->GetDOC_c();
        ndoc_w_D += mesh->GetDOC_d();
    }

    for (auto& item : otherphysicslist) {
        nphysicsitems++;

        item->SetOffset_x(this->offset_x + ncoords);
        item->SetOffset_w(this->offset_w + ncoords_w);
        item->SetOffset_L(this->offset_L + ndoc_w);

        item->Setup();

        ncoords += item->GetDOF();
        ncoords_w += item->GetDOF_w();
        ndoc_w += item->GetDOC();
        ndoc_w_C += item->GetDOC_c();
        ndoc_w_D += item->GetDOC_d();
    }

    ndoc = ndoc_w + nbodies;          // number of constraints including quaternion constraints.
    nsysvars = ncoords + ndoc;        // total number of variables (coordinates + lagrangian multipliers)
    nsysvars_w = ncoords_w + ndoc_w;  // total number of variables (with 6 dof per body)

    // number of degrees of freedom (approximate - does not consider constr. redundancy, etc)
    ndof = ncoords_w - ndoc_w;
}

// Update assembly's own properties first (ChTime and assets, if any).
// Then update all contents of this assembly.
void ChAssembly::Update(double mytime, bool update_assets) {
    ChPhysicsItem::Update(mytime, update_assets);
    Update(update_assets);
}

// Update all physical items (bodies, links, meshes, etc), including their auxiliary variables.
// Updates all forces (automatic, as children of bodies)
// Updates all markers (automatic, as children of bodies).
void ChAssembly::Update(bool update_assets) {
    //// NOTE: do not switch these to range for loops (may want to use OMP for)
    for (int ip = 0; ip < (int)bodylist.size(); ++ip) {
        bodylist[ip]->Update(ChTime, update_assets);
    }
    for (int ip = 0; ip < (int)otherphysicslist.size(); ++ip) {
        otherphysicslist[ip]->Update(ChTime, update_assets);
    }
    for (int ip = 0; ip < (int)linklist.size(); ++ip) {
        linklist[ip]->Update(ChTime, update_assets);
    }
    for (int ip = 0; ip < (int)meshlist.size(); ++ip) {
        meshlist[ip]->Update(ChTime, update_assets);
    }
}

void ChAssembly::SetNoSpeedNoAcceleration() {
    for (auto& body : bodylist) {
        body->SetNoSpeedNoAcceleration();
    }
    for (auto& link : linklist) {
        link->SetNoSpeedNoAcceleration();
    }
    for (auto& mesh : meshlist) {
        mesh->SetNoSpeedNoAcceleration();
    }
    for (auto& item : otherphysicslist) {
        item->SetNoSpeedNoAcceleration();
    }
}

void ChAssembly::IntStateGather(const unsigned int off_x,
                                ChState& x,
                                const unsigned int off_v,
                                ChStateDelta& v,
                                double& T) {
    unsigned int displ_x = off_x - this->offset_x;
    unsigned int displ_v = off_v - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntStateGather(displ_x + body->GetOffset_x(), x, displ_v + body->GetOffset_w(), v, T);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntStateGather(displ_x + link->GetOffset_x(), x, displ_v + link->GetOffset_w(), v, T);
    }
    for (auto& mesh : meshlist) {
        mesh->IntStateGather(displ_x + mesh->GetOffset_x(), x, displ_v + mesh->GetOffset_w(), v, T);
    }
    for (auto& item : otherphysicslist) {
        item->IntStateGather(displ_x + item->GetOffset_x(), x, displ_v + item->GetOffset_w(), v, T);
    }
    T = GetChTime();
}

void ChAssembly::IntStateScatter(const unsigned int off_x,
                                 const ChState& x,
                                 const unsigned int off_v,
                                 const ChStateDelta& v,
                                 const double T) {
    unsigned int displ_x = off_x - this->offset_x;
    unsigned int displ_v = off_v - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntStateScatter(displ_x + body->GetOffset_x(), x, displ_v + body->GetOffset_w(), v, T);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntStateScatter(displ_x + link->GetOffset_x(), x, displ_v + link->GetOffset_w(), v, T);
    }
    for (auto& mesh : meshlist) {
        mesh->IntStateScatter(displ_x + mesh->GetOffset_x(), x, displ_v + mesh->GetOffset_w(), v, T);
    }
    for (auto& item : otherphysicslist) {
        item->IntStateScatter(displ_x + item->GetOffset_x(), x, displ_v + item->GetOffset_w(), v, T);
    }
    SetChTime(T);

    // Note: all those IntStateScatter() above should call Update() automatically
    // for each object in the loop, therefore:
    // -do not call Update() on this.
    // -do not call ChPhysicsItem::IntStateScatter() -it calls this->Update() anyway-
    // because this would cause redundant updates.
}

void ChAssembly::IntStateGatherAcceleration(const unsigned int off_a, ChStateDelta& a) {
    unsigned int displ_a = off_a - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntStateGatherAcceleration(displ_a + body->GetOffset_w(), a);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntStateGatherAcceleration(displ_a + link->GetOffset_w(), a);
    }
    for (auto& mesh : meshlist) {
        mesh->IntStateGatherAcceleration(displ_a + mesh->GetOffset_w(), a);
    }
    for (auto& item : otherphysicslist) {
        item->IntStateGatherAcceleration(displ_a + item->GetOffset_w(), a);
    }
}

// From state derivative (acceleration) to system, sometimes might be needed
void ChAssembly::IntStateScatterAcceleration(const unsigned int off_a, const ChStateDelta& a) {
    unsigned int displ_a = off_a - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntStateScatterAcceleration(displ_a + body->GetOffset_w(), a);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntStateScatterAcceleration(displ_a + link->GetOffset_w(), a);
    }
    for (auto& mesh : meshlist) {
        mesh->IntStateScatterAcceleration(displ_a + mesh->GetOffset_w(), a);
    }
    for (auto& item : otherphysicslist) {
        item->IntStateScatterAcceleration(displ_a + item->GetOffset_w(), a);
    }
}

// From system to reaction forces (last computed) - some timestepper might need this
void ChAssembly::IntStateGatherReactions(const unsigned int off_L, ChVectorDynamic<>& L) {
    unsigned int displ_L = off_L - this->offset_L;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntStateGatherReactions(displ_L + body->GetOffset_L(), L);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntStateGatherReactions(displ_L + link->GetOffset_L(), L);
    }
    for (auto& mesh : meshlist) {
        mesh->IntStateGatherReactions(displ_L + mesh->GetOffset_L(), L);
    }
    for (auto& item : otherphysicslist) {
        item->IntStateGatherReactions(displ_L + item->GetOffset_L(), L);
    }
}

// From reaction forces to system, ex. store last computed reactions in ChLink objects for plotting etc.
void ChAssembly::IntStateScatterReactions(const unsigned int off_L, const ChVectorDynamic<>& L) {
    unsigned int displ_L = off_L - this->offset_L;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntStateScatterReactions(displ_L + body->GetOffset_L(), L);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntStateScatterReactions(displ_L + link->GetOffset_L(), L);
    }
    for (auto& mesh : meshlist) {
        mesh->IntStateScatterReactions(displ_L + mesh->GetOffset_L(), L);
    }
    for (auto& item : otherphysicslist) {
        item->IntStateScatterReactions(displ_L + item->GetOffset_L(), L);
    }
}

void ChAssembly::IntStateIncrement(const unsigned int off_x,
                                   ChState& x_new,
                                   const ChState& x,
                                   const unsigned int off_v,
                                   const ChStateDelta& Dv) {
    unsigned int displ_x = off_x - this->offset_x;
    unsigned int displ_v = off_v - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntStateIncrement(displ_x + body->GetOffset_x(), x_new, x, displ_v + body->GetOffset_w(), Dv);
    }

    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntStateIncrement(displ_x + link->GetOffset_x(), x_new, x, displ_v + link->GetOffset_w(), Dv);
    }

    for (auto& mesh : meshlist) {
        mesh->IntStateIncrement(displ_x + mesh->GetOffset_x(), x_new, x, displ_v + mesh->GetOffset_w(), Dv);
    }

    for (auto& item : otherphysicslist) {
        item->IntStateIncrement(displ_x + item->GetOffset_x(), x_new, x, displ_v + item->GetOffset_w(), Dv);
    }
}

void ChAssembly::IntLoadResidual_F(const unsigned int off,  ///< offset in R residual
                                   ChVectorDynamic<>& R,    ///< result: the R residual, R += c*F
                                   const double c)          ///< a scaling factor
{
    unsigned int displ_v = off - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntLoadResidual_F(displ_v + body->GetOffset_w(), R, c);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntLoadResidual_F(displ_v + link->GetOffset_w(), R, c);
    }
    for (auto& mesh : meshlist) {
        mesh->IntLoadResidual_F(displ_v + mesh->GetOffset_w(), R, c);
    }
    for (auto& item : otherphysicslist) {
        item->IntLoadResidual_F(displ_v + item->GetOffset_w(), R, c);
    }
}

void ChAssembly::IntLoadResidual_Mv(const unsigned int off,      ///< offset in R residual
                                    ChVectorDynamic<>& R,        ///< result: the R residual, R += c*M*v
                                    const ChVectorDynamic<>& w,  ///< the w vector
                                    const double c               ///< a scaling factor
) {
    unsigned int displ_v = off - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntLoadResidual_Mv(displ_v + body->GetOffset_w(), R, w, c);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntLoadResidual_Mv(displ_v + link->GetOffset_w(), R, w, c);
    }
    for (auto& mesh : meshlist) {
        mesh->IntLoadResidual_Mv(displ_v + mesh->GetOffset_w(), R, w, c);
    }
    for (auto& item : otherphysicslist) {
        item->IntLoadResidual_Mv(displ_v + item->GetOffset_w(), R, w, c);
    }
}

void ChAssembly::IntLoadResidual_CqL(const unsigned int off_L,    ///< offset in L multipliers
                                     ChVectorDynamic<>& R,        ///< result: the R residual, R += c*Cq'*L
                                     const ChVectorDynamic<>& L,  ///< the L vector
                                     const double c               ///< a scaling factor
) {
    unsigned int displ_L = off_L - this->offset_L;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntLoadResidual_CqL(displ_L + body->GetOffset_L(), R, L, c);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntLoadResidual_CqL(displ_L + link->GetOffset_L(), R, L, c);
    }
    for (auto& mesh : meshlist) {
        mesh->IntLoadResidual_CqL(displ_L + mesh->GetOffset_L(), R, L, c);
    }
    for (auto& item : otherphysicslist) {
        item->IntLoadResidual_CqL(displ_L + item->GetOffset_L(), R, L, c);
    }
}

void ChAssembly::IntLoadConstraint_C(const unsigned int off_L,  ///< offset in Qc residual
                                     ChVectorDynamic<>& Qc,     ///< result: the Qc residual, Qc += c*C
                                     const double c,            ///< a scaling factor
                                     bool do_clamp,             ///< apply clamping to c*C?
                                     double recovery_clamp      ///< value for min/max clamping of c*C
) {
    unsigned int displ_L = off_L - this->offset_L;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntLoadConstraint_C(displ_L + body->GetOffset_L(), Qc, c, do_clamp, recovery_clamp);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntLoadConstraint_C(displ_L + link->GetOffset_L(), Qc, c, do_clamp, recovery_clamp);
    }
    for (auto& mesh : meshlist) {
        mesh->IntLoadConstraint_C(displ_L + mesh->GetOffset_L(), Qc, c, do_clamp, recovery_clamp);
    }
    for (auto& item : otherphysicslist) {
        item->IntLoadConstraint_C(displ_L + item->GetOffset_L(), Qc, c, do_clamp, recovery_clamp);
    }
}

void ChAssembly::IntLoadConstraint_Ct(const unsigned int off_L,  ///< offset in Qc residual
                                      ChVectorDynamic<>& Qc,     ///< result: the Qc residual, Qc += c*Ct
                                      const double c             ///< a scaling factor
) {
    unsigned int displ_L = off_L - this->offset_L;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntLoadConstraint_Ct(displ_L + body->GetOffset_L(), Qc, c);
    }
    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntLoadConstraint_Ct(displ_L + link->GetOffset_L(), Qc, c);
    }
    for (auto& mesh : meshlist) {
        mesh->IntLoadConstraint_Ct(displ_L + mesh->GetOffset_L(), Qc, c);
    }
    for (auto& item : otherphysicslist) {
        item->IntLoadConstraint_Ct(displ_L + item->GetOffset_L(), Qc, c);
    }
}

void ChAssembly::IntToDescriptor(const unsigned int off_v,
                                 const ChStateDelta& v,
                                 const ChVectorDynamic<>& R,
                                 const unsigned int off_L,
                                 const ChVectorDynamic<>& L,
                                 const ChVectorDynamic<>& Qc) {
    unsigned int displ_L = off_L - this->offset_L;
    unsigned int displ_v = off_v - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntToDescriptor(displ_v + body->GetOffset_w(), v, R, displ_L + body->GetOffset_L(), L, Qc);
    }

    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntToDescriptor(displ_v + link->GetOffset_w(), v, R, displ_L + link->GetOffset_L(), L, Qc);
    }

    for (auto& mesh : meshlist) {
        mesh->IntToDescriptor(displ_v + mesh->GetOffset_w(), v, R, displ_L + mesh->GetOffset_L(), L, Qc);
    }

    for (auto& item : otherphysicslist) {
        item->IntToDescriptor(displ_v + item->GetOffset_w(), v, R, displ_L + item->GetOffset_L(), L, Qc);
    }
}

void ChAssembly::IntFromDescriptor(const unsigned int off_v,
                                   ChStateDelta& v,
                                   const unsigned int off_L,
                                   ChVectorDynamic<>& L) {
    unsigned int displ_L = off_L - this->offset_L;
    unsigned int displ_v = off_v - this->offset_w;

    for (auto& body : bodylist) {
        if (body->IsActive())
            body->IntFromDescriptor(displ_v + body->GetOffset_w(), v, displ_L + body->GetOffset_L(), L);
    }

    for (auto& link : linklist) {
        if (link->IsActive())
            link->IntFromDescriptor(displ_v + link->GetOffset_w(), v, displ_L + link->GetOffset_L(), L);
    }

    for (auto& mesh : meshlist) {
        mesh->IntFromDescriptor(displ_v + mesh->GetOffset_w(), v, displ_L + mesh->GetOffset_L(), L);
    }

    for (auto& item : otherphysicslist) {
        item->IntFromDescriptor(displ_v + item->GetOffset_w(), v, displ_L + item->GetOffset_L(), L);
    }
}

// -----------------------------------------------------------------------------

void ChAssembly::InjectVariables(ChSystemDescriptor& mdescriptor) {
    for (auto& body : bodylist) {
        body->InjectVariables(mdescriptor);
    }
    for (auto& link : linklist) {
        link->InjectVariables(mdescriptor);
    }
    for (auto& mesh : meshlist) {
        mesh->InjectVariables(mdescriptor);
    }
    for (auto& item : otherphysicslist) {
        item->InjectVariables(mdescriptor);
    }
}

void ChAssembly::VariablesFbReset() {
    for (auto& body : bodylist) {
        body->VariablesFbReset();
    }
    for (auto& link : linklist) {
        link->VariablesFbReset();
    }
    for (auto& mesh : meshlist) {
        mesh->VariablesFbReset();
    }
    for (auto& item : otherphysicslist) {
        item->VariablesFbReset();
    }
}

void ChAssembly::VariablesFbLoadForces(double factor) {
    for (auto& body : bodylist) {
        body->VariablesFbLoadForces(factor);
    }
    for (auto& link : linklist) {
        link->VariablesFbLoadForces(factor);
    }
    for (auto& mesh : meshlist) {
        mesh->VariablesFbLoadForces(factor);
    }
    for (auto& item : otherphysicslist) {
        item->VariablesFbLoadForces(factor);
    }
}

void ChAssembly::VariablesFbIncrementMq() {
    for (auto& body : bodylist) {
        body->VariablesFbIncrementMq();
    }
    for (auto& link : linklist) {
        link->VariablesFbIncrementMq();
    }
    for (auto& mesh : meshlist) {
        mesh->VariablesFbIncrementMq();
    }
    for (auto& item : otherphysicslist) {
        item->VariablesFbIncrementMq();
    }
}

void ChAssembly::VariablesQbLoadSpeed() {
    for (auto& body : bodylist) {
        body->VariablesQbLoadSpeed();
    }
    for (auto& link : linklist) {
        link->VariablesQbLoadSpeed();
    }
    for (auto& mesh : meshlist) {
        mesh->VariablesQbLoadSpeed();
    }
    for (auto& item : otherphysicslist) {
        item->VariablesQbLoadSpeed();
    }
}

void ChAssembly::VariablesQbSetSpeed(double step) {
    for (auto& body : bodylist) {
        body->VariablesQbSetSpeed(step);
    }
    for (auto& link : linklist) {
        link->VariablesQbSetSpeed(step);
    }
    for (auto& mesh : meshlist) {
        mesh->VariablesQbSetSpeed(step);
    }
    for (auto& item : otherphysicslist) {
        item->VariablesQbSetSpeed(step);
    }
}

void ChAssembly::VariablesQbIncrementPosition(double dt_step) {
    for (auto& body : bodylist) {
        body->VariablesQbIncrementPosition(dt_step);
    }
    for (auto& link : linklist) {
        link->VariablesQbIncrementPosition(dt_step);
    }
    for (auto& mesh : meshlist) {
        mesh->VariablesQbIncrementPosition(dt_step);
    }
    for (auto& item : otherphysicslist) {
        item->VariablesQbIncrementPosition(dt_step);
    }
}

void ChAssembly::InjectConstraints(ChSystemDescriptor& mdescriptor) {
    for (auto& body : bodylist) {
        body->InjectConstraints(mdescriptor);
    }
    for (auto& link : linklist) {
        link->InjectConstraints(mdescriptor);
    }
    for (auto& mesh : meshlist) {
        mesh->InjectConstraints(mdescriptor);
    }
    for (auto& item : otherphysicslist) {
        item->InjectConstraints(mdescriptor);
    }
}

void ChAssembly::ConstraintsBiReset() {
    for (auto& body : bodylist) {
        body->ConstraintsBiReset();
    }
    for (auto& link : linklist) {
        link->ConstraintsBiReset();
    }
    for (auto& mesh : meshlist) {
        mesh->ConstraintsBiReset();
    }
    for (auto& item : otherphysicslist) {
        item->ConstraintsBiReset();
    }
}

void ChAssembly::ConstraintsBiLoad_C(double factor, double recovery_clamp, bool do_clamp) {
    for (auto& body : bodylist) {
        body->ConstraintsBiLoad_C(factor, recovery_clamp, do_clamp);
    }
    for (auto& link : linklist) {
        link->ConstraintsBiLoad_C(factor, recovery_clamp, do_clamp);
    }
    for (auto& mesh : meshlist) {
        mesh->ConstraintsBiLoad_C(factor, recovery_clamp, do_clamp);
    }
    for (auto& item : otherphysicslist) {
        item->ConstraintsBiLoad_C(factor, recovery_clamp, do_clamp);
    }
}

void ChAssembly::ConstraintsBiLoad_Ct(double factor) {
    for (auto& body : bodylist) {
        body->ConstraintsBiLoad_Ct(factor);
    }
    for (auto& link : linklist) {
        link->ConstraintsBiLoad_Ct(factor);
    }
    for (auto& mesh : meshlist) {
        mesh->ConstraintsBiLoad_Ct(factor);
    }
    for (auto& item : otherphysicslist) {
        item->ConstraintsBiLoad_Ct(factor);
    }
}

void ChAssembly::ConstraintsBiLoad_Qc(double factor) {
    for (auto& body : bodylist) {
        body->ConstraintsBiLoad_Qc(factor);
    }
    for (auto& link : linklist) {
        link->ConstraintsBiLoad_Qc(factor);
    }
    for (auto& mesh : meshlist) {
        mesh->ConstraintsBiLoad_Qc(factor);
    }
    for (auto& item : otherphysicslist) {
        item->ConstraintsBiLoad_Qc(factor);
    }
}

void ChAssembly::ConstraintsFbLoadForces(double factor) {
    for (auto& body : bodylist) {
        body->ConstraintsFbLoadForces(factor);
    }
    for (auto& link : linklist) {
        link->ConstraintsFbLoadForces(factor);
    }
    for (auto& mesh : meshlist) {
        mesh->ConstraintsFbLoadForces(factor);
    }
    for (auto& item : otherphysicslist) {
        item->ConstraintsFbLoadForces(factor);
    }
}

void ChAssembly::ConstraintsLoadJacobians() {
    for (auto& body : bodylist) {
        body->ConstraintsLoadJacobians();
    }
    for (auto& link : linklist) {
        link->ConstraintsLoadJacobians();
    }
    for (auto& mesh : meshlist) {
        mesh->ConstraintsLoadJacobians();
    }
    for (auto& item : otherphysicslist) {
        item->ConstraintsLoadJacobians();
    }
}

void ChAssembly::ConstraintsFetch_react(double factor) {
    for (auto& body : bodylist) {
        body->ConstraintsFetch_react(factor);
    }
    for (auto& link : linklist) {
        link->ConstraintsFetch_react(factor);
    }
    for (auto& mesh : meshlist) {
        mesh->ConstraintsFetch_react(factor);
    }
    for (auto& item : otherphysicslist) {
        item->ConstraintsFetch_react(factor);
    }
}

void ChAssembly::InjectKRMmatrices(ChSystemDescriptor& mdescriptor) {
    for (auto& body : bodylist) {
        body->InjectKRMmatrices(mdescriptor);
    }
    for (auto& link : linklist) {
        link->InjectKRMmatrices(mdescriptor);
    }
    for (auto& mesh : meshlist) {
        mesh->InjectKRMmatrices(mdescriptor);
    }
    for (auto& item : otherphysicslist) {
        item->InjectKRMmatrices(mdescriptor);
    }
}

void ChAssembly::KRMmatricesLoad(double Kfactor, double Rfactor, double Mfactor) {
    for (auto& body : bodylist) {
        body->KRMmatricesLoad(Kfactor, Rfactor, Mfactor);
    }
    for (auto& link : linklist) {
        link->KRMmatricesLoad(Kfactor, Rfactor, Mfactor);
    }
    for (auto& mesh : meshlist) {
        mesh->KRMmatricesLoad(Kfactor, Rfactor, Mfactor);
    }
    for (auto& item : otherphysicslist) {
        item->KRMmatricesLoad(Kfactor, Rfactor, Mfactor);
    }
}

// -----------------------------------------------------------------------------
//  STREAMING - FILE HANDLING

void ChAssembly::ShowHierarchy(ChStreamOutAscii& m_file, int level) {
    std::string mtabs;
    for (int i = 0; i < level; ++i)
        mtabs += "  ";

    m_file << "\n" << mtabs << "List of the " << (int)bodylist.size() << " added rigid bodies: \n";
    for (auto& body : bodylist) {
        m_file << mtabs << "  BODY:       " << body->GetName() << "\n";

        for (auto& marker : body->GetMarkerList()) {
            m_file << mtabs << "    MARKER:  " << marker->GetName() << "\n";
        }

        for (auto& force : body->GetForceList()) {
            m_file << mtabs << "    FORCE:  " << force->GetName() << "\n";
        }
    }

    m_file << "\n" << mtabs << "List of the " << (int)linklist.size() << " added links: \n";
    for (auto& link : linklist) {
        m_file << mtabs << "  LINK:  " << link->GetName() << " [" << typeid(link.get()).name() << "]\n";
        if (auto malink = std::dynamic_pointer_cast<ChLinkMarkers>(link)) {
            if (malink->GetMarker1())
                m_file << mtabs << "    marker1:  " << malink->GetMarker1()->GetName() << "\n";
            if (malink->GetMarker2())
                m_file << mtabs << "    marker2:  " << malink->GetMarker2()->GetName() << "\n";
        }
    }

    m_file << "\n" << mtabs << "List of the " << (int)meshlist.size() << " added meshes: \n";
    for (auto& mesh : meshlist) {
        m_file << mtabs << "  MESH :   " << mesh->GetName() << "\n";
    }

    m_file << "\n" << mtabs << "List of other " << (int)otherphysicslist.size() << " added physic items: \n";
    for (auto& item : otherphysicslist) {
        m_file << mtabs << "  PHYSIC ITEM :   " << item->GetName() << " [" << typeid(item.get()).name() << "]\n";

        // recursion:
        if (auto assem = std::dynamic_pointer_cast<ChAssembly>(item))
            assem->ShowHierarchy(m_file, level + 1);
    }

    m_file << "\n\n";
}

void ChAssembly::ArchiveOUT(ChArchiveOut& marchive) {
    // version number
    marchive.VersionWrite<ChAssembly>();

    // serialize parent class
    ChPhysicsItem::ArchiveOUT(marchive);

    // serialize all member data:

    marchive << CHNVP(bodylist, "bodies");
    marchive << CHNVP(linklist, "links");
    marchive << CHNVP(meshlist, "meshes");
    marchive << CHNVP(otherphysicslist, "other_physics_items");
}

void ChAssembly::ArchiveIN(ChArchiveIn& marchive) {
    // version number
    int version = marchive.VersionRead<ChAssembly>();

    // deserialize parent class
    ChPhysicsItem::ArchiveIN(marchive);

    // stream in all member data:
    std::vector<std::shared_ptr<ChBody>> tempbodies;
    std::vector<std::shared_ptr<ChLink>> templinks;
    std::vector<std::shared_ptr<ChMesh>> tempmeshes;
    std::vector<std::shared_ptr<ChPhysicsItem>> tempitems;
    marchive >> CHNVP(tempbodies, "bodies");
    marchive >> CHNVP(templinks, "links");
    marchive >> CHNVP(tempmeshes, "meshes");
    marchive >> CHNVP(tempitems, "other_physics_items");
    // trick needed because the "Add...()" functions are required
    RemoveAllBodies();
    for (auto& body : tempbodies) {
        AddBody(body);
    }
    RemoveAllLinks();
    for (auto& link : templinks) {
        AddLink(link);
    }
    RemoveAllMeshes();
    for (auto& mesh : tempmeshes) {
        AddMesh(mesh);
    }
    RemoveAllOtherPhysicsItems();
    for (auto& item : tempitems) {
        AddOtherPhysicsItem(item);
    }

    // Recompute statistics, offsets, etc.
    Setup();
}

}  // end namespace chrono


text:
// This file is automatically generated.

package adila.db;

/*
 * Alcatel EVO7
 *
 * DEVICE: EVO7
 * MODEL: starTIM tab 7
 */
final class evo7_startim20tab207 {
    public static final String DATA = "Alcatel|EVO7|";
}


text:
A BookMarks App Thing!

This is a small web application that allows you to store and categorise your bookmarks.

## Installation ##
You require virtualenv to be installed to set this up, this lives in the package `python-virtualenv` under Ubuntu.

Clone the repo:
> git clone https://github.com/RossBrunton/BMAT.git bmat/

Create a virtualenv:
> virtualenv -p /usr/bin/python2.7 bmat

Enter this directory:
> cd bmat

Activate the virtualenv:
> source ./bin/activate

Install Django, six and requests:
> pip install -r requirements.txt

After this, rename `settings_local.py.sample`, to `settings_locals.py`, and give it a random secret key.

If you want to use MySQL, install mysqlclient as follows:
> pip install mysqlclient

And then rename `db.cnf.sample` to `db.cnf` and fill in your database details.

If you want to use a sqlite file (or any of Django's database backends) uncomment and possibly edit the relevent section
in `settings_local.py`.

Sync the database:
> manage.py migrate

Create an account:
> manage.py createsuperuser

Run the server (development only):
> manage.py runserver

For production, set up as you normally would a Django project. See
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/ for details on how to do this on Apache.

## Super Interesting Legal Stuff ##
This is licensed under the MIT License, see COPYING.txt for details.
Generally, you can do whatever you want with it. I'd appreciate it if you mentioned me, however.


text:
require 'ruby-hl7'
class HL7::Message::Segment::NK1 < HL7::Message::Segment
  add_field :set_id
  add_field :name
  add_field :relationship
  add_field :address
  add_field :phone_number
  add_field :organization_name, :idx => 13
  add_field :primary_language, :idx => 20
  add_field :contact_persons_name, :idx => 30
  add_field :contact_persons_telephone_number
  add_field :contact_persons_address
end


text:
#!/usr/bin/env python
# header.py - Generate C++ header files from IDL.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""Print a C++ header file for the IDL files specified on the command line"""

import sys, os.path, re, xpidl, itertools, glob

printdoccomments = False

if printdoccomments:
    def printComments(fd, clist, indent):
        for c in clist:
            fd.write("%s%s\n" % (indent, c))
else:
    def printComments(fd, clist, indent):
        pass

def firstCap(str):
    return str[0].upper() + str[1:]

def attributeParamName(a):
    return "a" + firstCap(a.name)

def attributeParamNames(a):
    l = [attributeParamName(a)]
    if a.implicit_jscontext:
        l.insert(0, "cx")
    return ", ".join(l)

def attributeNativeName(a, getter):
    binaryname = a.binaryname is not None and a.binaryname or firstCap(a.name)
    return "%s%s" % (getter and 'Get' or 'Set', binaryname)

def attributeReturnType(a, macro):
    """macro should be NS_IMETHOD or NS_IMETHODIMP"""
    if (a.nostdcall):
        return macro == "NS_IMETHOD" and "virtual nsresult" or "nsresult"
    else:
        return macro

def attributeParamlist(a, getter):
    l = ["%s%s" % (a.realtype.nativeType(getter and 'out' or 'in'),
                   attributeParamName(a))]
    if a.implicit_jscontext:
        l.insert(0, "JSContext* cx")

    return ", ".join(l)

def attributeAsNative(a, getter):
        deprecated = a.deprecated and "NS_DEPRECATED " or ""
        params = {'deprecated': deprecated,
                  'returntype': attributeReturnType(a, 'NS_IMETHOD'),
                  'binaryname': attributeNativeName(a, getter),
                  'paramlist': attributeParamlist(a, getter)}
        return "%(deprecated)s%(returntype)s %(binaryname)s(%(paramlist)s)" % params

def methodNativeName(m):
    return m.binaryname is not None and m.binaryname or firstCap(m.name)

def methodReturnType(m, macro):
    """macro should be NS_IMETHOD or NS_IMETHODIMP"""
    if m.nostdcall and m.notxpcom:
        return "%s%s" % (macro == "NS_IMETHOD" and "virtual " or "",
                         m.realtype.nativeType('in').strip())
    elif m.nostdcall:
        return "%snsresult" % (macro == "NS_IMETHOD" and "virtual " or "")
    elif m.notxpcom:
        return "%s_(%s)" % (macro, m.realtype.nativeType('in').strip())
    else:
        return macro

def methodAsNative(m):
    return "%s %s(%s)" % (methodReturnType(m, 'NS_IMETHOD'),
                          methodNativeName(m),
                          paramlistAsNative(m))

def paramlistAsNative(m, empty='void'):
    l = [paramAsNative(p) for p in m.params]

    if m.implicit_jscontext:
        l.append("JSContext* cx")

    if m.optional_argc:
        l.append('uint8_t _argc')

    if not m.notxpcom and m.realtype.name != 'void':
        l.append(paramAsNative(xpidl.Param(paramtype='out',
                                           type=None,
                                           name='_retval',
                                           attlist=[],
                                           location=None,
                                           realtype=m.realtype)))

    if len(l) == 0:
        return empty

    return ", ".join(l)

def paramAsNative(p):
    return "%s%s" % (p.nativeType(),
                     p.name)

def paramlistNames(m):
    names = [p.name for p in m.params]

    if m.implicit_jscontext:
        names.append('cx')

    if m.optional_argc:
        names.append('_argc')

    if not m.notxpcom and m.realtype.name != 'void':
        names.append('_retval')

    if len(names) == 0:
        return ''
    return ', '.join(names)

header = """/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM %(filename)s
 */

#ifndef __gen_%(basename)s_h__
#define __gen_%(basename)s_h__
"""

include = """
#ifndef __gen_%(basename)s_h__
#include "%(basename)s.h"
#endif
"""

jspubtd_include = """
#include "jspubtd.h"
"""

infallible_includes = """
#include "mozilla/Assertions.h"
#include "mozilla/Util.h"
"""

header_end = """/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
"""

footer = """
#endif /* __gen_%(basename)s_h__ */
"""

forward_decl = """class %(name)s; /* forward declaration */

"""

def idl_basename(f):
    """returns the base name of a file with the last extension stripped"""
    return os.path.basename(f).rpartition('.')[0]

def print_header(idl, fd, filename):
    fd.write(header % {'filename': filename,
                       'basename': idl_basename(filename)})

    foundinc = False
    for inc in idl.includes():
        if not foundinc:
            foundinc = True
            fd.write('\n')
        fd.write(include % {'basename': idl_basename(inc.filename)})

    if idl.needsJSTypes():
        fd.write(jspubtd_include)

    # Include some extra files if any attributes are infallible.
    for iface in [p for p in idl.productions if p.kind == 'interface']:
        for attr in [m for m in iface.members if isinstance(m, xpidl.Attribute)]:
            if attr.infallible:
                fd.write(infallible_includes)
                break

    fd.write('\n')
    fd.write(header_end)

    for p in idl.productions:
        if p.kind == 'include': continue
        if p.kind == 'cdata':
            fd.write(p.data)
            continue

        if p.kind == 'forward':
            fd.write(forward_decl % {'name': p.name})
            continue
        if p.kind == 'interface':
            write_interface(p, fd)
            continue
        if p.kind == 'typedef':
            printComments(fd, p.doccomments, '')
            fd.write("typedef %s %s;\n\n" % (p.realtype.nativeType('in'),
                                             p.name))

    fd.write(footer % {'basename': idl_basename(filename)})

iface_header = r"""
/* starting interface:    %(name)s */
#define %(defname)s_IID_STR "%(iid)s"

#define %(defname)s_IID \
  {0x%(m0)s, 0x%(m1)s, 0x%(m2)s, \
    { %(m3joined)s }}

"""

uuid_decoder = re.compile(r"""(?P<m0>[a-f0-9]{8})-
                              (?P<m1>[a-f0-9]{4})-
                              (?P<m2>[a-f0-9]{4})-
                              (?P<m3>[a-f0-9]{4})-
                              (?P<m4>[a-f0-9]{12})$""", re.X)

iface_prolog = """ {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(%(defname)s_IID)

"""

iface_epilog = """};

  NS_DEFINE_STATIC_IID_ACCESSOR(%(name)s, %(defname)s_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_%(macroname)s """

iface_forward = """

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_%(macroname)s(_to) """

iface_forward_safe = """

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_%(macroname)s(_to) """

iface_template_prolog = """

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class %(implclass)s : public %(name)s
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_%(macroname)s

  %(implclass)s();

private:
  ~%(implclass)s();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(%(implclass)s, %(name)s)

%(implclass)s::%(implclass)s()
{
  /* member initializers and constructor code */
}

%(implclass)s::~%(implclass)s()
{
  /* destructor code */
}

"""

example_tmpl = """%(returntype)s %(implclass)s::%(nativeName)s(%(paramList)s)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
"""

iface_template_epilog = """/* End of implementation class template. */
#endif

"""

attr_infallible_tmpl = """\
  inline %(realtype)s%(nativename)s(%(args)s)
  {
    %(realtype)sresult;
    mozilla::DebugOnly<nsresult> rv = %(nativename)s(%(argnames)s&result);
    MOZ_ASSERT(NS_SUCCEEDED(rv));
    return result;
  }
"""

def write_interface(iface, fd):
    if iface.namemap is None:
        raise Exception("Interface was not resolved.")

    def write_const_decls(g):
        fd.write("  enum {\n")
        enums = []
        for c in g:
            printComments(fd, c.doccomments, '  ')
            basetype = c.basetype
            value = c.getValue()
            enums.append("    %(name)s = %(value)s%(signed)s" % {
                         'name': c.name,
                         'value': value,
                         'signed': (not basetype.signed) and 'U' or ''})
        fd.write(",\n".join(enums))
        fd.write("\n  };\n\n")

    def write_method_decl(m):
        printComments(fd, m.doccomments, '  ')

        fd.write("  /* %s */\n" % m.toIDL())
        fd.write("  %s = 0;\n\n" % methodAsNative(m))

    def write_attr_decl(a):
        printComments(fd, a.doccomments, '  ')

        fd.write("  /* %s */\n" % a.toIDL());

        fd.write("  %s = 0;\n" % attributeAsNative(a, True))
        if a.infallible:
            fd.write(attr_infallible_tmpl %
                     {'realtype': a.realtype.nativeType('in'),
                      'nativename': attributeNativeName(a, getter=True),
                      'args': '' if not a.implicit_jscontext else 'JSContext* cx',
                      'argnames': '' if not a.implicit_jscontext else 'cx, '})

        if not a.readonly:
            fd.write("  %s = 0;\n" % attributeAsNative(a, False))
        fd.write("\n")

    defname = iface.name.upper()
    if iface.name[0:2] == 'ns':
        defname = 'NS_' + defname[2:]

    names = uuid_decoder.match(iface.attributes.uuid).groupdict()
    m3str = names['m3'] + names['m4']
    names['m3joined'] = ", ".join(["0x%s" % m3str[i:i+2] for i in xrange(0, 16, 2)])

    if iface.name[2] == 'I':
        implclass = iface.name[:2] + iface.name[3:]
    else:
        implclass = '_MYCLASS_'

    names.update({'defname': defname,
                  'macroname': iface.name.upper(),
                  'name': iface.name,
                  'iid': iface.attributes.uuid,
                  'implclass': implclass})

    fd.write(iface_header % names)

    printComments(fd, iface.doccomments, '')

    fd.write("class ")
    foundcdata = False
    for m in iface.members:
        if isinstance(m, xpidl.CDATA):
            foundcdata = True

    if not foundcdata:
        fd.write("NS_NO_VTABLE ")

    if iface.attributes.deprecated:
        fd.write("MOZ_DEPRECATED ")
    fd.write(iface.name)
    if iface.base:
        fd.write(" : public %s" % iface.base)
    fd.write(iface_prolog % names)

    for key, group in itertools.groupby(iface.members, key=type):
        if key == xpidl.ConstMember:
            write_const_decls(group) # iterator of all the consts
        else:
            for member in group:
                if key == xpidl.Attribute:
                    write_attr_decl(member)
                elif key == xpidl.Method:
                    write_method_decl(member)
                elif key == xpidl.CDATA:
                    fd.write(" %s" % member.data)
                else:
                    raise Exception("Unexpected interface member: %s" % member)

    fd.write(iface_epilog % names)

    for member in iface.members:
        if isinstance(member, xpidl.Attribute):
            fd.write("\\\n  %s; " % attributeAsNative(member, True))
            if not member.readonly:
                fd.write("\\\n  %s; " % attributeAsNative(member, False))
        elif isinstance(member, xpidl.Method):
            fd.write("\\\n  %s; " % methodAsNative(member))
    if len(iface.members) == 0:
        fd.write('\\\n  /* no methods! */')
    elif not member.kind in ('attribute', 'method'):
       fd.write('\\')

    fd.write(iface_forward % names)

    def emitTemplate(tmpl, tmpl_notxpcom=None):
        if tmpl_notxpcom == None:
            tmpl_notxpcom = tmpl
        for member in iface.members:
            if isinstance(member, xpidl.Attribute):
                fd.write(tmpl % {'asNative': attributeAsNative(member, True),
                                 'nativeName': attributeNativeName(member, True),
                                 'paramList': attributeParamNames(member)})
                if not member.readonly:
                    fd.write(tmpl % {'asNative': attributeAsNative(member, False),
                                     'nativeName': attributeNativeName(member, False),
                                     'paramList': attributeParamNames(member)})
            elif isinstance(member, xpidl.Method):
                if member.notxpcom:
                    fd.write(tmpl_notxpcom % {'asNative': methodAsNative(member),
                                              'nativeName': methodNativeName(member),
                                              'paramList': paramlistNames(member)})
                else:
                    fd.write(tmpl % {'asNative': methodAsNative(member),
                                     'nativeName': methodNativeName(member),
                                     'paramList': paramlistNames(member)})
        if len(iface.members) == 0:
            fd.write('\\\n  /* no methods! */')
        elif not member.kind in ('attribute', 'method'):
            fd.write('\\')

    emitTemplate("\\\n  %(asNative)s { return _to %(nativeName)s(%(paramList)s); } ")

    fd.write(iface_forward_safe % names)

    # Don't try to safely forward notxpcom functions, because we have no
    # sensible default error return.  Instead, the caller will have to
    # implement them.
    emitTemplate("\\\n  %(asNative)s { return !_to ? NS_ERROR_NULL_POINTER : _to->%(nativeName)s(%(paramList)s); } ",
                 "\\\n  %(asNative)s; ")

    fd.write(iface_template_prolog % names)

    for member in iface.members:
        if isinstance(member, xpidl.ConstMember) or isinstance(member, xpidl.CDATA): continue
        fd.write("/* %s */\n" % member.toIDL())
        if isinstance(member, xpidl.Attribute):
            fd.write(example_tmpl % {'implclass': implclass,
                                     'returntype': attributeReturnType(member, 'NS_IMETHODIMP'),
                                     'nativeName': attributeNativeName(member, True),
                                     'paramList': attributeParamlist(member, True)})
            if not member.readonly:
                fd.write(example_tmpl % {'implclass': implclass,
                                         'returntype': attributeReturnType(member, 'NS_IMETHODIMP'),
                                         'nativeName': attributeNativeName(member, False),
                                         'paramList': attributeParamlist(member, False)})
        elif isinstance(member, xpidl.Method):
            fd.write(example_tmpl % {'implclass': implclass,
                                     'returntype': methodReturnType(member, 'NS_IMETHODIMP'),
                                     'nativeName': methodNativeName(member),
                                     'paramList': paramlistAsNative(member, empty='')})
        fd.write('\n')

    fd.write(iface_template_epilog)

if __name__ == '__main__':
    from optparse import OptionParser
    o = OptionParser()
    o.add_option('-I', action='append', dest='incdirs', default=['.'],
                 help="Directory to search for imported files")
    o.add_option('--cachedir', dest='cachedir', default=None,
                 help="Directory in which to cache lex/parse tables.")
    o.add_option('-o', dest='outfile', default=None,
                 help="Output file (default is stdout)")
    o.add_option('-d', dest='depfile', default=None,
                 help="Generate a make dependency file")
    o.add_option('--regen', action='store_true', dest='regen', default=False,
                 help="Regenerate IDL Parser cache")
    options, args = o.parse_args()
    file = args[0] if args else None

    if options.cachedir is not None:
        if not os.path.isdir(options.cachedir):
            os.mkdir(options.cachedir)
        sys.path.append(options.cachedir)

    # The only thing special about a regen is that there are no input files.
    if options.regen:
        if options.cachedir is None:
            print >>sys.stderr, "--regen useless without --cachedir"
        # Delete the lex/yacc files.  Ply is too stupid to regenerate them
        # properly
        for fileglobs in [os.path.join(options.cachedir, f) for f in ["xpidllex.py*", "xpidlyacc.py*"]]:
            for filename in glob.glob(fileglobs):
                os.remove(filename)

    # Instantiate the parser.
    p = xpidl.IDLParser(outputdir=options.cachedir)

    if options.regen:
        sys.exit(0)

    if options.depfile is not None and options.outfile is None:
        print >>sys.stderr, "-d requires -o"
        sys.exit(1)

    if options.outfile is not None:
        outfd = open(options.outfile, 'w')
        closeoutfd = True
    else:
        outfd = sys.stdout
        closeoutfd = False

    idl = p.parse(open(file).read(), filename=file)
    idl.resolve(options.incdirs, p)
    print_header(idl, outfd, file)

    if closeoutfd:
        outfd.close()

    if options.depfile is not None:
        dirname = os.path.dirname(options.depfile)
        if dirname:
            try:
                os.makedirs(dirname)
            except:
                pass
        depfd = open(options.depfile, 'w')
        deps = [dep.replace('\\', '/') for dep in idl.deps]

        print >>depfd, "%s: %s" % (options.outfile, " ".join(deps))


text:
<?php

declare(strict_types=1);

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class StartQuizType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add("submit", SubmitType::class, array(
                'attr' => array('class' => "btn btn-large start-btn"),
                'label' => "start_quiz.btn",
            ));
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(array(
            'translation_domain' => 'translations',
        ));
    }
}