text:
#include "dis-intern.h"

/*
 * Immediate fields
 */

static struct bitfield bfsrcposoff = { 17, 5 };
static struct bitfield bfszoff = { 22, 5 };
static struct bitfield bfdstposoff = { 27, 5 };
static struct rbitfield mimmoff = { { 14, 18 }, BF_SIGNED };
static struct rbitfield btargoff = { { 14, 18 }, BF_SIGNED, .pcrel = 1 };
#define BFSRCPOS atomimm, &bfsrcposoff
#define BFDSTPOS atomimm, &bfdstposoff
#define BFSZ atomimm, &bfszoff
#define MIMM atomrimm, &mimmoff
#define BTARG atombtarg, &btargoff

/*
 * Register fields
 */

static struct sreg reg_sr[] = {
	{ 0, 0, SR_ZERO },
	{ -1 },
};
static struct bitfield reg1_bf = { 8, 3 };
static struct bitfield reg2_bf = { 11, 3 };
static struct bitfield reg3_bf = { 14, 3 };
static struct reg reg1_r = { &reg1_bf, "r", .specials = reg_sr };
static struct reg reg2_r = { &reg2_bf, "r", .specials = reg_sr };
static struct reg reg3_r = { &reg3_bf, "r", .specials = reg_sr };
#define REG1 atomreg, &reg1_r
#define REG2 atomreg, &reg2_r
#define REG3 atomreg, &reg3_r

/*
 * The Fermi PGRAPH MACRO ISA.
 *
 * Code space is 0x800 32-bit words long and part of PGRAPH context. Code
 * addresses are counted in 32-bit words.  The MACRO unit sits between PFIFO
 * and PGRAPH_DISPATCH. It processes the following methods:
 *
 *  - 0x114: set upload address [in words]
 *  - 0x118: upload a single word of code to current upload index, increment
 *           the index
 *  - 0x11c: set binding macro index
 *  - 0x120: bind macro specified by 0x11c to code starting at given address
 *  - 0x3800+i*8: launch macro #i [XXX: check range]
 *  - 0x3804+i*8: send an extra param
 *  - any other: pass through to DISPATCH unchanged
 *
 * There are 8 GPRs, $r0-$r7, $r0 is hardwired to 0. $r1 is set on launch to
 * the data sent to the 0x3800+i*8 method that caused the launch. There's
 * a carry flag for adc and sbb opcodes.
 *
 * The state also includes "current method address" and "current method
 * increment". They're both set using various "maddr" ops as listed below -
 * bits 0-11 of operand are shifted left by 2 and become the method address,
 * bits 12-17 are shifted left by 2 and become the increment. Other bits
 * are ignored. A "send" op sends a method specified by the current address
 * with the param used as data, then increments current address by current
 * increment.
 *
 * A macro is also allowed to submit method reads. This is done by using
 * the read op. The operand's bits 0-11 are shifted left by 2 and used as
 * method address to read.
 *
 * A macro can also pull extra parameters by the "parm" op and its variations.
 * "parm" will wait until a 0x3804+i*8 method is submitted from PFIFO and load
 * its data to the destination. If an unconsumed parameter remains after macro
 * exits, or if a non-3804 method is submitted while macro is waiting for
 * a parameter, a trap occurs.
 *
 * As for flow control, there are branch on zero / non-zero instructions, and
 * every instruction can be marked with the "exit" modifier which causes the
 * macro to end. Normal branches and "exit" have delay slots - they don't
 * actually take effect until the next instruction finishes. Branches also
 * have "annul" variants which don't have delay slots. Combining "exit" with
 * a branch is a special case: the exit happens if and only if the branch
 * is not taken. It's an error to use a branch in a delay slot.
 *
 * Stuff marked SC below is not actually a separate instruction, just
 * a special case of a more generic insn.
 */

F1(exit, 7, N("exit"));

/* various stuff that can be done to result of arith/logic operations */
static struct insn tabdst[] = {
	{ 0x00000000, 0x00000070, N("parm"), REG1, N("ign") },	// ignore result, fetch param to REG1
	{ 0x00000010, 0x00000070, N("mov"), REG1 },			// store result to REG1
	{ 0x00000020, 0x00000770, N("maddr") }, // SC
	{ 0x00000020, 0x00000070, N("maddr"), REG1 },		// use result as maddr and store it to REG1
	{ 0x00000030, 0x00000070, N("parm"), REG1, N("send") },	// send result, then fetch param to REG1
	{ 0x00000040, 0x00000770, N("send") }, // SC
	{ 0x00000040, 0x00000070, N("send"), REG1 },		// send result and store it to REG1
	{ 0x00000050, 0x00000070, N("parm"), REG1, N("maddr") },	// use result as maddr, then fetch param to REG1
	{ 0x00000060, 0x00000770, N("parmsend"), N("maddr") }, // SC
	{ 0x00000060, 0x00000070, N("parmsend"), N("maddr"), REG1 },// use result as maddr and store it to REG1, then fetch param and send it.
	{ 0x00000070, 0x00000770, N("maddrsend") }, // SC
	{ 0x00000070, 0x00000070, N("maddrsend"), REG1 },		// use result as maddr, then send bits 12-17 of result, then store result to REG1
	{ 0, 0, OOPS },
};

F1(annul, 5, N("annul")); // if set, delay slot insn is annuled if branch taken [ie. branch behaves as if delay slots didn't exist]

static struct insn tabm[] = {
	{ 0x00000000, 0x003e0007, T(dst), SESTART, N("add"), REG2, REG3, SEEND },
	{ 0x00020000, 0x003e0007, T(dst), SESTART, N("adc"), REG2, REG3, SEEND },
	{ 0x00040000, 0x003e0007, T(dst), SESTART, N("sub"), REG2, REG3, SEEND },
	{ 0x00060000, 0x003e0007, T(dst), SESTART, N("sbb"), REG2, REG3, SEEND },
	{ 0x00100000, 0x003e0007, T(dst), SESTART, N("xor"), REG2, REG3, SEEND },
	{ 0x00120000, 0x003e0007, T(dst), SESTART, N("or"), REG2, REG3, SEEND },
	{ 0x00140000, 0x003e0007, T(dst), SESTART, N("and"), REG2, REG3, SEEND },
	{ 0x00160000, 0x003e0007, T(dst), SESTART, N("andn"), REG2, REG3, SEEND }, // REG2 & ~REG3
	{ 0x00180000, 0x003e0007, T(dst), SESTART, N("nand"), REG2, REG3, SEEND }, // ~(REG2 & REG3)
	{ 0x00000011, 0xffffffff, N("nop") }, // SC
	{ 0x00000091, 0xffffffff }, // SC [just exit]
	{ 0x00000001, 0xfffff87f, N("parm"), REG1 }, // SC
	{ 0x00000001, 0x00003807, T(dst), MIMM }, // SC
	{ 0x00000001, 0xffffc007, T(dst), REG2 }, // SC
	{ 0x00000001, 0x00000007, T(dst), SESTART, N("add"), REG2, MIMM, SEEND },
	// take REG2, replace BFSZ bits starting at BFDSTPOS with BFSZ bits starting at BFSRCPOS in REG3.
	{ 0x00000002, 0x00000007, T(dst), SESTART, N("extrinsrt"), REG2, REG3, BFSRCPOS, BFSZ, BFDSTPOS, SEEND },
	// take BFSZ bits starting at REG2 in REG3, shift left by BFDSTPOS
	{ 0x00000003, 0x00000007, T(dst), SESTART, N("extrshl"), REG3, REG2, BFSZ, BFDSTPOS, SEEND },
	// take BFSZ bits starting at BFSRCPOS in REG3, shift left by REG2
	{ 0x00000004, 0x00000007, T(dst), SESTART, N("extrshl"), REG3, BFSRCPOS, BFSZ, REG2, SEEND },
	{ 0x00000015, 0x00003877, N("read"), REG1, MIMM }, // SC
	{ 0x00000015, 0x00000077, N("read"), REG1, SESTART, N("add"), REG2, MIMM, SEEND },
	{ 0x00000007, 0x00003817, N("bra"), T(annul), BTARG },
	{ 0x00000007, 0x00000017, N("braz"), T(annul), REG2, BTARG },
	{ 0x00000017, 0x00000017, N("branz"), T(annul), REG2, BTARG },
	{ 0, 0, T(dst), OOPS, REG2 },
};

static struct insn tabroot[] = {
	{ 0, 0, OP1B, T(exit), T(m) },
};

struct disisa macro_isa_s = {
	tabroot,
	1,
	1,
	4,
};


text:
package org.robolectric.shadows;

import static android.bluetooth.BluetoothDevice.BOND_NONE;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
import static org.robolectric.shadow.api.Shadow.directlyOn;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.IBluetooth;
import android.content.Context;
import android.os.ParcelUuid;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;

@Implements(BluetoothDevice.class)
public class ShadowBluetoothDevice {

  public static BluetoothDevice newInstance(String address) {
    return ReflectionHelpers.callConstructor(
        BluetoothDevice.class, ReflectionHelpers.ClassParameter.from(String.class, address));
  }

  @RealObject private BluetoothDevice realBluetoothDevice;
  private String name;
  private ParcelUuid[] uuids;
  private int bondState = BOND_NONE;
  private boolean createdBond = false;
  private boolean fetchUuidsWithSdpResult = false;
  private int fetchUuidsWithSdpCount = 0;
  private int type = BluetoothDevice.DEVICE_TYPE_UNKNOWN;

