text:
using Data;
using System.Collections.Generic;
using WebSite.Code.Attributes;
using WebSite.Models.Base;

namespace WebSite.Models
{
    public class TagModel : BaseModel<TagModel, Tag>
    {
        public TagModel()
        {
            Posts = new List<PostModel>();
        }

        public int Id { get; set; }

        [LocalizedRequired("TagNameIsMandatory")]
        [LocalizedStringLength(3, 50, "TagNameRequirements")]
        [LocalizedDisplayName("Name")]
        public string Name { get; set; }

        public List<PostModel> Posts { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Regina</logradouro><bairro>Macaxeira</bairro><cidade>Recife</cidade><uf>PE</uf><cep>52090280</cep></feed>


text:
using System.Collections.Generic;
using IxMilia.Step.Tokens;

namespace IxMilia.Step.Syntax
{
    internal class StepOmittedSyntax : StepSyntax
    {
        public override StepSyntaxType SyntaxType => StepSyntaxType.Omitted;

        public StepOmittedSyntax(StepOmittedToken value)
            : base(value.Line, value.Column)
        {
        }

        public override IEnumerable<StepToken> GetTokens()
        {
            yield return StepOmittedToken.Instance;
        }
    }
}


text:
React.render(
        React.createElement('h1',null,'Render Basic of test Index'),
        document.getElementById('example')
      );


text:
<?php

namespace Robin\Ntlm\Crypt\Des;

use InvalidArgumentException;
use Robin\Ntlm\Crypt\CipherMode;
use Robin\Ntlm\Crypt\Exception\CryptographicFailureException;

/**
 * An engine used to encrypt data using the DES standard algorithm.
 */
interface DesEncrypterInterface
{

    /**
     * Encrypts using the DES standard algorithm.
     *
     * @link https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
     * @link https://en.wikipedia.org/wiki/Initialization_vector
     * @param string $key The key to encrypt the data with.
     * @param string $data The data to encrypt.
     * @param int $mode The {@link CipherMode cipher mode} of operation.
     * @param string $initialization_vector The initialization vector used to
     *   encrypt the data in an unpredictable or reproducable fashion.
     * @return string The encrypted data as a binary string.
     * @throws InvalidArgumentException If the provided cipher mode isn't an
     *   available option.
     * @throws CryptographicFailureException If the encryption fails.
     */
    public function encrypt($key, $data, $mode, $initialization_vector);
}


text:
layout: default
---

{{ page.title | downcase }}

{% for image in page.images %}

 {{ image.exif.model }}

 {{ image.exif.exposure_time }}

 {{ image.exif.f_number }}

{% endfor %}

        « {{ site.gallery.title }}


text:
Provides a way to logging all console events

### Configuration

#### Register `ConsoleProcessManagerBundle` in your app.
Add `RedCircle\ConsoleProcessManagerBundle\ConsoleProcessManagerBundle::enable($application);` in your console file in app directory.

**Example of `AppKernel.php` file:**
```
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            ...
            new RedCircle\ConsoleProcessManagerBundle\ConsoleProcessManagerBundle(),
        );

    return $bundles;
    }
}
```

### Troubleshooting

#### Unknown Entity namespace alias 'ConsoleProcessManagerBundle'.
If you are using `entity_managers.default.mappings`, and have bellow issue.
```
[Doctrine\ORM\ORMException]
Unknown Entity namespace alias 'ConsoleProcessManagerBundle'.
```
Simply add `ConsoleProcessManagerBundle: ~` in your `config.yml` file.

```
entity_managers:
    default:
        mappings:
            ...
            ConsoleProcessManagerBundle: ~
```


text:
module.exports = {
  ecmaFeatures: {
    jsx: true
  },

  extends: [
    'eslint-config-airbnb-base/rules/strict',
    'eslint-config-airbnb/rules/react'
  ].map(require.resolve),

  plugins: [
    'react-native'
  ],

  rules: {
    'react-native/split-platform-components': 'off',
    'react-native/no-unused-styles': 'error',
    'react-native/no-inline-styles': 'error',
    'react-native/no-color-literals': 'error'
  }
}


text:
/*
 * 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.
 */
package org.ngrinder.perftest.service.monitor;

import org.apache.commons.io.FileUtils;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.ngrinder.monitor.share.domain.SystemInfo;
import org.ngrinder.perftest.service.AbstractAgentReadyTest;

import java.io.File;
import java.io.IOException;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Monitor Client Service Test
 */
public class MonitorClientServiceTest extends AbstractAgentReadyTest {
	private File tempReport;

	@Before
	public void before() {
		tempReport = new File(System.getProperty("java.io.tmpdir"), "tmp-report");
		FileUtils.deleteQuietly(tempReport);
		tempReport.mkdir();
	}

	@After
	public void after() {
		tempReport.deleteOnExit();
	}

	@Test
	public void testMonitorClient() throws IOException {
		MonitorClientService client = new MonitorClientService("127.0.0.1", 13243);
		client.init();
		final SystemInfo monitorData = client.getSystemInfo();
		assertThat(monitorData.isParsed(), is(false));
		sleep(3000);
		client.update();
		SystemInfo monitorData2 = client.getSystemInfo();
		assertThat(monitorData2.isParsed(), is(true));
		assertThat(monitorData2, Matchers.notNullValue());
		assertThat(monitorData, not(monitorData2));

	}

}


text:
//
//  QFXVideoTableViewCell.m
//  QuFaXian
//
//  Created by hzy on 16/5/18.
//  Copyright © 2016年 Sugar. All rights reserved.
//

#import "QFXVideoTableViewCell.h"

@interface QFXVideoTableViewCell ()

// 底部存放标题标签的View
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *storeViewHeight;

// 头像按钮距离顶部的高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconBtnMarginTopValue;

// 头像按钮的宽度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconBtnWidth;
// 头像按钮的高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iconBtnHeight;

// 播放按钮距离顶部的高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playBtnMarginTopValue;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playBtnWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playBtnHeight;

@end

@implementation QFXVideoTableViewCell
//// 存放标题label和内容描述label的View
//@property (weak, nonatomic) IBOutlet UIView *storeLabelView;
//
//// 标题label
//@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
//
//// 内容描述label
//@property (weak, nonatomic) IBOutlet UILabel *descriptionLabel;
//
//// 视频类型label
//@property (weak, nonatomic) IBOutlet UILabel *videoTypeLabel;
//
//// 头像按钮
//@property (weak, nonatomic) IBOutlet UIButton *iconBtn;
//
//// 时间按钮
//@property (weak, nonatomic) IBOutlet UIButton *timeBtn;
//
//// 播放按钮
//@property (weak, nonatomic) IBOutlet UIButton *playBtn;
//
//// 创建cell的方法
//+ (instancetype)videoTableViewCell:(UITableView *)tableView;

+ (instancetype)videoTableViewCell:(UITableView *)tableView
{
    static NSString *ID = @"video_tableViewCell";
    QFXVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"QFXVideoTableViewCell" owner:nil options:nil] firstObject];
    }
    return cell;
}

/*
- (void)layoutSubviews
{
    // 设置storeViewHeight的高度
    self.storeViewHeight.constant = CGRectGetMaxY(self.descriptionLabel.frame) + 26;

    // 重置cell的frame
    CGRect temp = self.frame;
    temp.size.height = self.storeViewHeight.constant / (99 / 235);
    self.frame = temp;

    self.iconBtnMarginTopValue.constant = self.frame.size.height * (89 / 235);
    self.iconBtnWidth.constant = self.frame.size.width * (45 / 235);
    self.iconBtnHeight.constant = self.iconBtnWidth.constant;

    self.playBtnMarginTopValue.constant = self.frame.size.height * (13 / 235);
    self.playBtnWidth.constant = self.frame.size.width * (55 / 375);
    self.playBtnHeight.constant = self.playBtnWidth.constant;
}
*/

//- (void)setVideoDataModel:(QFXVideoDataModel *)videoDataModel
//{
//    _videoDataModel = videoDataModel;
//    [self layoutIfNeeded];
//    self.videoDataModel.cellHeight = CGRectGetMaxY(self.descriptionLabel.frame) + 26 + 10;
//}

