text:
package net.lizhaoweb.demo.hadoop.hbase2mysql;

import net.lizhaoweb.demo.hadoop.io.MediaWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 李召(John.Lee)
 * @version 1.0.0.0.1
 * @EMAIL 404644381@qq.com
 * @notes Created on 2017年08月07日

 * Revision of last commit:$Revision$

 * Author of last commit:$Author$

 * Date of last commit:$Date$

 */
public class DBOutputReducer extends Reducer<Text, Text, MediaWritable, Text> {

    private static final Pattern MEDIA_PATTERN = Pattern.compile("^(\\d+)\u0001(.*)\u0001(.*)\u0001(\\d+)\u0001([a-zA-Z0-9.]+)\u0001(\\d+)\u0001([a-fA-F0-9]+)\u0001([a-zA-Z0-9/.]+)\u0001([a-fA-F0-9nul]*)\u0001([a-zA-Z0-9/.\\\\:]*)\u0001(\\d+)\u0001(.+)\u0001(\\d+)\u0001(.+)\u0001(\\d+)\u0001(\\d+)\\s*$");

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        String line = values.iterator().next().toString();
        Matcher matcher = MEDIA_PATTERN.matcher(line);
        if (!matcher.find()) {
            return;
        }
        MediaWritable r = new MediaWritable();
        r.setId(Long.valueOf(matcher.group(1)));
        r.setName(matcher.group(2));
        r.setDescription(matcher.group(3));
        r.setDuration(Integer.valueOf(matcher.group(4)));
        r.setSurfix(matcher.group(5));
        r.setType(Integer.valueOf(matcher.group(6)));
        r.setMd5(matcher.group(7));
        r.setOssAddress(matcher.group(8));
        r.setOssETag(matcher.group(9));
        r.setFilePath(matcher.group(10));
        r.setCreatorId(Long.valueOf(matcher.group(11)));
        r.setCreator(matcher.group(12));
        r.setCheckerId(Long.valueOf(matcher.group(13)));
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            r.setCreateTime(simpleDateFormat.parse(matcher.group(14)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        r.setFlag(Integer.valueOf(matcher.group(15)));
        r.setState(Integer.valueOf(matcher.group(16)));
        context.write(r, new Text(r.getName()));
    }
}


text:
require 'spec_helper'

describe SportsSouth::Order do

  it 'has a API_URL constant' do
    expect(SportsSouth::Order::API_URL).not_to be_nil
  end

  it 'has a SHIP_VIA constant' do
    expect(SportsSouth::Order::SHIP_VIA).not_to be_nil
  end

  describe '#initialize' do
    let(:order) { SportsSouth::Order.new(username: "bob", password: "secret", customer_number: "10001", source: "ruby-gem") }

    it { expect(order).to respond_to(:order_number) }
  end

  describe "#add_header" do
    let(:order) { SportsSouth::Order.new(username: "bob", password: "secret", customer_number: "10001", source: "ruby-gem") }
    let(:params) do
      {
        purchase_order: "1000",
        sales_message:  %q(Order via AmmoReady.com),
        shipping: {
          name: "Fake name",
          attn: "Transferee - Fake Transferee",
          address_one: "123 Bob Ln.",
          address_two: "",
          city:        "Greenville",
          state:       "SC",
          zip:         "29601",
          phone:       "8009915555",
          ship_via:    :premium_ground,
        }
      }
    end

    before do
      stub_request(:post, "http://webservices.theshootingwarehouse.com/smart/orders.asmx/AddHeader").
        with(body: {
          "AdultSignature" => "false",
          "CustomerNumber" => "bob",
          "CustomerOrderNumber" => "1000",
          "Insurance" => "false",
          "PO" => "1000",
          "Password" => "secret",
          "SalesMessage" => "Order via AmmoReady.com",
          "ShipToAddr1" => "123 Bob Ln.",
          "ShipToAddr2" => "",
          "ShipToAttn" => "Transferee - Fake Transferee",
          "ShipToCity" => "Greenville",
          "ShipToName" => "Fake name",
          "ShipToPhone" => "8009915555",
          "ShipToState" => "SC",
          "ShipToZip" => "29601",
          "ShipVia" => "G",
          "Signature" => "false",
          "Source" => "ammor",
          "UserName" => "bob"
        }, headers: {
          'Accept' => '*/*',
          'Content-Type' => 'application/x-www-form-urlencoded',
          'User-Agent' => "sports_south rubygems.org/gems/sports_south v(#{SportsSouth::VERSION})"
        }).to_return(status: 200, body: add_header_response, headers: {})
      order.add_header(params)
    end

    it { expect(order.order_number).to eq('1200099') }
  end

end

redpajama_set_name: RedPajamaGithub


text:
package io.vertigo.orchestra.webservices;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.inject.Inject;

import io.vertigo.orchestra.definitions.OrchestraDefinitionManager;
import io.vertigo.orchestra.definitions.ProcessDefinition;
import io.vertigo.vega.webservice.WebServices;
import io.vertigo.vega.webservice.stereotype.GET;
import io.vertigo.vega.webservice.stereotype.InnerBodyParam;
import io.vertigo.vega.webservice.stereotype.POST;
import io.vertigo.vega.webservice.stereotype.PUT;
import io.vertigo.vega.webservice.stereotype.PathParam;
import io.vertigo.vega.webservice.stereotype.PathPrefix;

/**
 * WebService API for managing ProcessDefinitions
 * @author mlaroche.
 * @version $Id$
 */
@PathPrefix("/orchestra/definitions")
public class WsDefinition implements WebServices {

	@Inject
	private OrchestraDefinitionManager definitionManager;

	/**
	 * Retourne un processus par son id.
	 * @param processName l'id du processus
	 * @return le processus
	 */
	@GET("/{processName}")
	public ProcessDefinition getProcessById(@PathParam("processName") final String processName) {
		return definitionManager.getProcessDefinition(processName);
	}

	/**
	 * Retourne la liste des processus correspondant à un critère de recherche.
	 * @param criteria le critère
	 * @return la liste de resultats
	 */
	@POST("/_search")
	public List<ProcessDefinition> searchProcessByLabel(@InnerBodyParam("criteria") final String criteria) {
		//TODO voir comment faire autrement
		final List<ProcessDefinition> definitions = definitionManager.getAllProcessDefinitions();
		if ("*".equals(criteria)) {
			return definitions;
		}
		return definitions
				.stream()
				.filter(definition -> definition.getLabel().startsWith(criteria))
				.collect(Collectors.toList());
	}

	/**
	 * Met à jour les propriétés d'un processus.
	 * @param processName l'id du processus à mettre à jour
	 * @param cronExpression la nouvelle expression cron de récurrence
	 * @param multiExecution le processus autorise-t-il la multi-exécution
	 * @param rescuePerdiodSeconds le temps de validité d'une planification
	 * @param active si le processus est actif
	 * @return le processus mis à jour
	 */
	@PUT("/{processName}/properties")
	public ProcessDefinition updateProcessProperties(@PathParam("processName") final String processName, @InnerBodyParam("cronExpression") final Optional<String> cronExpression,
			@InnerBodyParam("multiExecution") final boolean multiExecution, @InnerBodyParam("rescuePeriod") final int rescuePerdiodSeconds, @InnerBodyParam("active") final boolean active) {

		definitionManager.updateProcessDefinitionProperties(processName, cronExpression, multiExecution, rescuePerdiodSeconds, active);
		return definitionManager.getProcessDefinition(processName);
	}

	/**
	 * Mets à jour les paramètres initiaux de démarrage d'un processus
	 * @param processName l'id du processus à mettre à jour
	 * @param initialParams les nouveaux paramètres à utiliser (JSON sous forme de string)
	 * @return le processus mis à jour
	 */
	@PUT("/{processName}/params")
	public ProcessDefinition updateInitialParams(@PathParam("processName") final String processName, @InnerBodyParam("initialParams") final Map<String, String> initialParams) {
		definitionManager.updateProcessDefinitionInitialParams(processName, initialParams);
		return definitionManager.getProcessDefinition(processName);
	}
}


text:
/**
 *
 */
package com.redv.jplanet.conf.betwixt;

import java.io.File;

import junit.framework.TestCase;

import org.apache.commons.lang.SystemUtils;

import com.redv.jplanet.Planet;
import com.redv.jplanet.Subscription;
import com.redv.jplanet.User;

/**
 * @author sutra
 *
 */
public class BetwixtConfigTest extends TestCase {