  /**
   * Implements getService() in the same way the original method does, but ignores any Exceptions
   * from invoking {@link android.bluetooth.BluetoothAdapter#getBluetoothService}.
   */
  @Implementation
  protected static IBluetooth getService() {
    // Attempt to call the underlying getService method, but ignore any Exceptions. This allows us
    // to easily create BluetoothDevices for testing purposes without having any actual Bluetooth
    // capability.
    try {
      return directlyOn(BluetoothDevice.class, "getService");
    } catch (Exception e) {
      // No-op.
    }
    return null;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Implementation
  protected String getName() {
    return name;
  }

  /** Sets the return value for {@link BluetoothDevice#getType}. */
  public void setType(int type) {
    this.type = type;
  }

  /**
   * Overrides behavior of {@link BluetoothDevice#getType} to return pre-set result.
   *
   * @return Value set by calling {@link ShadowBluetoothDevice#setType}. If setType has not
   *     previously been called, will return BluetoothDevice.DEVICE_TYPE_UNKNOWN.
   */
  @Implementation(minSdk = JELLY_BEAN_MR2)
  protected int getType() {
    return type;
  }

  /** Sets the return value for {@link BluetoothDevice#getUuids}. */
  public void setUuids(ParcelUuid[] uuids) {
    this.uuids = uuids;
  }

  /**
   * Overrides behavior of {@link BluetoothDevice#getUuids} to return pre-set result.
   *
   * @returns Value set by calling {@link ShadowBluetoothDevice#setUuids}. If setUuids has not
   *     previously been called, will return null.
   */
  @Implementation
  protected ParcelUuid[] getUuids() {
    return uuids;
  }

  /** Sets value of bond state for {@link BluetoothDevice#getBondState}. */
  public void setBondState(int bondState) {
    this.bondState = bondState;
  }

  /**
   * Overrides behavior of {@link BluetoothDevice#getBondState} to return pre-set result.
   *
   * @returns Value set by calling {@link ShadowBluetoothDevice#setBondState}. If setBondState has
   *     not previously been called, will return {@link BluetoothDevice#BOND_NONE} to indicate the
   *     device is not bonded.
   */
  @Implementation
  protected int getBondState() {
    return bondState;
  }

  /** Sets whether this device has been bonded with. */
  public void setCreatedBond(boolean createdBond) {
    this.createdBond = createdBond;
  }

  /** Returns whether this device has been bonded with. */
  @Implementation
  protected boolean createBond() {
    return createdBond;
  }

  /** Sets value of the return result for {@link BluetoothDevice#fetchUuidsWithSdp}. */
  public void setFetchUuidsWithSdpResult(boolean fetchUuidsWithSdpResult) {
    this.fetchUuidsWithSdpResult = fetchUuidsWithSdpResult;
  }

  /**
   * Overrides behavior of {@link BluetoothDevice#fetchUuidsWithSdp}. This method updates the
   * counter which counts the number of invocations of this method.
   *
   * @returns Value set by calling {@link ShadowBluetoothDevice#setFetchUuidsWithSdpResult}. If not
   *     previously set, will return false by default.
   */
  @Implementation
  protected boolean fetchUuidsWithSdp() {
    fetchUuidsWithSdpCount++;
    return fetchUuidsWithSdpResult;
  }

  /** Returns the number of times fetchUuidsWithSdp has been called. */
  public int getFetchUuidsWithSdpCount() {
    return fetchUuidsWithSdpCount;
  }

  @Implementation(minSdk = JELLY_BEAN_MR2)
  protected BluetoothGatt connectGatt(
      Context context, boolean autoConnect, BluetoothGattCallback callback) {
    return ShadowBluetoothGatt.newInstance(realBluetoothDevice);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Minsal\shcpBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MntExpedienteEstablecimiento
 *
 * @ORM\Table(name="mnt_expediente_establecimiento", indexes={@ORM\Index(name="IDX_8715ED227DFA12F6", columns={"id_establecimiento"})})
 * @ORM\Entity
 */
class MntExpedienteEstablecimiento
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="mnt_expediente_establecimiento_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="id_paciente_inicial", type="bigint", nullable=true)
     */
    private $idPacienteInicial;

    /**
     * @var integer
     *
     * @ORM\Column(name="id_paciente_siap_local", type="bigint", nullable=true)
     */
    private $idPacienteSiapLocal;

    /**
     * @var integer
     *
     * @ORM\Column(name="id_numero_expediente", type="bigint", nullable=true)
     */
    private $idNumeroExpediente;

    /**
     * @var \CtlEstablecimiento
     *
     * @ORM\ManyToOne(targetEntity="CtlEstablecimiento")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_establecimiento", referencedColumnName="id")
     * })
     */
    private $idEstablecimiento;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set idPacienteInicial
     *
     * @param integer $idPacienteInicial
     * @return MntExpedienteEstablecimiento
     */
    public function setIdPacienteInicial($idPacienteInicial)
    {
        $this->idPacienteInicial = $idPacienteInicial;

        return $this;
    }

    /**
     * Get idPacienteInicial
     *
     * @return integer
     */
    public function getIdPacienteInicial()
    {
        return $this->idPacienteInicial;
    }

    /**
     * Set idPacienteSiapLocal
     *
     * @param integer $idPacienteSiapLocal
     * @return MntExpedienteEstablecimiento
     */
    public function setIdPacienteSiapLocal($idPacienteSiapLocal)
    {
        $this->idPacienteSiapLocal = $idPacienteSiapLocal;

        return $this;
    }

    /**
     * Get idPacienteSiapLocal
     *
     * @return integer
     */
    public function getIdPacienteSiapLocal()
    {
        return $this->idPacienteSiapLocal;
    }

    /**
     * Set idNumeroExpediente
     *
     * @param integer $idNumeroExpediente
     * @return MntExpedienteEstablecimiento
     */
    public function setIdNumeroExpediente($idNumeroExpediente)
    {
        $this->idNumeroExpediente = $idNumeroExpediente;

        return $this;
    }

    /**
     * Get idNumeroExpediente
     *
     * @return integer
     */
    public function getIdNumeroExpediente()
    {
        return $this->idNumeroExpediente;
    }

    /**
     * Set idEstablecimiento
     *
     * @param \Minsal\shcpBundle\Entity\CtlEstablecimiento $idEstablecimiento
     * @return MntExpedienteEstablecimiento
     */
    public function setIdEstablecimiento(\Minsal\shcpBundle\Entity\CtlEstablecimiento $idEstablecimiento = null)
    {
        $this->idEstablecimiento = $idEstablecimiento;

        return $this;
    }

    /**
     * Get idEstablecimiento
     *
     * @return \Minsal\shcpBundle\Entity\CtlEstablecimiento
     */
    public function getIdEstablecimiento()
    {
        return $this->idEstablecimiento;
    }
}


text:
package com.firelizzard.firecraft.initialization;

import com.firelizzard.firecraft.api.Initialization;
import com.firelizzard.firecraft.gui.SecureItemSinkInHand;
import com.firelizzard.firecraft.gui.SecureItemSinkSlot;
import com.firelizzard.firecraft.logistics.DisenchantModule;
import com.firelizzard.firecraft.logistics.EnergyItemSinkModule;
import com.firelizzard.firecraft.logistics.SecureItemSinkModule;
import com.firelizzard.firecraft.network.SecureItemSinkMode;
import com.firelizzard.firecraft.network.SecureItemSinkPacket;

import logisticspipes.LogisticsPipes;
import logisticspipes.network.NewGuiHandler;
import logisticspipes.network.PacketHandler;
import logisticspipes.network.abstractguis.GuiProvider;
import logisticspipes.network.abstractpackets.ModernPacket;

@Initialization
public class FireCraftLogisticsIntegration {
//	public static final SecureItemSinkModule module = new SecureItemSinkModule();

	@Initialization.Post
	public static void postInit() {
		LogisticsPipes.ModuleItem.registerModule(1000, SecureItemSinkModule.class);
		LogisticsPipes.ModuleItem.registerModule(1001, EnergyItemSinkModule.class);
		LogisticsPipes.ModuleItem.registerModule(1002, DisenchantModule.class);

		int cid1 = NewGuiHandler.guilist.size();

		GuiProvider inst1 = new SecureItemSinkInHand(cid1++);
		NewGuiHandler.guilist.add(inst1);
		NewGuiHandler.guimap.put(SecureItemSinkInHand.class, inst1);

		inst1 = new SecureItemSinkSlot(cid1++);
		NewGuiHandler.guilist.add(inst1);
		NewGuiHandler.guimap.put(SecureItemSinkSlot.class, inst1);

		int cid2 = PacketHandler.packetlist.size();

		ModernPacket inst2 = new SecureItemSinkMode(cid2++);
		PacketHandler.packetlist.add(inst2);
		PacketHandler.packetmap.put(SecureItemSinkMode.class, inst2);

		inst2 = new SecureItemSinkPacket(cid2++);
		PacketHandler.packetlist.add(inst2);
		PacketHandler.packetmap.put(SecureItemSinkPacket.class, inst2);
	}
}


text:
<?php
namespace R4F\SiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use R4F\SiteBundle\Entity\Message;
use R4F\SiteBundle\Form\MessageType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class MessageController extends Controller
{
    /**
     * @Template()
     */
    public function listMessagesAction($id)
    {
        $messages = $this->getDoctrine()
            ->getRepository('R4FSiteBundle:Message')
            ->getMessages($id)
        ;

        return array('messages' => $messages);
    }

    /**
     * @Template()
     */
    public function indexAction($id)
    {
        $message = new Message;
        $form = $this->createForm(new MessageType, $message);
        $validator = $this->get('validator');
        $liste_erreurs = $validator->validate($message);
        $request = $this->get('request');
        $course = $this->getDoctrine()
                    ->getEntityManager()
                    ->getRepository('R4FSiteBundle:Course')
                    ->find($id)
        ;

        if( $request->getMethod() == 'POST' )
        {
            $form->bindRequest($request);
            if( $form->isValid() )
            {
                $em = $this->getDoctrine()->getEntityManager();

                $user = $this->container->get('security.context')->getToken()->getUser();
                $message->setUser($user);
                $message->setCourse($course);

                $em->persist($message);
                $em->flush();

                $this->get('session')->setFlash('notice', 'Your message is sended');

            }
        }

        return $this->render('R4FSiteBundle:Message:index.html.twig', array(
            'form' => $form->createView(),
            'course' => $course,
        ));

    }
}


text:
using System.Web.Mvc;
using MyPersonalBlog.Infrastructure;
using MyPersonalBlog.Models;

namespace MyPersonalBlog.Areas.Admin.Controllers
{
    [Authorize]
    public class SettingsController : Controller
    {
        ISettingsProvider _settingsProvider;

        public SettingsController(ISettingsProvider settingsProvider)
        {
            _settingsProvider = settingsProvider;
        }

        public ViewResult Index()
        {

            Settings settings = _settingsProvider.GetSettings();

            return View("Edit", settings);
        }

        [HttpPost]
        public ActionResult Save(Settings settings)
        {
            if (ModelState.IsValid)
            {
                _settingsProvider.SaveSettings(settings);

                return RedirectToAction("Index", "Settings");
            }

            return View("Edit", settings);
        }
    }
}


text:
{% load compress %}
{% load staticfiles %}
{% load i18n %}
<!DOCTYPE html>

		<title>{% block title %}{% endblock %}{% if url_name != "index" %} :: {% endif %}
            {{ settings.PRETIX_INSTANCE_NAME }}</title>
		{% compress css %}
    		<link rel="stylesheet" type="text/less" href="{% static "pretixcontrol/less/main.less" %}" />
		{% endcompress %}
		{% compress js %}

		{% endcompress %}
        {{ html_head|safe }}
        <meta name="viewport" content="width=device-width, initial-scale=1">

                    <button type="button" class="navbar-toggle"
                            data-toggle="collapse" data-target=".navbar-nav-collapse">
                        {% trans "Toggle navigation" %}

                    </button>
                    <button type="button" class="navbar-toggle navbar-events"
                            data-toggle="collapse" data-target=".navbar-events-collapse">

                    </button>
                    {{ settings.PRETIX_INSTANCE_NAME }}

                            {{ request.event }}

{% trans "Event overview" %}

                            {% regroup request.user.events_cache by organizer as event_list %}
                            {% for g in event_list %}

{{ g.grouper }}

                                {% for e in g.list %}

{{ e.name }}

                                {% endfor %}
                            {% endfor %}

                             {{ request.user.get_full_name }}

                            {% trans "Log out" %}

{% trans "Event overview" %}

                            {% for e in request.user.events_cache %}

                                        {{ e.name }}

                            {% endfor %}

                            {% block nav %}

                                        {% trans "Dashboard" %}

                                        {% trans "Events" %}

                                        {% trans "Organizers" %}

                            {% endblock %}

                    {% if messages %}
                        {% for message in messages %}

                                {{ message }}

                        {% endfor %}
                    {% endif %}

                    {% block content %}
                    {% endblock %}

                        {% with "href='http://pretix.eu'" as a_attr %}
                            {% blocktrans trimmed %}
                                powered by pretix
                            {% endblocktrans %}
                        {% endwith %}


text:
package me.kutan.korn.blog.model;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.util.Date;

/**
 * Project: korn-blog
 * Author: Korn Kutan <korn@kutan.me>
 * Date: 4/11/2015
 */

@Data
@Entity
@Table(name = "ENTRIES")
@EqualsAndHashCode(callSuper = false)
public class Entry extends BaseEntity {

    @Id
    @GeneratedValue(strategy= GenerationType.SEQUENCE)
    private Long id;

    @Column(name = "slug", nullable = false, unique = true)
    private String slug;

    @Column(name = "title", nullable = false)
    private String title;

    @Column(name = "body", columnDefinition = "TEXT")
    private String body;

    @Column(name = "markdown", columnDefinition = "TEXT")
    private String markdown;

    @Column(name = "type")
    private String type;

    @Column(name = "is_published")
    private boolean published;

    @Column(name = "published_date")
    private Date publishedDate;

    public Entry() {
    }

    public Entry(String title, String slug, Date updatedDate) {
        this.title = title;
        this.slug  = slug;
        setUpdatedDate(updatedDate);
    }

    public Entry(String title, String slug, Date updatedDate, Date publishedDate) {
        this.title = title;
        this.slug  = slug;
        this.publishedDate = publishedDate;
        setUpdatedDate(updatedDate);
    }
}


text:
class GalleryController < ApplicationController

  before_filter :login_required, :except => [:index, :list, :album]

  def index
    list
    render :action=>"list"
  end

  def list
    @photos = Photo.find :all, :order=>"position DESC"
    @albums = Album.find :all
  end

  def album
    @albums = Album.find :all
    @album = Album.find params[:id]
    @photos = @album.photos
    render :action=>"list"
  end

  def new
    @photo = Photo.new(params[:photo])
    if request.post?
      if @photo.valid? and !params[:file].nil?
        @photo.user_id = session[:user]
        @photo.save
        @photo.write(params[:file])
        flash[:notice] = 'Photo was successfully created.'
        redirect_to :action => 'list'
      else
        flash[:notice] = 'Please specify a file' if params[:file].nil?
      end
    end
  end

  def edit
    @photo = Photo.find(params[:id])
    if request.post? and @photo.update_attributes(params[:photo])
      @photo.write(params[:file]) unless params[:file].nil?
      flash[:notice] = 'Photo was successfully updated.'
      redirect_to :action => 'list'
    end
  end

  def destroy
    @photo = Photo.find(params[:id].split("_")[1])
    @photo.destroy
    @photos = Photo.find :all
    render :partial=>"gallery/photo", :collection=>@photos
  end
end


text:
file(REMOVE_RECURSE
  "CMakeFiles/src.dir/creature_example.cpp.o"
  "CMakeFiles/src.dir/event_broker.cpp.o"
  "src"
  "src.pdb"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/src.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
"""Google Cloud Storage client.

This library evolved from the Google App Engine GCS client available at
https://github.com/GoogleCloudPlatform/appengine-gcs-client.
"""

from __future__ import absolute_import

import errno
import io
import logging
import multiprocessing
import os
import re
import threading
import time
import traceback
from builtins import object

import httplib2

from apache_beam.io.filesystemio import Downloader
from apache_beam.io.filesystemio import DownloaderStream
from apache_beam.io.filesystemio import PipeStream
from apache_beam.io.filesystemio import Uploader
from apache_beam.io.filesystemio import UploaderStream
from apache_beam.utils import retry

__all__ = ['GcsIO']

# Issue a friendlier error message if the storage library is not available.
# TODO(silviuc): Remove this guard when storage is available everywhere.
try:
  # pylint: disable=wrong-import-order, wrong-import-position
  # pylint: disable=ungrouped-imports
  import apitools.base.py.transfer as transfer
  from apitools.base.py.batch import BatchApiRequest
  from apitools.base.py.exceptions import HttpError
  from apache_beam.internal.gcp import auth
  from apache_beam.io.gcp.internal.clients import storage
except ImportError:
  raise ImportError(
      'Google Cloud Storage I/O not supported for this execution environment '
      '(could not import storage API client).')

# This is the size of each partial-file read operation from GCS.  This
# parameter was chosen to give good throughput while keeping memory usage at
# a reasonable level; the following table shows throughput reached when
# reading files of a given size with a chosen buffer size and informed the
# choice of the value, as of 11/2016:
#
# +---------------+------------+-------------+-------------+-------------+
# |               | 50 MB file | 100 MB file | 200 MB file | 400 MB file |
# +---------------+------------+-------------+-------------+-------------+
# | 8 MB buffer   | 17.12 MB/s | 22.67 MB/s  | 23.81 MB/s  | 26.05 MB/s  |
# | 16 MB buffer  | 24.21 MB/s | 42.70 MB/s  | 42.89 MB/s  | 46.92 MB/s  |
# | 32 MB buffer  | 28.53 MB/s | 48.08 MB/s  | 54.30 MB/s  | 54.65 MB/s  |
# | 400 MB buffer | 34.72 MB/s | 71.13 MB/s  | 79.13 MB/s  | 85.39 MB/s  |
# +---------------+------------+-------------+-------------+-------------+
DEFAULT_READ_BUFFER_SIZE = 16 * 1024 * 1024

# This is the number of seconds the library will wait for GCS operations to
# complete.
DEFAULT_HTTP_TIMEOUT_SECONDS = 60

# This is the number of seconds the library will wait for a partial-file read
# operation from GCS to complete before retrying.
DEFAULT_READ_SEGMENT_TIMEOUT_SECONDS = 60

# This is the size of chunks used when writing to GCS.
WRITE_CHUNK_SIZE = 8 * 1024 * 1024

# Maximum number of operations permitted in GcsIO.copy_batch() and
# GcsIO.delete_batch().
MAX_BATCH_OPERATION_SIZE = 100

# Batch endpoint URL for GCS.
# We have to specify an API specific endpoint here since Google APIs global
# batch endpoints will be deprecated on 03/25/2019.
# See https://developers.googleblog.com/2018/03/discontinuing-support-for-json-rpc-and.html.  # pylint: disable=line-too-long
# Currently apitools library uses a global batch endpoint by default:
# https://github.com/google/apitools/blob/master/apitools/base/py/batch.py#L152
# TODO: remove this constant and it's usage after apitools move to using an API
# specific batch endpoint or after Beam gcsio module start using a GCS client
# library that does not use global batch endpoints.
GCS_BATCH_ENDPOINT = 'https://www.googleapis.com/batch/storage/v1'

def proxy_info_from_environment_var(proxy_env_var):
  """Reads proxy info from the environment and converts to httplib2.ProxyInfo.

  Args:
    proxy_env_var: environment variable string to read, http_proxy or
       https_proxy (in lower case).
       Example: http://myproxy.domain.com:8080

  Returns:
    httplib2.ProxyInfo constructed from the environment string.
  """
  proxy_url = os.environ.get(proxy_env_var)
  if not proxy_url:
    return None
  proxy_protocol = proxy_env_var.lower().split('_')[0]
  if not re.match('^https?://', proxy_url, flags=re.IGNORECASE):
    logging.warn("proxy_info_from_url requires a protocol, which is always "
                 "http or https.")
    proxy_url = proxy_protocol + '://' + proxy_url
  return httplib2.proxy_info_from_url(proxy_url, method=proxy_protocol)

def get_new_http():
  """Creates and returns a new httplib2.Http instance.

  Returns:
    An initialized httplib2.Http instance.
  """
  proxy_info = None
  for proxy_env_var in ['http_proxy', 'https_proxy']:
    if os.environ.get(proxy_env_var):
      proxy_info = proxy_info_from_environment_var(proxy_env_var)
      break
  # Use a non-infinite SSL timeout to avoid hangs during network flakiness.
  return httplib2.Http(proxy_info=proxy_info,
                       timeout=DEFAULT_HTTP_TIMEOUT_SECONDS)

def parse_gcs_path(gcs_path, object_optional=False):
  """Return the bucket and object names of the given gs:// path."""
  match = re.match('^gs://([^/]+)/(.*)$', gcs_path)
  if match is None or (match.group(2) == '' and not object_optional):
    raise ValueError('GCS path must be in the form gs://<bucket>/<object>.')
  return match.group(1), match.group(2)

class GcsIOError(IOError, retry.PermanentException):
  """GCS IO error that should not be retried."""
  pass

class GcsIO(object):
  """Google Cloud Storage I/O client."""

  def __new__(cls, storage_client=None):
    if storage_client:
      # This path is only used for testing.
      return super(GcsIO, cls).__new__(cls)
    else:
      # Create a single storage client for each thread.  We would like to avoid
      # creating more than one storage client for each thread, since each
      # initialization requires the relatively expensive step of initializing
      # credentaials.
      local_state = threading.local()
      if getattr(local_state, 'gcsio_instance', None) is None:
        credentials = auth.get_service_credentials()
        storage_client = storage.StorageV1(
            credentials=credentials,
            get_credentials=False,
            http=get_new_http())
        local_state.gcsio_instance = super(GcsIO, cls).__new__(cls)
        local_state.gcsio_instance.client = storage_client
      return local_state.gcsio_instance

  def __init__(self, storage_client=None):
    # We must do this check on storage_client because the client attribute may
    # have already been set in __new__ for the singleton case when
    # storage_client is None.
    if storage_client is not None:
      self.client = storage_client

  def open(self,
           filename,
           mode='r',
           read_buffer_size=DEFAULT_READ_BUFFER_SIZE,
           mime_type='application/octet-stream'):
    """Open a GCS file path for reading or writing.

    Args:
      filename (str): GCS file path in the form ``gs://<bucket>/<object>``.
      mode (str): ``'r'`` for reading or ``'w'`` for writing.
      read_buffer_size (int): Buffer size to use during read operations.
      mime_type (str): Mime type to set for write operations.

    Returns:
      GCS file object.

    Raises:
      ~exceptions.ValueError: Invalid open file mode.
    """
    if mode == 'r' or mode == 'rb':
      downloader = GcsDownloader(self.client, filename,
                                 buffer_size=read_buffer_size)
      return io.BufferedReader(DownloaderStream(downloader, mode=mode),
                               buffer_size=read_buffer_size)
    elif mode == 'w' or mode == 'wb':
      uploader = GcsUploader(self.client, filename, mime_type)
      return io.BufferedWriter(UploaderStream(uploader, mode=mode),
                               buffer_size=128 * 1024)
    else:
      raise ValueError('Invalid file open mode: %s.' % mode)

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def delete(self, path):
    """Deletes the object at the given GCS path.

    Args:
      path: GCS file path pattern in the form gs://<bucket>/<name>.
    """
    bucket, object_path = parse_gcs_path(path)
    request = storage.StorageObjectsDeleteRequest(
        bucket=bucket, object=object_path)
    try:
      self.client.objects.Delete(request)
    except HttpError as http_error:
      if http_error.status_code == 404:
        # Return success when the file doesn't exist anymore for idempotency.
        return
      raise

  # We intentionally do not decorate this method with a retry, as retrying is
  # handled in BatchApiRequest.Execute().
  def delete_batch(self, paths):
    """Deletes the objects at the given GCS paths.

    Args:
      paths: List of GCS file path patterns in the form gs://<bucket>/<name>,
             not to exceed MAX_BATCH_OPERATION_SIZE in length.

    Returns: List of tuples of (path, exception) in the same order as the paths
             argument, where exception is None if the operation succeeded or
             the relevant exception if the operation failed.
    """
    if not paths:
      return []
    batch_request = BatchApiRequest(
        batch_url=GCS_BATCH_ENDPOINT,
        retryable_codes=retry.SERVER_ERROR_OR_TIMEOUT_CODES)
    for path in paths:
      bucket, object_path = parse_gcs_path(path)
      request = storage.StorageObjectsDeleteRequest(
          bucket=bucket, object=object_path)
      batch_request.Add(self.client.objects, 'Delete', request)
    api_calls = batch_request.Execute(self.client._http) # pylint: disable=protected-access
    result_statuses = []
    for i, api_call in enumerate(api_calls):
      path = paths[i]
      exception = None
      if api_call.is_error:
        exception = api_call.exception
        # Return success when the file doesn't exist anymore for idempotency.
        if isinstance(exception, HttpError) and exception.status_code == 404:
          exception = None
      result_statuses.append((path, exception))
    return result_statuses

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def copy(self, src, dest):
    """Copies the given GCS object from src to dest.

    Args:
      src: GCS file path pattern in the form gs://<bucket>/<name>.
      dest: GCS file path pattern in the form gs://<bucket>/<name>.
    """
    src_bucket, src_path = parse_gcs_path(src)
    dest_bucket, dest_path = parse_gcs_path(dest)
    request = storage.StorageObjectsCopyRequest(
        sourceBucket=src_bucket,
        sourceObject=src_path,
        destinationBucket=dest_bucket,
        destinationObject=dest_path)
    self.client.objects.Copy(request)

  # We intentionally do not decorate this method with a retry, as retrying is
  # handled in BatchApiRequest.Execute().
  def copy_batch(self, src_dest_pairs):
    """Copies the given GCS object from src to dest.

    Args:
      src_dest_pairs: list of (src, dest) tuples of gs://<bucket>/<name> files
                      paths to copy from src to dest, not to exceed
                      MAX_BATCH_OPERATION_SIZE in length.

    Returns: List of tuples of (src, dest, exception) in the same order as the
             src_dest_pairs argument, where exception is None if the operation
             succeeded or the relevant exception if the operation failed.
    """
    if not src_dest_pairs:
      return []
    batch_request = BatchApiRequest(
        batch_url=GCS_BATCH_ENDPOINT,
        retryable_codes=retry.SERVER_ERROR_OR_TIMEOUT_CODES)
    for src, dest in src_dest_pairs:
      src_bucket, src_path = parse_gcs_path(src)
      dest_bucket, dest_path = parse_gcs_path(dest)
      request = storage.StorageObjectsCopyRequest(
          sourceBucket=src_bucket,
          sourceObject=src_path,
          destinationBucket=dest_bucket,
          destinationObject=dest_path)
      batch_request.Add(self.client.objects, 'Copy', request)
    api_calls = batch_request.Execute(self.client._http)  # pylint: disable=protected-access
    result_statuses = []
    for i, api_call in enumerate(api_calls):
      src, dest = src_dest_pairs[i]
      exception = None
      if api_call.is_error:
        exception = api_call.exception
        # Translate 404 to the appropriate not found exception.
        if isinstance(exception, HttpError) and exception.status_code == 404:
          exception = (
              GcsIOError(errno.ENOENT, 'Source file not found: %s' % src))
      result_statuses.append((src, dest, exception))
    return result_statuses

  # We intentionally do not decorate this method with a retry, since the
  # underlying copy and delete operations are already idempotent operations
  # protected by retry decorators.
  def copytree(self, src, dest):
    """Renames the given GCS "directory" recursively from src to dest.

    Args:
      src: GCS file path pattern in the form gs://<bucket>/<name>/.
      dest: GCS file path pattern in the form gs://<bucket>/<name>/.
    """
    assert src.endswith('/')
    assert dest.endswith('/')
    for entry in self.list_prefix(src):
      rel_path = entry[len(src):]
      self.copy(entry, dest + rel_path)

  # We intentionally do not decorate this method with a retry, since the
  # underlying copy and delete operations are already idempotent operations
  # protected by retry decorators.
  def rename(self, src, dest):
    """Renames the given GCS object from src to dest.

    Args:
      src: GCS file path pattern in the form gs://<bucket>/<name>.
      dest: GCS file path pattern in the form gs://<bucket>/<name>.
    """
    self.copy(src, dest)
    self.delete(src)

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def exists(self, path):
    """Returns whether the given GCS object exists.

    Args:
      path: GCS file path pattern in the form gs://<bucket>/<name>.
    """
    bucket, object_path = parse_gcs_path(path)
    try:
      request = storage.StorageObjectsGetRequest(
          bucket=bucket, object=object_path)
      self.client.objects.Get(request)  # metadata
      return True
    except HttpError as http_error:
      if http_error.status_code == 404:
        # HTTP 404 indicates that the file did not exist
        return False
      else:
        # We re-raise all other exceptions
        raise

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def checksum(self, path):
    """Looks up the checksum of a GCS object.

    Args:
      path: GCS file path pattern in the form gs://<bucket>/<name>.
    """
    bucket, object_path = parse_gcs_path(path)
    request = storage.StorageObjectsGetRequest(
        bucket=bucket, object=object_path)
    return self.client.objects.Get(request).crc32c

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def size(self, path):
    """Returns the size of a single GCS object.

    This method does not perform glob expansion. Hence the given path must be
    for a single GCS object.

    Returns: size of the GCS object in bytes.
    """
    bucket, object_path = parse_gcs_path(path)
    request = storage.StorageObjectsGetRequest(
        bucket=bucket, object=object_path)
    return self.client.objects.Get(request).size

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def last_updated(self, path):
    """Returns the last updated epoch time of a single GCS object.

    This method does not perform glob expansion. Hence the given path must be
    for a single GCS object.

    Returns: last updated time of the GCS object in second.
    """
    bucket, object_path = parse_gcs_path(path)
    request = storage.StorageObjectsGetRequest(
        bucket=bucket, object=object_path)
    datetime = self.client.objects.Get(request).updated
    return (time.mktime(datetime.timetuple()) - time.timezone
            + datetime.microsecond / 1000000.0)

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def list_prefix(self, path):
    """Lists files matching the prefix.

    Args:
      path: GCS file path pattern in the form gs://<bucket>/[name].

    Returns:
      Dictionary of file name -> size.
    """
    bucket, prefix = parse_gcs_path(path, object_optional=True)
    request = storage.StorageObjectsListRequest(bucket=bucket, prefix=prefix)
    file_sizes = {}
    counter = 0
    start_time = time.time()
    logging.info("Starting the size estimation of the input")
    while True:
      response = self.client.objects.List(request)
      for item in response.items:
        file_name = 'gs://%s/%s' % (item.bucket, item.name)
        file_sizes[file_name] = item.size
        counter += 1
        if counter % 10000 == 0:
          logging.info("Finished computing size of: %s files", len(file_sizes))
      if response.nextPageToken:
        request.pageToken = response.nextPageToken
      else:
        break
    logging.info("Finished listing %s files in %s seconds.",
                 counter, time.time() - start_time)
    return file_sizes

class GcsDownloader(Downloader):
  def __init__(self, client, path, buffer_size):
    self._client = client
    self._path = path
    self._bucket, self._name = parse_gcs_path(path)
    self._buffer_size = buffer_size

    # Get object state.
    self._get_request = (storage.StorageObjectsGetRequest(
        bucket=self._bucket, object=self._name))
    try:
      metadata = self._get_object_metadata(self._get_request)
    except HttpError as http_error:
      if http_error.status_code == 404:
        raise IOError(errno.ENOENT, 'Not found: %s' % self._path)
      else:
        logging.error('HTTP error while requesting file %s: %s', self._path,
                      http_error)
        raise
    self._size = metadata.size

    # Ensure read is from file of the correct generation.
    self._get_request.generation = metadata.generation

    # Initialize read buffer state.
    self._download_stream = io.BytesIO()
    self._downloader = transfer.Download(
        self._download_stream, auto_transfer=False, chunksize=self._buffer_size)
    self._client.objects.Get(self._get_request, download=self._downloader)

  @retry.with_exponential_backoff(
      retry_filter=retry.retry_on_server_errors_and_timeout_filter)
  def _get_object_metadata(self, get_request):
    return self._client.objects.Get(get_request)

  @property
  def size(self):
    return self._size

  def get_range(self, start, end):
    self._download_stream.seek(0)
    self._download_stream.truncate(0)
    self._downloader.GetRange(start, end - 1)
    return self._download_stream.getvalue()

class GcsUploader(Uploader):
  def __init__(self, client, path, mime_type):
    self._client = client
    self._path = path
    self._bucket, self._name = parse_gcs_path(path)
    self._mime_type = mime_type

    # Set up communication with child thread.
    parent_conn, child_conn = multiprocessing.Pipe()
    self._child_conn = child_conn
    self._conn = parent_conn

    # Set up uploader.
    self._insert_request = (storage.StorageObjectsInsertRequest(
        bucket=self._bucket, name=self._name))
    self._upload = transfer.Upload(
        PipeStream(self._child_conn),
        self._mime_type,
        chunksize=WRITE_CHUNK_SIZE)
    self._upload.strategy = transfer.RESUMABLE_UPLOAD

    # Start uploading thread.
    self._upload_thread = threading.Thread(target=self._start_upload)
    self._upload_thread.daemon = True
    self._upload_thread.last_error = None
    self._upload_thread.start()

  # TODO(silviuc): Refactor so that retry logic can be applied.
  # There is retry logic in the underlying transfer library but we should make
  # it more explicit so we can control the retry parameters.
  @retry.no_retries  # Using no_retries marks this as an integration point.
  def _start_upload(self):
    # This starts the uploader thread.  We are forced to run the uploader in
    # another thread because the apitools uploader insists on taking a stream
    # as input. Happily, this also means we get asynchronous I/O to GCS.
    #
    # The uploader by default transfers data in chunks of 1024 * 1024 bytes at
    # a time, buffering writes until that size is reached.
    try:
      self._client.objects.Insert(self._insert_request, upload=self._upload)
    except Exception as e:  # pylint: disable=broad-except
      logging.error('Error in _start_upload while inserting file %s: %s',
                    self._path, traceback.format_exc())
      self._upload_thread.last_error = e
    finally:
      self._child_conn.close()

  def put(self, data):
    try:
      self._conn.send_bytes(data.tobytes())
    except EOFError:
      if self._upload_thread.last_error is not None:
        raise self._upload_thread.last_error # pylint: disable=raising-bad-type
      raise

  def finish(self):
    self._conn.close()
    # TODO(udim): Add timeout=DEFAULT_HTTP_TIMEOUT_SECONDS * 2 and raise if
    # isAlive is True.
    self._upload_thread.join()
    # Check for exception since the last put() call.
    if self._upload_thread.last_error is not None:
      raise self._upload_thread.last_error  # pylint: disable=raising-bad-type


text:
<?php namespace Ciarand\Midterm;

use Ciarand\Midterm\Reporter\ReporterInterface;
use Ciarand\Midterm\Result\TestResult;
use Ciarand\Midterm\Collection\SuiteCollection;

/**
 * The Midterm class is the driver for the tests. It holds the list of
 * reporters and test suites and is responsible for beginning the test run (via
 * `go()`)
 */
class Midterm extends BaseComponent
{
    /**
     * A collection of reporters
     *
     * @var array<ReporterInterface>
     */
    protected $reporters = array();

    /**
     * A collection of Suites to run
     *
     * @var array<Suite>
     */
    protected $suites;

    protected $exitCode = 0;

    protected $container;

    public function __construct(Container $container)
    {
        $this->suites = new SuiteCollection;

        $this->container = $container;
    }

    /**
     * Runs each of the specs
     *
     * @SuppressWarnings(PHPMD.ShortMethodNames)
     */
    public function go()
    {
        $result = $this->container->make(TestResult::className(), $this->suites);
        $result->on("spec_fail", array($this, "onSpecFail"));

        foreach ($this->reporters as $reporter) {
            $reporter->subscribe($result);
        }

        $result->beginTest();

        foreach ($this->suites as $suite) {
            $result->setCurrentSuite($suite);
            $suite->run();
        }

        $result->endTest();

        return $this->exitCode;
    }

    /**
     * Takes a file glob and runs all files that match the glob
     *
     * @param string $glob
     */
    public function addGlob($glob)
    {
        …($glob);
    }

    /**
     * Adds a suite to the list of suites to run
     *
     * @param Suite $suite
     */
    public function addSuite(Suite $suite)
    {
        $this->suites[] = $suite;
    }

    /**
     * Adds a reporter
     *
     * @param ReporterInterface $reporter
     */
    public function addReporter(ReporterInterface $reporter)
    {
        $this->reporters[] = $reporter;
    }

    /**
     * Gets the current active Suite object
     *
     * @return Suite
     */
    public function getCurrentSuite()
    {
        return $this->suites->end();
    }

    public function onSpecFail()
    {
        $this->exitCode = 1;
    }

    public function getContainer()
    {
        return $this->container;
    }
}


text:
#ifndef Fennel_InstructionCommon_Included
#define Fennel_InstructionCommon_Included

//! \file InstructionCommon.h
//! External users should include this file if they intend to manipulate
//! instructions directly, otherwise only include CalcCommon.h

#include "fennel/calculator/RegisterReference.h"
#include "fennel/tuple/StandardTypeDescriptor.h"

#include "fennel/calculator/BoolInstruction.h"
#include "fennel/calculator/JumpInstruction.h"
#include "fennel/calculator/NativeInstruction.h"
#include "fennel/calculator/NativeNativeInstruction.h"
#include "fennel/calculator/BoolNativeInstruction.h"
#include "fennel/calculator/IntegralNativeInstruction.h"
#include "fennel/calculator/PointerInstruction.h"
#include "fennel/calculator/PointerPointerInstruction.h"
#include "fennel/calculator/BoolPointerInstruction.h"
#include "fennel/calculator/IntegralPointerInstruction.h"
#include "fennel/calculator/PointerIntegralInstruction.h"
#include "fennel/calculator/ReturnInstruction.h"
#include "fennel/calculator/CastInstruction.h"

#include "fennel/calculator/ExtendedInstruction.h"
#include "fennel/calculator/ExtendedInstructionTable.h"
#include "fennel/calculator/ExtString.h"
#include "fennel/calculator/ExtRegExp.h"
#include "fennel/calculator/ExtMath.h"
#include "fennel/calculator/ExtDateTime.h"
#include "fennel/calculator/ExtCast.h"
#include "fennel/calculator/ExtDynamicVariable.h"
#include "fennel/calculator/ExtWinAggFuncs.h"

#endif

// End InstructionCommon.h


text:
package com.wso2telco.dep.oneapivalidation.util;

import com.wso2telco.core.dbutils.exception.ThrowableError;
public enum FileNames {

	ONEAPI_VALIDATION_CONF_FILE("oneapi-validation-conf.properties");

	FileNames(String fileName) {

		this.fileName = fileName;
	}

	private String fileName;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}


text:
package org.burroloco.donkey.slurp.http;

import edge.javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class ControlServletRequest implements HttpServletRequest {
    private static final String MESSAGE = "Hello World";
    private static final String DATE = "2009-01-01";

    public Enumeration getParameterNames() {
        List list = new ArrayList();
        list.add("Date");
        list.add("Message");
        return Collections.enumeration(list);
    }

    public String getParameter(String s) {
        if (s.equals("Date")) return DATE;
        if (s.equals("Message")) return MESSAGE;
        else throw new IllegalArgumentException(s + " not expected.");
    }
}


text:
<?php
/*
 * This file is part of the Sulu CMS.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\Sales\OrderBundle\Order;

use Sulu\Bundle\Sales\OrderBundle\Order\OrderManger;
use Symfony\Component\DependencyInjection\ContainerInterface;

class OrderUpdater
{
    /**
     * @var Array
     */
    private $scheduledIds;

    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(
        ContainerInterface $container
    ) {
        $this->container = $container;
        $this->scheduledIds = [];
    }

    /**
     * @return EntityManager
     */
    private function getEntityManager()
    {
        return $this->container->get('doctrine.orm.entity_manager');
    }

    /**
     * @return OrderManager
     */
    private function getOrderManager()
    {
        return $this->container->get('sulu_sales_order.order_manager');
    }

    /**
     * Offers depending to an id are going to be updated
     * if processIds() is called.
     *
     * @param string $id
     */
    public function scheduleForUpdate($id)
    {
        if ($id) {
            $this->scheduledIds[] = $id;
        }
    }

    /**
     * Process (update total net price) all offers
     * for the scheduled Items.
     */
    public function processIds()
    {
        $orders = [];
        foreach ($this->scheduledIds as $id) {
            $order = $this->getOrderManager()->findOrderEntityForItemWithId($id);
            if (!in_array($order->getId(), $orders)) {
                $orders[] = $order->getId();
                $order->updateTotalNetPrice();
            }
        }
        unset($this->scheduledIds);
        $this->scheduledIds = [];
        $this->getEntityManager()->flush();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
	<string name="app_name" formatted="false">hackathon4</string>
	<string name="welcome" formatted="false">%sへようこそ!</string>
</resources>


text:
package org.apache.sysml.runtime.instructions.cp;

import org.apache.sysml.lops.Ctable;
import org.apache.sysml.parser.Expression.DataType;
import org.apache.sysml.parser.Expression.ValueType;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;
import org.apache.sysml.runtime.instructions.Instruction;
import org.apache.sysml.runtime.instructions.InstructionUtils;
import org.apache.sysml.runtime.matrix.data.CTableMap;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
import org.apache.sysml.runtime.matrix.operators.SimpleOperator;
import org.apache.sysml.runtime.util.DataConverter;
import org.apache.sysml.runtime.util.LongLongDoubleHashMap.EntryType;

public class CtableCPInstruction extends ComputationCPInstruction {
	private final String _outDim1;
	private final String _outDim2;
	private final boolean _dim1Literal;
	private final boolean _dim2Literal;
	private final boolean _isExpand;
	private final boolean _ignoreZeros;

	private CtableCPInstruction(CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out,
			String outputDim1, boolean dim1Literal, String outputDim2, boolean dim2Literal, boolean isExpand,
			boolean ignoreZeros, String opcode, String istr) {
		super(CPType.Ctable, null, in1, in2, in3, out, opcode, istr);
		_outDim1 = outputDim1;
		_dim1Literal = dim1Literal;
		_outDim2 = outputDim2;
		_dim2Literal = dim2Literal;
		_isExpand = isExpand;
		_ignoreZeros = ignoreZeros;
	}

	public static CtableCPInstruction parseInstruction(String inst)
	{
		String[] parts = InstructionUtils.getInstructionPartsWithValueType(inst);
		InstructionUtils.checkNumFields ( parts, 7 );

		String opcode = parts[0];

		//handle opcode
		if ( !(opcode.equalsIgnoreCase("ctable") || opcode.equalsIgnoreCase("ctableexpand")) ) {
			throw new DMLRuntimeException("Unexpected opcode in TertiaryCPInstruction: " + inst);
		}
		boolean isExpand = opcode.equalsIgnoreCase("ctableexpand");

		//handle operands
		CPOperand in1 = new CPOperand(parts[1]);
		CPOperand in2 = new CPOperand(parts[2]);
		CPOperand in3 = new CPOperand(parts[3]);

		//handle known dimension information
		String[] dim1Fields = parts[4].split(Instruction.LITERAL_PREFIX);
		String[] dim2Fields = parts[5].split(Instruction.LITERAL_PREFIX);

		CPOperand out = new CPOperand(parts[6]);
		boolean ignoreZeros = Boolean.parseBoolean(parts[7]);

		// ctable does not require any operator, so we simply pass-in a dummy operator with null functionobject
		return new CtableCPInstruction(in1, in2, in3, out, dim1Fields[0], Boolean.parseBoolean(dim1Fields[1]), dim2Fields[0], Boolean.parseBoolean(dim2Fields[1]), isExpand, ignoreZeros, opcode, inst);
	}

	private Ctable.OperationTypes findCtableOperation() {
		DataType dt1 = input1.getDataType();
		DataType dt2 = input2.getDataType();
		DataType dt3 = input3.getDataType();
		return Ctable.findCtableOperationByInputDataTypes(dt1, dt2, dt3);
	}

	@Override
	public void processInstruction(ExecutionContext ec) {
		MatrixBlock matBlock1 = ec.getMatrixInput(input1.getName(), getExtendedOpcode());
		MatrixBlock matBlock2=null, wtBlock=null;
		double cst1, cst2;

		CTableMap resultMap = new CTableMap(EntryType.INT);
		MatrixBlock resultBlock = null;
		Ctable.OperationTypes ctableOp = findCtableOperation();
		ctableOp = _isExpand ? Ctable.OperationTypes.CTABLE_EXPAND_SCALAR_WEIGHT : ctableOp;

		long outputDim1 = (_dim1Literal ? (long) Double.parseDouble(_outDim1) : (ec.getScalarInput(_outDim1, ValueType.DOUBLE, false)).getLongValue());
		long outputDim2 = (_dim2Literal ? (long) Double.parseDouble(_outDim2) : (ec.getScalarInput(_outDim2, ValueType.DOUBLE, false)).getLongValue());

		boolean outputDimsKnown = (outputDim1 != -1 && outputDim2 != -1);
		if ( outputDimsKnown ) {
			int inputRows = matBlock1.getNumRows();
			int inputCols = matBlock1.getNumColumns();
			boolean sparse = MatrixBlock.evalSparseFormatInMemory(outputDim1, outputDim2, inputRows*inputCols);
			//only create result block if dense; it is important not to aggregate on sparse result
			//blocks because it would implicitly turn the O(N) algorithm into O(N log N).
			if( !sparse )
				resultBlock = new MatrixBlock((int)outputDim1, (int)outputDim2, false);
		}
		if( _isExpand ){
			resultBlock = new MatrixBlock( matBlock1.getNumRows(), Integer.MAX_VALUE, true );
		}

		switch(ctableOp) {
			case CTABLE_TRANSFORM: //(VECTOR)
				// F=ctable(A,B,W)
				matBlock2 = ec.getMatrixInput(input2.getName(), getExtendedOpcode());
				wtBlock = ec.getMatrixInput(input3.getName(), getExtendedOpcode());
				matBlock1.ctableOperations((SimpleOperator)_optr, matBlock2, wtBlock, resultMap, resultBlock);
				break;
			case CTABLE_TRANSFORM_SCALAR_WEIGHT: //(VECTOR/MATRIX)
				// F = ctable(A,B) or F = ctable(A,B,1)
				matBlock2 = ec.getMatrixInput(input2.getName(), getExtendedOpcode());
				cst1 = ec.getScalarInput(input3.getName(), input3.getValueType(), input3.isLiteral()).getDoubleValue();
				matBlock1.ctableOperations((SimpleOperator)_optr, matBlock2, cst1, _ignoreZeros, resultMap, resultBlock);
				break;
			case CTABLE_EXPAND_SCALAR_WEIGHT: //(VECTOR)
				// F = ctable(seq,A) or F = ctable(seq,B,1)
				matBlock2 = ec.getMatrixInput(input2.getName(), getExtendedOpcode());
				cst1 = ec.getScalarInput(input3.getName(), input3.getValueType(), input3.isLiteral()).getDoubleValue();
				// only resultBlock.rlen known, resultBlock.clen set in operation
				matBlock1.ctableSeqOperations(matBlock2, cst1, resultBlock);
				break;
			case CTABLE_TRANSFORM_HISTOGRAM: //(VECTOR)
				// F=ctable(A,1) or F = ctable(A,1,1)
				cst1 = ec.getScalarInput(input2.getName(), input2.getValueType(), input2.isLiteral()).getDoubleValue();
				cst2 = ec.getScalarInput(input3.getName(), input3.getValueType(), input3.isLiteral()).getDoubleValue();
				matBlock1.ctableOperations((SimpleOperator)_optr, cst1, cst2, resultMap, resultBlock);
				break;
			case CTABLE_TRANSFORM_WEIGHTED_HISTOGRAM: //(VECTOR)
				// F=ctable(A,1,W)
				wtBlock = ec.getMatrixInput(input3.getName(), getExtendedOpcode());
				cst1 = ec.getScalarInput(input2.getName(), input2.getValueType(), input2.isLiteral()).getDoubleValue();
				matBlock1.ctableOperations((SimpleOperator)_optr, cst1, wtBlock, resultMap, resultBlock);
				break;

			default:
				throw new DMLRuntimeException("Encountered an invalid ctable operation ("+ctableOp+") while executing instruction: " + this.toString());
		}

		if(input1.getDataType() == DataType.MATRIX)
			ec.releaseMatrixInput(input1.getName(), getExtendedOpcode());
		if(input2.getDataType() == DataType.MATRIX)
			ec.releaseMatrixInput(input2.getName(), getExtendedOpcode());
		if(input3.getDataType() == DataType.MATRIX)
			ec.releaseMatrixInput(input3.getName(), getExtendedOpcode());

		if ( resultBlock == null ){
			//we need to respect potentially specified output dimensions here, because we might have
			//decided for hash-aggregation just to prevent inefficiency in case of sparse outputs.
			if( outputDimsKnown )
				resultBlock = DataConverter.convertToMatrixBlock( resultMap, (int)outputDim1, (int)outputDim2 );
			else
				resultBlock = DataConverter.convertToMatrixBlock( resultMap );
		}
		else
			resultBlock.examSparsity();

		// Ensure right dense/sparse output representation for special cases
		// such as ctable expand (guarded by released input memory)
		if( checkGuardedRepresentationChange(matBlock1, matBlock2, resultBlock) ) {
			resultBlock.examSparsity();
		}

		ec.setMatrixOutput(output.getName(), resultBlock, getExtendedOpcode());
	}
}


text:
package com.lucien.spirit.admin.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.lucien.spirit.admin.model.Role;

@Repository
public interface RoleDao extends JpaRepository<Role, Long> {

}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_proxying_url_loader_factory.h"

#include "base/barrier_closure.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_params.h"
#include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_proxy_configurator.h"
#include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_service.h"
#include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_service_factory.h"
#include "chrome/browser/preloading/prefetch/prefetch_proxy/prefetch_proxy_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_constants.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/client_hints.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/mojom/early_hints.mojom.h"
#include "third_party/blink/public/common/client_hints/client_hints.h"

namespace {

const char kAllowedUAClientHint[] = "sec-ch-ua";
const char kAllowedUAMobileClientHint[] = "sec-ch-ua-mobile";

// Little helper class for
// |CheckRedirectsBeforeRunningResourceSuccessfulCallback| since size_t can't be
// ref counted.
class SuccessCount : public base::RefCounted<SuccessCount> {
 public:
  SuccessCount() = default;

  SuccessCount(const SuccessCount&) = delete;
  SuccessCount& operator=(const SuccessCount&) = delete;

  void Increment() { count_++; }
  size_t count() const { return count_; }

 private:
  friend class RefCounted<SuccessCount>;
  ~SuccessCount() = default;

  size_t count_ = 0;
};

// This is the eligibility callback for
// |CheckRedirectsBeforeRunningResourceSuccessfulCallback|. If |eligible| is
// true, then |success_count| is incremented. If |success_count| ever matches
// the size of |resources|, then |callback| is run for every url in |resources|.
void SingleURLEligibilityCheckResult(
    const std::vector<GURL>& resources,
    PrefetchProxyProxyingURLLoaderFactory::ResourceLoadSuccessfulCallback
        callback,
    scoped_refptr<SuccessCount> success_count,
    const GURL& url,
    bool eligible,
    absl::optional<PrefetchProxyPrefetchStatus> not_used) {
  if (eligible) {
    success_count->Increment();
  }

  // If even one url is not eligible, then this if block will never be executed.
  // Once no more callbacks reference the given arguments, they will all be
  // cleaned up and |callback| will be destroyed, never having been run,,
  if (success_count->count() == resources.size()) {
    for (const GURL& resource_url : resources) {
      callback.Run(resource_url);
    }
  }
}

// This method checks every url in |resources|, checking if it is eligible to be
// cached by Prefetch Proxy. If every element is eligible, then all urls are run
// on |callback|. If even a single url is not eligible, |callback| is never run.
void CheckRedirectsBeforeRunningResourceSuccessfulCallback(
    Profile* profile,
    const std::vector<GURL>& resources,
    PrefetchProxyProxyingURLLoaderFactory::ResourceLoadSuccessfulCallback
        callback) {
  DCHECK(profile);
  DCHECK(callback);

  scoped_refptr<SuccessCount> success_count =
      base::MakeRefCounted<SuccessCount>();

  for (const GURL& url : resources) {
    PrefetchProxyTabHelper::CheckEligibilityOfURL(
        profile, url,
        PrefetchType(/*use_isolated_network_context=*/true,
                     /*use_prefetch_proxy=*/true,
                     /*can_prefetch_subresources=*/true),
        base::BindOnce(&SingleURLEligibilityCheckResult, resources, callback,
                       success_count));
  }
}

}  // namespace

PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::InProgressRequest(
    Profile* profile,
    PrefetchProxyProxyingURLLoaderFactory* parent_factory,
    network::mojom::URLLoaderFactory* target_factory,
    ResourceLoadSuccessfulCallback on_resource_load_successful,
    mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver,
    int32_t request_id,
    uint32_t options,
    const network::ResourceRequest& request,
    mojo::PendingRemote<network::mojom::URLLoaderClient> client,
    const net::MutableNetworkTrafficAnnotationTag& traffic_annotation)
    : profile_(profile),
      parent_factory_(parent_factory),
      on_resource_load_successful_(on_resource_load_successful),
      target_client_(std::move(client)),
      loader_receiver_(this, std::move(loader_receiver)) {
  redirect_chain_.push_back(request.url);

  mojo::PendingRemote<network::mojom::URLLoaderClient> proxy_client =
      client_receiver_.BindNewPipeAndPassRemote();

  target_factory->CreateLoaderAndStart(
      target_loader_.BindNewPipeAndPassReceiver(), request_id, options, request,
      std::move(proxy_client), traffic_annotation);

  // Calls |OnBindingsClosed| only after both disconnect handlers have been run.
  base::RepeatingClosure closure = base::BarrierClosure(
      2, base::BindOnce(&InProgressRequest::OnBindingsClosed,
                        base::Unretained(this)));
  loader_receiver_.set_disconnect_handler(closure);
  client_receiver_.set_disconnect_handler(closure);
}

PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::~InProgressRequest() {
  if (destruction_callback_) {
    std::move(destruction_callback_).Run();
  }
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::FollowRedirect(
    const std::vector<std::string>& removed_headers,
    const net::HttpRequestHeaders& modified_headers,
    const net::HttpRequestHeaders& modified_cors_exempt_headers,
    const absl::optional<GURL>& new_url) {
  target_loader_->FollowRedirect(removed_headers, modified_headers,
                                 modified_cors_exempt_headers, new_url);
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::SetPriority(
    net::RequestPriority priority,
    int32_t intra_priority_value) {
  target_loader_->SetPriority(priority, intra_priority_value);
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    PauseReadingBodyFromNet() {
  target_loader_->PauseReadingBodyFromNet();
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    ResumeReadingBodyFromNet() {
  target_loader_->ResumeReadingBodyFromNet();
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    OnReceiveEarlyHints(network::mojom::EarlyHintsPtr early_hints) {
  target_client_->OnReceiveEarlyHints(std::move(early_hints));
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    OnReceiveResponse(network::mojom::URLResponseHeadPtr head,
                      mojo::ScopedDataPipeConsumerHandle body,
                      absl::optional<mojo_base::BigBuffer> cached_metadata) {
  if (head) {
    head_ = head->Clone();
  }
  target_client_->OnReceiveResponse(std::move(head), std::move(body),
                                    std::move(cached_metadata));
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    OnReceiveRedirect(const net::RedirectInfo& redirect_info,
                      network::mojom::URLResponseHeadPtr head) {
  redirect_chain_.push_back(redirect_info.new_url);
  target_client_->OnReceiveRedirect(redirect_info, std::move(head));
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::OnUploadProgress(
    int64_t current_position,
    int64_t total_size,
    OnUploadProgressCallback callback) {
  target_client_->OnUploadProgress(current_position, total_size,
                                   std::move(callback));
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    OnTransferSizeUpdated(int32_t transfer_size_diff) {
  target_client_->OnTransferSizeUpdated(transfer_size_diff);
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    SetOnCompleteRecordMetricsCallback(
        OnCompleteRecordMetricsCallback callback) {
  on_complete_metrics_callback_ = std::move(callback);
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::OnComplete(
    const network::URLLoaderCompletionStatus& status) {
  if (on_complete_metrics_callback_) {
    std::move(on_complete_metrics_callback_)
        .Run(redirect_chain_[0], head_ ? head_->Clone() : nullptr, status);
  }
  MaybeReportResourceLoadSuccess(status);
  target_client_->OnComplete(status);
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    OnBindingsClosed() {
  // Destroys |this|.
  parent_factory_->RemoveRequest(this);
}

void PrefetchProxyProxyingURLLoaderFactory::InProgressRequest::
    MaybeReportResourceLoadSuccess(
        const network::URLLoaderCompletionStatus& status) {
  if (status.error_code != net::OK) {
    return;
  }

  if (!head_) {
    return;
  }

  if (!head_->headers) {
    return;
  }

  if (head_->headers->response_code() >= net::HTTP_MULTIPLE_CHOICES) {
    return;
  }

  if (head_->headers->response_code() < net::HTTP_OK) {
    return;
  }

  if (!on_resource_load_successful_) {
    return;
  }

  if (!profile_) {
    return;
  }

  DCHECK_GT(redirect_chain_.size(), 0U);

  // Check each url in the redirect chain before reporting success.
  CheckRedirectsBeforeRunningResourceSuccessfulCallback(
      profile_, redirect_chain_, on_resource_load_successful_);
}

PrefetchProxyProxyingURLLoaderFactory::AbortRequest::~AbortRequest() = default;
PrefetchProxyProxyingURLLoaderFactory::AbortRequest::AbortRequest(
    mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver,
    mojo::PendingRemote<network::mojom::URLLoaderClient> client)
    : target_client_(std::move(client)),
      loader_receiver_(this, std::move(loader_receiver)) {
  loader_receiver_.set_disconnect_handler(base::BindOnce(
      &PrefetchProxyProxyingURLLoaderFactory::AbortRequest::OnBindingClosed,
      base::Unretained(this)));

  // PostTask the failure to get it out of this message loop, allowing the mojo
  // pipes to settle in.
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(
          &PrefetchProxyProxyingURLLoaderFactory::AbortRequest::Abort,
          weak_factory_.GetWeakPtr()));
}

void PrefetchProxyProxyingURLLoaderFactory::AbortRequest::Abort() {
  target_client_->OnComplete(
      network::URLLoaderCompletionStatus(net::ERR_FAILED));
}

void PrefetchProxyProxyingURLLoaderFactory::AbortRequest::FollowRedirect(
    const std::vector<std::string>& removed_headers,
    const net::HttpRequestHeaders& modified_headers,
    const net::HttpRequestHeaders& modified_cors_exempt_headers,
    const absl::optional<GURL>& new_url) {}
void PrefetchProxyProxyingURLLoaderFactory::AbortRequest::SetPriority(
    net::RequestPriority priority,
    int32_t intra_priority_value) {}
void PrefetchProxyProxyingURLLoaderFactory::AbortRequest::
    PauseReadingBodyFromNet() {}
void PrefetchProxyProxyingURLLoaderFactory::AbortRequest::
    ResumeReadingBodyFromNet() {}

void PrefetchProxyProxyingURLLoaderFactory::AbortRequest::OnBindingClosed() {
  delete this;
}

PrefetchProxyProxyingURLLoaderFactory::PrefetchProxyProxyingURLLoaderFactory(
    ResourceMetricsObserver* metrics_observer,
    int frame_tree_node_id,
    mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver,
    mojo::PendingRemote<network::mojom::URLLoaderFactory>
        network_process_factory,
    mojo::PendingRemote<network::mojom::URLLoaderFactory> isolated_factory,
    DisconnectCallback on_disconnect,
    ResourceLoadSuccessfulCallback on_resource_load_successful)
    : metrics_observer_(metrics_observer),
      frame_tree_node_id_(frame_tree_node_id),
      on_resource_load_successful_(std::move(on_resource_load_successful)),
      on_disconnect_(std::move(on_disconnect)) {
  DCHECK(metrics_observer_);

  network_process_factory_.Bind(std::move(network_process_factory));
  network_process_factory_.set_disconnect_handler(base::BindOnce(
      &PrefetchProxyProxyingURLLoaderFactory::OnNetworkProcessFactoryError,
      base::Unretained(this)));

  isolated_factory_.Bind(std::move(isolated_factory));
  isolated_factory_.set_disconnect_handler(base::BindOnce(
      &PrefetchProxyProxyingURLLoaderFactory::OnIsolatedFactoryError,
      base::Unretained(this)));

  proxy_receivers_.Add(this, std::move(loader_receiver));
  proxy_receivers_.set_disconnect_handler(base::BindRepeating(
      &PrefetchProxyProxyingURLLoaderFactory::OnProxyBindingError,
      base::Unretained(this)));
}

PrefetchProxyProxyingURLLoaderFactory::
    ~PrefetchProxyProxyingURLLoaderFactory() = default;

void PrefetchProxyProxyingURLLoaderFactory::NotifyPageNavigatedToAfterSRP(
    const std::set<GURL>& cached_subresources) {
  previously_cached_subresources_ = cached_subresources;
}

bool PrefetchProxyProxyingURLLoaderFactory::ShouldHandleRequestForPrerender()
    const {
  return !previously_cached_subresources_.has_value();
}

void PrefetchProxyProxyingURLLoaderFactory::CreateLoaderAndStart(
    mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver,
    int32_t request_id,
    uint32_t options,
    const network::ResourceRequest& request,
    mojo::PendingRemote<network::mojom::URLLoaderClient> client,
    const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_);
  if (!web_contents) {
    return;
  }

  Profile* profile =
      Profile::FromBrowserContext(web_contents->GetBrowserContext());

  // If this request is happening during a prerender then check if it is
  // eligible for caching before putting it on the network.
  if (ShouldHandleRequestForPrerender()) {
    // Do not allow insecure resources to be fetched due to risk of privacy
    // leaks in an HSTS setting.
    if (!request.url.SchemeIs(url::kHttpsScheme)) {
      auto abort_request = std::make_unique<AbortRequest>(
          std::move(loader_receiver), std::move(client));
      // The request will manage its own lifecycle based on the mojo pipes.
      abort_request.release();
      return;
    }

    // Check if this prerender has exceeded its max number of subresources.
    request_count_++;
    if (request_count_ > PrefetchProxyMaxSubresourcesPerPrerender()) {
      metrics_observer_->OnResourceThrottled(request.url);
      auto abort_request = std::make_unique<AbortRequest>(
          std::move(loader_receiver), std::move(client));
      // The request will manage its own lifecycle based on the mojo pipes.
      abort_request.release();
      return;
    }

    // Check that the proxy server is available. If not, fast abort the request.
    PrefetchProxyService* prefetch_proxy_service =
        PrefetchProxyServiceFactory::GetForProfile(profile);
    if (prefetch_proxy_service && !prefetch_proxy_service->proxy_configurator()
                                       ->IsPrefetchProxyAvailable()) {
      metrics_observer_->OnProxyUnavailableForResource(request.url);
      auto abort_request = std::make_unique<AbortRequest>(
          std::move(loader_receiver), std::move(client));
      // The request will manage its own lifecycle based on the mojo pipes.
      abort_request.release();
      return;
    }

    // We must check if the request can be cached and set the appropriate load
    // flag if so.
    PrefetchProxyTabHelper::CheckEligibilityOfURL(
        profile, request.url,
        PrefetchType(/*use_isolated_network_context=*/true,
                     /*use_prefetch_proxy=*/true,
                     /*can_prefetch_subresources=*/true),
        base::BindOnce(
            &PrefetchProxyProxyingURLLoaderFactory::OnEligibilityResult,
            weak_factory_.GetWeakPtr(), profile, std::move(loader_receiver),
            request_id, options, request, std::move(client),
            traffic_annotation));
    return;
  }

  // This request is happening after the user clicked to a prerendered page.
  DCHECK(previously_cached_subresources_.has_value());
  const std::set<GURL>& cached_subresources = *previously_cached_subresources_;
  if (cached_subresources.find(request.url) != cached_subresources.end()) {
    // Load this resource from |isolated_factory_|'s cache.
    auto in_progress_request = std::make_unique<InProgressRequest>(
        profile, this, isolated_factory_.get(), base::NullCallback(),
        std::move(loader_receiver), request_id, options, request,
        std::move(client), traffic_annotation);
    in_progress_request->SetOnCompleteRecordMetricsCallback(
        base::BindOnce(&PrefetchProxyProxyingURLLoaderFactory::
                           RecordSubresourceMetricsAfterClick,
                       base::Unretained(this)));
    requests_.insert(std::move(in_progress_request));
  } else {
    // Resource was not cached during the NSP, so load it normally.
    // No metrics callback here, since there's nothing important to record.
    requests_.insert(std::make_unique<InProgressRequest>(
        profile, this, network_process_factory_.get(), base::NullCallback(),
        std::move(loader_receiver), request_id, options, request,
        std::move(client), traffic_annotation));
  }
}

void PrefetchProxyProxyingURLLoaderFactory::OnEligibilityResult(
    Profile* profile,
    mojo::PendingReceiver<network::mojom::URLLoader> loader_receiver,
    int32_t request_id,
    uint32_t options,
    const network::ResourceRequest& request,
    mojo::PendingRemote<network::mojom::URLLoaderClient> client,
    const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
    const GURL& url,
    bool eligible,
    absl::optional<PrefetchProxyPrefetchStatus> status) {
  DCHECK_EQ(request.url, url);
  DCHECK(!previously_cached_subresources_.has_value());
  DCHECK(request.cors_exempt_headers.HasHeader(
      content::kCorsExemptPurposeHeaderName));
  DCHECK(request.load_flags & net::LOAD_PREFETCH);
  DCHECK(!request.trusted_params.has_value());

  network::ResourceRequest isolated_request = request;

  // Ensures that the U-A string is set to the Isolated Network Context's
  // default.
  isolated_request.headers.RemoveHeader("User-Agent");

  // Ensures that the Accept-Language string is set to the Isolated Network
  // Context's default.
  isolated_request.headers.RemoveHeader("Accept-Language");

  // Strip out all Client Hints.
  for (const auto& elem : network::GetClientHintToNameMap()) {
    const auto& header = elem.second;
    // UA Client Hint and UA Mobile are ok to send.
    if (header == kAllowedUAClientHint ||
        header == kAllowedUAMobileClientHint) {
      continue;
    }
    isolated_request.headers.RemoveHeader(header);
  }

  ResourceLoadSuccessfulCallback resource_load_successful_callback =
      on_resource_load_successful_;

  // If this subresource is eligible for prefetching then it can be cached. If
  // not, it must still be put on the wire to avoid privacy attacks but should
  // not be cached or change any cookies.
  if (!eligible) {
    if (status) {
      metrics_observer_->OnResourceNotEligible(url, *status);
    }

    isolated_request.load_flags |= net::LOAD_DISABLE_CACHE;
    isolated_request.credentials_mode = network::mojom::CredentialsMode::kOmit;

    // Don't report loaded resources that won't go in the cache.
    resource_load_successful_callback = base::NullCallback();
  }

  auto in_progress_request = std::make_unique<InProgressRequest>(
      profile, this, isolated_factory_.get(), resource_load_successful_callback,
      std::move(loader_receiver), request_id, options, isolated_request,
      std::move(client), traffic_annotation);
  in_progress_request->SetOnCompleteRecordMetricsCallback(
      base::BindOnce(&PrefetchProxyProxyingURLLoaderFactory::
                         RecordSubresourceMetricsDuringPrerender,
                     base::Unretained(this)));
  requests_.insert(std::move(in_progress_request));
}

void PrefetchProxyProxyingURLLoaderFactory::
    RecordSubresourceMetricsDuringPrerender(
        const GURL& url,
        network::mojom::URLResponseHeadPtr head,
        const network::URLLoaderCompletionStatus& status) {
  base::UmaHistogramSparse("PrefetchProxy.Prefetch.Subresources.NetError",
                           std::abs(status.error_code));
  if (head && head->headers) {
    base::UmaHistogramSparse("PrefetchProxy.Prefetch.Subresources.RespCode",
                             head->headers->response_code());
  }

  metrics_observer_->OnResourceFetchComplete(url, std::move(head), status);
}

void PrefetchProxyProxyingURLLoaderFactory::RecordSubresourceMetricsAfterClick(
    const GURL& url,
    network::mojom::URLResponseHeadPtr head,
    const network::URLLoaderCompletionStatus& status) {
  UMA_HISTOGRAM_BOOLEAN("PrefetchProxy.AfterClick.Subresources.UsedCache",
                        status.exists_in_cache);
  metrics_observer_->OnResourceUsedFromCache(url);
}

void PrefetchProxyProxyingURLLoaderFactory::Clone(
    mojo::PendingReceiver<network::mojom::URLLoaderFactory> loader_receiver) {
  proxy_receivers_.Add(this, std::move(loader_receiver));
}

void PrefetchProxyProxyingURLLoaderFactory::OnNetworkProcessFactoryError() {
  // Stop calls to CreateLoaderAndStart() when |network_process_factory_| is
  // invalid.
  network_process_factory_.reset();
  proxy_receivers_.Clear();

  MaybeDestroySelf();
}

void PrefetchProxyProxyingURLLoaderFactory::OnIsolatedFactoryError() {
  // Stop calls to CreateLoaderAndStart() when |isolated_factory_| is
  // invalid.
  isolated_factory_.reset();
  proxy_receivers_.Clear();

  MaybeDestroySelf();
}

void PrefetchProxyProxyingURLLoaderFactory::OnProxyBindingError() {
  if (proxy_receivers_.empty()) {
    network_process_factory_.reset();
  }

  MaybeDestroySelf();
}

void PrefetchProxyProxyingURLLoaderFactory::RemoveRequest(
    InProgressRequest* request) {
  auto it = requests_.find(request);
  DCHECK(it != requests_.end());
  requests_.erase(it);

  MaybeDestroySelf();
}

void PrefetchProxyProxyingURLLoaderFactory::MaybeDestroySelf() {
  // Even if all URLLoaderFactory pipes connected to this object have been
  // closed it has to stay alive until all active requests have completed.
  if (network_process_factory_.is_bound() || isolated_factory_.is_bound() ||
      !requests_.empty()) {
    return;
  }

  // Deletes |this|.
  std::move(on_disconnect_).Run(this);
}


text:
import fnmatch
import traceback

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
    check_sdk,
    create_connection,
    get_dict_of_struct,
    ovirt_full_argument_spec,
)

ANSIBLE_METADATA = {'status': 'preview',
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = '''
---
module: ovirt_affinity_labels_facts
short_description: Retrieve facts about one or more oVirt affinity labels
author: "Ondra Machacek (@machacekondra)"
version_added: "2.3"
description:
    - "Retrieve facts about one or more oVirt affinity labels."
notes:
    - "This module creates a new top-level C(affinity_labels) fact, which
       contains a list of affinity labels."
options:
    name:
      description:
        - "Name of the affinity labels which should be listed."
    vm:
      description:
        - "Name of the VM, which affinity labels should be listed."
    host:
      description:
        - "Name of the host, which affinity labels should be listed."
extends_documentation_fragment: ovirt
'''

EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:

# Gather facts about all affinity labels, which names start with C(label):
- ovirt_affinity_labels_facts:
    name: label*
- debug:
    var: affinity_labels

# Gather facts about all affinity labels, which are assigned to VMs
# which names start with C(postgres):
- ovirt_affinity_labels_facts:
    vm: postgres*
- debug:
    var: affinity_labels

# Gather facts about all affinity labels, which are assigned to hosts
# which names start with C(west):
- ovirt_affinity_labels_facts:
    host: west*
- debug:
    var: affinity_labels

# Gather facts about all affinity labels, which are assigned to hosts
# which names start with C(west) or VMs which names start with C(postgres):
- ovirt_affinity_labels_facts:
    host: west*
    vm: postgres*
- debug:
    var: affinity_labels
'''

RETURN = '''
ovirt_vms:
    description: "List of dictionaries describing the affinity labels. Affinity labels attribues are mapped to dictionary keys,
                  all affinity labels attributes can be found at following url: https://ovirt.example.com/ovirt-engine/api/model#types/affinity_label."
    returned: On success.
    type: list
'''

def main():
    argument_spec = ovirt_full_argument_spec(
        name=dict(default=None),
        host=dict(default=None),
        vm=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        affinity_labels_service = connection.system_service().affinity_labels_service()
        labels = []
        all_labels = affinity_labels_service.list()
        if module.params['name']:
            labels.extend([
                l for l in all_labels
                if fnmatch.fnmatch(l.name, module.params['name'])
            ])
        if module.params['host']:
            hosts_service = connection.system_service().hosts_service()
            labels.extend([
                label
                for label in all_labels
                for host in connection.follow_link(label.hosts)
                if fnmatch.fnmatch(hosts_service.service(host.id).get().name, module.params['host'])
            ])
        if module.params['vm']:
            vms_service = connection.system_service().vms_service()
            labels.extend([
                label
                for label in all_labels
                for vm in connection.follow_link(label.vms)
                if fnmatch.fnmatch(vms_service.service(vm.id).get().name, module.params['vm'])
            ])

        if not (module.params['vm'] or module.params['host'] or module.params['name']):
            labels = all_labels

        module.exit_json(
            changed=False,
            ansible_facts=dict(
                affinity_labels=[
                    get_dict_of_struct(l) for l in labels
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)

if __name__ == '__main__':
    main()


text:
using System;

namespace Hepsi.CommandProcessor
{
    /// <summary>
    /// Interface IRequest
    /// Base class of <see cref="Command"/> and <see cref="Event"/>. A request that can be handled by the Command Processor/Dispatcher
    /// </summary>
    public interface IRequest
    {
        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>The identifier.</value>
        Guid Id { get; set; }
    }
}


text:
RSpec.describe Rule::Method, type: :rule do
  subject(:instance) { described_class.new(:a_method, 'a source value', 'a boundary') }

  it { is_expected.to respond_to(:rule_method, :src, :bound) }

  describe '#met?' do
    subject(:met) { instance.met? }

    let(:src) { 100 }
    let(:bound) { 101 }

    context 'with a predefined method' do
      let(:instance) { described_class.new(:maximum, src, bound) }

      before { allow(instance).to receive(:maximum) }

      it 'sends rule method as message to self' do
        met
        expect(instance).to have_received(:maximum)
      end
    end
  end

  describe '#unmet?' do
    subject(:unmet) { instance.unmet? }

    let(:src) { 100 }
    let(:bound) { 101 }

    context 'with a predefined method' do
      let(:instance) { described_class.new(:maximum, src, bound) }

      before do
        allow(instance).to receive(:met?).and_return true
      end

      it 'sends met? message to self' do
        unmet
        expect(instance).to have_received(:met?)
      end

      it 'inverts result of met?' do
        is_expected.to be false
      end
    end
  end

  describe '#maximum' do
    shared_examples 'maximum with bound of' do |bound|
      context "with bound of #{bound.class}" do
        subject(:call) { instance.maximum }

        let(:instance) { described_class.new(:irrelevant, src, bound, options) }
        let(:options) { {} }

        context 'when source greater than bound' do
          let(:src) { bound + 1 }

          it { is_expected.to be_falsey }
        end

        context 'when source equal to bound' do
          let(:src) { bound }

          it { is_expected.to be_truthy }
        end

        context 'when source less than bound' do
          let(:src) { bound - 1 }

          it { is_expected.to be_truthy }
        end

        context 'when source nil' do
          let(:src) { nil }

          it { expect { call }.to raise_error NoMethodError }

          context 'with allow_nil: true' do
            let(:options) { { allow_nil: true } }

            it { is_expected.to be_truthy }
          end

          context 'with allow_nil: false' do
            let(:options) { { allow_nil: false } }

            it { expect { call }.to raise_error NoMethodError }
          end
        end
      end
    end

    include_examples 'maximum with bound of', 100
    include_examples 'maximum with bound of', Date.today
  end

  describe '#minimum' do
    shared_examples 'minimum with bound of' do |bound|
      context "with bound of #{bound.class}" do
        subject(:call) { instance.minimum }

        let(:instance) { described_class.new(:irrelevant, src, bound, options) }
        let(:options) { {} }

        context 'when source greater than bound' do
          let(:src) { bound + 1 }

          it { is_expected.to be_truthy }
        end

        context 'when source equal to bound' do
          let(:src) { bound }

          it { is_expected.to be_truthy }
        end

        context 'when source less than bound' do
          let(:src) { bound - 1 }

          it { is_expected.to be_falsey }
        end

        context 'when source nil' do
          let(:src) { nil }

          it { expect { call }.to raise_error NoMethodError }

          context 'with allow_nil: true' do
            let(:options) { { allow_nil: true } }

            it { is_expected.to be_truthy }
          end

          context 'with allow_nil: false' do
            let(:options) { { allow_nil: false } }

            it { expect { call }.to raise_error NoMethodError }
          end
        end
      end
    end

    include_examples 'minimum with bound of', 100
    include_examples 'minimum with bound of', Date.today
  end

  describe '#equal' do
    shared_examples 'equal with bound of' do |bound|
      context "with bound of #{bound.class}" do
        subject { instance.equal }

        let(:instance) { described_class.new(:irrelevant, src, bound, options) }
        let(:options) { {} }

        context 'when source greater than bound' do
          let(:src) { bound + 1 }

          it { is_expected.to be_falsey }
        end

        context 'when source equal to bound' do
          let(:src) { bound }

          it { is_expected.to be_truthy }
        end

        context 'when source less than bound' do
          let(:src) { bound - 1 }

          it { is_expected.to be_falsey }
        end

        context 'when source nil' do
          let(:src) { nil }

          it { is_expected.to be_falsey }

          context 'with allow_nil: true' do
            let(:options) { { allow_nil: true } }

            it { is_expected.to be_truthy }
          end

          context 'with allow_nil: false' do
            let(:options) { { allow_nil: false } }

            it { is_expected.to be_falsey }
          end
        end
      end
    end

    include_examples 'equal with bound of', 100
    include_examples 'equal with bound of', Date.today
  end

  describe '#inclusion' do
    subject { instance.inclusion }

    let(:instance) { described_class.new(:irrelevant, src, bound, options) }
    let(:bound) { [101, 102] }
    let(:options) { {} }

    context 'when source is nil' do
      let(:src) { nil }

      it { is_expected.to be_falsey }

      context 'with allow_nil: true' do
        let(:options) { { allow_nil: true } }

        it { is_expected.to be_truthy }
      end

      context 'with allow_nil: false' do
        let(:options) { { allow_nil: false } }

        it { is_expected.to be_falsey }
      end
    end

    context 'when source in bound array' do
      let(:src) { 101 }

      it { is_expected.to be_truthy }

      context 'with allow_nil: true' do
        let(:options) { { allow_nil: true } }

        it { is_expected.to be_truthy }
      end

      context 'with allow_nil: false' do
        let(:options) { { allow_nil: false } }

        it { is_expected.to be_truthy }
      end
    end

    context 'when source not in bound array' do
      let(:src) { 99 }

      it { is_expected.to be_falsey }

      context 'with allow_nil: true' do
        let(:options) { { allow_nil: true } }

        it { is_expected.to be_falsey }
      end

      context 'with allow_nil: false' do
        let(:options) { { allow_nil: false } }

        it { is_expected.to be_falsey }
      end
    end
  end

  describe '#exclusion' do
    subject { instance.exclusion }

    let(:instance) { described_class.new(:irrelevant, src, bound, options) }
    let(:bound) { [101, 102] }
    let(:options) { {} }

    context 'when source is nil' do
      let(:src) { nil }

      it { is_expected.to be_truthy }

      context 'with allow_nil: true' do
        let(:options) { { allow_nil: true } }

        it { is_expected.to be_truthy }
      end

      context 'with allow_nil: false' do
        let(:options) { { allow_nil: false } }

        it { is_expected.to be_falsey }
      end
    end

    context 'when source in bound array' do
      let(:src) { 101 }

      it { is_expected.to be_falsey }

      context 'with allow_nil: true' do
        let(:options) { { allow_nil: true } }

        it { is_expected.to be_falsey }
      end

      context 'with allow_nil: false' do
        let(:options) { { allow_nil: false } }

        it { is_expected.to be_falsey }
      end
    end

    context 'when source NOT in bound array' do
      let(:src) { 99 }

      it { is_expected.to be_truthy }

      context 'with allow_nil: true' do
        let(:options) { { allow_nil: true } }

        it { is_expected.to be_truthy }
      end

      context 'with allow_nil: false' do
        let(:options) { { allow_nil: false } }

        it { is_expected.to be_truthy }
      end
    end
  end
end


text:
<!DOCTYPE html>

	<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
	<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no">
	<meta content="telephone=no" name="format-detection">
	<title>MOJOY</title>

			Copyright © 2017 MOJOY TEAM

	<link href="src/app.css" rel="stylesheet">


text:
package com.haskforce.settings;

import com.haskforce.HaskellModuleType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleConfigurationEditor;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.roots.ui.configuration.ClasspathEditor;
import com.intellij.openapi.roots.ui.configuration.DefaultModuleEditorsProvider;
import com.intellij.openapi.roots.ui.configuration.JavaContentEntriesEditor;
import com.intellij.openapi.roots.ui.configuration.ModuleConfigurationState;

/** Provides the editors available in Project Structure > Modules. */
public class HaskellModuleConfigurationEditor extends DefaultModuleEditorsProvider {
    public ModuleConfigurationEditor[] createEditors(ModuleConfigurationState state) {
        Module module = state.getCurrentRootModel().getModule();
        if (!(ModuleType.get(module) instanceof HaskellModuleType)) {
            return ModuleConfigurationEditor.EMPTY;
        }
        return new ModuleConfigurationEditor[]{
                new JavaContentEntriesEditor(module.getName(), state),
                // new CabalFilesEditor(state),
                new ClasspathEditor(state),
        };
    }
}


text: Test that all nodes from the detached DOM tree will get into one group in the heap snapshot. Bug 107819.


text:
import React                from 'react';
import ReactDOM             from 'react-dom';
import TestUtils            from 'react-addons-test-utils';
import wrapInDndContext     from '../../../../../specs_support/dnd_wrapper';
import { MovableWords, __RewireAPI__ as RewireAPI }     from './movable_words';

describe('movable words', () => {
  var result, props;
  beforeEach(() => {
    props = {
      wordChain: [1],
      answers: [{
        id: 1,
        material: "asdf"
      }],
      selectAnswer: () => {}
    };

    const WrappedComponent = wrapInDndContext(MovableWords);
    RewireAPI.__Rewire__('ItemChain', () => { return
WordChain
});
    result = TestUtils.renderIntoDocument(<WrappedComponent {...props} />);
  });

  it('renders the word chain', () => {
    expect(ReactDOM.findDOMNode(result).textContent).toContain("WordChain");
  });

  it('renders the word cloud', () => {
    expect(ReactDOM.findDOMNode(result).textContent).toContain("asdf");
  });
});