- (void)awakeFromNib {

    self.titleLabel.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 40;
    self.descriptionLabel.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 30;

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
package gui.components.borders;

import java.awt.*;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;

import javax.swing.UIManager;

import com.bulenkov.iconloader.util.DoubleColor;

import utils.Utilities;

/**
 *
 * @author Administrator
 */
public class RoundedTitleBorder extends RoundedBorder
{
	private final String title;
	private String info;
	private final Color[] backgroundColor;

	public RoundedTitleBorder(String title, Color lineColor, Color[] backgroundColor)
	{
		super(lineColor);
		this.title = title;
		this.backgroundColor = backgroundColor;
	}

	public RoundedTitleBorder(String title, Color lineColor, Color[] backgroundColor, int cornerRadius)
	{
		super(lineColor, cornerRadius);
		this.title = title;
		this.backgroundColor = backgroundColor;
	}

	public RoundedTitleBorder(String title, Color lineColor, Color[] backgroundColor, int br1, int br2, int br3, int br4)
	{
		super(lineColor, br1, br2, br3, br4);
		this.title = title;
		this.backgroundColor = backgroundColor;
	}

	public RoundedTitleBorder(String title, String info, Color lineColor, Color[] backgroundColor, int br1, int br2, int br3, int br4)
	{
		super(lineColor, br1, br2, br3, br4);
		this.title = title;
		this.info = info;
		this.backgroundColor = backgroundColor;
	}

	public Insets getBorderInsets(Component c, Insets insets)
	{
		Insets borderInsets = super.getBorderInsets(c, insets);
		borderInsets.top = getTitleHeight(c)+2;
		borderInsets.bottom = 2;
		borderInsets.left = borderInsets.right = 5;
		return borderInsets;
	}

	protected int getTitleHeight(Component c)
	{
		FontMetrics metrics = c.getFontMetrics(c.getFont());
		return (int) (metrics.getHeight() * 1.80);
	}

	public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
	{
		int titleHeight = getTitleHeight(c);

		// Creates title bar
		Graphics2D g2 = (Graphics2D) g.create();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		//GradientPaint lGradientPaint = new GradientPaint(0, 0, c1, 0, titleHeight, c2);
		g2.setPaint(backgroundColor.length<2 ? backgroundColor[0] : new GradientPaint(0, 0, backgroundColor[0], 0, titleHeight, backgroundColor[1]));
		Path2D titlebar;
		if (cornerRadius > 0)
			titlebar = getRoundRect(x, y, width - 1, titleHeight - 1, cornerRadius, cornerRadius, 0, 0);
		else
			titlebar = getRoundRect(x, y, width - 1, titleHeight - 1, br1, br2, 0, 0);
		g2.fill(titlebar);
		g2.setColor(Utilities.deriveColorAlpha(this.color, 255));
		g2.drawLine(x + 1, titleHeight - 1, width - 2, titleHeight - 1);
		g2.setComposite(AlphaComposite.DstIn);
		g2.fillRect(x, y, width, titleHeight);
		g2.dispose();

		// draw rounded border
		super.paintBorder(c, g, x, y, width, height);

		// draw title string
		g2 = (Graphics2D) g.create();
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		g2.setColor(c.getForeground());
		g2.setFont(c.getFont().deriveFont(Font.BOLD));
		FontMetrics metrics = c.getFontMetrics(c.getFont().deriveFont(Font.BOLD));
		g2.drawString(title, x + 8, y + (titleHeight - metrics.getHeight()) / 2 + metrics.getAscent());
		if (info != null && !info.equals(""))
		{
			metrics = c.getFontMetrics(c.getFont().deriveFont(Font.ITALIC));
			g2.setFont(c.getFont().deriveFont(Font.ITALIC));
			g2.drawString(info, x + width - 8 - metrics.stringWidth(info), y + (titleHeight - metrics.getHeight()) / 2 + metrics.getAscent());
		}

		g2.dispose();

	}
}


text:
namespace NServiceBus.AcceptanceTests.Recoverability
{
    using System;
    using System.Threading.Tasks;
    using AcceptanceTesting;
    using EndpointTemplates;
    using NUnit.Framework;

    public class When_message_with_TimeToBeReceived_fails : NServiceBusAcceptanceTest
    {
        [Test]
        public async Task Should_not_honor_TimeToBeReceived_for_error_message()
        {
            var context = await Scenario.Define<Context>()
                .WithEndpoint<EndpointThatThrows>(b => b
                    .When(session => session.SendLocal(new MessageThatFails()))
                    .DoNotFailOnErrorMessages())
                .WithEndpoint<EndpointThatHandlesErrorMessages>()
                .Done(c => c.MessageFailed && c.TTBRHasExpiredAndMessageIsStillInErrorQueue)
                .Run();

            Assert.IsTrue(context.MessageFailed);
            Assert.IsTrue(context.TTBRHasExpiredAndMessageIsStillInErrorQueue);
        }

        class Context : ScenarioContext
        {
            public bool MessageFailed { get; set; }
            public DateTime? FirstTimeProcessedByErrorHandler { get; set; }
            public bool TTBRHasExpiredAndMessageIsStillInErrorQueue { get; set; }
        }

        class EndpointThatThrows : EndpointConfigurationBuilder
        {
            public EndpointThatThrows()
            {
                EndpointSetup<DefaultServer>(b => { b.SendFailedMessagesTo("errorQueueForAcceptanceTest"); });
            }

            class ThrowingMessageHandler : IHandleMessages<MessageThatFails>
            {
                public ThrowingMessageHandler(Context context)
                {
                    this.context = context;
                }

                public Task Handle(MessageThatFails message, IMessageHandlerContext context1)
                {
                    context.MessageFailed = true;
                    throw new SimulatedException();
                }

                Context context;
            }
        }

        class EndpointThatHandlesErrorMessages : EndpointConfigurationBuilder
        {
            public EndpointThatHandlesErrorMessages()
            {
                EndpointSetup<DefaultServer>()
                    .CustomEndpointName("errorQueueForAcceptanceTest");
            }

            class ErrorMessageHandler : IHandleMessages<MessageThatFails>
            {
                public ErrorMessageHandler(Context testContext)
                {
                    this.testContext = testContext;
                }

                public Task Handle(MessageThatFails message, IMessageHandlerContext context)
                {
                    var errorProcessingStarted = DateTime.Now;
                    if (testContext.FirstTimeProcessedByErrorHandler == null)
                    {
                        testContext.FirstTimeProcessedByErrorHandler = errorProcessingStarted;
                    }

                    var ttbr = TimeSpan.Parse(context.MessageHeaders[Headers.TimeToBeReceived]);
                    var ttbrExpired = errorProcessingStarted > testContext.FirstTimeProcessedByErrorHandler.Value + ttbr;
                    if (ttbrExpired)
                    {
                        testContext.TTBRHasExpiredAndMessageIsStillInErrorQueue = true;
                        var timeElapsedSinceFirstHandlingOfErrorMessage = errorProcessingStarted - testContext.FirstTimeProcessedByErrorHandler.Value;
                        Console.WriteLine("Error message not removed because of TTBR({0}) after {1}. Succeeded.", ttbr, timeElapsedSinceFirstHandlingOfErrorMessage);
                    }
                    else
                    {
                        return context.HandleCurrentMessageLater();
                    }

                    return Task.FromResult(0); // ignore messages from previous test runs
                }

                Context testContext;
            }
        }

        [TimeToBeReceived("00:00:03")]
        public class MessageThatFails : IMessage
        {
        }
    }
}


text:
from django.core.management.base import LabelCommand

class Command(LabelCommand):
    help = "Test Label-based commands"
    requires_system_checks = []

    def handle_label(self, label, **options):
        print(
            "EXECUTE:LabelCommand label=%s, options=%s"
            % (label, sorted(options.items()))
        )


text:
package mx.bigdata.sat.contabilidad_electronica;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.util.JAXBSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import mx.bigdata.sat.ce_catalogo_cuentas.schema.Catalogo;
import mx.bigdata.sat.common.NamespacePrefixMapperImpl;
import mx.bigdata.sat.common.URIResolverImpl;
import mx.bigdata.sat.security.KeyLoaderEnumeration;
import mx.bigdata.sat.security.factory.KeyLoaderFactory;

import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public final class CuentasContablesv11 {

	private static final String XSLT = "/xslt/ce_catalogo_cuentas/CatalogoCuentas_1_1.xslt";

	private static final String[] XSD = new String[] {
		"/xsd/ce_catalogo_cuentas/CatalogoCuentas_1_1.xsd"
	};

	private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

	private static final String BASE_CONTEXT = "mx.bigdata.sat.ce_catalogo_cuentas.schema";

	private final static Joiner JOINER = Joiner.on(':');

	private final JAXBContext context ;

	public static final ImmutableMap<String, String> PREFIXES =
			ImmutableMap.of("http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas", "catalogocuentas",
							"http://www.w3.org/2001/XMLSchema-instance","xsi");

	// ,"http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas", "catalogocuentas"

	private final Map<String, String> localPrefixes = Maps.newHashMap(PREFIXES);

	/*************************************************************************************************************/

	/*************************************************************************************************************/

	private TransformerFactory tf;

//	final Comprobante document;
	final Catalogo document;

	public CuentasContablesv11(InputStream in, String... contexts) throws Exception {
		this.context = getContext(contexts);
		this.document = load(in);
	}

	public CuentasContablesv11(Catalogo catalogo, String... contexts) throws Exception {
		this.context = getContext(contexts);
		this.document = copy(catalogo);
	}

	public void addNamespace(String uri, String prefix) {
		localPrefixes.put(uri, prefix);
	}

	public void setTransformerFactory(TransformerFactory tf) {
		this.tf = tf;
		tf.setURIResolver(new URIResolverImpl());
	}

	public Catalogo sellarComprobante(PrivateKey key, X509Certificate cert) throws Exception {
		sellar(key, cert);
		return doGetCatalogo();
	}

	public void validar() throws Exception {
		validar(null);
	}

	public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
		cert.checkValidity();
		String signature = getSignature(key);
		document.setSello(signature);
		byte[] bytes = cert.getEncoded();
		Base64 b64 = new Base64(-1);
		String certStr = b64.encodeToString(bytes);
		document.setCertificado(certStr);
		BigInteger bi = cert.getSerialNumber();
		document.setNoCertificado(new String(bi.toByteArray()));
	}

	public void validar(ErrorHandler handler) throws Exception {
		SchemaFactory sf =
				SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Source[] schemas = new Source[XSD.length];
		for (int i = 0; i < XSD.length; i++) {
			schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
		}
		Schema schema = sf.newSchema(schemas);
		Validator validator = schema.newValidator();
		if (handler != null) {
			validator.setErrorHandler(handler);
		}
		validator.validate(new JAXBSource(context, document));
	}

	public void verificar() throws Exception {
		String certStr = document.getCertificado();
		Base64 b64 = new Base64();
		byte[] cbs = b64.decode(certStr);

		X509Certificate cert = KeyLoaderFactory.createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER,new ByteArrayInputStream(cbs)).getKey();

		String sigStr = document.getSello();
		byte[] signature = b64.decode(sigStr);
		byte[] bytes = getOriginalBytes();
		Signature sig = Signature.getInstance("SHA1withRSA");
		sig.initVerify(cert);
		sig.update(bytes);
		boolean bool = sig.verify(signature);
		if (!bool) {
			throw new Exception("Invalid signature");
		}
	}

	public void guardar(OutputStream out) throws Exception {
		Marshaller m = context.createMarshaller();
		m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl(localPrefixes));
		m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas " + "http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas/CatalogoCuentas_1_1.xsd");
		byte[] xmlHeaderBytes = XML_HEADER.getBytes("UTF8");
		out.write(xmlHeaderBytes);
		m.marshal(document, out);
	}

	public String getCadenaOriginal() throws Exception {
		byte[] bytes = getOriginalBytes();
		return new String(bytes, "UTF8");
	}

	public static Catalogo newComprobante(InputStream in) throws Exception {
		return load(in);
	}