	/*
	 * (非 Javadoc)
	 *
	 * @see junit.framework.TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
	}

	/*
	 * (非 Javadoc)
	 *
	 * @see junit.framework.TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
	}

	/**
	 * {@link com.redv.jplanet.conf.betwixt.BetwixtConfigReader#read()} 的测试方法。
	 *
	 * @throws Exception
	 */
	public void testRead() throws Exception {
		Planet planet = new Planet();
		planet.setAdminEmail("adminEmail");
		planet.setAdminName("adminName");
		planet.setCopyright("copyright");
		planet.setDescription("description");
		planet.setGroupingDateFormat("yyyy-MM-dd");
		planet.setKeywords("keyword,keyword");
		planet.setLanguage("zh-CN");
		planet.setMailSubject("mailSubject");
		planet.setPostDateFormat("yyyy-MM-dd HH:mm:ss");
		planet.setSiteUrl("http://example.com/");
		planet.setTitle("title");
		planet.setUpdatePeriod(12L);

		planet.addEditor(new User("http://sutra.openid.org.cn/"));
		planet.addEditor(new User("http://another.example.com/"));

		Subscription subscription = new Subscription();
		subscription.setDescription("description");
		subscription.setFeedUrl("http://feed.example.com/");
		subscription.setSiteUrl("http://example.com/");
		subscription.setTitle("example");

		planet.addSubscription(subscription);

		File tmpFile = File.createTempFile("jplanet", "BetwixtConfigTest",
				SystemUtils.getJavaIoTmpDir());
		try {
			BetwixtConfigWriter bcw = new BetwixtConfigWriter(tmpFile);
			bcw.write(planet);

			BetwixtConfigReader bcr = new BetwixtConfigReader(tmpFile);
			Planet readPlanet = bcr.read();
			assertEquals(planet, readPlanet);
		} finally {
			if (!tmpFile.delete()) {
				tmpFile.deleteOnExit();
			}
		}
	}

