text:
/****************************************************************************
**
** Copyright (c) 2007-2008, Apple, Inc.
**
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
**   * Redistributions of source code must retain the above copyright notice,
**     this list of conditions and the following disclaimer.
**
**   * Redistributions in binary form must reproduce the above copyright notice,
**     this list of conditions and the following disclaimer in the documentation
**     and/or other materials provided with the distribution.
**
**   * Neither the name of Apple, Inc. nor the names of its contributors
**     may be used to endorse or promote products derived from this software
**     without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
****************************************************************************/

/*
 *  qmacdefines_mac_p.h
 *  All the defines you'll ever need for Qt/Mac :-)
 */

/* This is just many defines. Therefore it doesn't need things like:
QT_BEGIN_HEADER

QT_BEGIN_NAMESPACE

QT_MODULE(Gui)

QT_END_NAMESPACE

QT_END_HEADER

Yes, it is an informative comment ;-)
*/

#include <QtCore/qglobal.h>

#ifdef qDebug
#  define old_qDebug qDebug
#  undef qDebug
#endif

#ifdef __LP64__
typedef signed int OSStatus;
#else
typedef signed long OSStatus;
#endif

#ifdef __OBJC__
#    ifdef slots
#      define old_slots slots
#      undef slots
#    endif
#include <Cocoa/Cocoa.h>
#    ifdef old_slots
#      undef slots
#      define slots
#      undef old_slots
#    endif
#endif
#ifdef QT_MAC_USE_COCOA
    typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
    typedef struct OpaqueEventRef * EventRef;
    typedef struct OpaqueMenuRef * MenuRef;
    typedef struct OpaquePasteboardRef* PasteboardRef;
    typedef struct OpaqueRgnHandle * RgnHandle;
    typedef const struct __HIShape *HIShapeRef;
    typedef struct __HIShape *HIMutableShapeRef;
    typedef struct CGRect CGRect;
    typedef struct CGImage *CGImageRef;
    typedef struct CGContext *CGContextRef;
    typedef struct GDevice * GDPtr;
    typedef GDPtr * GDHandle;
    typedef struct OpaqueIconRef * IconRef;
#   ifdef __OBJC__
        typedef NSWindow* OSWindowRef;
        typedef NSView *OSViewRef;
        typedef NSMenu *OSMenuRef;
        typedef NSEvent *OSEventRef;
#   else
        typedef void *OSWindowRef;
        typedef void *OSViewRef;
        typedef void *OSMenuRef;
        typedef void *OSEventRef;
#   endif
#else  // Carbon
    typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
    typedef struct OpaqueEventRef * EventRef;
    typedef struct OpaqueMenuRef * MenuRef;
    typedef struct OpaquePasteboardRef* PasteboardRef;
    typedef struct OpaqueRgnHandle * RgnHandle;
    typedef const struct __HIShape *HIShapeRef;
    typedef struct __HIShape *HIMutableShapeRef;
    typedef struct CGRect CGRect;
    typedef struct CGImage *CGImageRef;
    typedef struct CGContext *CGContextRef;
    typedef struct GDevice * GDPtr;
    typedef GDPtr * GDHandle;
    typedef struct OpaqueIconRef * IconRef;
    typedef struct OpaqueWindowPtr * WindowRef;
    typedef struct OpaqueControlRef * HIViewRef;
    typedef WindowRef OSWindowRef;
    typedef HIViewRef OSViewRef;
    typedef MenuRef OSMenuRef;
    typedef EventRef OSEventRef;
#endif  // QT_MAC_USE_COCOA

typedef PasteboardRef OSPasteboardRef;
typedef struct AEDesc AEDescList;
typedef AEDescList AERecord;
typedef AERecord AppleEvent;

#ifdef check
#undef check
#endif

#ifdef old_qDebug
#  undef qDebug
#  define qDebug QT_NO_QDEBUG_MACRO
#  undef old_qDebug
#endif


text:
package com.google.cloud.bqsh

import scopt.OptionParser

object ScpOptionParser extends OptionParser[ScpConfig]("scp") with ArgParser[ScpConfig]{
  override def parse(args: Seq[String], env: Map[String,String]): Option[ScpConfig] = parse(args, ScpConfig())

  head("scp", Bqsh.UserAgent)

  help("help").text("prints this usage text")

  opt[Long]("count")
    .optional
    .text("(optional) number of records to copy (default: unlimited)")
    .action((x,c) => c.copy(limit = x))

  opt[Unit]("noCompress")
    .optional
    .text("(optional) compress output with gzip (default: true)")
    .action((_,c) => c.copy(compress = false))

  opt[String]("inDD")
    .optional
    .text("DD to be uploaded (INFILE will be used if not provided)")
    .action((x,c) => c.copy(inDD = x))

  opt[String]("inDsn")
    .optional
    .text("DSN to be uploaded")
    .action((x,c) => c.copy(inDsn = x))

  opt[String]("gcsOutUri")
    .optional
    .text("GCS URI of dataset copy")
    .action((x,c) => c.copy(gcsOutUri = x))

  checkConfig{x =>
    if (x.inDD.nonEmpty && x.inDsn.nonEmpty) {
      failure("only one of --inDD or --inDsn may be specified")
    } else success
  }
}

redpajama_set_name: RedPajamaGithub


text:
Some scripts to calculate similarity metrics of files that I wrote for malware analysis coursework.

These scripts have 2 purposes:
* Automate other scripts.
* Perform calculations and output CSV files.

They automate the following:

https://github.com/hdg7/EnTS

https://github.com/hdg7/NCD

To use ents_1, ents_2, first clean the folder ( I start with a new folder for each set of EnTS calculations):

!!! Do not run if you don't understand what is going on !!!
```
rm -r test/;
rm -r recon/;
rm or*;
rm sub*;
rm seg*;
rm wav*;
rm rec*;
rm file*;
```

Run this. It's the same as ents_1.py , but ents_1.py does not work. I have to figure out some silly thing I missed.

```
mkdir test recon;
for f in ../folder/*.format;
do
    ./entCalculator -i $f;
done;
mv segm* test/;
mv rec* recon/;
rm -r sub*;
rm -r or*;
rm -r wav*;
```
To do the calculations:

```python ents_2.py```

Using automate1.py

I'm calculating NCD and CR here, just edit the python file to something that suits your need (mostly just automation)


text:
$.widget("ui.timespinner", $.ui.spinner, {
    options: {
        // seconds
        step: 60 * 1000,
        // hours
        page: 60
    },

    _parse: function (value) {
        if (typeof value === "string") {
            // already a timestamp
            if (Number(value) == value) {
                return Number(value);
            }
            return +Globalize.parseDate(value);
        }
        return value;
    },

    _format: function (value) {
        return Globalize.format(new Date(value), "t");
    }
});

$(document).ready(function () {
    function sixty(value) {
        value = parseInt(value, 10);
        if (value >= 0 && value <= 59) {
            return ( value < 10 ? "0" : "" ) + value;
        }
    }

    $(".datepickerfield").not('.daterange').datepicker({dateFormat: 'yy-mm-dd'});

    $(".daterange").datepicker({
        numberOfMonths: 2,
        dateFormat: 'yy-mm-dd',
        showButtonPanel: true,
        onClose: function (selectedDate) {
            $this = $(this);
            if ($this.hasClass('daterange')) {
                if ($this.attr('data-position') == 'start')
                    $('[data-auto="' + $this.attr('data-target') + '"]').datepicker("option", "minDate", selectedDate);
                else if ($this.attr('data-position') == 'end')
                    $('[data-auto="' + $this.attr('data-target') + '"]').datepicker("option", "maxDate", selectedDate);
            }
        }
    });

});


text:
module InstanceAgent
  class LinuxUtil
    def self.supported_versions()
      [0.0]
    end

    def self.supported_oses()
      ['linux']
    end

    def self.prepare_script_command(script, absolute_cmd_path)
      runas = !!script.runas
      sudo = !!script.sudo

      if runas && sudo
        return 'sudo su ' + script.runas + ' -c ' + absolute_cmd_path
      end

      if runas && !sudo
        return 'su ' + script.runas + ' -c ' + absolute_cmd_path
      end

      if !runas && sudo
        return 'sudo ' + absolute_cmd_path
      end

      # If neither sudo or runas is specified, execute the
      # command as the code deploy agent user
      absolute_cmd_path
    end

    def self.quit()
      # Send kill signal to parent and exit
      Process.kill('TERM', Process.ppid)
    end

    def self.script_executable?(path)
      File.executable?(path)
    end

    def self.extract_tar(bundle_file, dst)
      FileUtils.mkdir_p(dst)
      execute_tar_command("/bin/tar -xpsf #{bundle_file} -C #{dst}")
    end

    def self.extract_tgz(bundle_file, dst)
      FileUtils.mkdir_p(dst)
      execute_tar_command("/bin/tar -zxpsf #{bundle_file} -C #{dst}")
    end

    def self.supports_process_groups?()
      true
    end

    def self.codedeploy_version_file
      File.join(ProcessManager::Config.config[:root_dir], '..')
    end

    def self.fallback_version_file
      "/opt/codedeploy-agent"
    end

    private
    def self.execute_tar_command(cmd)
      log(:debug, "Executing #{cmd}")

      output = `#{cmd} 2>&1`
      exit_status = $?.exitstatus

      log(:debug, "Command status: #{$?}")
      log(:debug, "Command output: #{output}")

      if exit_status != 0
        msg = "Error extracting tar archive: #{exit_status}"
        log(:error, msg)
        raise msg
      end
    end

    private
    def self.log(severity, message)
      raise ArgumentError, "Unknown severity #{severity.inspect}" unless InstanceAgent::Log::SEVERITIES.include?(severity.to_s)
      InstanceAgent::Log.send(severity.to_sym, "#{self.to_s}: #{message}")
    end

  end
end


text:
package balances

type Report struct {
	Currency string
	rows     []Transaction
}

func NewReport(currency string, rows []Transaction) Report {
	return Report{
		Currency: currency,
		rows:     rows,
	}
}

func (r *Report) Balance() float64 {
	var total float64
	total += r.Deposits()
	total -= r.Withdrawals()
	return total
}

func (r *Report) Deposits() float64 {
	var total float64
	for _, row := range r.rows {
		if row.Type == TypeDeposit {
			total += row.Amount
		}
	}
	return total
}

func (r *Report) Withdrawals() float64 {
	var total float64
	for _, row := range r.rows {
		if row.Type == TypeWithdrawal {
			total += row.Amount
		}
	}
	return total
}