//	public ComprobanteBase getComprobante() throws Exception {
//		return new CFDv32ComprobanteBase(doGetCatalogo());
//	}

	Catalogo doGetCatalogo() throws Exception {
		return copy(document);
	}

	byte[] getOriginalBytes() throws Exception {
		JAXBSource in = new JAXBSource(context, document);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Result out = new StreamResult(baos);
		TransformerFactory factory = tf;
		if (factory == null) {
			factory = TransformerFactory.newInstance();
			factory.setURIResolver(new URIResolverImpl());
		}
		Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
		transformer.transform(in, out);
		return baos.toByteArray();
	}

	String getSignature(PrivateKey key) throws Exception {
		byte[] bytes = getOriginalBytes();
		Signature sig = Signature.getInstance("SHA1withRSA");
		sig.initSign(key);
		sig.update(bytes);
		byte[] signed = sig.sign();
		Base64 b64 = new Base64(-1);
		return b64.encodeToString(signed);
	}

	// FUNCIONES AUXILIARES
	private static JAXBContext getContext(String[] contexts) throws Exception {
		List<String> ctx = Lists.asList(BASE_CONTEXT, contexts);
		return JAXBContext.newInstance(JOINER.join(ctx));
	}

	private static Catalogo load(InputStream source, String... contexts)
			throws Exception {
		JAXBContext context = getContext(contexts);
		try {
			Unmarshaller u = context.createUnmarshaller();
			return (Catalogo) u.unmarshal(source);
		} finally {
			source.close();
		}
	}

	  // Defensive deep-copy
	  private Catalogo copy(Catalogo catalogo) throws Exception {
	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	    dbf.setNamespaceAware(true);
	    DocumentBuilder db = dbf.newDocumentBuilder();
	    Document doc = db.newDocument();
	    Marshaller m = context.createMarshaller();
	    m.marshal(catalogo, doc);
	    Unmarshaller u = context.createUnmarshaller();
	    return (Catalogo) u.unmarshal(doc);
	  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zergatul.Cryptography.Symmetric
{
    public abstract class AbstractStreamCipher
    {
        public abstract int KeySize { get; }
        public abstract int BlockSize { get; }
        public abstract int NonceSize { get; }

        public abstract KeyStream InitKeyStream(byte[] key, byte[] nonce, uint counter);
    }
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2019] EMBL-European Bioinformatics Institute

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.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=cut

=head1 NAME

Bio::EnsEMBL::BaseAlignFeature - Baseclass providing a common abstract
implmentation for alignment features

=head1 SYNOPSIS

  my $feat = new Bio::EnsEMBL::DnaPepAlignFeature(
    -slice        => $slice,
    -start        => 100,
    -end          => 120,
    -strand       => 1,
    -hseqname     => 'SP:RF1231',
    -hstart       => 200,
    -hend         => 220,
    -analysis     => $analysis,
    -cigar_string => '10M3D5M2I',
    -align_type   => 'ensembl'
  );

  where $analysis is a Bio::EnsEMBL::Analysis object.

  Alternatively if you have an array of ungapped features:

    my $feat =
      new Bio::EnsEMBL::DnaPepAlignFeature( -features => \@features );

  where @features is an array of Bio::EnsEMBL::FeaturePair objects.

  There is a method to (re)create ungapped features from the cigar_string:

    my @ungapped_features = $feat->ungapped_features();

  where @ungapped_features is an array of Bio::EnsEMBL::FeaturePair's.

  Bio::EnsEMBL::BaseAlignFeature inherits from:
    Bio::EnsEMBL::FeaturePair, which in turn inherits from:
      Bio::EnsEMBL::Feature,
  thus methods from both parent classes are available.

  The cigar_string is a condensed representation of the matches and gaps
  which make up the gapped alignment (where CIGAR stands for
  Concise Idiosyncratic Gapped Alignment Report).

  CIGAR format is: n <matches> [ x <deletes or inserts> m <matches> ]*
  where M = match, D = delete, I = insert; n, m are match lengths;
  x is delete or insert length.

  Spaces are omitted, thus: "23M4I12M2D1M"
  as are counts for any lengths of 1, thus 1M becomes M: "23M4I12M2DM"

  To make things clearer this is how a blast HSP would be parsed:

  >AK014066
         Length = 146

    Minus Strand HSPs:

    Score = 76 (26.8 bits), Expect = 1.4, P = 0.74
    Identities = 20/71 (28%), Positives = 29/71 (40%), Frame = -1

  Query:   479 GLQAPPPTPQGCRLIPPPPLGLQAPLPTLRAVGSSHHHP*GRQGSSLSSFRSSLASKASA 300
               G  APPP PQG R   P P G + P   L             + + ++  R  +A   +
  Sbjct:     7 GALAPPPAPQG-RWAFPRPTG-KRPATPLHGTARQDRQVRRSEAAKVTGCRGRVAPHVAP 64

  Query:   299 SSPHNPSPLPS 267
                  H P+P P+
  Sbjct:    65 PLTHTPTPTPT 75

  The alignment goes from 479 down to 267 in the query sequence on the reverse
  strand, and from 7 to 75 in the subject sequence.

  The alignment is made up of the following ungapped pieces:

  query_seq start 447 , sbjct_seq hstart  7 , match length  33 , strand -1
  query_seq start 417 , sbjct_seq hstart 18 , match length  27 , strand -1
  query_seq start 267 , sbjct_seq hstart 27 , match length 147 , strand -1

  When assembled into a DnaPepAlignFeature where:
    (seqname, start, end, strand) refer to the query sequence,
    (hseqname, hstart, hend, hstrand) refer to the subject sequence,
  these ungapped pieces are represented by the cigar string:
    33M3I27M3I147M
  with start 267, end 479, strand -1, and hstart 7, hend 75, hstrand 1.

=head1 CAVEATS

  AlignFeature cigar strings have the opposite 'sense'
  ('D' and 'I' swapped) compared with Exonerate cigar strings.

  Exonerate modules in Bio::EnsEMBL::Analysis use this convention:

   The longer genomic sequence specified by:
      exonerate:    target
      AlignFeature: (sequence, start, end, strand)

   A shorter sequence (such as EST or protein) specified by:
      exonerate:    query
      AlignFeature: (hsequence, hstart, hend, hstrand)

  The resulting AlignFeature cigar strings have 'D' and 'I'
  swapped compared with the Exonerate output, i.e.:

    exonerate:    M 123 D 1 M 11 I 1 M 39
    AlignFeature: 123MI11MD39M

=head1 METHODS

=cut

package Bio::EnsEMBL::BaseAlignFeature;

use Bio::EnsEMBL::FeaturePair;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);

use vars qw(@ISA);
use strict;

@ISA = qw(Bio::EnsEMBL::FeaturePair);

=head2 new

  Arg [..]   : List of named arguments. (-cigar_string , -features, -align_type) defined
               in this constructor, others defined in FeaturePair and
               SeqFeature superclasses.  Either cigar_string or a list
               of ungapped features should be provided - not both.
  Example    : $baf = new BaseAlignFeatureSubclass(-cigar_string => '3M3I12M', -align_type => 'ensembl');
  Description: Creates a new BaseAlignFeature using either a cigar string or
               a list of ungapped features.  BaseAlignFeature is an abstract
               baseclass and should not actually be instantiated - rather its
               subclasses should be.
  Returntype : Bio::EnsEMBL::BaseAlignFeature
  Exceptions : thrown if both feature and cigar string args are provided
               thrown if neither feature nor cigar string args are provided
               warn if cigar string is provided without cigar type
  Caller     : general
  Status     : Stable

=cut

sub new {

  my $caller = shift;

  my $class = ref($caller) || $caller;

  my $self = $class->SUPER::new(@_);

  my ($cigar_string,$align_type,$features) = rearrange([qw(CIGAR_STRING ALIGN_TYPE FEATURES)], @_);

  if (defined($align_type)) {
    $self->{'align_type'} = $align_type;
  } else {
    warning("No align_type provided, using ensembl as default");
    $self->{'align_type'} = 'ensembl';
  }

  if (defined($cigar_string) && defined($features)) {
    throw("CIGAR_STRING or FEATURES argument is required - not both.");
  } elsif (defined($features)) {
    $self->_parse_features($features);

  } elsif (defined($cigar_string)) {
    $self->{'cigar_string'} = $cigar_string;
  } else {
    throw("CIGAR_STRING or FEATURES argument is required");
  }

  return $self;
}

=head2 cigar_string

  Arg [1]    : string $cigar_string
  Example    : $feature->cigar_string( "12MI3M" );
  Description: get/set for attribute cigar_string.
               cigar_string describes the alignment:
                 "xM" stands for x matches (or mismatches),
                 "xI" for x inserts into the query sequence,
                 "xD" for x deletions from the query sequence
                 where the query sequence is specified by (seqname, start, ...)
                 and the subject sequence by (hseqname, hstart, ...).
               An "x" that is 1 can be omitted.
               See the SYNOPSIS for an example.
  Returntype : string
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub cigar_string {
  my $self = shift;
  $self->{'cigar_string'} = shift if(@_);
  return $self->{'cigar_string'};
}

=head2 align_type

  Arg [1]    : type $align_type
  Example    : $feature->align_type( "ensembl" );
  Description: get/set for attribute align_type.
               align_type specifies which cigar string
               is used to describe the alignment:
               The default is 'ensembl'
  Returntype : string
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub align_type {
  my $self = shift;
  $self->{'align_type'} = shift if(@_);
  return $self->{'align_type'};
}

=head2 alignment_length

  Arg [1]    : None
  Description: return the alignment length (including indels) based on the alignment_type ('ensembl', 'mdtag')
  Returntype : int
  Exceptions :
  Caller     :
  Status     : Stable

=cut

sub alignment_length {
  my $self = shift;

  # ensembl: Internal CIGAR format
  if ($self->{'align_type'} eq 'ensembl') {
    return $self->_ensembl_cigar_alignment_length();
  # mdtag: MD Z String for mismatching positions. Regex : [0-9]+(([A-Z]|\^[A-Z]+)[0-9]+)* (Refer:  SAM/BAM specification)
  } elsif ($self->{'align_type'} eq 'mdtag') {
    return $self->_mdtag_alignment_length();
  } else {
    throw("No alignment_length method available for " . $self->{'align_type'});
  }

}

=head2 _ensembl_cigar_alignment_length

  Arg [1]    : None
  Description: return the alignment length (including indels) based on the cigar_string
  Returntype : int
  Exceptions :
  Caller     :
  Status     : Stable

=cut

sub _ensembl_cigar_alignment_length {
  my $self = shift;

  if (! defined $self->{'_alignment_length'} && defined $self->cigar_string) {

    my @pieces = ( $self->cigar_string =~ /(\d*[MDI])/g );
    unless (@pieces) {
      print STDERR "Error parsing cigar_string\n";
    }
    my $alignment_length = 0;
    foreach my $piece (@pieces) {
      my ($length) = ( $piece =~ /^(\d*)/ );
      if (! defined $length || $length eq "") {
        $length = 1;
      }
      $alignment_length += $length;
    }
    $self->{'_alignment_length'} = $alignment_length;
  }
  return $self->{'_alignment_length'};
}

=head2 ungapped_features

  Args       : none
  Example    : @ungapped_features = $align_feature->get_feature
  Description: converts the internal cigar_string into an array of
               ungapped feature pairs
  Returntype : list of Bio::EnsEMBL::FeaturePair
  Exceptions : cigar_string not set internally
  Caller     : general
  Status     : Stable

=cut

sub ungapped_features {
  my ($self) = @_;

  if (!defined($self->{'cigar_string'})) {
    throw("No cigar_string defined.  Can't return ungapped features");
  }

  return @{$self->_parse_cigar()};
}

=head2 strands_reversed

  Arg [1]    : int $strands_reversed
  Description: get/set for attribute strands_reversed
               0 means that strand and hstrand are the original strands obtained
                 from the alignment program used
               1 means that strand and hstrand have been flipped as compared to
                 the original result provided by the alignment program used.
                 You may want to use the reverse_complement method to restore the
                 original strandness.
  Returntype : int
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub strands_reversed {
   my ($self, $arg) = @_;

   if ( defined $arg ) {
      $self->{'strands_reversed'} = $arg ;
   }

   $self->{'strands_reversed'} = 0 unless (defined $self->{'strands_reversed'});

   return $self->{'strands_reversed'};
}

=head2 reverse_complement

  Args       : none
  Description: reverse complement the FeaturePair based on the cigar type
               modifing strand, hstrand and cigar_string in consequence
  Returntype : none
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub reverse_complement {
  my ($self) = @_;

  if ($self->{'align_type'} eq 'ensembl') {
    return $self->_ensembl_reverse_complement();
  } else {
    throw("no reverse_complement method implemented for " . $self->{'align_type'});
  }
}