	private void assertEquals(final Planet expected, final Planet actual) {
		assertEquals(expected.getAdminEmail(), actual.getAdminEmail());
		assertEquals(expected.getAdminName(), actual.getAdminName());
		assertEquals(expected.getCopyright(), actual.getCopyright());
		assertEquals(expected.getDescription(), actual.getDescription());
		assertEquals(expected.getEditors(), actual.getEditors());
		assertEquals(expected.getGroupingDateFormat(), actual
				.getGroupingDateFormat());
		assertEquals(expected.getKeywords(), actual.getKeywords());
		assertEquals(expected.getLanguage(), actual.getLanguage());
		assertEquals(expected.getMailSubject(), actual.getMailSubject());
		assertEquals(expected.getPostDateFormat(), actual.getPostDateFormat());
		assertEquals(expected.getSiteUrl(), actual.getSiteUrl());
		assertEquals(expected.getSubscriptions(), actual.getSubscriptions());
		assertEquals(expected.getTitle(), actual.getTitle());
		assertEquals(expected.getUpdatePeriod(), actual.getUpdatePeriod());
	}
}


text:
`sysinfobar` is a simple program that outputs OpenBSD system
information to stdout in a format that is expected to be piped to
[Xmobar](http://projects.haskell.org/xmobar/).

## Displayed information

* CPU usage in percent
* RAM usage in percent
* swap usage in percent
* network usage down/up in percent
* battery capacity as symbol and in minutes left (if available)
* date and time (currently only in German)

The information is also highlighted according to the
impact on the system.


text:
layout: post
title: opengles(1)
description: 记录下opengl的基本知识

tagline: original post at hetaodie.github.io
categories: [Python]
tags: [Python]
image0: /assets/media/python/python0.png
image1: /assets/media/python/python1.png
image2: /assets/media/android/camera2.png
image3: /assets/media/android/camera3.png
image4: /assets/media/android/camera4.png
image5: /assets/media/android/camera5.png
image6: /assets/media/android/camera6.png
image7: /assets/media/android/camera7.png
---

**目录**

* 目录
 {:toc  }

# 基础知识

## 基础语法
 {% highlight ruby %}

{% endhighlight %}

<!--本文所用的超链接-->

[1]:https://github.com/hetaodie/AVAudioRecorderDemo.git


text:
+++
title = "Straw"
developer = "~pocwet"
shortcode = "~pocwet/straw"
description = "Vote on what to publish."
license = "MIT"
website = "https://urbit.org"
bgColor = "#6C6973"
image = ""
+++

This app lets group members vote on whether a post is published to a notebook. It is intended for use with Studio, which you can install from ~tirrel/studio.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>BEAUHUNT</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/stylish-portfolio.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
  <link href='https://fonts.googleapis.com/css?family=Bree+Serif' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>

                BEAUHUNT

                Home

                Qué es

                Cómo funciona

                Contacto

Beauhunt

El Headhunter de Beauchef

Hemos decidido cerrar Beauhunt porque no fuimos capaces de lograr que las empresas nos pagaran. Agradecemos a todas las personas que confiaron en nosotros.


text:
package de.mineformers.kybology.core.block

import cpw.mods.fml.relauncher.{Side, SideOnly}
import de.mineformers.core.block.{TileProvider, BaseBlock}
import de.mineformers.core.client.util.{RenderingProxy, Rendering}
import de.mineformers.kybology.Core
import de.mineformers.kybology.Core.Names
import de.mineformers.kybology.core.client.renderer.item.RiftItemRenderer
import de.mineformers.kybology.core.client.renderer.tileentity.RiftRenderer
import de.mineformers.kybology.core.tileentity.TileRift
import net.minecraft.block.material.Material
import net.minecraft.util.{DamageSource, AxisAlignedBB}
import net.minecraft.world.World

/**
 * BlockRift
 *
 * @author PaleoCrafter
 */
class BlockRift extends BaseBlock(Names.Blocks.Rift, Core.CreativeTab, Material.rock) with TileProvider[TileRift] with Rendering {
  setBlockBounds(0.3F, 0.3F, 0.3F, 0.7F, 0.7F, 0.7F)
  setBlockUnbreakable()
  setResistance(6000000.0F)

  override def getCollisionBoundingBoxFromPool(world: World, x: Int, y: Int, z: Int): AxisAlignedBB = null

  override def getSelectedBoundingBoxFromPool(world: World, x: Int, y: Int, z: Int): AxisAlignedBB = AxisAlignedBB.getBoundingBox(0, 0, 0, 0, 0, 0)

  override def tileClass: Class[TileRift] = classOf[TileRift]

  @SideOnly(Side.CLIENT)
  override protected def createProxy: RenderingProxy = new RenderingProxy {
    @SideOnly(Side.CLIENT)
    override def createTileRenderer = new RiftRenderer

    @SideOnly(Side.CLIENT)
    override def createItemRenderer = new RiftItemRenderer
  }

  val damage = new DamageSource("kybology:rift")
}


text:
This book describes how to use the Matrix IRC bridge, giving an overview of functions for users and server administrators. If you
believe there are errors or omissions in the book, please open an issue on [GitHub](https://github.com/matrix-org/matrix-appservice-irc/issues)
or create a PR.

For an overview of the bridge, see the [README.md](https://github.com/matrix-org/matrix-appservice-irc).

A community maintained wiki also exists which can be found [here](https://github.com/matrix-org/matrix-appservice-irc/wiki).

The documentation is built from source and can be found in [the GitHub repo](https://github.com/matrix-org/matrix-appservice-irc/tree/develop/docs).


text:
<?php

namespace CodingBerlin\ExtraPromotionPlugin\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('extra_promotion');

        return $treeBuilder;
    }
}


text: require_relative "./routes/routes.rb"


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M4,11V4H11V11ZM4,20V13H11V20ZM13,11V4H20V11ZM13,20V13H20V20Z"/>
</vector>


text:
package org.atlasapi.system.legacy;

import java.util.Iterator;

import org.atlasapi.media.entity.Content;
import org.atlasapi.media.entity.Item;
import org.atlasapi.media.entity.Person;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.persistence.content.KnownTypeContentResolver;
import org.atlasapi.persistence.content.ResolvedContent;
import org.atlasapi.persistence.content.listing.ContentListingProgress;
import org.atlasapi.persistence.lookup.entry.LookupEntry;
import org.atlasapi.persistence.lookup.entry.LookupEntryStore;

import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class LegacyLookupResolvingContentListerTest {

    private @Mock LookupEntryStore lookupEntryStore;
    private @Mock KnownTypeContentResolver contentResolver;

    private Iterable<Publisher> publishers;
    private ContentListingProgress progress;

    private Item item;
    private Person person;

    private LookupEntry itemEntry;
    private LookupEntry personEntry;

    private LegacyContentLister contentLister;

    @Before
    public void setUp() throws Exception {
        contentLister = new LegacyLookupResolvingContentLister(lookupEntryStore, contentResolver);

        Publisher publisher = Publisher.BBC;

        publishers = ImmutableList.of(publisher);
        progress = ContentListingProgress.START;

        item = new Item("uriA", "uriA", publisher);
        person = new Person("uriB", "uriB", publisher);

        itemEntry = LookupEntry.lookupEntryFrom(item);
        personEntry = LookupEntry.lookupEntryFrom(person);
    }

    @Test
    public void testListContent() throws Exception {
        when(lookupEntryStore.allEntriesForPublishers(publishers, progress))
                .thenReturn(ImmutableList.of(itemEntry));
        when(contentResolver.findByLookupRefs(ImmutableList.of(itemEntry.lookupRef())))
                .thenReturn(
                        ResolvedContent.builder()
                                .put(itemEntry.uri(), item)
                                .build()
                );

        Iterator<Content> content = contentLister.listContent(publishers, progress);

        assertThat(content.hasNext(), is(true));
        assertThat(content.next(), sameInstance(item));
    }

    @Test
    public void testListContentFiltersNonContent() throws Exception {
        when(lookupEntryStore.allEntriesForPublishers(publishers, progress))
                .thenReturn(ImmutableList.of(personEntry));
        when(contentResolver.findByLookupRefs(ImmutableList.of(personEntry.lookupRef())))
                .thenReturn(
                        ResolvedContent.builder()
                                .put(personEntry.uri(), person)
                                .build()
                );

        Iterator<Content> content = contentLister.listContent(publishers, progress);

        assertThat(content.hasNext(), is(false));
    }

    @Test
    public void testListContentFiltersNonResolvingLookupEntries() throws Exception {
        when(lookupEntryStore.allEntriesForPublishers(publishers, progress))
                .thenReturn(ImmutableList.of(itemEntry));
        when(contentResolver.findByLookupRefs(ImmutableList.of(itemEntry.lookupRef())))
                .thenReturn(ResolvedContent.builder().build());

        Iterator<Content> content = contentLister.listContent(publishers, progress);

        assertThat(content.hasNext(), is(false));
    }
}


text:
export interface IONode {
    _endpoint : IOEndpoint
    _ioPromise : IOPromise< this >
}

export interface IOPromise<T> extends Promise<T> {
    abort? : () => void
}

export interface IOEndpoint {
    list( options : IOOptions, collection? ) : IOPromise<any>
    create( json : any, options : IOOptions, record? ) : IOPromise<any>
    update( id : string | number, json :any, options : IOOptions, record? ) : IOPromise<any>
    read( id : string | number, options : IOOptions, record? ) : IOPromise<any>
    destroy( id : string | number, options : IOOptions, record? ) : IOPromise<any>
    subscribe( events : IOEvents, collection? ) : IOPromise<any>
    unsubscribe( events : IOEvents, collection? ) : void
}

export interface IOOptions {
    ioUpdate? : boolean
}

export interface IOEvents {
    updated? : ( json : any ) => void
    removed? : ( json : any ) => void
}

export function getOwnerEndpoint( self ) : IOEndpoint {
    // Check if we are the member of the collection...
    const { collection } = self;
    if( collection ){
        return getOwnerEndpoint( collection );
    }

    // Now, if we're the member of the model...
    if( self._owner ){
        const { _endpoints } = self._owner;
        return _endpoints && _endpoints[ self._ownerKey ];
    }
}

/**
 * Create abortable promise.
 * Adds `promise.abort()` function which rejects the promise by default
 * initialize() function takes third optional argument `abort : ( resolve, reject ) => void`,
 * which can be used to add custom abort handling.
 */
declare var Promise: PromiseConstructorLike;

export function createIOPromise( initialize : InitIOPromise ) : IOPromise<any>{
    let resolve, reject, onAbort;

    function abort( fn ){
        onAbort = fn;
    }

    const promise : IOPromise<any> = new Promise( ( a_resolve, a_reject ) =>{
        reject = a_reject;
        resolve = a_resolve;
        initialize( resolve, reject, abort );
    }) as IOPromise<any>;

    promise.abort = () => {
        onAbort ? onAbort( resolve, reject ) : reject( new Error( "I/O Aborted" ) );
    }

    return promise;
}

export type InitIOPromise = ( resolve : ( x? : any ) => void, reject : ( x? : any ) => void, abort? : ( fn : Function ) => void ) => void;

export function startIO( self : IONode, promise : IOPromise<any>, options : IOOptions, thenDo : ( json : any ) => any ) : IOPromise<any> {
    // Stop pending I/O first...
    abortIO( self );

    // Mark future update transaction as IO transaction.
    options.ioUpdate = true;

    self._ioPromise = promise
        .then( resp => {
            self._ioPromise = null;

            const result = thenDo ? thenDo( resp ) : resp;

            triggerAndBubble( self, 'sync', self, resp, options );

            return result;
        } )
        .catch( err => {
            self._ioPromise = null;

            // Overlaps with a new `error` event.
            triggerAndBubble( self, 'error', self, err, options );

            throw err;
        } ) as IOPromise<any>;

    self._ioPromise.abort = promise.abort;

    return self._ioPromise;
}

export function abortIO( self : IONode ){
    if( self._ioPromise && self._ioPromise.abort ){
        self._ioPromise.abort();
        self._ioPromise = null;
    }
}

export function triggerAndBubble( eventSource, ...args ){
    eventSource.trigger.apply( eventSource, args );
    const { collection } = eventSource;
    collection && collection.trigger.apply( collection, args );
}


text:
<?php

namespace Honeybadger\Logger;

use \Honeybadger\Logger;

/**
 * Writes log entries to nowhere with the expectation that developers interested
 * in this library's messages will implement their own logger or use a
 * bundle/module already written for their framework or choice to replace this
 * default in [Honeybadger::$logger].
 *
 * TODO: Investigate to see if logging to STDERR by default is feasible.
 *
 * @package   Honeybadger
 * @category  Logging
 */
class Void extends Logger {

	public function write($severity, $message = NULL)
	{
		// noop
	}

}


text:
<?php

class opForceEncodingToUTF8Safeguard extends opSafeguard
{
  public function isAvailable()
  {
    return (sfConfig::get('sf_app') !== 'mobile_frontend');
  }

  public function apply(sfEvent $event, $value = null)
  {
    $request = $this->context->getRequest();

    if ($request instanceof opWebRequest)
    {
      $request->convertEncodingForInput('UTF-8');
    }
  }
}


text:
#ifndef __LINUX_PREEMPT_H
#define __LINUX_PREEMPT_H

/*
 * include/linux/preempt.h - macros for accessing and manipulating
 * preempt_count (used for kernel preemption, interrupt count, etc.)
 */

#include <linux/thread_info.h>
#include <linux/linkage.h>
#include <linux/list.h>

#if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_PREEMPT_TRACER)
  extern void add_preempt_count(int val);
  extern void sub_preempt_count(int val);
#else
# define add_preempt_count(val)	do { preempt_count() += (val); } while (0)
# define sub_preempt_count(val)	do { preempt_count() -= (val); } while (0)
#endif

#define inc_preempt_count() add_preempt_count(1)
#define dec_preempt_count() sub_preempt_count(1)

#define preempt_count()	(current_thread_info()->preempt_count)

#ifdef CONFIG_PREEMPT

asmlinkage void preempt_schedule(void);

#define preempt_disable() \
do { \
	inc_preempt_count(); \
	barrier(); \
} while (0)

#define preempt_enable_no_resched() \
do { \
	barrier(); \
	dec_preempt_count(); \
} while (0)

#define preempt_check_resched() \
do { \
	if (unlikely(test_thread_flag(TIF_NEED_RESCHED))) \
		preempt_schedule(); \
} while (0)

#define preempt_enable() \
do { \
	preempt_enable_no_resched(); \
	barrier(); \
	preempt_check_resched(); \
} while (0)

/* For debugging and tracer internals only! */
#define add_preempt_count_notrace(val)			\
	do { preempt_count() += (val); } while (0)
#define sub_preempt_count_notrace(val)			\
	do { preempt_count() -= (val); } while (0)
#define inc_preempt_count_notrace() add_preempt_count_notrace(1)
#define dec_preempt_count_notrace() sub_preempt_count_notrace(1)

#define preempt_disable_notrace() \
do { \
	inc_preempt_count_notrace(); \
	barrier(); \
} while (0)

#define preempt_enable_no_resched_notrace() \
do { \
	barrier(); \
	dec_preempt_count_notrace(); \
} while (0)

/* preempt_check_resched is OK to trace */
#define preempt_enable_notrace() \
do { \
	preempt_enable_no_resched_notrace(); \
	barrier(); \
	preempt_check_resched(); \
} while (0)

#else

#define preempt_disable()		do { } while (0)
#define preempt_enable_no_resched()	do { } while (0)
#define preempt_enable()		do { } while (0)
#define preempt_check_resched()		do { } while (0)

#define preempt_disable_notrace()		do { } while (0)
#define preempt_enable_no_resched_notrace()	do { } while (0)
#define preempt_enable_notrace()		do { } while (0)

#endif

#ifdef CONFIG_PREEMPT_NOTIFIERS

struct preempt_notifier;

/**
 * preempt_ops - notifiers called when a task is preempted and rescheduled
 * @sched_in: we're about to be rescheduled:
 *    notifier: struct preempt_notifier for the task being scheduled
 *    cpu:  cpu we're scheduled on
 * @sched_out: we've just been preempted
 *    notifier: struct preempt_notifier for the task being preempted
 *    next: the task that's kicking us out
 */
struct preempt_ops {
	void (*sched_in)(struct preempt_notifier *notifier, int cpu);
	void (*sched_out)(struct preempt_notifier *notifier,
			  struct task_struct *next);
};

/**
 * preempt_notifier - key for installing preemption notifiers
 * @link: internal use
 * @ops: defines the notifier functions to be called
 *
 * Usually used in conjunction with container_of().
 */
struct preempt_notifier {
	struct hlist_node link;
	struct preempt_ops *ops;
};

void preempt_notifier_register(struct preempt_notifier *notifier);
void preempt_notifier_unregister(struct preempt_notifier *notifier);

static inline void preempt_notifier_init(struct preempt_notifier *notifier,
				     struct preempt_ops *ops)
{
	INIT_HLIST_NODE(&notifier->link);
	notifier->ops = ops;
}

#endif

#endif /* __LINUX_PREEMPT_H */


text:
require 'pazy/attributes'
require 'pazy/enumerable'
require 'pazy/accumulator'
require 'pazy/hash_map'

class Pazy::Depth_First_Traversal
  include Pazy::Enumerable
  include Pazy::Attributes

  def initialize(sources, &adjacencies)
    @sources     = sources
    @adjacencies = adjacencies
    freeze
  end

  def each(&block)
    if block_given?
      traversal.each &block
    else
      self
    end
  end

  def empty?
    traversal.empty?
  end

  def parent(v)
    traversal.info[v]
  end

  def index(v)
    dfs_index[v]
  end

  def low(v)
    min_back[v]
  end

  private

  lazy_attr :dfs_index do
    Pazy::HashMap.new + traversal.with_index
  end

  # This method implements the traversal itself via an Accumulator
  # instance.  In addition to providing an ordering of vertices via
  # the 'each' method, the result also has a method info which
  # returns a map from each vertex to its predecessor in the
  # traversal graph. Sources of the traversal point to themselves in
  # this map.
  lazy_attr :traversal do
    visit = proc do |state, e|
      u, v = e
      if state.marked?(v)
        state
      else
        adj = @adjacencies.call(v)
        adj.map { |w| [v, w] }.inject(state.with_mark(v, u), &visit).after(v)
      end
    end
    @sources.map { |s| [s, s] }.inject(Pazy::Accumulator.new, &visit)
  end

  # TODO describe this attribute
  lazy_attr :min_back do
    visit = proc do |state, edge|
      u, v = edge
      if index(v) >= index(u)
        incident = @adjacencies.call(v).map { |w| [v, w] }
        tmp_state = incident.inject(state.with_mark(v, index(v)), &visit)
        tmp_state.with_mark(u, [tmp_state.info[u], tmp_state.info[v]].min)
      elsif parent(u) != v
        state.with_mark(u, [state.info[u], index(v)].min)
      else
        state
      end
    end
    (@sources.map { |r| [r, r] }.inject(Pazy::Accumulator.new, &visit)).info
  end
end


text:
/*
Title: UserID
*/

UserID can be used to show the particular user's ID when used within that particular service.

## Usage

> $(userid)


text:
#ifndef __XMLSEC_STRINGS_H__
#define __XMLSEC_STRINGS_H__

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#include <libxml/tree.h>

#include <xmlsec/xmlsec.h>

/*************************************************************************
 *
 * Global Namespaces
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNs[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecDSigNs[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecEncNs[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsNs[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXPathNs[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXPath2Ns[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXPointerNs[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoap11Ns[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoap12Ns[];

/*************************************************************************
 *
 * DSig Nodes
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeSignature[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeSignedInfo[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeSignatureValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCanonicalizationMethod[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeSignatureMethod[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDigestMethod[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDigestValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeObject[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeManifest[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeSignatureProperties[];

/*************************************************************************
 *
 * Encryption Nodes
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeEncryptedData[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeEncryptionMethod[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeEncryptionProperties[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeEncryptionProperty[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCipherData[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCipherValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCipherReference[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeReferenceList[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDataReference[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeKeyReference[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCarriedKeyName[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecTypeEncContent[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecTypeEncElement[];

/*************************************************************************
 *
 * XKMS nodes, attributes  and value strings
 *
 ************************************************************************/
#ifndef XMLSEC_NO_XKMS
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsServerRequestResultName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsServerRequestStatusName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsServerRequestLocateName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsServerRequestValidateName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsServerRequestCompoundName[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeResult[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeStatusRequest[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeStatusResult[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeLocateRequest[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeLocateResult[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeValidateRequest[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeValidateResult[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCompoundRequest[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCompoundResult[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeMessageExtension[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeOpaqueClientData[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeResponseMechanism[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRespondWith[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodePendingNotification[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeQueryKeyBinding[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeKeyUsage[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeUseKeyWith[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeTimeInstant[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRequestSignatureValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeUnverifiedKeyBinding[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeValidityInterval[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeStatus[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeValidReason[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeInvalidReason[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeIndeterminateReason[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrService[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrNonce[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrOriginalRequestId[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrResponseLimit[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrMechanism[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrIdentifier[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrApplication[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrResultMajor[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrResultMinor[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrRequestId[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrNotBefore[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrNotOnOrAfter[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrTime[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrStatusValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecResponseMechanismPending[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResponseMechanismRepresent[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResponseMechanismRequestSignatureValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithKeyName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithX509Cert[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithX509Chain[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithX509CRL[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithOCSP[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithRetrievalMethod[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithPGP[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithPGPWeb[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithSPKI[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecRespondWithPrivateKey[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecStatusResultSuccess[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecStatusResultFailed[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecStatusResultPending[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyUsageEncryption[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyUsageSignature[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyUsageExchange[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyBindingStatusValid[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyBindingStatusInvalid[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyBindingStatusIndeterminate[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyBindingReasonIssuerTrust[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyBindingReasonRevocationStatus[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyBindingReasonValidityInterval[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecKeyBindingReasonSignature[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMajorCodeSuccess[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMajorCodeVersionMismatch[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMajorCodeSender[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMajorCodeReceiver[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMajorCodeRepresent[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMajorCodePending[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeNoMatch[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeTooManyResponses[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeIncomplete[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeFailure[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeRefused[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeNoAuthentication[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeMessageNotSupported[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeUnknownResponseId[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecResultMinorCodeNotSynchronous[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapFaultReasonLang[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapFaultReasonUnsupportedVersion[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapFaultReasonUnableToProcess[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapFaultReasonServiceUnavailable[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapFaultReasonMessageNotSupported[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapFaultReasonMessageInvalid[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapSubcodeValueMessageNotSupported[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsSoapSubcodeValueBadMessage[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsFormatStrPlain[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsFormatStrSoap11[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXkmsFormatStrSoap12[];

#endif /* XMLSEC_NO_XKMS */

/*************************************************************************
 *
 * KeyInfo and Transform Nodes
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeKeyInfo[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeReference[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeTransforms[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeTransform[];

/*************************************************************************
 *
 * Attributes
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrId[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrURI[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrType[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrMimeType[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrEncoding[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrAlgorithm[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrTarget[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrFilter[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrRecipient[];

/*************************************************************************
 *
 * AES strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameAESKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeAESKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefAESKeyValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameAes128Cbc[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefAes128Cbc[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameAes192Cbc[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefAes192Cbc[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameAes256Cbc[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefAes256Cbc[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameKWAes128[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefKWAes128[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameKWAes192[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefKWAes192[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameKWAes256[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefKWAes256[];

/*************************************************************************
 *
 * BASE64 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameBase64[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefBase64[];

/*************************************************************************
 *
 * C14N strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameC14N[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefC14N[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameC14NWithComments[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefC14NWithComments[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameC14N11[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefC14N11[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameC14N11WithComments[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefC14N11WithComments[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameExcC14N[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefExcC14N[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameExcC14NWithComments[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefExcC14NWithComments[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNsExcC14N[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNsExcC14NWithComments[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeInclusiveNamespaces[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecAttrPrefixList[];

/*************************************************************************
 *
 * DES strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameDESKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDESKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefDESKeyValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameDes3Cbc[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefDes3Cbc[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameKWDes3[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefKWDes3[];

/*************************************************************************
 *
 * DSA strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameDSAKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefDSAKeyValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAP[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAQ[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAG[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAJ[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAX[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAY[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSASeed[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDSAPgenCounter[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameDsaSha1[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefDsaSha1[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameDsaSha256[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefDsaSha256[];

/*************************************************************************
 *
 * ECDSA strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameECDSAKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefECDSAKeyValue[];

/* XXX-MAK: More constants will be needed later. */
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAP[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAQ[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAG[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAJ[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAX[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAY[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSASeed[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeECDSAPgenCounter[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameEcdsaSha1[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefEcdsaSha1[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameEcdsaSha224[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefEcdsaSha224[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameEcdsaSha256[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefEcdsaSha256[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameEcdsaSha384[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefEcdsaSha384[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameEcdsaSha512[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefEcdsaSha512[];

/*************************************************************************
 *
 * GOST2001 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameGOST2001KeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeGOST2001KeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefGOST2001KeyValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameGost2001GostR3411_94[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefGost2001GostR3411_94[];

/*************************************************************************
 *
 * EncryptedKey
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameEncryptedKey[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeEncryptedKey[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefEncryptedKey[];

/*************************************************************************
 *
 * Enveloped transform strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameEnveloped[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefEnveloped[];

/*************************************************************************
 *
 * HMAC strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHMACKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeHMACKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHMACKeyValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeHMACOutputLength[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHmacMd5[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHmacMd5[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHmacRipemd160[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHmacRipemd160[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHmacSha1[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHmacSha1[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHmacSha224[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHmacSha224[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHmacSha256[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHmacSha256[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHmacSha384[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHmacSha384[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameHmacSha512[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefHmacSha512[];

/*************************************************************************
 *
 * KeyName strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameKeyName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeKeyName[];

/*************************************************************************
 *
 * KeyValue strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeKeyValue[];

/*************************************************************************
 *
 * Memory Buffer strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameMemBuf[];

/*************************************************************************
 *
 * MD5 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameMd5[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefMd5[];

/*************************************************************************
 *
 * RetrievalMethod
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRetrievalMethod[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRetrievalMethod[];

/*************************************************************************
 *
 * RIPEMD160 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRipemd160[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRipemd160[];

/*************************************************************************
 *
 * RSA strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRSAKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRSAKeyValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRSAKeyValue[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRSAModulus[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRSAExponent[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRSAPrivateExponent[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaMd5[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaMd5[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaRipemd160[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaRipemd160[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaSha1[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaSha1[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaSha224[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaSha224[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaSha256[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaSha256[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaSha384[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaSha384[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaSha512[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaSha512[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaPkcs1[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaPkcs1[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRsaOaep[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRsaOaep[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRsaOAEPparams[];

/*************************************************************************
 *
 * GOSTR3411_94 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameGostR3411_94[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefGostR3411_94[];

/*************************************************************************
 *
 * SHA1 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameSha1[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefSha1[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameSha224[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefSha224[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameSha256[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefSha256[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameSha384[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefSha384[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameSha512[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefSha512[];

/*************************************************************************
 *
 * X509 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameX509Data[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509Data[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefX509Data[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509Certificate[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509CRL[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509SubjectName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509IssuerSerial[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509IssuerName[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509SerialNumber[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeX509SKI[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameRawX509Cert[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefRawX509Cert[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameX509Store[];

/*************************************************************************
 *
 * PGP strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNamePGPData[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodePGPData[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefPGPData[];

/*************************************************************************
 *
 * SPKI strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameSPKIData[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeSPKIData[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefSPKIData[];

/*************************************************************************
 *
 * XPath/XPointer strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameXPath[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeXPath[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecNameXPath2[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeXPath2[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXPath2FilterIntersect[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXPath2FilterSubtract[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecXPath2FilterUnion[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameXPointer[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeXPointer[];

/*************************************************************************
 *
 * Xslt strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNameXslt[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecHrefXslt[];

#ifndef XMLSEC_NO_SOAP
/*************************************************************************
 *
 * SOAP 1.1/1.2 strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeEnvelope[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeHeader[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeBody[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeFault[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeFaultCode[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeFaultString[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeFaultActor[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeFaultDetail[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeCode[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeReason[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeNode[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeRole[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeDetail[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeValue[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeSubcode[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecNodeText[];

XMLSEC_EXPORT_VAR const xmlChar xmlSecSoapFaultCodeVersionMismatch[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoapFaultCodeMustUnderstand[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoapFaultCodeClient[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoapFaultCodeServer[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoapFaultCodeReceiver[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoapFaultCodeSender[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecSoapFaultDataEncodningUnknown[];

#endif /* XMLSEC_NO_SOAP */

/*************************************************************************
 *
 * Utility strings
 *
 ************************************************************************/
XMLSEC_EXPORT_VAR const xmlChar xmlSecStringEmpty[];
XMLSEC_EXPORT_VAR const xmlChar xmlSecStringCR[];

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __XMLSEC_STRINGS_H__ */


text:
/* The declaration [2] should be removed because it's defining the
 * same font as [1]. */
@font-face { font-family: avenir; font-weight: bold; src: url('x'); } /* 1 */
@font-face { font-family: avenir; font-weight: bold; src: url('y'); } /* 2 */
@font-face { font-family: avenir; font-weight: normal; src: url('z'); }


text:
<?php

namespace App\Http\Middleware;

use Closure;
use App\ForumForum;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
class RedirectIfNotAuthTopic {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $urlArray = explode('/', $request->url());
        for ($i = 0; $i < count($urlArray); $i++) {
            if ($urlArray[$i] == 'forum') {
                $forum = ForumForum::findOrFail($urlArray[$i + 1]);
                if ($forum->getPermissionTopic() == 1) {

                    return $next($request);
                }
                if (Auth::user() != NULL) {
                    if (Auth::user()->rang()->first()->getId() >= $forum->getPermissionTopic()) {

                        return $next($request);
                    }
                }
            }
        }
        return new RedirectResponse(url('/forum/'.$forum->getId().'/topic'));
    }

}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse

import buff
import huffman
import mbrotli

# Read a bit_width-bits little endian number from the InBitBuff in_bits.
def ReadNum(in_bits, bit_width):
  val = 0
  for i in xrange(bit_width):
    val |= in_bits.ReadBit() << i
  return val

# Read MNIBBLES from the InBitBuff in_bits.
def ReadMNIBBLES(in_bits):
  # The prefix code bits are read most significant bit first, but mbrotli has
  # them least significant bit first.
  msb = in_bits.ReadBit()
  lsb = in_bits.ReadBit()
  return mbrotli.MNIBBLES_decoder[str(lsb) + str(msb)]

# Read MLEN from the InBitBuff in_bits.
def ReadMLEN(in_bits, MNIBBLES):
  num_bits = MNIBBLES*4
  val = ReadNum(in_bits, num_bits)
  if MNIBBLES > 4:
    assert val >= 1<<(num_bits-4)
  return val + 1

# Read NBLTYPES from the InBitBuff in_bits. Always positive.
# Also useful for values sharing the same structure.
def ReadNBLTYPES(in_bits):
  v_bottom, num_bits = huffman.ReadCodedElement(in_bits,
                                                mbrotli.NBLTYPES_huffman)
  return v_bottom + ReadNum(in_bits, num_bits)

# Read all the context modes from the InBitBuff in_bits.
def ReadContextModes(in_bits, NBLTYPESL):
  return [ReadNum(in_bits, 2) for _ in xrange(NBLTYPESL)]

# Read a prefix code (an entire huffman tree) from the InBitBuff in_bits.
# Only simple prefix trees are supported. Returns the huffman tree.
def ReadPrefixCode(in_bits, alphabet_size):
  two_bits = ReadNum(in_bits, 2)
  if two_bits != 1:
    assert False, 'complex prefix trees not supported'
  NSYM = ReadNum(in_bits, 2) + 1
  assert alphabet_size >= 1
  ALPHABET_BITS = (alphabet_size-1).bit_length()
  symbols = [ReadNum(in_bits, ALPHABET_BITS) for i in xrange(NSYM)]
  if NSYM == 1:
    return symbols[0]
  elif NSYM == 2:
    lengths = [1, 1]
    symbols = sorted(symbols)
  elif NSYM == 3:
    lengths = [1, 2, 2]
    symbols = symbols[:1] + sorted(symbols[1:])
  else:
    assert NSYM == 4
    tree_select = in_bits.ReadBit()
    if tree_select == 0:
      lengths = [2, 2, 2, 2]
      symbols = sorted(symbols)
    else:
      assert tree_select == 1
      lengths = [1, 2, 3, 3]
      symbols = symbols[:2] + sorted(symbols[2:])
  assert len(lengths) == NSYM

  MAX_BITS = max(lengths)
  bl_count = [0]*(MAX_BITS+1)
  for length in lengths:
    bl_count[length] += 1

  code = 0
  assert bl_count[0] == 0
  next_code = [None]*(MAX_BITS+1)
  for bits in xrange(1, MAX_BITS+1):
    code = (code + bl_count[bits-1]) << 1
    next_code[bits] = code

  numeric_codes = [None]*NSYM
  for n in xrange(NSYM):
    l = lengths[n]
    if l != 0:
      numeric_codes[n] = next_code[l]
      next_code[l] += 1

  pairs = [
      (symbol, format(numeric_code, '0{}b'.format(l))[::-1]) for
       symbol, numeric_code, l in zip(symbols, numeric_codes, lengths)
  ]
  return huffman.MakeTreeFromPairs(pairs)

# Reads an insert and copy length element from the InBitBuff in_bits.
# Returns ILEN, CLEN, distance_symbol_0
def ComputeInsertAndCopyLength(in_bits, insert_copy_length_symbol):
  distance_symbol_0 = False
  if insert_copy_length_symbol <= 63:
    assert insert_copy_length_symbol >= 0
    distance_symbol_0 = True
    insert_length_code_start = 0
    copy_length_code_start = 0
  elif insert_copy_length_symbol <= 127:
    distance_symbol_0 = True
    insert_length_code_start = 0
    copy_length_code_start = 8
  elif insert_copy_length_symbol <= 191:
    insert_length_code_start = 0
    copy_length_code_start = 0
  elif insert_copy_length_symbol <= 255:
    insert_length_code_start = 0
    copy_length_code_start = 8
  elif insert_copy_length_symbol <= 319:
    insert_length_code_start = 8
    copy_length_code_start = 0
  elif insert_copy_length_symbol <= 383:
    insert_length_code_start = 8
    copy_length_code_start = 8
  elif insert_copy_length_symbol <= 447:
    insert_length_code_start = 0
    copy_length_code_start = 16
  elif insert_copy_length_symbol <= 511:
    insert_length_code_start = 16
    copy_length_code_start = 0
  elif insert_copy_length_symbol <= 575:
    insert_length_code_start = 8
    copy_length_code_start = 16
  elif insert_copy_length_symbol <= 639:
    insert_length_code_start = 16
    copy_length_code_start = 8
  elif insert_copy_length_symbol <= 703:
    insert_length_code_start = 16
    copy_length_code_start = 16
  else:
    assert False, 'bad insert_copy_length_symbol'
  bottom_6 = insert_copy_length_symbol & 0x3f
  insert_length_code = insert_length_code_start + (bottom_6 >> 3)
  copy_length_code = copy_length_code_start + (bottom_6 & 0x7)
  insert_length_extra_bits, insert_length_start = mbrotli.insert_length_codes[
      insert_length_code]
  copy_length_extra_bits, copy_length_start = mbrotli.copy_length_codes[
      copy_length_code]
  ILEN = insert_length_start + ReadNum(in_bits, insert_length_extra_bits)
  CLEN = copy_length_start + ReadNum(in_bits, copy_length_extra_bits)
  return ILEN, CLEN, distance_symbol_0

# A class to track the most recently used distances.
class LastDistances(object):
  def __init__(self):
    self.b = [16, 15, 11, 4]
    self.i = 3

  # Indicate that the distance dist was just used.
  def Push(self, dist):
    assert dist > 0
    self.i += 1
    self.i %= 4
    self.b[self.i] = dist

  # Get the distance that happened back ago.
  def GetPrevious(self, back):
    assert 0 < back <= 4
    index = (self.i - (back - 1)) % 4
    return self.b[index]

# Given a distance symbol, compute what distance should be used.
# NPOSTFIX must be 0, and distance_symbol must be small enough that extra bits
# aren't needed.
def ComputeDistance(distance_symbol, last_distance, NDIRECT):
  assert 0 <= distance_symbol <= 15 + NDIRECT
  assert 0 <= NDIRECT <= 15  # NDIRECT > 15 not implemented
  d = ComputeDistanceInternal(distance_symbol, last_distance, NDIRECT)
  assert d > 0
  return d

# A helper for ComputeDistance
def ComputeDistanceInternal(distance_symbol, last_distances, NDIRECT):
  if distance_symbol == 0:
    return last_distances.GetPrevious(1)
  elif distance_symbol == 1:
    return last_distances.GetPrevious(2)
  elif distance_symbol == 2:
    return last_distances.GetPrevious(3)
  elif distance_symbol == 3:
    return last_distances.GetPrevious(4)
  elif distance_symbol == 4:
    return last_distances.GetPrevious(1) - 1
  elif distance_symbol == 5:
    return last_distances.GetPrevious(1) + 1
  elif distance_symbol == 6:
    return last_distances.GetPrevious(1) - 2
  elif distance_symbol == 7:
    return last_distances.GetPrevious(1) + 2
  elif distance_symbol == 8:
    return last_distances.GetPrevious(1) - 3
  elif distance_symbol == 9:
    return last_distances.GetPrevious(1) + 3
  elif distance_symbol == 10:
    return last_distances.GetPrevious(2) - 1
  elif distance_symbol == 11:
    return last_distances.GetPrevious(2) + 1
  elif distance_symbol == 12:
    return last_distances.GetPrevious(2) - 2
  elif distance_symbol == 13:
    return last_distances.GetPrevious(2) + 2
  elif distance_symbol == 14:
    return last_distances.GetPrevious(2) - 3
  elif distance_symbol == 15:
    return last_distances.GetPrevious(2) + 3
  v = distance_symbol - 15
  assert 0 < v <= NDIRECT
  return v

# Reads from the InBitBuff in_bits until it's byte aligned, and verifies all
# read bits are 0.
def ReadCheckTillBoundary(in_bits):
  while in_bits.TillBoundary() != 0:
    ignored_bit = in_bits.ReadBit()
    assert ignored_bit == 0

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument("in_file")
  parser.add_argument("out_file")
  parser.add_argument("--only_short", help="Only decompress short metablocks",
                      action="store_true")
  args = parser.parse_args()
  with open(args.in_file, 'rb') as f:
    in_bits = buff.InBitBuff(f.read())

  WBITS = huffman.ReadCodedElement(in_bits, mbrotli.WBITS_huffman)
  window_size = (1 << WBITS) - 16

  result = buff.OutByteBuff()
  last_distances = LastDistances()
  last_print_at = 0
  while True:
    ISLAST = in_bits.ReadBit()
    if ISLAST:
      ISLASTEMPTY = in_bits.ReadBit()
      if ISLASTEMPTY:
        print('ISLASTEMPTY')
        ReadCheckTillBoundary(in_bits)
        break
    MNIBBLES = ReadMNIBBLES(in_bits)
    if not MNIBBLES:
      assert in_bits.ReadBit() == 0
      assert False, 'MSKIPLEN not implemented'
    MLEN = ReadMLEN(in_bits, MNIBBLES)
    short = MLEN <= 50
    if not ISLAST:
      ISUNCOMPRESSED = in_bits.ReadBit()
      if ISUNCOMPRESSED:
        ReadCheckTillBoundary(in_bits)
        for c in in_bits.ReadBytes(MLEN):
          if short or not args.only_short:
            result.PutByte(c)
        continue

    for _ in range(3):  # loop for each three block categories (i = L, I, D)
      NBLTYPESi = ReadNBLTYPES(in_bits)
      assert NBLTYPESi == 1, 'NBLTYPESi >= 2 not implemented'
      # Thus BTYPE_i = 0 and BLEN_i = 16777216

    NPOSTFIX = ReadNum(in_bits, 2)
    assert NPOSTFIX == 0
    NDIRECT_top = ReadNum(in_bits, 4)
    NDIRECT = NDIRECT_top << NPOSTFIX
    # returns CMODE but we don't need it
    ReadContextModes(in_bits, 1)  # NBLTYPESL is 1
    NTREESL = ReadNBLTYPES(in_bits)
    if NTREESL != 1:
      assert False, 'literal context map not implemented'
    # CMAPL = [0]*(64*NBLTYPESL) but not needed
    NTREESD = ReadNBLTYPES(in_bits)
    if NTREESD != 1:
      assert False, 'distance context map not implemented'
    # CMAPD = [0]*(4*NBLTYPESD) but not needed
    # It's known that NTREESL, NBLTYPESI, NTREESD are 1, so these are 1-element
    # lists respectively.
    HTREEL = [ReadPrefixCode(in_bits, 256)]
    HTREEI = [ReadPrefixCode(in_bits, 704)]
    HTREED = [ReadPrefixCode(in_bits, 16 + NDIRECT + (48 << NPOSTFIX))]

    bytes_produced_in_meta_block = 0
    while True:
      # Don't bother decrementing/checking BLEN_I because it's huge.
      # We know there's only one possible BTYPE_I value: 0.
      insert_copy_length_symbol = huffman.ReadCodedElement(in_bits, HTREEI[0])
      ILEN, CLEN, distance_symbol_0 = ComputeInsertAndCopyLength(
          in_bits, insert_copy_length_symbol)
      for i in xrange(ILEN):
        # Don't bother decrementing/checking BLEN_L because it's huge.
        # Every element of CMAPL is 0, so there's no need to use CMODE and
        # BTYPE_L to find context mode to find context ID and CIDL.
        literal = huffman.ReadCodedElement(in_bits, HTREEL[0])
        if short or not args.only_short:
          result.PutByte(chr(literal))
        bytes_produced_in_meta_block += 1
      if bytes_produced_in_meta_block == MLEN:
        break
      assert bytes_produced_in_meta_block < MLEN

      if distance_symbol_0:
        backward_distance = last_distances.GetPrevious(1)
      else:
        # Don't bother decrementing/checking BLEN_D because it's huge.
        # Every element of CMAPD is 0, so there's no need to compute context ID,
        # CIDD from CLEN.
        distance_symbol = huffman.ReadCodedElement(in_bits, HTREED[0])
        backward_distance = ComputeDistance(distance_symbol, last_distances,
                                            NDIRECT)
        if distance_symbol != 0:
          assert backward_distance < window_size + 1, (
              'static dictionary not supported')
          last_distances.Push(backward_distance)

      assert backward_distance > 0
      if backward_distance < window_size + 1:
        if short or not args.only_short:
          result.CopyNFromBack(CLEN, backward_distance)
        bytes_produced_in_meta_block += CLEN
      else:
        assert False, 'static dictionary not supported'
      if bytes_produced_in_meta_block == MLEN:
        break
    assert bytes_produced_in_meta_block == MLEN
    if ISLAST:
      print('End of ISLAST metablock')
      ReadCheckTillBoundary(in_bits)
      break
    if short and args.only_short:
      print(result.GetBytes())
    if in_bits.BitsRead() > last_print_at + 1000000:
      print('Bits read: {}'.format(in_bits.BitsRead()))
      last_print_at = in_bits.BitsRead()
  print('All done')
  assert in_bits.TillBoundary() == 0
  assert in_bits.BitsLeft() == 0
  with open(args.out_file, 'wb') as fo:
    fo.write(result.GetBytes())

main()


text:
Reports extension properties that conflict with synthetic ones that have been automatically produced from Java get or set methods.

Such properties should be either removed or renamed to avoid breaking code by future changes in the compiler.

A quick-fix deletes an extention property.

Example:

  val File.name: String
      get() = getName()

A quick-fix adds the @Deprecated annotation:

  @Deprecated("Is replaced with automatic synthetic extension", ReplaceWith("name"), level = DeprecationLevel.HIDDEN)
  val File.name: String
      get() = getName()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="Andy Chu">
    <meta name="robots" content="noindex">

    <title>Yeah. That's a 404.</title>

    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/grayscale.css" rel="stylesheet">

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

                    Andy Chu

Yikes. Well That Escalated Quickly.

404: Page Not Found

You're definitely on the wrong page and those Tumbeasts aren't going to let those servers go.
Let's back away slowly...

                 Back to AndyChu.me

Built from the Grayscale Bootstrap Theme using Bootstrap, Font Awesome, and Thumbnail Grid with Expanding Preview.

Tumbeasts from Matthew Inman of The Oatmeal.


text:
<?php

namespace Magento\Downloadable\Api;

use Magento\Catalog\Model\Product;
use Magento\Downloadable\Model\Sample;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;

class SampleRepositoryTest extends WebapiAbstract
{
    /**
     * @var array
     */
    protected $createServiceInfo;

    /**
     * @var string
     */
    protected $testImagePath;

    /**
     * @var array
     */
    protected $updateServiceInfo;

    /**
     * @var array
     */
    protected $deleteServiceInfo;

    protected function setUp()
    {
        $this->createServiceInfo = [
            'rest' => [
                'resourcePath' => '/V1/products/downloadable-product/downloadable-links/samples',
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
            ],
            'soap' => [
                'service' => 'downloadableSampleRepositoryV1',
                'serviceVersion' => 'V1',
                'operation' => 'downloadableSampleRepositoryV1Save',
            ],
        ];

        $this->updateServiceInfo = [
            'rest' => [
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
            ],
            'soap' => [
                'service' => 'downloadableSampleRepositoryV1',
                'serviceVersion' => 'V1',
                'operation' => 'downloadableSampleRepositoryV1Save',
            ],
        ];

        $this->deleteServiceInfo = [
            'rest' => [
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
            ],
            'soap' => [
                'service' => 'downloadableSampleRepositoryV1',
                'serviceVersion' => 'V1',
                'operation' => 'downloadableSampleRepositoryV1Delete',
            ],
        ];

        $this->testImagePath = __DIR__ . str_replace('/', DIRECTORY_SEPARATOR, '/_files/test_image.jpg');
    }

    /**
     * Retrieve product that was updated by test
     *
     * @param bool $isScopeGlobal if true product store ID will be set to 0
     * @return Product
     */
    protected function getTargetProduct($isScopeGlobal = false)
    {
        if ($isScopeGlobal) {
            $product = Bootstrap::getObjectManager()->get('Magento\Catalog\Model\ProductFactory')
                ->create()->setStoreId(0)->load(1);
        } else {
            $product = Bootstrap::getObjectManager()->get('Magento\Catalog\Model\ProductFactory')->create()->load(1);
        }

        return $product;
    }

    /**
     * Retrieve product sample by its ID (or first sample if ID is not specified)
     *
     * @param Product $product
     * @param int|null $sampleId
     * @return Sample|null
     */
    protected function getTargetSample(Product $product, $sampleId = null)
    {
        $samples = $product->getExtensionAttributes()->getDownloadableProductSamples();
        if ($sampleId) {
            /* @var $sample \Magento\Downloadable\Model\Sample */
            if ($samples) {
                foreach ($samples as $sample) {
                    if ($sample->getId() == $sampleId) {
                        return $sample;
                    }
                }
            }

            return null;
        }

        // return first sample
        return $samples[0];
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     */
    public function testCreateUploadsProvidedFileContent()
    {
        $requestData = [
            'isGlobalScopeContent' => true,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Title',
                'sort_order' => 1,
                'sample_file_content' => [
                    'file_data' => base64_encode(file_get_contents($this->testImagePath)),
                    'name' => 'image.jpg',
                ],
                'sample_type' => 'file',
            ],
        ];

        $newSampleId = $this->_webApiCall($this->createServiceInfo, $requestData);
        $globalScopeSample = $this->getTargetSample($this->getTargetProduct(true), $newSampleId);
        $sample = $this->getTargetSample($this->getTargetProduct(), $newSampleId);
        $this->assertNotNull($sample);
        $this->assertNotNull($sample->getId());
        $this->assertEquals($requestData['sample']['title'], $sample->getTitle());
        $this->assertEquals($requestData['sample']['title'], $globalScopeSample->getTitle());
        $this->assertEquals($requestData['sample']['sort_order'], $sample->getSortOrder());
        $this->assertEquals($requestData['sample']['sample_type'], $sample->getSampleType());
        $this->assertStringEndsWith('.jpg', $sample->getSampleFile());
        $this->assertNull($sample->getSampleUrl());
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     */
    public function testCreateSavesTitleInStoreViewScope()
    {
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Store View Title',
                'sort_order' => 1,
                'sample_url' => 'http://www.sample.example.com/',
                'sample_type' => 'url',
            ],
        ];

        $newSampleId = $this->_webApiCall($this->createServiceInfo, $requestData);
        $sample = $this->getTargetSample($this->getTargetProduct(), $newSampleId);
        $globalScopeSample = $this->getTargetSample($this->getTargetProduct(true), $newSampleId);
        $this->assertNotNull($sample);
        $this->assertEquals($requestData['sample']['title'], $sample->getTitle());
        $this->assertEquals($requestData['sample']['sort_order'], $sample->getSortOrder());
        $this->assertEquals($requestData['sample']['sample_url'], $sample->getSampleUrl());
        $this->assertEquals($requestData['sample']['sample_type'], $sample->getSampleType());
        $this->assertEmpty($globalScopeSample->getTitle());
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     */
    public function testCreateSavesProvidedUrls()
    {
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Sample with URL resource',
                'sort_order' => 1,
                'sample_url' => 'http://www.sample.example.com/',
                'sample_type' => 'url',
            ],
        ];

        $newSampleId = $this->_webApiCall($this->createServiceInfo, $requestData);
        $sample = $this->getTargetSample($this->getTargetProduct(), $newSampleId);
        $this->assertNotNull($sample);
        $this->assertEquals($requestData['sample']['title'], $sample->getTitle());
        $this->assertEquals($requestData['sample']['sort_order'], $sample->getSortOrder());
        $this->assertEquals($requestData['sample']['sample_type'], $sample->getSampleType());
        $this->assertEquals($requestData['sample']['sample_url'], $sample->getSampleUrl());
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     * @expectedException \Exception
     * @expectedExceptionMessage Invalid sample type.
     */
    public function testCreateThrowsExceptionIfSampleTypeIsInvalid()
    {
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Sample with URL resource',
                'sort_order' => 1,
                'sample_type' => 'invalid',
            ],
        ];

        $this->_webApiCall($this->createServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     * @expectedException \Exception
     * @expectedExceptionMessage Provided content must be valid base64 encoded data.
     */
    public function testCreateThrowsExceptionIfSampleFileContentIsNotAValidBase64EncodedString()
    {
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Sample Title',
                'sort_order' => 1,
                'sample_type' => 'file',
                'sample_file_content' => [
                    'file_data' => 'not_a_base64_encoded_content',
                    'name' => 'image.jpg',
                ],
            ],
        ];

        $this->_webApiCall($this->createServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     * @expectedException \Exception
     * @expectedExceptionMessage Provided file name contains forbidden characters.
     */
    public function testCreateThrowsExceptionIfSampleFileNameContainsForbiddenCharacters()
    {
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Title',
                'sort_order' => 15,
                'sample_type' => 'file',
                'sample_file_content' => [
                    'file_data' => base64_encode(file_get_contents($this->testImagePath)),
                    'name' => 'name/with|forbidden{characters',
                ],
            ],
        ];

        $this->_webApiCall($this->createServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     * @expectedException \Exception
     * @expectedExceptionMessage Sample URL must have valid format.
     */
    public function testCreateThrowsExceptionIfSampleUrlHasWrongFormat()
    {
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Sample Title',
                'sort_order' => 1,
                'sample_type' => 'url',
                'sample_url' => 'http://example<.>com/',
            ],
        ];

        $this->_webApiCall($this->createServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable.php
     * @expectedException \Exception
     * @expectedExceptionMessage Sort order must be a positive integer.
     * @dataProvider getInvalidSortOrder
     */
    public function testCreateThrowsExceptionIfSortOrderIsInvalid($sortOrder)
    {
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'title' => 'Sample Title',
                'sort_order' => $sortOrder,
                'sample_type' => 'url',
                'sample_url' => 'http://example.com/',
            ],
        ];
        $this->_webApiCall($this->createServiceInfo, $requestData);
    }

    /**
     * @return array
     */
    public function getInvalidSortOrder()
    {
        return [
            [-1],
        ];
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php
     * @expectedException \Exception
     * @expectedExceptionMessage Provided product must be type 'downloadable'.
     */
    public function testCreateThrowsExceptionIfTargetProductTypeIsNotDownloadable()
    {
        $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/simple/downloadable-links/samples';
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'simple',
            'sample' => [
                'title' => 'Sample Title',
                'sort_order' => 50,
                'sample_type' => 'url',
                'sample_url' => 'http://example.com/',
            ],
        ];
        $this->_webApiCall($this->createServiceInfo, $requestData);
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage Requested product doesn't exist
     */
    public function testCreateThrowsExceptionIfTargetProductDoesNotExist()
    {
        $this->createServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links/samples';
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'wrong-sku',
            'sample' => [
                'title' => 'Title',
                'sort_order' => 15,
                'sample_type' => 'url',
                'sample_url' => 'http://example.com/',
            ],
        ];
        $this->_webApiCall($this->createServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
     */
    public function testUpdate()
    {
        $sampleId = $this->getTargetSample($this->getTargetProduct())->getId();
        $this->updateServiceInfo['rest']['resourcePath']
            = "/V1/products/downloadable-product/downloadable-links/samples/{$sampleId}";
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'id' => $sampleId,
                'title' => 'Updated Title',
                'sort_order' => 2,
                'sample_type' => 'url',
            ],
        ];

        $this->assertEquals($sampleId, $this->_webApiCall($this->updateServiceInfo, $requestData));
        $sample = $this->getTargetSample($this->getTargetProduct(), $sampleId);
        $this->assertNotNull($sample);
        $this->assertEquals($requestData['sample']['id'], $sample->getId());
        $this->assertEquals($requestData['sample']['title'], $sample->getTitle());
        $this->assertEquals($requestData['sample']['sort_order'], $sample->getSortOrder());
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
     */
    public function testUpdateSavesDataInGlobalScopeAndDoesNotAffectValuesStoredInStoreViewScope()
    {
        $originalSample = $this->getTargetSample($this->getTargetProduct());
        $sampleId = $originalSample->getId();
        $this->updateServiceInfo['rest']['resourcePath']
            = "/V1/products/downloadable-product/downloadable-links/samples/{$sampleId}";
        $requestData = [
            'isGlobalScopeContent' => true,
            'sku' => 'downloadable-product',
            'sample' => [
                'id' => $sampleId,
                'title' => 'Updated Title',
                'sort_order' => 2,
                'sample_type' => 'url',
            ],
        ];

        $this->assertEquals($sampleId, $this->_webApiCall($this->updateServiceInfo, $requestData));
        $sample = $this->getTargetSample($this->getTargetProduct(), $sampleId);
        $globalScopeSample = $this->getTargetSample($this->getTargetProduct(true), $sampleId);
        $this->assertNotNull($sample);
        // Title was set on store view level in fixture so it must be the same
        $this->assertEquals($originalSample->getTitle(), $sample->getTitle());
        $this->assertEquals($requestData['sample']['title'], $globalScopeSample->getTitle());
        $this->assertEquals($requestData['sample']['sort_order'], $sample->getSortOrder());
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage Requested product doesn't exist
     */
    public function testUpdateThrowsExceptionIfTargetProductDoesNotExist()
    {
        $this->updateServiceInfo['rest']['resourcePath'] = '/V1/products/wrong-sku/downloadable-links/samples/1';
        $requestData = [
            'isGlobalScopeContent' => true,
            'sku' => 'wrong-sku',
            'sample' => [
                'id' => 1,
                'title' => 'Updated Title',
                'sort_order' => 2,
                'sample_type' => 'url',
            ],
        ];
        $this->_webApiCall($this->updateServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
     * @expectedException \Exception
     * @expectedExceptionMessage There is no downloadable sample with provided ID.
     */
    public function testUpdateThrowsExceptionIfThereIsNoDownloadableSampleWithGivenId()
    {
        $sampleId = 9999;
        $this->updateServiceInfo['rest']['resourcePath']
            = "/V1/products/downloadable-product/downloadable-links/samples/{$sampleId}";
        $requestData = [
            'isGlobalScopeContent' => true,
            'sku' => 'downloadable-product',
            'sample' => [
                'id' => $sampleId,
                'title' => 'Title',
                'sort_order' => 2,
                'sample_type' => 'url',
            ],
        ];

        $this->_webApiCall($this->updateServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
     * @expectedException \Exception
     * @expectedExceptionMessage Sort order must be a positive integer.
     * @dataProvider getInvalidSortOrder
     */
    public function testUpdateThrowsExceptionIfSortOrderIsInvalid($sortOrder)
    {
        $sampleId = $this->getTargetSample($this->getTargetProduct())->getId();
        $this->updateServiceInfo['rest']['resourcePath']
            = "/V1/products/downloadable-product/downloadable-links/samples/{$sampleId}";
        $requestData = [
            'isGlobalScopeContent' => false,
            'sku' => 'downloadable-product',
            'sample' => [
                'id' => $sampleId,
                'title' => 'Updated Sample Title',
                'sort_order' => $sortOrder,
                'sample_type' => 'url',
            ],
        ];
        $this->_webApiCall($this->updateServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
     */
    public function testDelete()
    {
        $sampleId = $this->getTargetSample($this->getTargetProduct())->getId();
        $this->deleteServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-links/samples/{$sampleId}";
        $requestData = [
            'id' => $sampleId,
        ];

        $this->assertTrue($this->_webApiCall($this->deleteServiceInfo, $requestData));
        $sample = $this->getTargetSample($this->getTargetProduct(), $sampleId);
        $this->assertNull($sample);
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage There is no downloadable sample with provided ID.
     */
    public function testDeleteThrowsExceptionIfThereIsNoDownloadableSampleWithGivenId()
    {
        $sampleId = 9999;
        $this->deleteServiceInfo['rest']['resourcePath'] = "/V1/products/downloadable-links/samples/{$sampleId}";
        $requestData = [
            'id' => $sampleId,
        ];

        $this->_webApiCall($this->deleteServiceInfo, $requestData);
    }

    /**
     * @magentoApiDataFixture Magento/Downloadable/_files/product_downloadable_with_files.php
     * @dataProvider getListForAbsentProductProvider
     */
    public function testGetList($urlTail, $method, $expectations)
    {
        $sku = 'downloadable-product';

        $serviceInfo = [
            'rest' => [
                'resourcePath' => '/V1/products/' . $sku . $urlTail,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => 'downloadableSampleRepositoryV1',
                'serviceVersion' => 'V1',
                'operation' => 'downloadableSampleRepositoryV1' . $method,
            ],
        ];

        $requestData = ['sku' => $sku];

        $list = $this->_webApiCall($serviceInfo, $requestData);

        $this->assertEquals(1, count($list));

        $link = reset($list);
        foreach ($expectations['fields'] as $index => $value) {
            $this->assertEquals($value, $link[$index]);
        }
        $this->assertNotEmpty($link['sample_file']);
    }

    public function getListForAbsentProductProvider()
    {
        $sampleExpectation = [
            'fields' => [
                'title' => 'Downloadable Product Sample Title',
                'sort_order' => 0,
                'sample_type' => 'file'
            ]
        ];

        return [
            'samples' => [
                '/downloadable-links/samples',
                'GetList',
                $sampleExpectation,
            ],
        ];
    }
}