text:
require 'amorail/version'
require 'amorail/config'
require 'amorail/client'
require 'amorail/exceptions'
require 'amorail/entity'
require 'amorail/property'
require 'amorail/access_token'
require 'amorail/store_adapters'

Gem.find_files('amorail/entities/*.rb').each { |path| require path }

# AmoCRM API integration.
# https://www.amocrm.com/
module Amorail
  extend self

  def config
    @config ||= Config.new
  end

  def properties
    client.properties
  end

  def configure
    yield(config) if block_given?
  end

  def client
    ClientRegistry.client || (@client ||= Client.new)
  end

  def reset
    @config = nil
    @client = nil
  end

  def with_client(client)
    client = Client.new(client) unless client.is_a?(Client)
    ClientRegistry.client = client
    yield
  ensure
    ClientRegistry.client = nil
  end

  def token_store=(args)
    adapter, options = Array(args)
    @token_store = StoreAdapters.build_by_name(adapter, options)
  rescue NameError => e
    raise e.class, "Token store adapter for :#{adapter} haven't been found", e.backtrace
  end

  def token_store
    unless instance_variable_defined?(:@token_store)
      self.token_store = :memory
    end

    @token_store
  end

  class ClientRegistry # :nodoc:
    extend ActiveSupport::PerThreadRegistry

    attr_accessor :client
  end

  require 'amorail/railtie' if defined?(Rails)
end


text:
SpecBegin(JCCircularCollectionViewProxy)

__block UICollectionView *collectionView = nil;
__block id mockDataSource = nil;
__block id mockDelegate = nil;
__block JCCircularCollectionViewProxy *proxy = nil;

before(^{
  mockDataSource = [OCMockObject mockForProtocol:@protocol(JCCircularCollectionViewProxyDataSource)];
  mockDelegate = [OCMockObject mockForProtocol:@protocol(UICollectionViewDelegateFlowLayout)];
  collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)
                                      collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
  [[[mockDataSource stub] andReturnValue:@1] numberOfSectionsInCollectionView:collectionView];
  [[[mockDelegate stub] andReturnValue:[NSValue valueWithCGSize:CGSizeMake(50, 50)]]
   collectionView:collectionView
   layout:collectionView.collectionViewLayout
   sizeForItemAtIndexPath:[OCMArg any]];
  proxy = [collectionView circularProxyWithDataSource:mockDataSource
                                             delegate:mockDelegate];
});

describe(@"data source", ^{
  before(^{
    [[[mockDataSource stub] andReturnValue:@99] collectionView:collectionView numberOfItemsInSection:0];
  });

  it(@"should return proxied count", ^{
    expect([proxy collectionView:collectionView numberOfItemsInSection:0]).to.equal(99 * 7000);
  });

  it(@"should dequeue cell from true data source and pass on cell for configuration", ^{
    id obj = @"";
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3000 inSection:0];
    [[[mockDataSource stub] andReturn:obj] collectionView:collectionView cellForItemAtIndexPath:indexPath];
    [[mockDataSource expect] collectionView:collectionView configureCell:obj
                               forIndexPath:[OCMArg checkWithBlock:^BOOL(NSIndexPath *indexPath)
    {
      return [indexPath isEqual:[NSIndexPath indexPathForRow:30 inSection:0]];
    }]];
    [proxy collectionView:collectionView cellForItemAtIndexPath:indexPath];
  });

  it(@"should forward data source method", ^{
    [[mockDataSource expect] collectionView:nil viewForSupplementaryElementOfKind:nil atIndexPath:nil];
    [proxy collectionView:nil viewForSupplementaryElementOfKind:nil atIndexPath:nil];
  });
});

describe(@"delegate", ^{
  it(@"should forward delegate method", ^{
    [[mockDelegate expect] collectionView:nil layout:nil referenceSizeForHeaderInSection:0];
    [proxy collectionView:nil layout:nil referenceSizeForHeaderInSection:0];
  });
});

SpecEnd