=head2 _ensembl_reverse_complement

  Args       : none
  Description: reverse complement the FeaturePair for ensembl cigar string,
               modifing strand, hstrand and cigar_string in consequence
  Returntype : none
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub _ensembl_reverse_complement {
  my ($self) = @_;

  # reverse strand in both sequences
  $self->strand($self->strand * -1);
  $self->hstrand($self->hstrand * -1);

  # reverse cigar_string as consequence
  my $cigar_string = $self->cigar_string;
  $cigar_string =~ s/(D|I|M)/$1 /g;
  my @cigar_pieces = split / /,$cigar_string;
  $cigar_string = "";
  while (my $piece = pop @cigar_pieces) {
    $cigar_string .= $piece;
  }

  $self->{'strands_reversed'} = 0 unless (defined $self->{'strands_reversed'});

  if ($self->strands_reversed) {
    $self->strands_reversed(0)
  } else {
    $self->strands_reversed(1);
  }

  $self->cigar_string($cigar_string);
}

=head2 transform

  Arg  1     : String $coordinate_system_name
  Arg [2]    : String $coordinate_system_version
  Example    : $feature = $feature->transform('contig');
               $feature = $feature->transform('chromosome', 'NCBI33');
  Description: Moves this AlignFeature to the given coordinate system.
               If the feature cannot be transformed to the destination
               coordinate system undef is returned instead.
  Returntype : Bio::EnsEMBL::BaseAlignFeature;
  Exceptions : wrong parameters
  Caller     : general
  Status     : Medium Risk

=cut

sub transform {
  my $self = shift;

  my $new_feature = $self->SUPER::transform(@_);
  if ( !defined($new_feature)
    || $new_feature->length() != $self->length() )
  {
    my @segments = @{ $self->project(@_) };

    if ( !@segments ) {
      return undef;
    }

    my @ungapped;
    foreach my $f ( $self->ungapped_features() ) {
      $f = $f->transform(@_);
      if ( defined($f) ) {
        push( @ungapped, $f );
      } else {
        warning( "Failed to transform alignment feature; "
            . "ungapped component could not be transformed" );
        return undef;
      }
    }

    eval { $new_feature = $self->new( -features => \@ungapped ); };

    if ($@) {
      warning($@);
      return undef;
    }
  } ## end if ( !defined($new_feature...))

  return $new_feature;
}

=head2 _parse_ensembl_cigar

  Args       : none
  Description: PRIVATE (internal) method - creates ungapped features from
               internally stored cigar line in ensembl format
  Returntype : list of Bio::EnsEMBL::FeaturePair
  Exceptions : none
  Caller     : ungapped_features
  Status     : Stable

=cut

sub _parse_ensembl_cigar {
  my ( $self ) = @_;

  my $query_unit = $self->_query_unit();
  my $hit_unit = $self->_hit_unit();

  my $string = $self->{'cigar_string'};

  throw("No cigar string defined in object") if(!defined($string));

  my @pieces = ( $string =~ /(\d*[MDI])/g );

  my @features;
  my $strand1 = $self->{'strand'} || 1;
  my $strand2 = $self->{'hstrand'}|| 1;

  my ( $start1, $start2 );

  if( $strand1 == 1 ) {
    $start1 = $self->{'start'};
  } else {
    $start1 = $self->{'end'};
  }

  if( $strand2 == 1 ) {
    $start2 = $self->{'hstart'};
  } else {
    $start2 = $self->{'hend'};
  }

  #
  # Construct ungapped blocks as FeaturePairs objects for each MATCH
  #
  foreach my $piece (@pieces) {

    my ($length) = ( $piece =~ /^(\d*)/ );
    if( $length eq "" ) { $length = 1 }
    my $mapped_length;

    # explicit if statements to avoid rounding problems
    # and make sure we have sane coordinate systems
    if( $query_unit == 1 && $hit_unit == 3 ) {
      $mapped_length = $length*3;
    } elsif( $query_unit == 3 && $hit_unit == 1 ) {
      $mapped_length = $length / 3;
    } elsif ( $query_unit == 1 && $hit_unit == 1 ) {
      $mapped_length = $length;
    } else {
      throw("Internal error $query_unit $hit_unit, currently only " .
            "allowing 1 or 3 ");
    }

    if( int($mapped_length) != $mapped_length and
        ($piece =~ /M$/ or $piece =~ /D$/)) {
      throw("Internal error with mismapped length of hit, query " .
            "$query_unit, hit $hit_unit, length $length");
    }

    if( $piece =~ /M$/ ) {
      #
      # MATCH
      #
      my ( $qstart, $qend);
      if( $strand1 == 1 ) {
        $qstart = $start1;
        $qend = $start1 + $length - 1;
        $start1 = $qend + 1;
      } else {
        $qend = $start1;
        $qstart = $start1 - $length + 1;
        $start1 = $qstart - 1;
      }

      my ($hstart, $hend);
      if( $strand2 == 1 ) {
        $hstart = $start2;
        $hend = $start2 + $mapped_length - 1;
        $start2 = $hend + 1;
      } else {
        $hend = $start2;
        $hstart = $start2 - $mapped_length + 1;
        $start2 = $hstart - 1;
      }

      push @features, Bio::EnsEMBL::FeaturePair->new
        (-SLICE      => $self->{'slice'},
         -SEQNAME   => $self->{'seqname'},
         -START      => $qstart,
         -END        => $qend,
         -STRAND     => $strand1,
         -HSLICE      => $self->{'hslice'},
         -HSEQNAME   => $self->{'hseqname'},
         -HSTART     => $hstart,
         -HEND       => $hend,
         -HSTRAND    => $strand2,
         -SCORE      => $self->{'score'},
         -PERCENT_ID => $self->{'percent_id'},
         -ANALYSIS   => $self->{'analysis'},
         -P_VALUE    => $self->{'p_value'},
         -EXTERNAL_DB_ID => $self->{'external_db_id'},
         -HCOVERAGE   => $self->{'hcoverage'},
         -GROUP_ID    => $self->{'group_id'},
         -LEVEL_ID    => $self->{'level_id'});

      # end M cigar bits
    } elsif( $piece =~ /I$/ ) {
      #
      # INSERT
      #
      if( $strand1 == 1 ) {
        $start1 += $length;
      } else {
        $start1 -= $length;
      }
    } elsif( $piece =~ /D$/ ) {
      #
      # DELETION
      #
      if( $strand2 == 1 ) {
        $start2 += $mapped_length;
      } else {
        $start2 -= $mapped_length;
      }
    } else {
      throw( "Illegal cigar line $string!" );
    }
  }

  return \@features;
}

sub _parse_cigar {
  my $self = shift;

  if ($self->{'align_type'} eq 'ensembl') {
    return $self->_parse_ensembl_cigar();
  }
   else {
    throw("No parsing method implemented for " . $self->{'align_type'});
  }
}

=head2 _parse_features

  Arg  [1]   : listref Bio::EnsEMBL::FeaturePair $ungapped_features
  Description: creates internal cigar_string and start,end hstart,hend
               entries.
  Returntype : none, fills in values of self
  Exceptions : argument list undergoes many sanity checks - throws under many
               invalid conditions
  Caller     : new
  Status     : Stable

=cut

sub _parse_features {
  my ($self, $features) = @_;
  if ($self->{'align_type'} eq 'ensembl') {
    $self->_parse_ensembl_features($features);
  } else {
    throw("No _parse_features method implemented for " . $self->{'align_type'});
  }
}

my $message_only_once = 1;

sub _parse_ensembl_features {
  my ($self,$features ) = @_;

  if (ref($features) ne "ARRAY") {
    throw("features must be an array reference not a [".ref($features)."]");
  } elsif (scalar(@$features) == 0) {
    throw("features array must not be empty");
  }

  my $query_unit = $self->_query_unit();
  my $hit_unit = $self->_hit_unit();

  my $strand  = $features->[0]->strand;

  throw ('FeaturePair needs to have strand == 1 or strand == -1') if(!$strand);

  my @f;

  #
  # Sort the features on their start position
  # Ascending order on positive strand, descending on negative strand
  #
  if( $strand == 1 ) {
    @f = sort {$a->start <=> $b->start} @$features;
  } else {
    @f = sort { $b->start <=> $a->start} @$features;
  }

  my $hstrand     = $f[0]->hstrand;
  my $slice       = $f[0]->slice();
  my $hslice       = $f[0]->hslice();
  my $name        = $slice ? $slice->name() : undef;
  my $hname       = $f[0]->hseqname;
  my $score       = $f[0]->score;
  my $percent     = $f[0]->percent_id;
  my $analysis    = $f[0]->analysis;
  my $pvalue      = $f[0]->p_value();
  my $external_db_id = $f[0]->external_db_id;
  my $hcoverage   = $f[0]->hcoverage;
  my $group_id    = $f[0]->group_id;
  my $level_id    = $f[0]->level_id;

  my $seqname = $f[0]->seqname;
  # implicit strand 1 for peptide sequences
  $strand  ||= 1;
  $hstrand ||= 1;
  my $ori = $strand * $hstrand;

  throw("No features in the array to parse") if(scalar(@f) == 0);

  my $prev1; # where last feature q part ended
  my $prev2; # where last feature s part ended

  my $string;

  # Use strandedness info of query and hit to make sure both sets of
  # start and end  coordinates are oriented the right way around.
  my $f1start;
  my $f1end;
  my $f2end;
  my $f2start;

  if ($strand == 1) {
    $f1start = $f[0]->start;
    $f1end = $f[-1]->end;
  } else {
    $f1start = $f[-1]->start;
    $f1end = $f[0]->end;
  }

  if ($hstrand == 1) {
    $f2start = $f[0]->hstart;
    $f2end = $f[-1]->hend;
  } else {
    $f2start = $f[-1]->hstart;
    $f2end = $f[0]->hend;
  }

  #
  # Loop through each portion of alignment and construct cigar string
  #

  foreach my $f (@f) {
    #
    # Sanity checks
    #

    if (!$f->isa("Bio::EnsEMBL::FeaturePair")) {
      throw("Array element [$f] is not a Bio::EnsEMBL::FeaturePair");
    }
    if( defined($f->hstrand()) && $f->hstrand() != $hstrand ) {
      throw("Inconsistent hstrands in feature array");
    }
    if( defined($f->strand()) && ($f->strand != $strand)) {
      throw("Inconsistent strands in feature array");
    }
    if ( defined($name) && $name ne $f->slice->name()) {
      throw("Inconsistent names in feature array [$name - ".
            $f->slice->name()."]");
    }
    if ( defined($hname) && $hname ne $f->hseqname) {
      throw("Inconsistent hit names in feature array [$hname - ".
            $f->hseqname . "]");
    }
    if ( defined($score) && $score ne $f->score) {
      throw("Inconsisent scores in feature array [$score - " .
            $f->score . "]");
    }
    if (defined($f->percent_id) && $percent ne $f->percent_id) {
      throw("Inconsistent pids in feature array [$percent - " .
            $f->percent_id . "]");
    }
    if(defined($pvalue) && $pvalue != $f->p_value()) {
      throw("Inconsistant p_values in feature arraw [$pvalue " .
            $f->p_value() . "]");
    }
    if($seqname && $seqname ne $f->seqname){
      throw("Inconsistent seqname in feature array [$seqname - ".
            $f->seqname . "]");
    }
    my $start1 = $f->start;      #source sequence alignment start
    my $start2 = $f->hstart();   #hit sequence alignment start

    #
    # More sanity checking
    #
    if (defined($prev1)) {
      if ( $strand == 1 ) {
        if ($f->start < $prev1) {
          throw("Inconsistent coords in feature array (forward strand).\n" .
		       "Start [".$f->start()."] in current feature should be greater " .
           "than previous feature end [$prev1].");
        }
      } else {
        if ($f->end > $prev1) {
          throw("Inconsistent coords in feature array (reverse strand).\n" .
                "End [".$f->end() ."] should be less than previous feature " .
                "start [$prev1].");
        }
      }
    }

    my $length = ($f->end - $f->start + 1);    #length of source seq alignment
    my $hlength = ($f->hend - $f->hstart + 1); #length of hit seq alignment

    # using multiplication to avoid rounding errors, hence the
    # switch from query to hit for the ratios

    #
    # Yet more sanity checking
    #
    if($query_unit > $hit_unit){
      # I am going to make the assumption here that this situation will
      # only occur with DnaPepAlignFeatures, this may not be true
      my $query_p_length = sprintf "%.0f", ($length/$query_unit);
      my $hit_p_length = sprintf "%.0f", ($hlength * $hit_unit);
      if( $query_p_length != $hit_p_length) {
        throw( "Feature lengths not comparable Lengths:" .$length .
               " " . $hlength . " Ratios:" . $query_unit . " " .
               $hit_unit );
      }
    } else{
      my $query_d_length = sprintf "%.0f", ($length*$hit_unit);
      my $hit_d_length = sprintf "%.0f", ($hlength * $query_unit);
      if( $length * $hit_unit != $hlength * $query_unit ) {
        throw( "Feature lengths not comparable Lengths:" . $length .
               " " . $hlength . " Ratios:" . $query_unit . " " .
               $hit_unit );
      }
    }

    my $hlengthfactor = ($query_unit/$hit_unit);

    #
    # Check to see if there is an I type (insertion) gap:
    #   If there is a space between the end of the last source sequence
    #   alignment and the start of this one, then this is an insertion
    #

    my $insertion_flag = 0;
    if( $strand == 1 ) {
      if( ( defined $prev1 ) && ( $f->start > $prev1 + 1  )) {

        #there is an insertion
        $insertion_flag = 1;
        my $gap = $f->start - $prev1 - 1;
        if( $gap == 1 ) {
          $gap = ""; # no need for a number if gap length is 1
        }
        $string .= "$gap"."I";

      }

      #shift our position in the source seq alignment
      $prev1 = $f->end();
    } else {

      if(( defined $prev1 ) && ($f->end + 1 < $prev1 )) {

        #there is an insertion
        $insertion_flag = 1;
        my $gap = $prev1 - $f->end() - 1;
        if( $gap == 1 ) {
          $gap = ""; # no need for a number if gap length is 1
        }
        $string .= "$gap"."I";
      }

      #shift our position in the source seq alignment
      $prev1 = $f->start();
    }

    #
    # Check to see if there is a D type (deletion) gap
    #   There is a deletion gap if there is a space between the end of the
    #   last portion of the hit sequence alignment and this one
    #
    if( $hstrand == 1 ) {
      if((  defined $prev2 ) && ( $f->hstart() > $prev2 + 1 )) {

        #there is a deletion
        my $gap = $f->hstart - $prev2 - 1;
        my $gap2 = int( $gap * $hlengthfactor + 0.5 );

        if( $gap2 == 1 ) {
          $gap2 = "";  # no need for a number if gap length is 1
        }
        $string .= "$gap2"."D";

        #sanity check,  Should not be an insertion and deletion
        if($insertion_flag) {
          if ($message_only_once) {
            warning("Should not be an deletion and insertion on the " .
                    "same alignment region. cigar_line=$string\n");
            $message_only_once = 0;
          }
        }
      }
      #shift our position in the hit seq alignment
      $prev2 = $f->hend();

     } else {
      if( ( defined $prev2 ) && ( $f->hend() + 1 < $prev2 )) {

        #there is a deletion
        my $gap = $prev2 - $f->hend - 1;
        my $gap2 = int( $gap * $hlengthfactor + 0.5 );

        if( $gap2 == 1 ) {
          $gap2 = "";  # no need for a number if gap length is 1
        }
        $string .= "$gap2"."D";

        #sanity check,  Should not be an insertion and deletion
        if($insertion_flag) {
          if ($message_only_once) {
            warning("Should not be an deletion and insertion on the " .
                    "same alignment region. prev2 = $prev2; f->hend() = " .
                    $f->hend() . "; cigar_line = $string;\n");
            $message_only_once = 0;
          }
        }
      }
      #shift our position in the hit seq alignment
      $prev2 = $f->hstart();
    }

    my $matchlength = $f->end() - $f->start() + 1;
    if( $matchlength == 1 ) {
      $matchlength = "";
    }
    $string .= $matchlength."M";
  }

  $self->{'start'}      = $f1start;
  $self->{'end'}        = $f1end;
  $self->{'seqname'}    = $seqname;
  $self->{'strand'}     = $strand;
  $self->{'score'}      = $score;
  $self->{'percent_id'} = $percent;
  $self->{'analysis'}   = $analysis;
  $self->{'slice'}      = $slice;
  $self->{'hslice'}     = $hslice;
  $self->{'hstart'}     = $f2start;
  $self->{'hend'}       = $f2end;
  $self->{'hstrand'}    = $hstrand;
  $self->{'hseqname'}   = $hname;
  $self->{'cigar_string'} = $string;
  $self->{'p_value'}      = $pvalue;
  $self->{'external_db_id'} = $external_db_id;
  $self->{'hcoverage'}    = $hcoverage;
  $self->{'group_id'}     = $group_id;
  $self->{'level_id'}     = $level_id;
}

=head2 _hit_unit

  Args       : none
  Description: abstract method, overwrite with something that returns
               one or three
  Returntype : int 1,3
  Exceptions : none
  Caller     : internal
  Status     : Stable

=cut

sub _hit_unit {
  my $self = shift;
  throw( "Abstract method call!" );
}

=head2 _query_unit

  Args       : none
  Description: abstract method, overwrite with something that returns
               one or three
  Returntype : int 1,3
  Exceptions : none
  Caller     : internal
  Status     : Stable

=cut

sub _query_unit {
  my $self = shift;
  throw( "Abstract method call!" );
}

=head2 _mdtag_alignment_length

  Arg [1]    : None
  Description: return the alignment length (including indels) based on the mdtag (mdz) string
  Returntype : int
  Exceptions : none
  Caller     : internal
  Status     : Stable

=cut

sub _mdtag_alignment_length {
  my $self = shift;

  if (! defined $self->{'_alignment_length'} && defined $self->cigar_string) {
    my $mdz_string =  $self->cigar_string;
    my $chunks = $self->_get_mdz_chunks($mdz_string);
    my $alignment_length = 0;
    $alignment_length = $self->_get_mdz_alignment_length($chunks);
    $self->{'_alignment_length'} = $alignment_length;
  }
  return $self->{'_alignment_length'};
}

=head2 _get_mdz_chunks

  Arg [1]    : mdtag string - MD Z String for mismatching positions. Regex : [0-9]+(([A-Z]|\^[A-Z]+)[0-9]+)* (Refer:  SAM/BAM specification)
  Description: parses the mdtag string and group it according the type
               eg: MD:Z:35^VIVALE31^GRPLIQPRRKKAYQLEHTFQGLLGKRSLFTE10 returns ['35', '^', 'VIVALE', '31', '^', 'GRPLIQPRRKKAYQLEHTFQGLLGKRSLFTE', '10']
  Returntype : array of strings
  Exceptions : none
  Caller     : internal
  Status     : Stable

=cut
sub _get_mdz_chunks {
  my $self = shift;

  my $mdz_string = shift;
  my $alignment_length = 0;
  my @chunks;
    if ( $mdz_string =~ /^MD:Z:(.+)/ ){
      my $mdtag = $1;

      #if start to end is a number then all match return as it is
      if($mdtag =~/^\d+$/){
        return [$mdtag];
      } else{
        my @char_arr = split('',$mdtag);
        # Set up for the first loop, this also will handle
        # if the array is size one, as we'll have a character
        # in the current_chunk to push on the pile at the end.
        my $prev_type = $self->_get_mdz_chunk_type( $char_arr[0]);
        my $current_chunk = $char_arr[0];
        for(my $i = 1; $i <= $#char_arr; $i++) {
          my $cur_type = $self->_get_mdz_chunk_type( $char_arr[$i] );
          if($cur_type ne $prev_type) {
            # We've found a new character class, push the
            # current chunk on to the list
            push @chunks, $current_chunk;
            # Restart the current pile
            $current_chunk = $char_arr[$i];
           } else {
             # Same character class, put it on the current pile
             $current_chunk .= $char_arr[$i];
           }
           # Shift current type in to the prior slot
           $prev_type = $cur_type;
          }

        # Post loop cleanup of the last piece
        # This also handles an array of size one where
        # we never entered the loop, that one element
        # now gets pushed on the pile.
        push @chunks, $current_chunk;
      }
    }
  return \@chunks;
}

=head2 _get_mdz_alignment_length

  Arg [1]    : array of strings
  Description: calculate the alignment length from the given chunks
  Returntype : array of strings
  Exceptions : none
  Caller     : internal
  Status     : Stable

=cut

sub _get_mdz_alignment_length{
  my $self = shift;

  my $chunks = shift;
  my $length = 0;
   for(my $i=0; $i< scalar(@$chunks); $i++){
     my $chunk = $chunks->[$i];
     my $type = $self->_get_mdz_chunk_type($chunk);

    if($type eq 'num'){
      $length = $length + $chunk;
    }elsif($type eq 'alpha'){
      $length = $length + length($chunk);
    }elsif($type eq 'del'){
      #skip next chunk
      $i++;
    }

  }
  return $length;
}

=head2 _get_mdz_chunk_type

  Arg [1]    : char
  Description: get the chunk type
  Returntype : string
  Exceptions : none
  Caller     : internal
  Status     : Stable

=cut

sub _get_mdz_chunk_type{
  my $self = shift;
  my $char = shift;

  my $type;
  if($char eq '^'){
    $type = "del";
  } elsif($char =~ /\d+/){
    $type = 'num';
  } elsif($char =~ /\w+/){
    $type = 'alpha';
  }
  return $type;
}

=head2 _mdz_alignment_string

  Arg [1]    : input sequence
  Arg [2]    : MD Z String for mismatching positions. Regex : [0-9]+(([A-Z]|\^[A-Z]+)[0-9]+)* (Refer:  SAM/BAM specification)
               eg: MD:Z:96^RHKTDSFVGLMGKRALNS0V14
  Example    : $pf->alignment_strings
  Description: Allows to rebuild the alignment string of both the seq and hseq sequence
  Returntype : array reference containing 2 strings
               the first corresponds to seq
               the second corresponds to hseq
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