text:
![](https://github.com/RolandJansen/intermix.js/workflows/build\/test/badge.svg)
[![Code Climate](https://codeclimate.com/github/RolandJansen/intermix.js/badges/gpa.svg)](https://codeclimate.com/github/RolandJansen/intermix.js)
[![Test Coverage](https://codeclimate.com/github/RolandJansen/intermix.js/badges/coverage.svg)](https://codeclimate.com/github/RolandJansen/intermix.js/coverage)

---

## Warning

This software is in an early stage and the API is still under development. The current release (0.8.0) is just a milestone and not ment to be used in production environments.

---

## About

Intermix is a framework that can be used to create browser-based audio applications with a different approach than most other audio libraries. Its focus is not on high level abstractions of the Web Audio API. Instead it provides an architecture for plugins that can be used in any context that uses intermix.

With Redux as its foundation, intermix is also a predictable state container: No side effects, nothing unexpected - actions performed in Intermix are completely predictable.

## Install

`npm install intermix`

or if you prefer yarn

`yarn add intermix`

## Usage

Load intermix into your module with ES2015 module syntax
```javascript
import * as intermix from "intermix";
```

or with CommonJS module require
```javascript
const intermix = require("intermix");
```

now you can start building an audio app. For example instantiate a sequencer and a synth
```javascript
const sequencerUID = intermix.addPlugin('Sequencer');
const synthUID = intermix.addPlugin('Synth');
```

you can build a sequencer-part and add it to the score
```javascript
// Sequencer parts are containers that hold notes and other events.
// They have a length of 1 full note, divided into 16 steps by default.
const seqPartUID = intermix.addSeqPart();

// action creators are functions that send actions to a plugin
const seqActionCreators = intermix.getActionCreators(sequencerUID);

// The following binds the part to the synth plugin and adds it to the score.
// Now all events in the part will be routed to the synth
seqActionCreators.addToScore([seqPartUID, synthUID]);
```

There's much more you can do with intermix. The API doc in the project wiki is a good starting point and there will be more infos on the webpage soon.

## Concept

Most of the API is message based. Intermix messages are an amalgam of [OSC](https://en.wikipedia.org/wiki/Open_Sound_Control) messages and [Redux](https://redux.js.org/) actions:

```javascript
{
    address: "/intermix/plugin/i2342/envAttack",
    type: "envAttack",
    typeTag: ",sff",
    value: ["Envelope Attack", 0.42, 0.0],
}
```

The action above is of type "envAttack". It would be send to a plugin with the ID "i2342". The attack value is 0.42 and it will be executed at second 0 (which means right now).

The _typeTag_ says that the value is a tuple of type `[string, float, float]`. Controller actions normally start with a string that holds a name followed by the actual value and the time in seconds when the action should be executed. The execution time is vital in a browser because there's no _realtime_ like in an os-native app. Executing actions in the sequencer means to schedule them to be executed in the near future.

For an app developer there's no need to build these actions manually as intermix provides action creators for all managed plugins. These functions create and dispatch actions for you.

A plugin developer can write action definitions that are consumed by intermix to build the internal logic at runtime:

```javascript
{
    address: "/intermix/plugin/<UID>/envAttack",
    typeTag: ",sff",
    description: "Envelope Attack with name, value and start time",
}
```

## Features

* Architecture for browser-based audio plugins
* Predictable State Container for all managed plugins
* Message based, easily extendible OSC-like API
* Build-in sequencer with rock solid timing
* Simple build-in synth- and sampler plugins

## Dependencies

* [Redux](https://redux.js.org/)

Note: Redux is often used together with the React UI framework but this is totally up to you. Intermix can be combined with any UI technology you like.

## Browser Compatibility

| Chrome | Firefox | Edge     | Internet Explorer | Opera    | Safari   |
|--------|---------|----------|-------------------|----------|----------|
| 83+    | 77+ (*) | untested | untested          | untested | untested |

\* Sample accurate pause/resume of sounds not tested (didn't work in previous versions).

## License
Licensed under the [GNU Lesser General Public License V3](https://www.gnu.org/licenses/lgpl-3.0.en.html)


text:
#ifndef ZEPHYR_INCLUDE_ARCH_POSIX_POSIX_SOC_IF_H_
#define ZEPHYR_INCLUDE_ARCH_POSIX_POSIX_SOC_IF_H_

/*
 * This file lists the functions the POSIX architecture core expects the
 * SOC or board will provide
 *
 * All functions listed here must be provided by the implementation of the SOC
 * or all its boards
 */

#include <arch/posix/posix_trace.h>
#include "soc_irq.h" /* Must exist and define _ARCH_IRQ/ISR_* macros */

#ifdef __cplusplus
extern "C" {
#endif

void posix_halt_cpu(void);
void posix_atomic_halt_cpu(unsigned int imask);

void posix_irq_enable(unsigned int irq);
void posix_irq_disable(unsigned int irq);
int  posix_irq_is_enabled(unsigned int irq);
unsigned int posix_irq_lock(void);
void posix_irq_unlock(unsigned int key);
void posix_irq_full_unlock(void);
int  posix_get_current_irq(void);
#ifdef CONFIG_IRQ_OFFLOAD
void posix_irq_offload(void (*routine)(const void *), const void *parameter);
#endif

#ifdef __cplusplus
}
#endif

#endif /* ZEPHYR_INCLUDE_ARCH_POSIX_POSIX_SOC_IF_H_ */


text:
#region License

#endregion

#region Imports

using Spring.Util;

#endregion

namespace Spring.Core.TypeResolution
{
    /// <summary>
    /// Resolves a generic <see cref="System.Type"/> by name.
    /// </summary>
    /// <author>Bruno Baia</author>
    public class GenericTypeResolver : TypeResolver
    {
        /// <summary>
        /// Resolves the supplied generic <paramref name="typeName"/> to a
        /// <see cref="System.Type"/> instance.
        /// </summary>
        /// <param name="typeName">
        /// The unresolved (possibly generic) name of a <see cref="System.Type"/>.
        /// </param>
        /// <returns>
        /// A resolved <see cref="System.Type"/> instance.
        /// </returns>
        /// <exception cref="System.TypeLoadException">
        /// If the supplied <paramref name="typeName"/> could not be resolved
        /// to a <see cref="System.Type"/>.
        /// </exception>
        public override Type Resolve(string typeName)
        {
            if (StringUtils.IsNullOrEmpty(typeName))
            {
                throw BuildTypeLoadException(typeName);
            }
            GenericArgumentsHolder genericInfo = new GenericArgumentsHolder(typeName);
            Type type = null;
            try
            {
                if (genericInfo.ContainsGenericArguments)
                {
                    type = TypeResolutionUtils.ResolveType(genericInfo.GenericTypeName);
                    if (!genericInfo.IsGenericDefinition)
                    {
                        string[] unresolvedGenericArgs = genericInfo.GetGenericArguments();
                        Type[] genericArgs = new Type[unresolvedGenericArgs.Length];
                        for (int i = 0; i < unresolvedGenericArgs.Length; i++)
                        {
                            genericArgs[i] = TypeResolutionUtils.ResolveType(unresolvedGenericArgs[i]);
                        }
                        type = type.MakeGenericType(genericArgs);
                    }
                    if (genericInfo.IsArrayDeclaration)
                    {
                        typeName = string.Format("{0}{1},{2}", type.FullName, genericInfo.GetArrayDeclaration(), type.Assembly.FullName);
                        type = null;
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is TypeLoadException)
                {
                    throw;
                }
                throw BuildTypeLoadException(typeName, ex);
            }

            if (type == null)
            {
                type = base.Resolve(typeName);
            }

            return type;
        }
    }
}


text:
package com.blnz.xsl.expr;

import com.blnz.xsl.om.*;

/**
 * a compiled XPath expression (component) that represents
 * the addition of two sub-expressions
 */
class AddExpr extends ConvertibleNumberExpr
{
    private transient final NumberExpr expr1;
    private transient final NumberExpr expr2;

    /**
     * construct with two NumberExpr(essions)
     */
    AddExpr(NumberExpr expr1, NumberExpr expr2)
    {
        super();
        this.expr1 = expr1;
        this.expr2 = expr2;
    }

    /**
     * evaluate to result of a double
     */
    public double eval(final Node node, final ExprContext context)
        throws XSLException
    {
        return expr1.eval(node, context) + expr2.eval(node, context);
    }
}


text:
"""
Copyright 2015 ARC Centre of Excellence for Climate Systems Science

author: Scott Wales <scott.wales@unimelb.edu.au>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from ftools.parser.Fortran03Parser   import Fortran03Parser
from ftools.parser.Fortran03Listener import Fortran03Listener

from antlr4.Token import Token

class Writer(Fortran03Listener):
    """
    Manages writing a parse tree to a stream::

        from ftools import Parser, Writer
        p = Parser().parse_file("test.f90")
        w = Writer(p.tokens, sys.stdout)
        ParseTreeWalker().walk(w, p.tree.program())
    """

    def __init__(self, bufferedTokenStream, outputStream):
        self.stream = outputStream
        self.hidden = bufferedTokenStream

    def writeToken(self, token):
        """
        Write a token
        """
        self.stream.write(token.text)

    def writeHidden(self, token):
        """
        Write hidden tokens to the left of this one
        """
        index = token.tokenIndex
        hidden = self.hidden.getHiddenTokensToLeft(index)
        if hidden:
            for t in hidden:
                self.writeToken(t)

    def writeFinalise(self):
        """
        Write out any final hidden tokens
        """
        index = len(self.hidden.tokens) - 1
        hidden = self.hidden.getHiddenTokensToLeft(index)
        if hidden:
            for t in hidden:
                self.writeToken(t)

    def visitTerminal(self, node):
        """
        Write out a terminal token
        """
        # node is a TerminalNodeImpl
        token = node.getSymbol()
        self.writeHidden(token)
        self.writeToken(token)

    def exitProgram(self, ctx):
        self.writeFinalise()


text:
<?php

namespace Swing\Models;

use PDO;

abstract class Model
{
    protected $pdo;

    private $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ];

    function __construct()
    {
        $host = getenv('MYSQL_HOST');
        $port = getenv('MYSQL_PORT');
        $db = getenv('MYSQL_DATABASE');
        $username = getenv('MYSQL_USER');
        $password = getenv('MYSQL_PASSWORD');
        $charset = 'utf8';

        $dsn = "mysql:host=$host;dbname=$db;port=$port;charset=$charset";

        $this->pdo = new PDO($dsn, $username, $password, $this->options);
    }
}


text:
  var fetchTextFromURL;
  if (typeof XMLHttpRequest != 'undefined') {
    fetchTextFromURL = function(url, authorization, fulfill, reject) {
      var xhr = new XMLHttpRequest();
      var sameDomain = true;
      var doTimeout = false;
      if (!('withCredentials' in xhr)) {
        // check if same domain
        var domainCheck = /^(\w+:)?\/\/([^\/]+)/.exec(url);
        if (domainCheck) {
          sameDomain = domainCheck[2] === window.location.host;
          if (domainCheck[1])
            sameDomain &= domainCheck[1] === window.location.protocol;
        }
      }
      if (!sameDomain && typeof XDomainRequest != 'undefined') {
        xhr = new XDomainRequest();
        xhr.onload = load;
        xhr.onerror = error;
        xhr.ontimeout = error;
        xhr.onprogress = function() {};
        xhr.timeout = 0;
        doTimeout = true;
      }
      function load() {
        fulfill(xhr.responseText);
      }
      function error() {
        reject(new Error('XHR error' + (xhr.status ? ' (' + xhr.status + (xhr.statusText ? ' ' + xhr.statusText  : '') + ')' : '') + ' loading ' + url));
      }

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200 || (xhr.status == 0 && xhr.responseText)) {
            load();
          } else {
            error();
          }
        }
      };
      xhr.open("GET", url, true);

      if (xhr.setRequestHeader) {
        xhr.setRequestHeader('Accept', 'application/x-es-module */*');
        // can set "authorization: true" to enable withCredentials only
        if (authorization) {
          if (typeof authorization == 'string')
            xhr.setRequestHeader('Authorization', authorization);
          xhr.withCredentials = true;
        }
      }

      if (doTimeout)
        setTimeout(function() {
          xhr.send();
        }, 0);

      xhr.send(null);
    };
  }
  else if (typeof require != 'undefined') {
    var fs;
    fetchTextFromURL = function(url, authorization, fulfill, reject) {
      if (url.substr(0, 8) != 'file:///')
        throw new Error('Unable to fetch "' + url + '". Only file URLs of the form file:/// allowed running in Node.');
      fs = fs || require('fs');
      if (isWindows)
        url = url.replace(/\//g, '\\').substr(8);
      else
        url = url.substr(7);
      return fs.readFile(url, function(err, data) {
        if (err) {
          return reject(err);
        }
        else {
          // Strip Byte Order Mark out if it's the leading char
          var dataString = data + '';
          if (dataString[0] === '\ufeff')
            dataString = dataString.substr(1);

          fulfill(dataString);
        }
      });
    };
  }
  else {
    throw new TypeError('No environment fetch API available.');
  }

  SystemLoader.prototype.fetch = function(load) {
    return new Promise(function(resolve, reject) {
      fetchTextFromURL(load.address, undefined, resolve, reject);
    });
  };


text:
<?php

namespace SMW\Tests\MediaWiki\Hooks;

use SMW\Tests\Utils\Mock\MockTitle;

use SMW\MediaWiki\Hooks\BeforePageDisplay;

use OutputPage;
use Language;

/**
 * @covers \SMW\MediaWiki\Hooks\BeforePageDisplay
 *
 *
 * @group SMW
 * @group SMWExtension
 *
 * @license GNU GPL v2+
 * @since 1.9
 *
 * @author mwjames
 */
class BeforePageDisplayTest extends \PHPUnit_Framework_TestCase {

	public function testCanConstruct() {

		$outputPage = $this->getMockBuilder( '\OutputPage' )
			->disableOriginalConstructor()
			->getMock();

		$skin = $this->getMockBuilder( '\Skin' )
			->disableOriginalConstructor()
			->getMock();

		$this->assertInstanceOf(
			'\SMW\MediaWiki\Hooks\BeforePageDisplay',
			new BeforePageDisplay( $outputPage, $skin )
		);
	}

	/**
	 * @dataProvider titleDataProvider
	 */
	public function testProcess( $setup, $expected ) {

		$skin = $this->getMockBuilder( '\Skin' )
			->disableOriginalConstructor()
			->getMock();

		$context = new \RequestContext();
		$context->setTitle( $setup['title'] );
		$context->setLanguage( Language::factory( 'en' ) );

		$outputPage = new OutputPage( $context );

		$instance = new BeforePageDisplay( $outputPage, $skin );
		$result   = $instance->process();

		$this->assertInternalType( 'boolean', $result );
		$this->assertTrue( $result );

		$contains = false;

		if ( method_exists( $outputPage, 'getHeadLinksArray' ) ) {
			foreach ( $outputPage->getHeadLinksArray() as $key => $value ) {
				if ( strpos( $value, 'ExportRDF' ) ){
					$contains = true;
					break;
				};
			}
		} else{
			// MW 1.19
			if ( strpos( $outputPage->getHeadLinks(), 'ExportRDF' ) ){
				$contains = true;
			};
		}

		$expected['result'] ? $this->assertTrue( $contains ) : $this->assertFalse( $contains );
	}

	public function titleDataProvider() {

		$language = Language::factory( 'en' );

		#0 Standard title
		$title = MockTitle::buildMockForMainNamespace();

		$title->expects( $this->atLeastOnce() )
			->method( 'getPrefixedText' )
			->will( $this->returnValue( 'Foo' ) );

		$title->expects( $this->atLeastOnce() )
			->method( 'isSpecialPage' )
			->will( $this->returnValue( false ) );

		$title->expects( $this->atLeastOnce() )
			->method( 'getPageLanguage' )
			->will( $this->returnValue( $language ) );

		$provider[] = array(
			array(
				'title'  => $title
			),
			array(
				'result' => true
			)
		);

		#1 as SpecialPage
		$title = MockTitle::buildMock();

		$title->expects( $this->atLeastOnce() )
			->method( 'isSpecialPage' )
			->will( $this->returnValue( true ) );

		$title->expects( $this->atLeastOnce() )
			->method( 'getPageLanguage' )
			->will( $this->returnValue( $language ) );

		$provider[] = array(
			array(
				'title'  => $title
			),
			array(
				'result' => false
			)
		);

		return $provider;
	}

}


text:
  arangodb::basics::WriteUnlocker obj(&lock, __FILE__, __LINE__)

#else

#define WRITE_UNLOCKER(obj, lock) arangodb::basics::WriteUnlocker obj(&lock)

#endif

namespace arangodb {
namespace basics {

////////////////////////////////////////////////////////////////////////////////
/// @brief write unlocker
///
/// A WriteUnlocker unlocks a read-write lock during its lifetime and reaquires
/// the write lock when it is destroyed.
////////////////////////////////////////////////////////////////////////////////

class WriteUnlocker {
  WriteUnlocker(WriteUnlocker const&) = delete;
  WriteUnlocker& operator=(WriteUnlocker const&) = delete;

 public:
//////////////////////////////////////////////////////////////////////////////
/// @brief unlocks the lock
///
/// The constructor unlocks the lock, the destructors aquires a write-lock.
//////////////////////////////////////////////////////////////////////////////

#ifdef TRI_SHOW_LOCK_TIME

  //////////////////////////////////////////////////////////////////////////////
  /// @brief unlocks the lock
  ///
  /// The constructor unlocks the lock, the destructors aquires a write-lock.
  //////////////////////////////////////////////////////////////////////////////

  WriteUnlocker(ReadWriteLocker* readWriteLock, char const* file, int line)
      : _readWriteLock(readWriteLock), _file(file), _line(line) {
    _readWriteLock->unlock();
  }

#else

  explicit WriteUnlocker(ReadWriteLock* readWriteLock)
      : _readWriteLock(readWriteLock) {
      _readWriteLock->unlock();
    }

#endif

  ////////////////////////////////////////////////////////////////////////////////
  /// @brief aquires the write-lock
  ////////////////////////////////////////////////////////////////////////////////

  ~WriteUnlocker() { _readWriteLock->writeLock(); }

 private:
  ////////////////////////////////////////////////////////////////////////////////
  /// @brief the read-write lock
  ////////////////////////////////////////////////////////////////////////////////

  basics::ReadWriteLock* _readWriteLock;

#ifdef TRI_SHOW_LOCK_TIME

  ////////////////////////////////////////////////////////////////////////////////
  /// @brief file
  ////////////////////////////////////////////////////////////////////////////////

  char const* _file;

  ////////////////////////////////////////////////////////////////////////////////
  /// @brief line number
  ////////////////////////////////////////////////////////////////////////////////

  int _line;

#endif
};
}
}

#endif


text:
<?php

/* bootstrap/carousel.html.twig */
class __TwigTemplate_1ce742c110194da77f51a7fd2a27d9765b0a447f78d4ec6e5439517adf3ddfb5 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "

        ";
        // line 3
        $context['_parent'] = $context;
        $context['_seq'] = twig_ensure_traversable(twig_get_array_keys_filter(($context["items"] ?? null)));
        $context['loop'] = array(
          'parent' => $context['_parent'],
          'index0' => 0,
          'index'  => 1,
          'first'  => true,
        );
        if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
            $length = count($context['_seq']);
            $context['loop']['revindex0'] = $length - 1;
            $context['loop']['revindex'] = $length;
            $context['loop']['length'] = $length;
            $context['loop']['last'] = 1 === $length;
        }
        foreach ($context['_seq'] as $context["_key"] => $context["index"]) {
            // line 4
            echo "
getAttribute($context["loop"], "first", array())) {
                echo " class=\"active\"";
            }
            echo ">

        ";
            ++$context['loop']['index0'];
            ++$context['loop']['index'];
            $context['loop']['first'] = false;
            if (isset($context['loop']['length'])) {
                --$context['loop']['revindex0'];
                --$context['loop']['revindex'];
                $context['loop']['last'] = 0 === $context['loop']['revindex0'];
            }
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['index'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 6
        echo "

        ";
        // line 9
        $context['_parent'] = $context;
        $context['_seq'] = twig_ensure_traversable(($context["items"] ?? null));
        $context['loop'] = array(
          'parent' => $context['_parent'],
          'index0' => 0,
          'index'  => 1,
          'first'  => true,
        );
        if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
            $length = count($context['_seq']);
            $context['loop']['revindex0'] = $length - 1;
            $context['loop']['revindex'] = $length;
            $context['loop']['length'] = $length;
            $context['loop']['last'] = 1 === $length;
        }
        foreach ($context['_seq'] as $context["_key"] => $context["item"]) {
            // line 10
            echo "        ";
            $context["values"] = $context["item"];
            // line 11
            echo "        ";
            if ($this->env->getExtension('Gravstrap\Twig\GravstrapTwigExtension')->instance_of(($context["values"] ?? null), "\\Thunder\\Shortcode\\Shortcode\\ProcessedShortcode")) {
                // line 12
                echo "            ";
                $context["values"] = array("image" => $this->getAttribute(                // line 13
$context["item"], "getParameter", array(0 => "image"), "method"), "caption" => twig_trim_filter($this->getAttribute(                // line 14
$context["item"], "content", array())));
                // line 16
                echo "        ";
            }
            // line 17
            echo "
getAttribute($context["loop"], "first", array())) {
                echo " active";
            }
            echo "\">
            ";
            // line 18
            echo $this->getAttribute($this->getAttribute($this->getAttribute($this->getAttribute($this->getAttribute(($context["grav"] ?? null), "page", array()), "find", array(0 => "/images"), "method"), "media", array()), "images", array()), $this->getAttribute(($context["values"] ?? null), "image", array()), array(), "array");
            echo "

";
            // line 19
            echo $this->getAttribute(($context["values"] ?? null), "caption", array());
            echo "

        ";
            ++$context['loop']['index0'];
            ++$context['loop']['index'];
            $context['loop']['first'] = false;
            if (isset($context['loop']['length'])) {
                --$context['loop']['revindex0'];
                --$context['loop']['revindex'];
                $context['loop']['last'] = 0 === $context['loop']['revindex0'];
            }
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 22
        echo "

        ";
        // line 26
        echo ($context["previous_label"] ?? null);
        echo "

        ";
        // line 30
        echo ($context["next_label"] ?? null);
        echo "

";
    }

    public function getTemplateName()
    {
        return "bootstrap/carousel.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  148 => 30,  143 => 28,  138 => 26,  133 => 24,  129 => 22,  112 => 19,  108 => 18,  101 => 17,  98 => 16,  96 => 14,  95 => 13,  93 => 12,  90 => 11,  87 => 10,  70 => 9,  65 => 6,  42 => 4,  25 => 3,  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("

        {% for index in items|keys %}

        {% endfor %}

        {% for item in items %}
        {% set values = item %}
        {% if(instanceof(values, '\\\\Thunder\\\\Shortcode\\\\Shortcode\\\\ProcessedShortcode')) %}
            {% set values = {
              'image': item.getParameter('image'),
              'caption': item.content|trim,
            } %}
        {% endif %}

            {{ grav.page.find('/images').media.images[values.image] }}

{{ values.caption }}

        {% endfor %}

        {{ previous_label }}

        {{ next_label }}

", "bootstrap/carousel.html.twig", "/Users/brookehopkins/Documents/Development/grav-admin/user/plugins/gravstrap/templates/bootstrap/carousel.html.twig");
    }
}


text:
package com.github.abel533.echarts.samples.bar;

import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Magic;
import com.github.abel533.echarts.code.MarkType;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.data.PointData;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.util.EnhancedOption;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

/**
 * @author liuzh
 */
public class BarTest1 {

    @Test
    public void test() {
        //地址:http://echarts.baidu.com/doc/example/bar1.html
        EnhancedOption option = new EnhancedOption();
        option.title().text("某地区蒸发量和降水量").subtext("纯属虚构");
        option.tooltip().trigger(Trigger.axis);
        option.legend("蒸发量", "降水量");
        option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar).show(true), Tool.restore, Tool.saveAsImage);
        option.calculable(true);
        option.xAxis(new CategoryAxis().data("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"));
        option.yAxis(new ValueAxis());

        Bar bar = new Bar("蒸发量");
        bar.data(2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3);
        bar.markPoint().data(new PointData().type(MarkType.max).name("最大值"), new PointData().type(MarkType.min).name("最小值"));
        bar.markLine().data(new PointData().type(MarkType.average).name("平均值"));

        Bar bar2 = new Bar("降水量");
        List<Double> list = Arrays.asList(2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3);
        bar2.data(list);
        bar2.markPoint().data(new PointData("年最高", 182.2).xAxis(7).yAxis(183).symbolSize(18), new PointData("年最低", 2.3).xAxis(11).yAxis(3));
        bar2.markLine().data(new PointData().type(MarkType.average).name("平均值"));

        option.series(bar, bar2);
        option.exportToHtml("bar1.html");
        option.view();
    }
}


text:
package com.adaptris.core.services.metadata.compare;

import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.DefaultMessageFactory;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class StartsWithTest {

  private StartsWith operator;

  private AdaptrisMessage message;

  @Before
  public void setUp() throws Exception {
    operator = new StartsWith();
    message = DefaultMessageFactory.getDefaultInstance().newMessage();
  }

  @Test
  public void testTrue() {
    operator.setValue("metadata");

    assertTrue(operator.apply(message, "metadata-starts-with-test"));
  }

  @Test
  public void testFalse() {
    operator.setValue("METADATA");

    assertFalse(operator.apply(message, "metadata-starts-with-test"));
  }
}


text:
package org.kaaproject.kaa.client.channel;

public class KaaInvalidChannelException extends Exception {

    private static final long serialVersionUID = -8871850288946945423L;

    public KaaInvalidChannelException(String message) {
        super(message);
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Csegő
 * Date: 2016. 12. 15.
 * Time: 2:14
 */

namespace JobZ\HomeBundle\Controller;

use JobZ\HomeBundle\Entity\Information;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class InformationController extends Controller
{
    /**
     * @Route("/information/{id}")
     */
    public function indexAction(Information $information)
    {
        return $this->render(
            'HomeBundle:Information:information.html.twig',
            array(
                'information' => $information
            )
        );
    }

}


text:
---
id: 587d7fb4367417b2b2512bfd
title: Añade palabras clave a tu package.json
challengeType: 2
forumTopicId: 301526
dashedName: add-keywords-to-your-package-json
---

# --description--

El campo `keywords` es donde puedes describir tu proyecto usando palabras clave relacionadas. A continuación un ejemplo:

```json
"keywords": [ "descriptive", "related", "words" ],
```

Como puedes ver, este campo está estructurado como un arreglo de cadenas con comillas dobles.

# --instructions--

Añade un arreglo de cadenas adecuadas al campo `keywords` en el archivo package.json de tu proyecto.

Una de las palabras clave debe ser "freecodecamp".

# --hints--

el archivo package.json debe tener una clave "keywords" válida

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/package.json').then(
    (data) => {
      var packJson = JSON.parse(data);
      assert(packJson.keywords, '"keywords" is missing');
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

El campo "keywords" debe ser un arreglo

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/package.json').then(
    (data) => {
      var packJson = JSON.parse(data);
      assert.isArray(packJson.keywords, '"keywords" is not an array');
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

"keywords" debe incluir "freecodecamp"

```js
(getUserInput) =>
  $.get(getUserInput('url') + '/_api/package.json').then(
    (data) => {
      var packJson = JSON.parse(data);
      assert.include(
        packJson.keywords,
        'freecodecamp',
        '"keywords" does not include "freecodecamp"'
      );
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

# --solutions--

```js
/**
  Backend challenges don't need solutions,
  because they would need to be tested against a full working project.
  Please check our contributing guidelines to learn more.
*/
```


text:
\documentclass{article}
\usepackage[a4paper,left=3.5cm,right=2.5cm,top=2.5cm,bottom=2.5cm]{geometry}
%%\usepackage[MeX]{polski}
%%\usepackage[cp1250]{inputenc}
\usepackage[utf8]{inputenc}
\usepackage[tableposition=top]{caption}
\usepackage{algorithmic}
\usepackage{graphicx}
\usepackage{enumerate}
\usepackage{multirow}
\usepackage{amsmath} %pakiet matematyczny
\usepackage{amssymb} %pakiet dodatkowych symboli
\usepackage{polski}
\usepackage{xypic}

\begin{document}
$$
\xymatrix{
\circ \ar[r] & \bullet \\
}
$$

\end{document}


text:
namespace Checkout.ApiServices.Reporting.ResponseModels
{
    public class QueryTransactionResponse : QueryResponse<Transaction>
    {

    }
}


text:
In order to run this example do:

## How to run with Gradle

	gradlew :crnk-integration-examples:dropwizard-simple-example:run

## The service will be available at

 	http://localhost:8080/projects


text:
package de.heikoseeberger.reactiveflows

import akka.actor.{ ActorLogging, ActorRef, ActorSystem, Props, ReceiveTimeout }
import akka.cluster.pubsub.DistributedPubSubMediator.Publish
import akka.cluster.sharding.{ ClusterSharding, ClusterShardingSettings, ShardRegion }
import akka.persistence.PersistentActor
import java.io.{ Serializable => JavaSerializable }
import java.time.Instant
import scala.concurrent.duration.FiniteDuration
import scala.math.{ max, min }

object Flow {

  sealed trait Command
  sealed trait Event
  sealed trait Serializable extends JavaSerializable

  // == Message protocol – start ==

  final case class GetPosts(seqNo: Long, count: Int) extends Serializable with Command
  final case class Posts(posts: Vector[Post])        extends Serializable

  final case class AddPost(text: String)               extends Serializable with Command
  final case class PostAdded(name: String, post: Post) extends Serializable with Event

  final case class Post(seqNo: Long, text: String, time: Instant)
  final case class CommandEnvelope(name: String, command: Command) extends Serializable
  private final case object Terminate

  // == Message protocol – end ==

  def apply(mediator: ActorRef, passivationTimeout: FiniteDuration): Props =
    Props(new Flow(mediator, passivationTimeout))

  def startSharding(system: ActorSystem,
                    mediator: ActorRef,
                    shardCount: Int,
                    passivationTimeout: FiniteDuration): ActorRef = {
    import ShardRegion._
    def shardId(name: String) = (name.hashCode.abs % shardCount).toString
    val extractEntityId: ExtractEntityId = {
      case CommandEnvelope(name, command) => (name, command)
    }
    val extractShardId: ExtractShardId = {
      case CommandEnvelope(name, _)      => shardId(name)
      case ShardRegion.StartEntity(name) => shardId(name)
    }
    ClusterSharding(system).start(
      className[Flow],
      Flow(mediator, passivationTimeout),
      ClusterShardingSettings(system),
      extractEntityId,
      extractShardId
    )
  }
}

final class Flow(mediator: ActorRef, passivationTimeout: FiniteDuration)
    extends PersistentActor
    with ActorLogging {
  import Flow._

  override val persistenceId = s"flow-${self.path.name}"

  private var posts = Vector.empty[Post]

  context.setReceiveTimeout(passivationTimeout)

  override def receiveCommand = {
    case GetPosts(seqNo, _) if seqNo < 0  => sender() ! InvalidCommand("seqNo < 0")
    case GetPosts(_, count) if count <= 0 => sender() ! InvalidCommand("count <= 0")
    case GetPosts(seqNo, count)           => handleGetPosts(seqNo, count)

    case AddPost("")   => sender() ! InvalidCommand("text empty")
    case AddPost(text) => handleAddPost(text)

    case ReceiveTimeout => context.parent ! ShardRegion.Passivate(Terminate)
    case Terminate      => context.stop(self)
  }

  override def receiveRecover = {
    case event: Event => handleEvent(event)
    // TODO Use Snapshots!
  }

  private def handleGetPosts(seqNo: Long, count: Int) = {
    // TODO: Using CQRS and a suitable read model makes this hacky Long->Int issue obsolete!
    val seqNoInt = min(seqNo, Int.MaxValue).toInt
    val n        = max(posts.size - 1 - seqNoInt, 0)
    sender() ! Posts(posts.slice(n, n + count))
  }

  private def handleAddPost(text: String) = {
    val post = Post(posts.size, text, Instant.now())
    persist(PostAdded(self.path.name, post)) { postAdded =>
      handleEvent(postAdded)
      mediator ! Publish(className[Event], postAdded)
      log.info("Post starting with '{}' added", text.take(42))
      sender() ! postAdded
    }
  }

  private def handleEvent(event: Event) =
    event match {
      case PostAdded(_, post) => posts +:= post
    }
}


text:
from typing import (
    Any,
    Callable,
    Dict,
    Iterable,
    List,
    MutableMapping,
    Optional,
    Tuple,
    TypeVar,
    TYPE_CHECKING,
)

import abc
import collections
import dataclasses
import functools
import re

import numpy as np

from cirq.circuits import Circuit
from cirq.ops import (
    FSimGate,
    Gate,
    ISwapPowGate,
    Moment,
    Operation,
    PhasedFSimGate,
    PhasedISwapPowGate,
    Qid,
    TwoQubitGate,
    rz,
)
from cirq_google.api import v2
from cirq_google.engine import CalibrationLayer, CalibrationResult

if TYPE_CHECKING:
    # Workaround for mypy custom dataclasses (python/mypy#5406)
    from dataclasses import dataclass as json_serializable_dataclass
else:
    from cirq.protocols import json_serializable_dataclass

_FLOQUET_PHASED_FSIM_HANDLER_NAME = 'floquet_phased_fsim_characterization'
T = TypeVar('T')

# Workaround for: https://github.com/python/mypy/issues/5858
def lru_cache_typesafe(func: Callable[..., T]) -> T:
    return functools.lru_cache(maxsize=None)(func)  # type: ignore

def _create_pairs_from_moment(moment: Moment) -> Tuple[Tuple[Tuple[Qid, Qid], ...], Gate]:
    """Creates instantiation parameters from a Moment.

    Given a moment, creates a tuple of pairs of qubits and the
    gate for instantiation of a sub-class of PhasedFSimCalibrationRequest,
    Sub-classes of PhasedFSimCalibrationRequest can call this function
    to implement a from_moment function.
    """
    gate = None
    pairs: List[Tuple[Qid, Qid]] = []
    for op in moment:
        if op.gate is None:
            raise ValueError('All gates in request object must be two qubit gates: {op}')
        if gate is None:
            gate = op.gate
        elif gate != op.gate:
            raise ValueError('All gates in request object must be identical {gate}!={op.gate}')
        if len(op.qubits) != 2:
            raise ValueError('All gates in request object must be two qubit gates: {op}')
        pairs.append((op.qubits[0], op.qubits[1]))
    if gate is None:
        raise ValueError('No gates found to create request {moment}')
    return tuple(pairs), gate

@json_serializable_dataclass(frozen=True)
class PhasedFSimCharacterization:
    """Holder for the unitary angles of the cirq.PhasedFSimGate.

    This class stores five unitary parameters (θ, ζ, χ, γ and φ) that describe the
    cirq.PhasedFSimGate which is the most general particle conserving two-qubit gate. The unitary
    of the underlying gate is:

        [[1,                        0,                       0,                0],
         [0,    exp(-i(γ + ζ)) cos(θ), -i exp(-i(γ - χ)) sin(θ),               0],
         [0, -i exp(-i(γ + χ)) sin(θ),    exp(-i(γ - ζ)) cos(θ),               0],
         [0,                        0,                       0,  exp(-i(2γ + φ))]]

    The parameters θ, γ and φ are symmetric and parameters ζ and χ asymmetric under the qubits
    exchange.

    All the angles described by this class are optional and can be left unknown. This is relevant
    for characterization routines that characterize only subset of the gate parameters. All the
    angles are assumed to take a fixed numerical values which reflect the current state of the
    characterized gate.

    This class supports JSON serialization and deserialization.

    Attributes:
        theta: θ angle in radians or None when unknown.
        zeta: ζ angle in radians or None when unknown.
        chi: χ angle in radians or None when unknown.
        gamma: γ angle in radians or None when unknown.
        phi: φ angle in radians or None when unknown.
    """

    theta: Optional[float] = None
    zeta: Optional[float] = None
    chi: Optional[float] = None
    gamma: Optional[float] = None
    phi: Optional[float] = None

    def asdict(self) -> Dict[str, float]:
        """Converts parameters to a dictionary that maps angle names to values."""
        return dataclasses.asdict(self)

    def all_none(self) -> bool:
        """Returns True if all the angles are None"""
        return (
            self.theta is None
            and self.zeta is None
            and self.chi is None
            and self.gamma is None
            and self.phi is None
        )

    def any_none(self) -> bool:
        """Returns True if any the angle is None"""
        return (
            self.theta is None
            or self.zeta is None
            or self.chi is None
            or self.gamma is None
            or self.phi is None
        )

    def parameters_for_qubits_swapped(self) -> 'PhasedFSimCharacterization':
        """Parameters for the gate with qubits swapped between each other.

        The angles theta, gamma and phi are kept unchanged. The angles zeta and chi are negated for
        the gate with swapped qubits.

        Returns:
            New instance with angles adjusted for swapped qubits.
        """
        return PhasedFSimCharacterization(
            theta=self.theta,
            zeta=-self.zeta if self.zeta is not None else None,
            chi=-self.chi if self.chi is not None else None,
            gamma=self.gamma,
            phi=self.phi,
        )

    def merge_with(self, other: 'PhasedFSimCharacterization') -> 'PhasedFSimCharacterization':
        """Substitutes missing parameter with values from other.

        Args:
            other: Parameters to use for None values.

        Returns:
            New instance of PhasedFSimCharacterization with values from this instance if they are
            set or values from other when some parameter is None.
        """
        return PhasedFSimCharacterization(
            theta=other.theta if self.theta is None else self.theta,
            zeta=other.zeta if self.zeta is None else self.zeta,
            chi=other.chi if self.chi is None else self.chi,
            gamma=other.gamma if self.gamma is None else self.gamma,
            phi=other.phi if self.phi is None else self.phi,
        )

    def override_by(self, other: 'PhasedFSimCharacterization') -> 'PhasedFSimCharacterization':
        """Overrides other parameters that are not None.

        Args:
            other: Parameters to use for override.

        Returns:
            New instance of PhasedFSimCharacterization with values from other if set (values from
            other that are not None). Otherwise the current values are used.
        """
        return other.merge_with(self)

SQRT_ISWAP_PARAMETERS = PhasedFSimCharacterization(
    theta=np.pi / 4, zeta=0.0, chi=0.0, gamma=0.0, phi=0.0
)

class PhasedFSimCalibrationOptions(abc.ABC):
    """Base class for calibration-specific options passed together with the requests."""

@dataclasses.dataclass(frozen=True)
class PhasedFSimCalibrationResult:
    """The PhasedFSimGate characterization result.

    Attributes:
        parameters: Map from qubit pair to characterization result. For each pair of characterized
            quibts a and b either only (a, b) or only (b, a) is present.
        gate: Characterized gate for each qubit pair. This is copied from the matching
            PhasedFSimCalibrationRequest and is included to preserve execution context.
    """

    parameters: Dict[Tuple[Qid, Qid], PhasedFSimCharacterization]
    gate: Gate
    options: PhasedFSimCalibrationOptions

    def override(self, parameters: PhasedFSimCharacterization) -> 'PhasedFSimCalibrationResult':
        """Creates the new results with certain parameters overridden for all characterizations.

        This functionality can be used to zero-out the corrected angles and do the analysis on
        remaining errors.

        Args:
            parameters: Parameters that will be used when overriding. The angles of that object
                which are not None will be used to replace current parameters for every pair stored.

        Returns:
            New instance of PhasedFSimCalibrationResult with certain parameters overriden.
        """
        return PhasedFSimCalibrationResult(
            parameters={
                pair: pair_parameters.override_by(parameters)
                for pair, pair_parameters in self.parameters.items()
            },
            gate=self.gate,
            options=self.options,
        )

    def get_parameters(self, a: Qid, b: Qid) -> Optional['PhasedFSimCharacterization']:
        """Returns parameters for a qubit pair (a, b) or None when unknown."""
        if (a, b) in self.parameters:
            return self.parameters[(a, b)]
        elif (b, a) in self.parameters:
            return self.parameters[(b, a)].parameters_for_qubits_swapped()
        else:
            return None

    @classmethod
    def _create_parameters_dict(
        cls,
        parameters: List[Tuple[Qid, Qid, PhasedFSimCharacterization]],
    ) -> Dict[Tuple[Qid, Qid], PhasedFSimCharacterization]:
        """Utility function to create parameters from JSON.

        Can be used from child classes to instantiate classes in a _from_json_dict_
        method."""
        return {(q_a, q_b): params for q_a, q_b, params in parameters}

    @classmethod
    def _from_json_dict_(
        cls,
        **kwargs,
    ) -> 'PhasedFSimCalibrationResult':
        """Magic method for the JSON serialization protocol.

        Converts serialized dictionary into a dict suitable for
        class instantiation."""
        del kwargs['cirq_type']
        kwargs['parameters'] = cls._create_parameters_dict(kwargs['parameters'])
        return cls(**kwargs)

    def _json_dict_(self) -> Dict[str, Any]:
        """Magic method for the JSON serialization protocol."""
        return {
            'cirq_type': 'PhasedFSimCalibrationResult',
            'gate': self.gate,
            'parameters': [(q_a, q_b, params) for (q_a, q_b), params in self.parameters.items()],
            'options': self.options,
        }

def merge_matching_results(
    results: Iterable[PhasedFSimCalibrationResult],
) -> Optional[PhasedFSimCalibrationResult]:
    """Merges a collection of results into a single result.

    Args:
        results: List of results to merge. They must be compatible with each other: all gate and
            options fields must be equal and every characterized pair must be present only in one of
            the characterizations.

    Returns:
        New PhasedFSimCalibrationResult that contains all the parameters from every result in
        results or None when the results list is empty.
    """
    all_parameters: Dict[Tuple[Qid, Qid], PhasedFSimCharacterization] = {}
    common_gate = None
    common_options = None
    for result in results:
        if common_gate is None:
            common_gate = result.gate
        elif common_gate != result.gate:
            raise ValueError(
                f'Only matching results can be merged, got gates {common_gate} and {result.gate}'
            )

        if common_options is None:
            common_options = result.options
        elif common_options != result.options:
            raise ValueError(
                f'Only matching results can be merged, got options {common_options} and '
                f'{result.options}'
            )

        if not all_parameters.keys().isdisjoint(result.parameters):
            raise ValueError(f'Only results with disjoint parameters sets can be merged')

        all_parameters.update(result.parameters)

    if common_gate is None or common_options is None:
        return None

    return PhasedFSimCalibrationResult(all_parameters, common_gate, common_options)

# We have to relax a mypy constraint, see https://github.com/python/mypy/issues/5374
@dataclasses.dataclass(frozen=True)  # type: ignore
class PhasedFSimCalibrationRequest(abc.ABC):
    """Description of the request to characterize PhasedFSimGate.

    Attributes:
        pairs: Set of qubit pairs to characterize. A single qubit can appear on at most one pair in
            the set.
        gate: Gate to characterize for each qubit pair from pairs. This must be a supported gate
            which can be described cirq.PhasedFSim gate. This gate must be serialized by the
            cirq_google.SerializableGateSet used
    """

    pairs: Tuple[Tuple[Qid, Qid], ...]
    gate: Gate  # Any gate which can be described by cirq.PhasedFSim

    # Workaround for: https://github.com/python/mypy/issues/1362
    @property  # type: ignore
    @lru_cache_typesafe
    def qubit_to_pair(self) -> MutableMapping[Qid, Tuple[Qid, Qid]]:
        """Returns mapping from qubit to a qubit pair that it belongs to."""
        # Returning mutable mapping as a cached result because it's hard to get a frozen dictionary
        # in Python...
        return collections.ChainMap(*({q: pair for q in pair} for pair in self.pairs))

    @abc.abstractmethod
    def to_calibration_layer(self) -> CalibrationLayer:
        """Encodes this characterization request in a CalibrationLayer object."""

    @abc.abstractmethod
    def parse_result(self, result: CalibrationResult) -> PhasedFSimCalibrationResult:
        """Decodes the characterization result issued for this request."""

@json_serializable_dataclass(frozen=True)
class FloquetPhasedFSimCalibrationOptions(PhasedFSimCalibrationOptions):
    """Options specific to Floquet PhasedFSimCalibration.

    Some angles require another angle to be characterized first so result might have more angles
    characterized than requested here.

    Attributes:
        characterize_theta: Whether to characterize θ angle.
        characterize_zeta: Whether to characterize ζ angle.
        characterize_chi: Whether to characterize χ angle.
        characterize_gamma: Whether to characterize γ angle.
        characterize_phi: Whether to characterize φ angle.
    """

    characterize_theta: bool
    characterize_zeta: bool
    characterize_chi: bool
    characterize_gamma: bool
    characterize_phi: bool

    def zeta_chi_gamma_correction_override(self) -> PhasedFSimCharacterization:
        """Gives a PhasedFSimCharacterization that can be used to override characterization after
        correcting for zeta, chi and gamma angles.
        """
        return PhasedFSimCharacterization(
            zeta=0.0 if self.characterize_zeta else None,
            chi=0.0 if self.characterize_chi else None,
            gamma=0.0 if self.characterize_gamma else None,
        )

"""PhasedFSimCalibrationOptions options with all angles characterization requests set to True."""
ALL_ANGLES_FLOQUET_PHASED_FSIM_CHARACTERIZATION = FloquetPhasedFSimCalibrationOptions(
    characterize_theta=True,
    characterize_zeta=True,
    characterize_chi=True,
    characterize_gamma=True,
    characterize_phi=True,
)

"""PhasedFSimCalibrationOptions with all but chi angle characterization requests set to True."""
WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION = FloquetPhasedFSimCalibrationOptions(
    characterize_theta=True,
    characterize_zeta=True,
    characterize_chi=False,
    characterize_gamma=True,
    characterize_phi=True,
)

"""PhasedFSimCalibrationOptions with theta, zeta and gamma angles characterization requests set to
True.

Those are the most efficient options that can be used to cancel out the errors by adding the
appropriate single-qubit Z rotations to the circuit. The angles zeta, chi and gamma can be removed
by those additions. The angle chi is disabled because it's not supported by Floquet characterization
currently. The angle theta is set enabled because it is characterized together with zeta and adding
it doesn't cost anything.
"""
THETA_ZETA_GAMMA_FLOQUET_PHASED_FSIM_CHARACTERIZATION = FloquetPhasedFSimCalibrationOptions(
    characterize_theta=True,
    characterize_zeta=True,
    characterize_chi=False,
    characterize_gamma=True,
    characterize_phi=False,
)

@dataclasses.dataclass(frozen=True)
class FloquetPhasedFSimCalibrationRequest(PhasedFSimCalibrationRequest):
    """PhasedFSim characterization request specific to Floquet calibration.

    Attributes:
        options: Floquet-specific characterization options.
    """

    options: FloquetPhasedFSimCalibrationOptions

    @classmethod
    def from_moment(cls, moment: Moment, options: FloquetPhasedFSimCalibrationOptions):
        """Creates a FloquetPhasedFSimCalibrationRequest from a Moment.

        Given a `Moment` object, this function extracts out the pairs of
        qubits and the `Gate` used to create a `FloquetPhasedFSimCalibrationRequest`
        object.  The moment must contain only identical two-qubit FSimGates.
        If dissimilar gates are passed in, a ValueError is raised.
        """
        pairs, gate = _create_pairs_from_moment(moment)
        return cls(pairs, gate, options)

    def to_calibration_layer(self) -> CalibrationLayer:
        circuit = Circuit([self.gate.on(*pair) for pair in self.pairs])
        return CalibrationLayer(
            calibration_type=_FLOQUET_PHASED_FSIM_HANDLER_NAME,
            program=circuit,
            args={
                'est_theta': self.options.characterize_theta,
                'est_zeta': self.options.characterize_zeta,
                'est_chi': self.options.characterize_chi,
                'est_gamma': self.options.characterize_gamma,
                'est_phi': self.options.characterize_phi,
                # Experimental option that should always be set to True.
                'readout_corrections': True,
            },
        )

    def parse_result(self, result: CalibrationResult) -> PhasedFSimCalibrationResult:
        decoded: Dict[int, Dict[str, Any]] = collections.defaultdict(lambda: {})
        for keys, values in result.metrics['angles'].items():
            for key, value in zip(keys, values):
                match = re.match(r'(\d+)_(.+)', str(key))
                if not match:
                    raise ValueError(f'Unknown metric name {key}')
                index = int(match[1])
                name = match[2]
                decoded[index][name] = value

        parsed = {}
        for data in decoded.values():
            a = v2.qubit_from_proto_id(data['qubit_a'])
            b = v2.qubit_from_proto_id(data['qubit_b'])
            parsed[(a, b)] = PhasedFSimCharacterization(
                theta=data.get('theta_est', None),
                zeta=data.get('zeta_est', None),
                chi=data.get('chi_est', None),
                gamma=data.get('gamma_est', None),
                phi=data.get('phi_est', None),
            )

        return PhasedFSimCalibrationResult(parameters=parsed, gate=self.gate, options=self.options)

    @classmethod
    def _from_json_dict_(
        cls,
        gate: Gate,
        pairs: List[Tuple[Qid, Qid]],
        options: FloquetPhasedFSimCalibrationOptions,
        **kwargs,
    ) -> 'PhasedFSimCalibrationRequest':
        """Magic method for the JSON serialization protocol.

        Converts serialized dictionary into a dict suitable for
        class instantiation."""
        instantiation_pairs = tuple((q_a, q_b) for q_a, q_b in pairs)
        return cls(instantiation_pairs, gate, options)

    def _json_dict_(self) -> Dict[str, Any]:
        """Magic method for the JSON serialization protocol."""
        return {
            'cirq_type': 'FloquetPhasedFSimCalibrationRequest',
            'pairs': [(pair[0], pair[1]) for pair in self.pairs],
            'gate': self.gate,
            'options': self.options,
        }

class IncompatibleMomentError(Exception):
    """Error that occurs when a moment is not supported by a calibration routine."""

@dataclasses.dataclass(frozen=True)
class PhaseCalibratedFSimGate:
    """Association of a user gate with gate to calibrate.

    This association stores information regarding rotation of the calibrated FSim gate by
    phase_exponent p:

        (Z^-p ⊗ Z^p) FSim (Z^p ⊗ Z^-p).

    The rotation should be reflected back during the compilation after the gate is calibrated and
    is equivalent to the shift of -2πp in the χ angle of PhasedFSimGate.

    Attributes:
        engine_gate: Gate that should be used for calibration purposes.
        phase_exponent: Phase rotation exponent p.
    """

    engine_gate: FSimGate
    phase_exponent: float

    def as_characterized_phased_fsim_gate(
        self, parameters: PhasedFSimCharacterization
    ) -> PhasedFSimGate:
        """Creates a PhasedFSimGate which represents the characterized engine_gate but includes
        deviations in unitary parameters.

        Args:
            parameters: The results of characterization of the engine gate.

        Returns:
            Instance of PhasedFSimGate that executes a gate according to the characterized
            parameters of the engine_gate.
        """
        return PhasedFSimGate(
            theta=parameters.theta,
            zeta=parameters.zeta,
            chi=parameters.chi - 2 * np.pi * self.phase_exponent,
            gamma=parameters.gamma,
            phi=parameters.phi,
        )

    def with_zeta_chi_gamma_compensated(
        self,
        qubits: Tuple[Qid, Qid],
        parameters: PhasedFSimCharacterization,
        *,
        engine_gate: Optional[TwoQubitGate] = None,
    ) -> Tuple[Tuple[Operation, ...], ...]:
        """Creates a composite operation that compensates for zeta, chi and gamma angles of the
        characterization.

        Args:
            qubits: Qubits that the gate should act on.
            parameters: The results of characterization of the engine gate.
            engine_gate: TwoQubitGate that represents the engine gate. When None, the internal
                engine_gate of this instance is used. This argument is useful for testing
                purposes.

        Returns:
            Tuple of tuple of operations that describe the compensated gate. The first index
            iterates over moments of the composed operation.
        """
        assert parameters.zeta is not None, "Zeta value must not be None"
        zeta = parameters.zeta

        assert parameters.gamma is not None, "Gamma value must not be None"
        gamma = parameters.gamma

        assert parameters.chi is not None, "Chi value must not be None"
        chi = parameters.chi + 2 * np.pi * self.phase_exponent

        if engine_gate is None:
            engine_gate = self.engine_gate

        a, b = qubits

        alpha = 0.5 * (zeta + chi)
        beta = 0.5 * (zeta - chi)

        return (
            (rz(0.5 * gamma - alpha).on(a), rz(0.5 * gamma + alpha).on(b)),
            (engine_gate.on(a, b),),
            (rz(0.5 * gamma - beta).on(a), rz(0.5 * gamma + beta).on(b)),
        )

def try_convert_sqrt_iswap_to_fsim(gate: Gate) -> Optional[PhaseCalibratedFSimGate]:
    """Converts an equivalent gate to FSimGate(theta=π/4, phi=0) if possible.

    Args:
        gate: Gate to verify.

    Returns:
        FSimGateCalibration with engine_gate FSimGate(theta=π/4, phi=0) if the provided gate is
        either FSimGate, ISWapPowGate, PhasedFSimGate or PhasedISwapPowGate that is equivalent to
        FSimGate(theta=±π/4, phi=0). None otherwise.
    """
    if isinstance(gate, FSimGate):
        if not np.isclose(gate.phi, 0.0):
            return None
        angle = gate.theta
    elif isinstance(gate, ISwapPowGate):
        angle = -gate.exponent * np.pi / 2
    elif isinstance(gate, PhasedFSimGate):
        if (
            not np.isclose(gate.zeta, 0.0)
            or not np.isclose(gate.chi, 0.0)
            or not np.isclose(gate.gamma, 0.0)
            or not np.isclose(gate.phi, 0.0)
        ):
            return None
        angle = gate.theta
    elif isinstance(gate, PhasedISwapPowGate):
        if not np.isclose(-gate.phase_exponent - 0.5, 0.0):
            return None
        angle = gate.exponent * np.pi / 2
    else:
        return None

    angle_canonical = angle % (2 * np.pi)

    if np.isclose(angle_canonical, np.pi / 4):
        return PhaseCalibratedFSimGate(FSimGate(theta=np.pi / 4, phi=0.0), 0.0)
    elif np.isclose(angle_canonical, 7 * np.pi / 4):
        return PhaseCalibratedFSimGate(FSimGate(theta=np.pi / 4, phi=0.0), 0.5)

    return None


text:
CSS Framework to help build fast, responsive and beautiful applications

## Installation
By far the easiest way to install the Izichi Design System is using a package manager such as NPM or Bower. You can also clone our
GitHub repository and compile the source manually.

## NPM
Use the command `npm install --save izichi-design-system`

## Bower
Use the command `bower install --save izichi-design-system`

## Build & Compile (manual compilation)
*This is an advanced use case, please only continue if you really do not want to use a package manager*

### Prerequisites
You need to have the following tools installed on your system to build the Izichi Design System:

1. [Node Package Manager](npmjs.com)
2. [Gulp Task Runner](gulpjs.com)

### Compile
Compile the source into usable CSS using the following steps:

1. `npm install`
2. `gulp build`

## Usage
Once the build steps above are complete, you will have the Izichi Design System sitting in the `src/css` folder.


text:
<?php

namespace BackBee\ApiBundle\Patcher\Exception;

/**
 * Exception thrown if an operation with invalid syntax is provided.
 *
 * @category    BackBee
 *
 * @copyright   Lp digital system
 * @author      e.chau <eric.chau@lp-digital.fr>
 */
class UnauthorizedPatchOperationException extends \Exception
{
    public function __construct($entity, $path, $operation)
    {
        parent::__construct("You are not allowed to $operation `$path` for ".get_class($entity).'.');
    }
}


text:
using Sitecore.DataExchange;
using Sitecore.DataExchange.Attributes;
using Sitecore.DataExchange.Contexts;
using Sitecore.DataExchange.Extensions;
using Sitecore.DataExchange.Models;
using Sitecore.DataExchange.Plugins;
using Sitecore.DataExchange.Processors;
using Sitecore.DataExchange.Processors.PipelineSteps;
using Sitecore.Services.Core.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SF.Feature.DEF.General
{
    [RequiredPipelineStepPlugins(new Type[] { typeof(PipelinesSettings), typeof(DataLocationSettings) })]
    [RequiredPipelineContextPlugins(new Type[] { typeof(IterableDataSettings) })]
    public class IterateAndRunPipelineAndStoreResultsStepProcessor : BasePipelineStepProcessor
    {
        public override void Process(PipelineStep pipelineStep, PipelineContext pipelineContext)
        {
            ILogger logger = pipelineContext.PipelineBatchContext.Logger;
            if (!this.CanProcess(pipelineStep, pipelineContext))
            {
                logger.Error("Pipeline step processing will abort because the pipeline step cannot be processed. (pipeline step: {0})", (object)pipelineStep.Name);
            }
            else
            {
                PipelinesSettings pipelinesSettings = pipelineStep.GetPipelinesSettings();
                if (pipelinesSettings == null || !pipelinesSettings.Pipelines.Any<Pipeline>())
                {
                    logger.Error("Pipeline step processing will abort because the pipeline step has no sub-pipelines assigned. (pipeline step: {0})", (object)pipelineStep.Name);
                }
                else
                {
                    IterableDataSettings iterableDataSettings = pipelineContext.GetIterableDataSettings();
                    if (iterableDataSettings == null || iterableDataSettings.Data == null)
                        return;

                    int num = 0;

                    try
                    {
                        var childRecordSettings = new ChildRecordSettings();

                        foreach (object element in iterableDataSettings.Data)
                        {

                            if (!pipelineContext.PipelineBatchContext.Stopped)
                            {
                                PipelineContext pipelineContext1 = new PipelineContext(pipelineContext.PipelineBatchContext);
                                SynchronizationSettings synchronizationSettings = this.ResolveSynchronizationSettingsAndSetElement(pipelineStep, pipelineContext, element);
                                //instatiate Target for filling.
                                synchronizationSettings.Target = new Dictionary<string, string>();

                                pipelineContext1.Plugins.Add((IPlugin)synchronizationSettings);
                                ParentPipelineContextSettings pipelineContextSettings = new ParentPipelineContextSettings()
                                {
                                    ParentPipelineContext = pipelineContext
                                };
                                pipelineContext1.Plugins.Add((IPlugin)pipelineContextSettings);
                                this.ProcessPipelines(pipelineStep, pipelinesSettings.Pipelines, pipelineContext1);

                                //Now Let's get the results
                                var record = pipelineContext1.GetPlugin<SynchronizationSettings>().Target as Dictionary<string, string>;
                                if (record != null)
                                {
                                    childRecordSettings.Records.Add(record);
                                }

                            }

                            num++;
                        }

                        //Add to the context so we can do something with this collection
                        pipelineContext.Plugins.Add(childRecordSettings);

                        logger.Info("{0} elements were iterated. (pipeline: {1}, pipeline step: {2})", (object)num, (object)pipelineContext.CurrentPipeline.Name, (object)pipelineContext.CurrentPipelineStep.Name, (object)pipelineContext);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message);
                        logger.Error(ex.StackTrace);
                        pipelineContext.CriticalError = true;
                    }
                }
            }
        }

        protected virtual SynchronizationSettings ResolveSynchronizationSettingsAndSetElement(PipelineStep pipelineStep, PipelineContext pipelineContext, object element)
        {
            DataLocationSettings locationSettings = pipelineStep.GetDataLocationSettings();
            SynchronizationSettings synchronizationSettings = new SynchronizationSettings();
            if (locationSettings.DataLocation == "Pipeline Context Source")
                synchronizationSettings.Source = element;
            if (locationSettings.DataLocation == "Pipeline Context Target")
                synchronizationSettings.Target = element;
            return synchronizationSettings;
        }

        protected virtual void ProcessPipelines(PipelineStep pipelineStep, ICollection<Pipeline> subPipelines, PipelineContext pipelineContext)
        {
            if (pipelineStep == null)
                throw new ArgumentNullException("pipelineStep");
            if (subPipelines == null)
                throw new ArgumentNullException("subPipelines");
            if (pipelineContext == null)
                throw new ArgumentNullException("pipelineContext");
            ILogger logger = pipelineContext.PipelineBatchContext.Logger;
            if (!subPipelines.Any<Pipeline>())
            {
                logger.Error("Pipeline step processing will abort because no pipelines are assigned to the pipeline step. (pipeline step: {0})", (object)pipelineStep.Name);
            }
            else
            {
                List<Pipeline> pipelineList = new List<Pipeline>();
                foreach (Pipeline subPipeline in (IEnumerable<Pipeline>)subPipelines)
                {
                   RunSubPipelines(pipelineContext, subPipeline);
                }

            }
        }

        private void RunSubPipelines(PipelineContext pipelineContext, Pipeline subPipeline)
        {
            ILogger logger = pipelineContext.PipelineBatchContext.Logger;
            pipelineContext.CurrentPipeline = subPipeline;
            IPipelineProcessor pipelineProcessor = subPipeline.PipelineProcessor;

            if (pipelineProcessor == null)
                logger.Error("Pipeline will be skipped because it does not have a processor assigned. (pipeline step: {0}, sub-pipeline: {1})", "Iterate and Run Async", (object)subPipeline.Name);
            else if (!pipelineProcessor.CanProcess(subPipeline, pipelineContext))
            {
                logger.Error("Pipeline will be skipped because the processor cannot processes the sub-pipeline. (pipeline step: {0}, sub-pipeline: {1}, sub-pipeline processor: {2})", "Iterate and Run Async", (object)subPipeline.Name, (object)pipelineProcessor.GetType().FullName);
            }
            else
            {
                pipelineProcessor.Process(subPipeline, pipelineContext);
                if (pipelineContext.CriticalError)
                {
                    logger.Error("Sub pipeline processing will not abort since it's done async");
                }
            }
        }

        protected virtual void OnCriticalError(Pipeline errorPipeline, IEnumerable<Pipeline> completedPipelines, PipelineStep pipelineStep, PipelineContext pipelineContext)
        {
        }

        public override bool CanProcess(PipelineStep pipelineStep, PipelineContext pipelineContext)
        {
            if (!base.CanProcess(pipelineStep, pipelineContext))
                return false;
            if (!string.IsNullOrWhiteSpace(pipelineStep.GetDataLocationSettings().DataLocation))
                return true;
            pipelineContext.PipelineBatchContext.Logger.Error("No data location is specified. (plugin: {0}, pipeline step: {1})", (object)typeof(DataLocationSettings), (object)pipelineStep.Name);
            return false;
        }
    }
}


text:
layout: default
title: CAS - Cassandra Ticket Registry
category: Ticketing
---

# Cassandra Ticket Registry

Cassandra integration is enabled by including the following dependency in the WAR overlay:

```xml
<dependency>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-server-support-cassandra-ticket-registry</artifactId>
    <version>${cas.version}</version>
</dependency>
```

This registry stores tickets in [Apache Cassandra](http://cassandra.apache.org/) instances. Tickets are expected to be found/stored in a `castickets` table
with a default write consistency of `LOCAL_QUORUM` and read consistency of `ONE`.

## Troubleshooting

To enable additional logging, configure the log4j configuration file to add the following levels:

```xml
...
<AsyncLogger name="com.datastax.driver" level="debug" additivity="false">
    <AppenderRef ref="console"/>
    <AppenderRef ref="file"/>
</AsyncLogger>
...
```

## Configuration

To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#cassandra-ticket-registry).


text:
Change Log
==========

Version 1.2.1 *(2011-10-20)*
----------------------------

Maven 3 is now required when building from the command line.

 * Update to support ADT 14.

Version 1.2.0 *(2011-10-04)*
----------------------------

 * Move to `com.directionalviewpager` package.
 * Change maven group and artifact to `com.directionalviewpager:library`.

Version 1.1.0 *(2011-09-28)*
----------------------------

 * Extend from `ViewPager` so it can be used with other APIs which require an
   instance of `ViewPager`.
 * Move to `com.jakewharton.android.view` package.

Version 1.0.0 *(2011-08-24)*
----------------------------

Initial release.


text:
#ifndef GAINPUTALLOCATOR_H_
#define GAINPUTALLOCATOR_H_

namespace gainput
{

/// Interface used to pass custom allocators to the library.
/**
 * If you want the library to use your custom allocator you should implement this interface.
 * Specifically, you should provide implementations for the Allocate() and Deallocate()
 * functions. All other (template) member functions are simply based on those two functions.
 *
 * \sa DefaultAllocator
 */
class GAINPUT_LIBEXPORT Allocator
{
public:
	enum { DefaultAlign = 0 };

	/// Allocates a number of bytes and returns a pointer to the allocated memory.
	/**
	 * \param size The number of bytes to allocate.
	 * \return A memory block encompassing at least size bytes.
	 */
	virtual void* Allocate(size_t size, size_t align = DefaultAlign) = 0;
	/// Deallocates the given memory.
	/**
	 * \param ptr The memory block to deallocate.
	 */
	virtual void Deallocate(void* ptr) = 0;

	/// An operator new-like function that allocates memory and calls T's constructor.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T>
	T* New()
	{
		return new (Allocate(sizeof(T))) T();
	}

	/// An operator new-like function that allocates memory and calls T's constructor with one parameter.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0>
	T* New(P0& p0)
	{
		return new (Allocate(sizeof(T))) T(p0);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with one parameter.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0>
	T* New(const P0& p0)
	{
		return new (Allocate(sizeof(T))) T(p0);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with two parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1>
	T* New(P0& p0, P1& p1)
	{
		return new (Allocate(sizeof(T))) T(p0, p1);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with two parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1>
	T* New(const P0& p0, P1& p1)
	{
		return new (Allocate(sizeof(T))) T(p0, p1);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with two parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1>
	T* New(P0& p0, const P1& p1)
	{
		return new (Allocate(sizeof(T))) T(p0, p1);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with the given parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1, class P2>
	T* New(P0& p0, const P1& p1, const P2& p2)
	{
		return new (Allocate(sizeof(T))) T(p0, p1, p2);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with the given parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1, class P2>
	T* New(P0& p0, const P1& p1, P2& p2)
	{
		return new (Allocate(sizeof(T))) T(p0, p1, p2);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with the given parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1, class P2, class P3>
	T* New(P0& p0, P1& p1, P2& p2, P3& p3)
	{
		return new (Allocate(sizeof(T))) T(p0, p1, p2, p3);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with the given parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1, class P2, class P3>
	T* New(P0& p0, const P1& p1, P2& p2, P3& p3)
	{
		return new (Allocate(sizeof(T))) T(p0, p1, p2, p3);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with the given parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1, class P2, class P3, class P4>
	T* New(P0& p0, P1& p1, P2& p2, P3& p3, P4& p4)
	{
		return new (Allocate(sizeof(T))) T(p0, p1, p2, p3, p4);
	}

	/// An operator new-like function that allocates memory and calls T's constructor with the given parameters.
	/**
	 * \return A pointer to an initialized instance of T.
	 */
	template <class T, class P0, class P1, class P2, class P3, class P4>
	T* New(P0& p0, const P1& p1, P2& p2, P3& p3, P4& p4)
	{
		return new (Allocate(sizeof(T))) T(p0, p1, p2, p3, p4);
	}

	/// An operator delete-like function that calls ptr's constructor and deallocates the memory.
	/**
	 * \param ptr The object to destruct and deallocate.
	 */
	template <class T>
	void Delete(T* ptr)
	{
		if (ptr)
		{
			ptr->~T();
			Deallocate(ptr);
		}
	}
};

/// The default allocator used by the library.
/**
 * Any allocation/deallocation calls are simply forwarded to \c malloc and \c free. Any
 * requested alignment is ignored.
 */
class GAINPUT_LIBEXPORT DefaultAllocator : public Allocator
{
public:
	void* Allocate(size_t size, size_t /*align*/)
	{
		return malloc(size);
	}

	void Deallocate(void* ptr)
	{
		free(ptr);
	}
};

/// Returns the default instance of the default allocator.
/**
 * \sa DefaultAllocator
 */
GAINPUT_LIBEXPORT DefaultAllocator& GetDefaultAllocator();

template<class K, class V>
class GAINPUT_LIBEXPORT HashMap;

/// An allocator that tracks an allocations that were done
/**
 * Any allocation/deallocation calls are simply forwarded to \c malloc and \c free. Any
 * requested alignment is ignored.
 */
class GAINPUT_LIBEXPORT TrackingAllocator : public Allocator
{
public:
	TrackingAllocator(Allocator& backingAllocator, Allocator& internalAllocator = GetDefaultAllocator());
	~TrackingAllocator();

	void* Allocate(size_t size, size_t align = DefaultAlign);
	void Deallocate(void* ptr);

	size_t GetAllocateCount() const { return allocateCount_; }
	size_t GetDeallocateCount() const { return deallocateCount_; }
	size_t GetAllocatedMemory() const { return allocatedMemory_; }

private:
	Allocator& backingAllocator_;
	Allocator& internalAllocator_;
	HashMap<void*, size_t>* allocations_;
	size_t allocateCount_;
	size_t deallocateCount_;
	size_t allocatedMemory_;
};

}

#endif


text:
import Modal from './src/modal';
export default Modal;