# Try to get the sequence from translation object
# mdz_string from current object
sub _mdz_alignment_string {
  my ($self, $input_seq, $mdz_string) = @_;

  my $chunks = $self->_get_mdz_chunks($mdz_string);

  my $target_seq = "";
  my $query_seq = "";

   #Handle first chunk, which is always a num
   my $first_chunk = $chunks->[0];
   my $first_chunk_type = $self->_get_mdz_chunk_type($first_chunk);

   my $offset = 0;
   if($first_chunk_type eq 'num'){
     if($first_chunk > 0){
       $target_seq = substr($input_seq, $offset, $first_chunk);

       #query and target are same at this point
       $query_seq = $target_seq;
       $offset = length($target_seq);
     }
   }else{
     die "First chunk should always be a num...something wrong\n";
   }

  for(my $i=1; $i < scalar(@$chunks); $i++){

    my $chunk = $chunks->[$i];
    my $chunk_type = $self->_get_mdz_chunk_type($chunk);

    if($chunk_type eq 'num'){
      #if 0, what follows next is a INSERT
      if($chunk == 0){
        my $insert_chunk = $chunks->[++$i];
        my $insert_chunk_type = $self->_get_mdz_chunk_type($insert_chunk);

        #insert_chunk_type is always alpha
        die if $insert_chunk_type eq "num";
        if($insert_chunk_type eq 'del'){
          $i--;
          next;
        }
        $target_seq = $target_seq . substr($input_seq, $offset, length($insert_chunk));
        $query_seq = $query_seq . $insert_chunk;

        $offset = $offset + length($insert_chunk);

      }else{
       #if non-0, then it is a match
        my $match_chunk = $chunks->[$i];
        my $match_chunk_type = $self->_get_mdz_chunk_type($match_chunk);

         #$match_chunk_type is always num
        die if $match_chunk_type ne "num";

        my $match_target_string = substr($input_seq, $offset, $match_chunk);

        $target_seq = $target_seq . $match_target_string;
        $query_seq = $query_seq . $match_target_string;

        $offset = $offset + $match_chunk;
      }

    }elsif($chunk_type eq 'alpha'){
        my $insert_chunk = $chunk;
        my $insert_chunk_type = $self->_get_mdz_chunk_type($insert_chunk);
        die if $insert_chunk_type ne "alpha";

        $target_seq = $target_seq . substr($input_seq, $offset, length($insert_chunk));
        $query_seq = $query_seq . $insert_chunk;

        $offset = $offset + length($insert_chunk);

    }elsif($chunk_type eq 'del'){
      #get next chunk which contains the deleted sequence
      my $del_chunk = $chunks->[++$i];
      my $del_chunk_type = $self->_get_mdz_chunk_type($del_chunk);

      #del_chunk_type is always alpha
      die if $del_chunk_type ne 'alpha';

      $target_seq = $target_seq . "-" x length($del_chunk);
      $query_seq = $query_seq . $del_chunk;

      #no change in offset
      $offset = $offset;

    }

  }

  return [$target_seq, $query_seq];

}

1;


text:
    <select
            ng-change="select(selected)"
            ng-model="selected"
            ng-disabled="!querySuccessful"
            ng-options="item as item.name for item in domainItems">
            <option value='' disabled selected>{{placeholder}}</option>
    </select>


text:
/*
Package slapd provides clean slapd instances for testing purposes.

You can use it on two ways:

Create a Config, and let the Configure() method create a exec.Command for you to run.
This can at times be tricky, because there is no clean way to test if the slapd is already
accepting connections.

Manually configure and run slapd and create a Config matching the values where appropriate.
You can then use the Clean() and Initialize() methods to reset the contents in the ldap.
This is much more reliable.
*/
package slapd


text:
using LiteNetLib.Utils;

namespace LiteNetLibManager
{
    public class EnterGameResponseMessage : INetSerializable
    {
        public long connectionId;
        public string serverSceneName;

        public void Deserialize(NetDataReader reader)
        {
            connectionId = reader.GetPackedLong();
            serverSceneName = reader.GetString();
        }

        public void Serialize(NetDataWriter writer)
        {
            writer.PutPackedLong(connectionId);
            writer.Put(serverSceneName);
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Phoma poolensis var. poolensis

### Remarks
null


text:
var crypto = require('crypto');
var _ = require('lodash');
var request = require('request');
var sortObject = require('deep-sort-object');
var apiRoot = 'https://platform.api.onesky.io/1/';

module.exports = function (grunt) {
    grunt.registerMultiTask('oneskyExport', 'Export translations from OneSky', function () {

        var done = this.async();

        // eslint-disable-next-line
        // TODO: Add isReady options (only download if translation is ready to be published)
        var options = this.options({
            authFile: 'onesky.json',
            dest: '/',
            projectId: '',
            sourceFile: '',
            output: '',
            sortKeys: false,
            indent: 4,
            exportType: 'multilingual',

            // Required only for exporting translations in separate language files
            locale: ''
        });

        return fetchTranslations();

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

        function fetchTranslations() {
            var api = getApi();
            var url = api.baseUrl + api.path;
            var requestOptions;
            var queryParams = { 'source_file_name': options.sourceFile };

            if (options.exportType === 'multilingual') {
                url = url + 'translations/multilingual';
                queryParams = _.extend(queryParams, { 'file_format': 'I18NEXT_MULTILINGUAL_JSON' });
            }

            if (options.exportType === 'locale') {
                url = url + 'translations';
                queryParams = _.extend(queryParams, { 'locale': options.locale });
            }

            requestOptions = {
                method: 'GET',
                url: url,
                headers: {
                    'Content-Type': 'application/json'
                },
                qs: {
                    'api_key': api.publicKey,
                    'timestamp': api.timestamp,
                    'dev_hash': api.devHash
                }
            };

            requestOptions.qs = _.extend(requestOptions.qs, queryParams);

            return request(requestOptions, onFetchTranslations);
        }

        function onFetchTranslations(error, response, body) {
            var contentType = 'application/json';

            if (!error) {
                if (response.statusCode === 200) {

                    if (_.has(response, 'headers.content-type')) {
                        contentType = response.headers['content-type'];
                    }
                    onFetchTranslationSuccess(body, contentType);
                } else {
                    onFetchTranslationError(response);
                }
            } else {
                grunt.fail.warn('Request error');
            }

            done();
        }

        function onFetchTranslationSuccess(data, contentType) {
            var fileName;
            var fileData = data;

            if (contentType === 'application/json') {
                data = JSON.parse(data);

                if (options.sortKeys) { data = sortObject(data); }
                fileData = JSON.stringify(data, null, options.indent) + '\n';
            }

            if (options.exportType === 'multilingual') {
                fileName = options.output || options.sourceFile;
                grunt.file.write(options.dest + fileName, fileData);
            }

            if (options.exportType === 'locale') {
                fileName = options.output || options.locale + '_' + options.sourceFile;
                grunt.file.write(options.dest + fileName, fileData);
            }

            grunt.log.ok('Translation Downloaded: ' + options.dest + fileName);
        }

        function onFetchTranslationError(error) {
            switch (error.statusCode) {
                case 400:
                    grunt.fail.warn('Invalid source file: ' + options.sourceFile);
                    break;
                case 401:
                    grunt.fail.warn('Unauthorized - Invalid OneSky API keys / project ID');
                    break;
                default:
                    break;
            }
        }

        function getApi() {
            var oneSkyKeys = grunt.file.readJSON(options.authFile);

            var timestamp = Math.floor(Date.now() / 1000);
            var devHash = crypto.createHash('md5').update(timestamp + oneSkyKeys.secretKey).digest('hex');

            return {
                baseUrl: apiRoot,
                path: 'projects/' + options.projectId + '/',
                publicKey: oneSkyKeys.publicKey,
                timestamp: timestamp,
                devHash: devHash
            };
        }
    });
};


text:
<?php

class AdmAccount extends BaseController
{
    public function getIndex()
    {
	if(Auth::check() && Auth::user()->userID == 1) : return Redirect::to("/adm/dashboard") ;
	else : return Redirect::to('/adm/login') ;
	endif;
    }

    public function getAccount()
    {
	$accounts = DB::table('tblAccount')->get();
	return View::make('adm.account.account')
		->with('accounts',$accounts);

    }

    public function getAccountAdd()
    {
	if(Auth::user()->userID != 1) : return Redirect::to("/") ; endif;

	$acc = DB::table('tblAccount')->where('ID','=',Input::get('ID'))->first();

	return View::make('adm.account.addaccount')
		->with('acc',$acc);

    }

    public function postAccountAdd()
    {
	$data = array(
	    'ID' => Input::get('ID'),
	    'AccID' => Input::get('AccID'),
	    'AccName' => Input::get('AccName'),
	    'AdminTel' => Input::get('AdminTel'),
	    'AdminEmail' => Input::get('AdminEmail')
	);

	$rules = array(
	    'ID' => 'required',
	    'AccID' => 'required',
	    'AccName' => 'required',
	    'AdminTel' => 'required',
	    'AdminEmail' => 'required|email'
	);

	$validator = Validator::make($data,$rules);

	if($validator->passes())
	{
	    //INSERTING TBLACCOUNT
	    DB::table('tblAccount')->insert($data);

	}
	else
	{
	    return Redirect::to('/adm/account/add')
		    ->withErrors($validator)
		    ->withInput();

	}
    }

    public function getAccountEdit()
    {
	if(Auth::user()->userID != 1) : return Redirect::to("/") ; endif;

	$acc = DB::table('tblAccount')->where('ID','=',Input::get('ID'))->first();

	return View::make('adm.account.editaccount')
		->with('acc',$acc);

    }

    public function postAccountEdit()
    {
	$data = array(
	    'ID' => Input::get('ID'),
	    'AccID' => Input::get('AccID'),
	    'AccName' => Input::get('AccName'),
	    'AdminTel' => Input::get('AdminTel'),
	    'AdminEmail' => Input::get('AdminEmail')
	);

	$rules = array(
	    'ID' => 'required',
	    'AccID' => 'required',
	    'AccName' => 'required',
	    'AdminTel' => 'required',
	    'AdminEmail' => 'required'
	);

	$validator = Validator::make($data,$rules);

	if($validator->passes())
	{
	    //SEE RELATIONAL TABLE, FIND ID RELATED
	    //updating tblAccount
	    DB::table('tblAccount')->where('ID','=',Input::get('ID'))->update($data);

	    //updating tblAdmin
	    DB::table('tblAdmin')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //updating tblGroup
	    DB::table('tblGroup')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //updating tblMessages
	    DB::table('tblMessages')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //updating tblMsgGroups
	    DB::table('tblMsgGroups')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //updating tblStop
	    DB::table('tblStop')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //updating tblStop
	    DB::table('tblStop')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //updating tblGrpMembrs
	    DB::table('tblGrpMembrs')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //updating tblRemove
	    DB::table('tblRemove')->where('ID','=',Input::get('ID'))->update(array('ID'=>Input::get('ID')));

	    //echo '{ "success": true }';

	}
	else
	{
	    return Redirect::to('/adm/account/add')
		    ->withErrors($validator)
		    ->withInput();

	}
    }

    public function getAccountDelete()
    {
	return "This can't perform now...";
    }

}


text:
{% for message in messages %}

        {# close-href is used because href is used by bootstrap to closing other divs #}
        ×
        {{ message|safe }}

{% endfor %}


text:
    #define _CSURFACE_H_

#include <%SDL_USER%/sdl/include/SDL.h>

//==============================================================================
class CSurface {
	public:
		CSurface();

	public:
		static SDL_Surface* OnLoad(char* File);

		static bool OnDraw(SDL_Surface* Surf_Dest, SDL_Surface* Surf_Src, int X, int Y);

		static bool OnDraw(SDL_Surface* Surf_Dest, SDL_Surface* Surf_Src, int X, int Y, int X2, int Y2, int W, int H);
};

//==============================================================================

#endif


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rubygems'
require 'benchmark'
require 'virtus'
require 'polecat'
require 'polecat/storage/binary_storage'
require 'polecat/storage/hash_storage'

n = 1500
docs = 50000
find = 25000

def run_threads1 threadcount, count, searcher, query
  threads = []
  count = count / threadcount
  threadcount.times do
    threads << Thread.new do
      for i in 1..count do
        searcher.search query
      end
    end
  end
  threads.each {|t| t.join }
end

def run_threads2 threadcount, count, searcher, query
  threads = []
  count = count / threadcount
  threadcount.times do
    threads << Thread.new do
      for i in 1..count do
        searcher.search_with_index query
      end
    end
  end
  threads.each {|t| t.join }
end

class Document
  include Virtus

  attribute :name1, Integer, :storage => Polecat::Storage::BinaryStorage
  attribute :name2, Integer, :storage => Polecat::Storage::HashStorage
  attribute :text, String
end

begin
  FileUtils.rm_r 'benchmark/index_dir'
rescue
end
Dir.mkdir 'benchmark/index_dir'
writer = Polecat::IndexWriter.new 'benchmark/index_dir'

(1..docs).each do |i|
  writer.add(Document.new(:name1 => i, :name2 => i, :text => "Lorem #{i} Ipsum"))
end

writer.write
searcher = Polecat::IndexSearcher.new :reader => writer.create_reader
searcher.load

Benchmark.bm do |x|
  query = Polecat::Query.new.add(Polecat::Term.new(:name1, :eq, find))
  x.report('1') { run_threads1 1, n, searcher, query.dup }
  x.report('2') { run_threads1 2, n, searcher, query.dup }
  x.report('4') { run_threads1 4, n, searcher, query.dup }
  x.report('8') { run_threads1 8, n, searcher, query.dup }
  query = Polecat::Query.new.add(Polecat::Term.new(:name1, :eq, find))
  x.report('1') { run_threads2 1, n, searcher, query.dup }
  x.report('2') { run_threads2 2, n, searcher, query.dup }
  x.report('4') { run_threads2 4, n, searcher, query.dup }
  x.report('8') { run_threads2 8, n, searcher, query.dup }
  query = Polecat::Query.new.add(Polecat::Term.new(:name2, :eq, find))
  x.report('1') { run_threads2 1, n, searcher, query.dup }
  x.report('2') { run_threads2 2, n, searcher, query.dup }
  x.report('4') { run_threads2 4, n, searcher, query.dup }
  x.report('8') { run_threads2 8, n, searcher, query.dup }
end


text:
Lists the git repository status'
## OPTIONS
## EXAMPLES
```bash
rafter status
```


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea subvulpina Nyl.

### Remarks
null


text:
/**
 * Basic setup
 * ================================
 *
 * Disable the auto mock for the class that's about to be tested and the utility class (the
 * utility class because otherwise I would have to mock some crazy Promises :P).
 */
jest.dontMock('../src/egojs.js');
jest.dontMock('../src/utils.js');
/**
 * Require the custom mock of LocallyDB, which also contains a mock class for LocallyDB tables.
 */
const mockDB = require('locallydb');
jest.setMock('locallydb', mockDB.module);
/**
 * Small hack to avoid creating a new mock for the utility class: I save the original request
 * method in a variable, generate a mock function, swap them in the test and restore them after.
 * So not proud.
 */
const EgoJSUtils = require('../src/utils.js');
const originalRequest = EgoJSUtils.default.request;
const mockRequest = jest.genMockFunction();
/**
 * Require the module to test.
 */
const EgoJS = require('../src/egojs.js').default;
/**
 * Dummy data
 * ================================
 *
 * The default settings "saved in the module".
 */
const dummySettings = {
    ghToken: 'Ros/ario',
};
/**
 * A random ID to use on DB record.
 */
const dummyId = 12;
/**
 * A package as the database saves it.
 */
const dummyPackage = {
    cid: dummyId,
    name: 'gulp-bundlerify',
    repository: 'homer0/gulp-bundlerify',
    npmPackage: 'gulp-bundlerify',
};
/**
 * A package without any NPM data.
 */
const dummyPackageWithoutNPM = {
    cid: dummyId,
    name: 'gulp-bundlerify',
    repository: 'homer0/gulp-bundlerify',
};
/**
 * A cache record for a GitHub repository.
 */
const dummyRepositoryStats = {
    cid: 1,
    infoKey: 'github',
    packageId: dummyId,
    time: 'to be set on the beforeEach',
    value: '{"forks":0,"stars":26,"watchers":26,"url":"homer0/gulp-bundlerify"}',
};
/**
 * A cache record for an NPM package.
 */
const dummyNPMStats = {
    cid: 2,
    infoKey: 'npm',
    packageId: dummyId,
    time: 'to be set on the beforeEach',
    value: '{"downloads":73,"url":"package/gulp-bundlerify"}',
};
/**
 * A reponse from the GitHub API.
 */
// jscs:disable
const dummyGitHubReponse = {
    forks_count: 1,
    stargazers_count: 2,
    watchers_count: 3,
    html_url: 'homer0.com',
};
// jscs:enable
/**
 * An error response from the GitHub API.
 */
const dummyGitHubErrorReponse = {
    message: 'Unknown error',
};
/**
 * A response from the NPM API.
 */
const dummyNPMReponse = {
    downloads: 12,
    package: 'charito',
};
/**
 * An error response from the NPM API.
 */
const dummyNPMErrorReponse = {
    error: 'Unknown error',
};
/**
 * A dummy error to use in the tests.
 */
const dummyError = new Error('Random Error');
/**
 * The suite.
 */
describe('EgoJS: Class', () => {

    beforeEach(() => {

        mockDB.mock.resetMocks();
        mockRequest.mockClear();
        dummyRepositoryStats.time = Date.now();
        dummyNPMStats.time = Date.now();

    });

    afterEach(() => {
        EgoJSUtils.default.request = originalRequest;
    });
    /**
     * @test {EgoJS#constructor}
     */
    it('should be a class with instance methods', () => {
        expect(() => EgoJS()).toThrow('Cannot call a class as a function');
        const instance = new EgoJS();
        expect(instance).toEqual(jasmine.any(EgoJS));
        expect(instance.addPackage).toEqual(jasmine.any(Function));
        expect(instance.editPackage).toEqual(jasmine.any(Function));
        expect(instance.getPackage).toEqual(jasmine.any(Function));
        expect(instance.removePackage).toEqual(jasmine.any(Function));
        expect(instance.getStats).toEqual(jasmine.any(Function));
        expect(instance.deleteCache).toEqual(jasmine.any(Function));
        expect(instance.setGitHubToken).toEqual(jasmine.any(Function));

        expect(mockDB.mock.mocks.collection.mock.calls.length).toEqual(3);

    });
    /**
     * @test {EgoJS#addPackage}
     */
    pit('should successfully add a package', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.item = dummyPackage;
        return instance.addPackage(
            dummyPackage.name,
            dummyPackage.repository,
            dummyPackage.npmPackage
        ).then((response) => {
            expect(response).toEqual(dummyPackage);
            expect(mockDB.mock.tables.packages.mocks.insert.mock.calls.length).toEqual(1);
        });
    });
    /**
     * @test {EgoJS#addPackage}
     */
    pit('should try to add a package and fail because the properties are invalid', () => {
        const instance = new EgoJS();
        return instance.addPackage(dummyPackage.name)
        .then(() => expect(true).toBeFalsy())
        .catch(() => expect(true).toBeTruthy());
    });
    /**
     * @test {EgoJS#addPackage}
     */
    pit('should try to add a package and fail because there\'s one with the same name', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.whereResults = [[dummyPackage]];
        return instance.addPackage(
            dummyPackage.name,
            dummyPackage.repository,
            dummyPackage.npmPackage
        ).then(() => expect(true).toBeFalsy())
        .catch(() => {
            expect(true).toBeTruthy();
            expect(mockDB.mock.tables.packages.mocks.where.mock.calls.length).toEqual(1);
        });
    });
    /**
     * @test {EgoJS#addPackage}
     */
    pit('should try to add a package and fail because the repo format is invalid', () => {
        const instance = new EgoJS();
        return instance.addPackage(
            dummyPackage.name,
            'some/invalid/format',
            dummyPackage.npmPackage
        ).then(() => expect(true).toBeFalsy())
        .catch(() => {
            expect(true).toBeTruthy();
            expect(mockDB.mock.tables.packages.mocks.where.mock.calls.length).toEqual(1);
        });
    });
    /**
     * @test {EgoJS#addPackage}
     */
    pit('should try to add a package and fail because there\'s one with the same repo', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.whereResults = [[], [dummyPackage]];
        return instance.addPackage(
            dummyPackage.name,
            dummyPackage.repository,
            dummyPackage.npmPackage
        ).then(() => expect(true).toBeFalsy())
        .catch(() => {
            expect(true).toBeTruthy();
            expect(mockDB.mock.tables.packages.mocks.where.mock.calls.length).toEqual(2);
        });
    });
    /**
     * @test {EgoJS#addPackage}
     */
    pit('should try to add a package and fail because there\'s one with the same npm URL', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.whereResults = [[], [], [dummyPackage]];
        return instance.addPackage(
            dummyPackage.name,
            dummyPackage.repository,
            dummyPackage.npmPackage
        ).then(() => expect(true).toBeFalsy())
        .catch(() => {
            expect(true).toBeTruthy();
            expect(mockDB.mock.tables.packages.mocks.where.mock.calls.length).toEqual(3);
        });
    });
    /**
     * @test {EgoJS#editPackage}
     */
    pit('should successfully edit a package', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.item = dummyPackage;

        return instance.editPackage(
            dummyId,
            dummyPackage.name,
            dummyPackage.repository,
            dummyPackage.npmPackage
        ).then((response) => {
            expect(response).toEqual(dummyPackage);
            const updateMock = mockDB.mock.tables.packages.mocks.update.mock;
            expect(updateMock.calls.length).toEqual(1);
            expect(updateMock.calls[0][0]).toEqual(dummyId);
            expect(updateMock.calls[0][1]).toEqual({
                name: dummyPackage.name,
                repository: dummyPackage.repository,
                npmPackage: dummyPackage.npmPackage,
            });
        });
    });
    /**
     * @test {EgoJS#getPackage}
     */
    pit('should successfully get a package by its ID', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.whereResults = [[dummyPackage]];

        return instance.getPackage(dummyId).then((response) => {
            const whereMock = mockDB.mock.tables.packages.mocks.where.mock;
            expect(whereMock.calls[0][0].cid).toEqual(dummyId);
            expect(response).toEqual(dummyPackage);
        });
    });
    /**
     * @test {EgoJS#getPackage}
     */
    pit('should successfully get a package by its name', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.whereResults = [[dummyPackage]];

        return instance.getPackage(dummyPackage.name, 'name').then((response) => {
            const whereMock = mockDB.mock.tables.packages.mocks.where.mock;
            expect(whereMock.calls[0][0].name).toEqual(dummyPackage.name);
            expect(response).toEqual(dummyPackage);
        });
    });
    /**
     * @test {EgoJS#getPackage}
     */
    pit('should try to get a package and fail because it doesn\'t exist', () => {
        const instance = new EgoJS();
        return instance.getPackage(dummyId)
        .then(() => expect(true).toBeFalsy())
        .catch(() => expect(true).toBeTruthy());
    });
    /**
     * @test {EgoJS#removePackage}
     */
    pit('should successfully remove a package by its ID', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.packages.whereResults = [[dummyPackage], [dummyPackage]];
        mockDB.mock.tables.cache.whereResults = [[dummyRepositoryStats, dummyNPMStats]];

        return instance.removePackage(dummyId).then((response) => {
            const whereMock = mockDB.mock.tables.packages.mocks.where.mock;
            expect(whereMock.calls[0][0].cid).toEqual(dummyId);
            const remMock = mockDB.mock.tables.packages.mocks.remove.mock;
            expect(remMock.calls[0][0]).toEqual(dummyId);
            expect(response).toEqual(dummyPackage);
        });
    });
    /**
     * @test {EgoJS#deleteCache}
     */
    it('should delete a package cache by its package ID', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.cache.items = [dummyRepositoryStats, dummyNPMStats];
        instance.deleteCache();
        const remMock = mockDB.mock.tables.cache.mocks.remove.mock;
        expect(remMock.calls.length).toEqual(2);
    });
    /**
     * @test {EgoJS#settings}
     */
    it('should be able to save settings for the first time', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.settings.whereResults = [[], [], [dummySettings]];
        expect(mockDB.mock.tables.settings.mocks.where.mock.calls.length).toEqual(1);
        instance.settings = dummySettings;
        expect(instance.settings).toEqual(dummySettings);
        expect(mockDB.mock.tables.settings.mocks.where.mock.calls.length).toEqual(3);
    });
    /**
     * @test {EgoJS#settings}
     */
    it('should be able to merge settings', () => {
        const savedSettings = {
            cid: dummyId,
            name: 'Rosario',
            settingId: 1,
        };
        const finalSettings = {
            ghToken: 'Ros/ario',
            name: 'Rosario',
        };
        const updateSettings = {
            cid: dummyId,
            ghToken: 'Ros/ario',
            name: 'Rosario',
            settingId: 1,
        };

        mockDB.mock.addTable('settings');
        mockDB.mock.tables.settings.whereResults = [
            [savedSettings],
            [savedSettings],
            [finalSettings],
        ];

        const instance = new EgoJS();
        expect(mockDB.mock.tables.settings.mocks.where.mock.calls.length).toEqual(1);
        instance.settings = dummySettings;
        expect(instance.settings).toEqual(finalSettings);
        const updateMock = mockDB.mock.tables.settings.mocks.update.mock;
        expect(updateMock.calls[0][1]).toEqual(updateSettings);
        expect(mockDB.mock.tables.settings.mocks.where.mock.calls.length).toEqual(2);
    });
    /**
     * @test {EgoJS#setGitHubToken}
     */
    it('should set the GitHub token setting using the setGitHubToken method', () => {
        const instance = new EgoJS();
        mockDB.mock.tables.settings.whereResults = [[], [], [dummySettings]];
        instance.setGitHubToken(dummySettings.ghToken);
        expect(instance.settings).toEqual(dummySettings);
    });
    /**
     * @test {EgoJS#getStats}
     */
    pit('should get the stats for the packages currently saved', () => {
        let requestsCounter = 0;
        const requestsResponses = [dummyGitHubReponse, dummyNPMReponse];
        mockRequest.mockImplementation((request) => {
            return new Promise((resolve) => {
                resolve(JSON.stringify(requestsResponses[requestsCounter]));
                requestsCounter++;
            });
        });

        EgoJSUtils.default.request = mockRequest;

        const instance = new EgoJS();
        mockDB.mock.tables.settings.whereResults = [[], [], [dummySettings]];
        mockDB.mock.tables.cache.whereResults = [
            [],
            [dummyRepositoryStats],
            [],
            [dummyNPMStats],
        ];
        instance.settings = dummySettings;
        mockDB.mock.tables.packages.items = [dummyPackage];
        const result = instance.getStats().then((response) => {
            expect(mockRequest.mock.calls.length).toEqual(2);
            expect(mockRequest.mock.calls[0][0].uri).toMatch(/api\.github\.com/ig);
            expect(mockRequest.mock.calls[1][0].uri).toMatch(/api\.npmjs\.org/ig);
        });

        return result;
    });
    /**
     * @test {EgoJS#getStats}
     */
    pit('should get the stats for the packages currently saved, using the cache', () => {
        let requestsCounter = 0;
        const requestsResponses = [dummyGitHubReponse, dummyNPMReponse];
        mockRequest.mockImplementation((request) => {
            return new Promise((resolve) => {
                resolve(JSON.stringify(requestsResponses[requestsCounter]));
                requestsCounter++;
            });
        });

        EgoJSUtils.default.request = mockRequest;

        const instance = new EgoJS();
        mockDB.mock.tables.settings.whereResults = [[], [], [dummySettings]];
        mockDB.mock.tables.cache.whereResults = [
            [dummyRepositoryStats],
            [dummyNPMStats],
        ];
        instance.settings = dummySettings;
        mockDB.mock.tables.packages.items = [dummyPackage];
        const result = instance.getStats().then((response) => {
            expect(mockRequest.mock.calls.length).toEqual(0);
        });

        return result;
    });
    /**
     * @test {EgoJS#getStats}
     */
    pit('should try to use an invalid cache to get stats', () => {
        const invalidTime = Date.now() - 3600000;
        dummyRepositoryStats.time = invalidTime;
        dummyNPMStats.time = invalidTime;
        let requestsCounter = 0;
        const requestsResponses = [dummyGitHubReponse, dummyNPMReponse];
        mockRequest.mockImplementation((request) => {
            return new Promise((resolve) => {
                resolve(JSON.stringify(requestsResponses[requestsCounter]));
                requestsCounter++;
            });
        });

        EgoJSUtils.default.request = mockRequest;

        const instance = new EgoJS();
        mockDB.mock.tables.settings.whereResults = [[], [], [dummySettings]];
        mockDB.mock.tables.cache.whereResults = [
            [dummyRepositoryStats],
            [dummyNPMStats],
        ];
        instance.settings = dummySettings;
        mockDB.mock.tables.packages.items = [dummyPackage];
        const result = instance.getStats().then((response) => {
            expect(mockRequest.mock.calls.length).toEqual(2);
        });

        return result;
    });
    /**
     * @test {EgoJS#getStats}
     */
    pit('should handle errors from GitHub and NPM', () => {
        let requestsCounter = 0;
        const requestsResponses = [dummyGitHubErrorReponse, dummyNPMErrorReponse];
        mockRequest.mockImplementation((request) => {
            return new Promise((resolve) => {
                resolve(JSON.stringify(requestsResponses[requestsCounter]));
                requestsCounter++;
            });
        });

        EgoJSUtils.default.request = mockRequest;

        const instance = new EgoJS();
        mockDB.mock.tables.settings.whereResults = [[], [], [dummySettings]];
        instance.settings = dummySettings;
        mockDB.mock.tables.packages.items = [dummyPackage];
        const result = instance.getStats()
        .then(() => expect(true).toBeFalsy())
        .catch(() => expect(true).toBeTruthy());

        return result;
    });
    /**
     * @test {EgoJS#getStats}
     */
    pit('should return empty stats if the package doesn\'t have a repo or an npm package', () => {
        let requestsCounter = 0;
        const requestsResponses = [dummyGitHubReponse];
        mockRequest.mockImplementation((request) => {
            return new Promise((resolve) => {
                resolve(JSON.stringify(requestsResponses[requestsCounter]));
                requestsCounter++;
            });
        });

        EgoJSUtils.default.request = mockRequest;

        const instance = new EgoJS();
        mockDB.mock.tables.settings.whereResults = [[], [], [dummySettings]];
        mockDB.mock.tables.cache.whereResults = [
            [],
            [dummyRepositoryStats],
        ];
        instance.settings = dummySettings;
        mockDB.mock.tables.packages.items = [dummyPackageWithoutNPM];
        const result = instance.getStats().then((response) => {
            expect(mockRequest.mock.calls.length).toEqual(1);
            expect(mockRequest.mock.calls[0][0].uri).toMatch(/api\.github\.com/ig);
        });

        return result;
    });

});


text:
SPL: RecursiveIteratorIterator::getSubIterator() with explicit level parameter
--CREDITS--
Matt Raines matt@raines.me.uk
#testfest London 2009-05-09
--FILE--
<?php
$sample_array = array(1, 2, array(3, 4));

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($sample_array));

$iterator->next();
$iterator->next();
$iterator->next();
var_dump($iterator->getSubIterator(-1));
var_dump($iterator->getSubIterator(0)->getArrayCopy());
var_dump($iterator->getSubIterator(1)->getArrayCopy());
var_dump($iterator->getSubIterator(2));
?>
--EXPECT--
NULL
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    int(4)
  }
}
array(2) {
  [0]=>
  int(3)
  [1]=>
  int(4)
}
NULL


text:
layout: default
title: Multi Robot
---

# Use Cases

Want to enable two identical robots to communicate without prior knowledge of each other.

## Example

Two robots drive down the street and encounter each other without knowing about the other a priori.


text: <?php echo do_shortcode($content); ?>


text:
@implementation MATwitterSavedSearchesList

@end


text:
using GST.Fake.Authentication.JwtBearer;
using GST.Library.TimeZone.DependencyInjection;
using GST.Library.TimeZone.ModelBinder;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace GST.Library.TimeZone.Tests.Misc
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTimeZoneService();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = FakeJwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = FakeJwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = FakeJwtBearerDefaults.AuthenticationScheme;
            }).AddFakeJwtBearer();

            services.AddMvc(option => option.UseDateTimeProvider(services))
                        .AddJsonOptions(jsonOption =>
                            jsonOption.UseDateTimeConverter(services));
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Palaeontologia Polonica 52: 155.

#### Original name
null

### Remarks
null