text:
<?php
  // src/Ddnet/PortfolioBundle/DataFixtures/ORM/LoadStatusData.php
namespace Ddnet\PortfolioBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Ddnet\PortfolioBundle\Entity\Status;

class LoadStatusData extends AbstractFixture implements OrderedFixtureInterface {
  public function load(ObjectManager $manager) {
    $abandoned = new Status();
    $abandoned->setName('abandoned');
    $abandoned->setSlug('abandoned');
    $manager->persist($abandoned);
    $this->addReference('status-abandoned', $abandoned);

    $planning = new Status();
    $planning->setName('planning');
    $planning->setSlug('planning');
    $manager->persist($planning);
    $this->addReference('status-planning', $planning);

    $active = new Status();
    $active->setName('active');
    $active->setSlug('active');
    $manager->persist($active);
    $this->addReference('status-active', $active);

    $completed = new Status();
    $completed->setName('completed');
    $completed->setSlug('completed');
    $manager->persist($completed);
    $this->addReference('status-completed', $completed);

    $hold = new Status();
    $hold->setName('on hold');
    $hold->setSlug('on-hold');
    $manager->persist($hold);
    $this->addReference('status-on-hold', $hold);

    $going = new Status();
    $going->setName('on going');
    $going->setSlug('on-going');
    $manager->persist($going);
    $this->addReference('status-on-going', $going);

    $manager->flush();
  }

  public function getOrder() { return 2; }
}


text:
package com.siyeh.ig.fixes.performance;

import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.siyeh.ig.LightInspectionTestCase;
import com.siyeh.ig.performance.ListRemoveInLoopInspection;
import org.jetbrains.annotations.NotNull;

public class ListRemoveInLoopFixTest extends LightQuickFixParameterizedTestCase {

  @NotNull
  @Override
  protected LocalInspectionTool[] configureLocalInspectionTools() {
    return new LocalInspectionTool[]{new ListRemoveInLoopInspection()};
  }

  @Override
  protected String getBasePath() {
    return "/com/siyeh/igfixes/fixes/list_remove_in_loop";
  }

  @NotNull
  @Override
  protected String getTestDataPath() {
    return PathManagerEx.getCommunityHomePath() + LightInspectionTestCase.INSPECTION_GADGETS_TEST_DATA_PATH;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>

        <record id="view_vat_declaration" model="ir.ui.view">
            <field name="name">Vat Declaraion</field>
            <field name="model">l1on_be.vat.declaration</field>
            <field name="arch" type="xml">
                <form string="Periodical VAT Declaration" version="7.0">
                    <group>
                        <group string="Declare Periodical VAT">
                            <field name="period_id" widget="selection"/>
                            <field name="tax_code_id" string="Company" widget="selection" groups="base.group_multi_company"/>
                        </group>
                        <group string="Advanced Options">
                            <field name="ask_restitution"/>
                            <field name="ask_payment"/>
                            <field name="client_nihil" string="Is Last Declaration"/>
                        </group>
                    </group>
                    <separator string="Comments"/>
                    <field name="comments"/>
                    <footer>
                        <button name="create_xml" string="Create XML" type="object" default_focus="1" class="oe_highlight"  />
                        or
                        <button string="Cancel" class="oe_link" special="cancel" />
                    </footer>
                </form>
            </field>
        </record>

        <record id="view_vat_save" model="ir.ui.view">
            <field name="name">Save XML</field>
            <field name="model">l1on_be.vat.declaration</field>
            <field name="arch" type="xml">
                <form string="Save xml" version="7.0">
                    <label string="Save the File with '.xml' extension."/>
                    <field name="name"/>
                    <field name="file_save" readonly="True" filename="name"/>
                </form>
            </field>
        </record>

        <record id="action_vat_declaration" model="ir.actions.act_window">
            <field name="name">Vat Declaration</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">l1on_be.vat.declaration</field>
            <field name="view_type">form</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="view_vat_declaration"/>
            <field name="target">new</field>
        </record>

        <menuitem
            name="Periodical VAT Declaration"
            parent="l10n_be.menu_finance_belgian_statement"
            action="action_vat_declaration"
            id="l10n_be.l10_be_vat_declaration"
            groups="account.group_account_manager"/>

    </data>
</openerp>


text:
<?php

declare(strict_types=1);

namespace SIAP\Reference\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Routing\Loader\YamlFileLoader as YamlRoutingLoader;

class ReferenceExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $locator = new FileLocator(__DIR__.'/../Resources/config');
        $loader  = new XmlFileLoader($container, $locator);
        $loader->load('services.xml');

        $yaml = new YamlFileLoader($container, $locator);
        $yaml->load('filters.yaml');
    }

    private function loadRoutes(ContainerBuilder $container, FileLocator $locator)
    {
        $loader = new YamlRoutingLoader($locator);
        $loader->load(__DIR__.'/../Resources/config/routes.yaml');
    }
}


text:
function createDataTableFiltering(selector) {
    var source = {
        dataType: "xml",
        dataFields: [
            { name: 'SupplierName', type: 'string' },
            { name: 'Quantity', type: 'number' },
            { name: 'OrderDate', type: 'date' },
            { name: 'OrderAddress', type: 'string' },
            { name: 'Freight', type: 'number' },
            { name: 'Price', type: 'number' },
            { name: 'City', type: 'string' },
            { name: 'ProductName', type: 'string' },
            { name: 'Address', type: 'string' }
        ],
        url: '../../sampledata/orderdetailsextended.xml',
        root: 'DATA',
        record: 'ROW'
    };
    var dataAdapter = new $.jqx.dataAdapter(source, {
        loadComplete: function () {
            // data is loaded.
        }
    });
    // initialization options - validated in typescript
    // jqwidgets.DataTableOptions has generated TS definition
    var options = {
        source: dataAdapter,
        pageable: true,
        altRows: true,
        filterable: true,
        width: 850,
        columns: [
            { text: 'Supplier Name', cellsAlign: 'center', align: 'center', dataField: 'SupplierName', width: 250 },
            { text: 'Name', cellsAlign: 'center', align: 'center', dataField: 'ProductName', width: 250 },
            { text: 'Quantity', dataField: 'Quantity', cellsFormat: 'd', cellsAlign: 'center', align: 'center', width: 120 },
            { text: 'Price', dataField: 'Price', cellsFormat: 'c2', align: 'center', cellsAlign: 'center', width: 120 },
            { text: 'City', cellsAlign: 'center', align: 'center', dataField: 'City' }
        ]
    };
    // creates an instance
    var myDataTable = jqwidgets.createInstance(selector, 'jqxDataTable', options);
}
//# sourceMappingURL=typescript-datatable-filtering.js.map


text:
from abc import ABCMeta, abstractmethod, abstractproperty
import logging

logger = logging.getLogger(__name__)

class BasePlasmaProperty(object):
    __metaclass__ = ABCMeta

    @abstractproperty
    def outputs(self):
        pass

    @property
    def name(self):
        return self.__class__.__name__

    def __init__(self):
        for output in self.outputs:
            setattr(self, output, None)

    def _update_type_str(self):
        """
        Get type string for Label

        Returns
        -------
            : ~str

        """
        self.type_str = repr(type(self.value))

    def get_latex_label(self):
        latex_template = r"""\textbf{{Name}} {name}
\textbf{{Formula}} {formula}
{description}
"""
        outputs = self.outputs.replace('_', r'\_')
        latex_name = getattr(self, 'latex_name', '')
        if latex_name != '':
            complete_name = '{0} [{1}]'.format(latex_name, self.latex_name)
        else:
            complete_name = latex_name

        latex_label = latex_template.format(name=complete_name,
                                     formula=getattr(self,
                                                     'latex_formula', '--'),
                                     description=getattr(self,
                                                         'latex_description',
                                                         ''))
        return latex_label.replace('\\', r'\\')

class ProcessingPlasmaProperty(BasePlasmaProperty):
    __metaclass__ = ABCMeta

    def __init__(self, plasma_parent):
        super(ProcessingPlasmaProperty, self).__init__()
        self.plasma_parent = plasma_parent
        self._update_inputs()

    def _update_inputs(self):
        """
        This function uses the CPython API to read the variable names from the
        `calculate`-function and makes the plasma routines easily programmable.
        """
        calculate_call_signature = self.calculate.func_code.co_varnames[
                                   :self.calculate.func_code.co_argcount]
        self.inputs = [item for item in calculate_call_signature if
                      item != 'self']

    def _get_input_values(self):
        return (self.plasma_parent.get_value(item) for item in self.inputs)

    def update(self):
        """
        Updates the processing Plasma by calling the `calculate`-method with
        the required inputs

        :return:
        """

        if len(self.outputs) == 1:
            setattr(self, self.outputs[0], self.calculate(
                *self._get_input_values()))
        else:
            new_values = self.calculate(*self._get_input_values())
            for i, output in enumerate(self.outputs):
                setattr(self, output, new_values[i])

    @abstractmethod
    def calculate(self, *args, **kwargs):
        raise NotImplementedError('This method needs to be implemented by '
                                  'processing plasma modules')

class HiddenPlasmaProperty(ProcessingPlasmaProperty):
    __metaclass__ = ABCMeta

    def __init__(self, plasma_parent):
        super(HiddenPlasmaProperty, self).__init__(plasma_parent)


text:
using namespace std;

template<typename T>
int extract(void)
{
    return 0;
}

template<typename T, typename ...Tail>
int extract(Tail...t)
{
    return extract<T, Tail...>(t...);
}

template<typename T, typename Head, typename ...Tail>
int extract(Head h, Tail...t)
{
    return 1+extract<T, Tail...>(t...);
}

int main(void)
{
  const auto e = extract<int>(12, 34, "x", 3.1);
  cout << e << endl;
  return 0;
}


text:
<?php
namespace Faker\Components\Config;

use Faker\Components\Config\InvalidConfigurationException,
    Faker\Components\Config\EntityInterface;

class Entity implements EntityInterface
{

    //  ----------------------------------------------------------------
    # Properties

    protected $dbschema;

    public function getSchema()
    {
        return $this->dbschema;
    }

    public function setSchema($schema)
    {
        $this->dbschema = $schema;
    }

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

    protected $dbuser;

    public function getUser()
    {
        return $this->dbuser;
    }

    public function setUser($user)
    {
        $this->dbuser = $user;
    }

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

    protected $dbtype;

    public function getType()
    {
        return $this->dbtype;
    }

     public function setType($type)
     {
        $this->dbtype = $type;
     }

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

    protected $dbport;

    public function getPort()
    {
        return $this->dbport;
    }

    public function setPort($port)
    {
        $this->dbport = $port;
    }

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

    protected $dbhost;

    public function getHost()
    {
        return $this->dbhost;
    }

    public function setHost($host)
    {
        $this->dbhost = $host;
    }

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

    protected $dbpassword;

    public function getPassword()
    {
        return $this->dbpassword;
    }

    public function setPassword($password)
    {
        $this->dbpassword = $password;
    }

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

    protected $dbmemory;

    public function getMemory()
    {
        return $this->dbmemory;
    }

    public function setMemory($memory)
    {
        $this->dbmemory = $memory;
    }

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

    protected $dbsocket;

    public function getUnixSocket()
    {
        return $this->dbsocket;
    }

    public function setUnixSocket($socket)
    {
        $this->dbsocket = $socket;
    }

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

    protected $dbpath;

    public function getPath()
    {
        return $this->dbpath;
    }

    public function setPath($path)
    {
        $this->dbpath = $path;
    }

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

    protected $dbcharset;

    public function getCharset()
    {
        return $this->dbcharset;
    }

    public function setCharset($set)
    {
        $this->dbcharset = $set;
    }

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

}
/* End of File */


text:
import React from 'react'

import Button from 'material-ui/Button'

export default ({
  onNext,
  onNextDisabled
}) =>
  <div
    className={'flex flex-row justify-end mt3'}
  >
    <Button
      variant={'raised'}
      color={'primary'}
      onTouchTap={onNext}
      children={'NEXT'}
      disabled={onNextDisabled}
    />
  </div>


text:
#region Apache License v2.0
//Copyright 2014 Stephen Yu

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

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

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

namespace StarMQ.Message
{
    using Model;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public interface IPipeline : IMessagingInterceptor
    {
        void Add(IMessagingInterceptor interceptor);
    }

    internal class InterceptorPipeline : IPipeline
    {
        private readonly IList<IMessagingInterceptor> _pipeline = new List<IMessagingInterceptor>();

        public void Add(IMessagingInterceptor interceptor)
        {
            if (interceptor == null)
                throw new ArgumentNullException("interceptor");

            _pipeline.Add(interceptor);
        }

        public IMessage<byte[]> OnSend(IMessage<byte[]> seed)
        {
            if (seed == null)
                throw new ArgumentNullException("seed");

            return _pipeline.Aggregate(seed, (acc, f) => f.OnSend(acc));
        }

        public IMessage<byte[]> OnReceive(IMessage<byte[]> seed)
        {
            if (seed == null)
                throw new ArgumentNullException("seed");

            return _pipeline.Reverse()
                .Aggregate(seed, (acc, f) => f.OnReceive(acc));
        }
    }
}


text:
from __future__ import absolute_import
from __future__ import print_function
from pyface.tasks.traits_dock_pane import TraitsDockPane
from pyface.tasks.traits_task_pane import TraitsTaskPane
from traits.api import HasTraits, Any, File, String, Int, Enum, Instance, Dict, \
    on_trait_change, Bool, Range
from traitsui.api import View, Item, UItem, EnumEditor

from pychron.canvas.canvas2D.video_canvas import VideoCanvas
from pychron.core.ui.stage_component_editor import VideoComponentEditor

# ============= standard library imports ========================
# ============= local library imports  ==========================
class Source(HasTraits):
    def url(self):
        return

class LocalSource(Source):
    path = File

    def traits_view(self):
        return View(UItem('path'))

    def url(self):
        return 'file://{}'.format(self.path)

class RemoteSource(Source):
    host = String('localhost', enter_set=True, auto_set=False)
    port = Int(1084, enter_set=True, auto_set=False)

    def traits_view(self):
        return View(
            Item('host'),
            Item('port'))

    def url(self):
        return 'pvs://{}:{}'.format(self.host, self.port)

class ControlsPane(TraitsDockPane):
    name = 'Controls'
    id = 'pychron.video.controls'
    show_grids = Bool(False)
    fps = Range(1, 12, 10)
    quality = Range(1, 75, 10)

    def traits_view(self):
        v = View(
            Item('show_grids', label='Grid'),
            Item('fps'),
            Item('quality'))
        return v

class SourcePane(TraitsDockPane):
    name = 'Source'
    id = 'pychron.video.source'
    kind = Enum('Remote', 'Local')
    source = Instance(Source)
    connections = Dict
    selected_connection = Any

    def traits_view(self):
        v = View(
            UItem('kind'),
            UItem('source',
                  style='custom'),
            UItem('selected_connection',
                  editor=EnumEditor(name='connections'),
                  style='custom'))
        return v

    def _kind_changed(self):
        if self.kind == 'Local':
            self.source = LocalSource()
        else:
            self.source = RemoteSource()

    def _source_default(self):
        return RemoteSource()

class BaseVideoPane(HasTraits):
    component = Any
    video = Any

    @on_trait_change('video:fps')
    def _update_fps(self):
        print('set component fps', self.video.fps)
        self.component.fps = self.video.fps

    def _video_changed(self):
        self.component.video = self.video

    def _component_default(self):
        c = VideoCanvas(video=self.video,
                        show_axes=False,
                        show_grids=False,
                        padding=5)
        return c

    def traits_view(self):
        v = View(UItem('component',
                       style='custom',
                       editor=VideoComponentEditor()))
        return v

class VideoPane(TraitsTaskPane, BaseVideoPane):
    pass

class VideoDockPane(TraitsDockPane, BaseVideoPane):
    id = 'pychron.video'
    name = 'Video'

# ============= EOF =============================================


text:
import { Student } from './student';

export class Class {
    _id: string;
    grade: string;
    subjects: string[];
    students: Student[];

    constructor() {
        this.grade = '';
        this.subjects = [];
        this.students = [];
    }
}


text:
package at.privatwolke.wifi;

import org.junit.Test;

public class TestWifiProvider {

	@Test
	public void test() {
		WirelessMontiorFactory.getInstance();
	}

}


text:
<?php

namespace net\authorize\api\contract\v1\TransactionResponseType;

/**
 * Class representing SplitTenderPaymentsAType
 */
class SplitTenderPaymentsAType
{

    /**
     * @property
     * \net\authorize\api\contract\v1\TransactionResponseType\SplitTenderPaymentsAType\SplitTenderPaymentAType[]
     * $splitTenderPayment
     */
    private $splitTenderPayment = null;

    /**
     * Adds as splitTenderPayment
     *
     * @return self
     * @param
     * \net\authorize\api\contract\v1\TransactionResponseType\SplitTenderPaymentsAType\SplitTenderPaymentAType
     * $splitTenderPayment
     */
    public function addSplitTenderPaymentToSplitTenderPayment(\net\authorize\api\contract\v1\TransactionResponseType\SplitTenderPaymentsAType\SplitTenderPaymentAType $splitTenderPayment)
    {
        $this->splitTenderPayment[] = $splitTenderPayment;
        return $this;
    }

    /**
     * isset splitTenderPayment
     *
     * @param scalar $index
     * @return boolean
     */
    public function issetSplitTenderPayment($index)
    {
        return isset($this->splitTenderPayment[$index]);
    }

    /**
     * unset splitTenderPayment
     *
     * @param scalar $index
     * @return void
     */
    public function unsetSplitTenderPayment($index)
    {
        unset($this->splitTenderPayment[$index]);
    }

    /**
     * Gets as splitTenderPayment
     *
     * @return
     * \net\authorize\api\contract\v1\TransactionResponseType\SplitTenderPaymentsAType\SplitTenderPaymentAType[]
     */
    public function getSplitTenderPayment()
    {
        return $this->splitTenderPayment;
    }

    /**
     * Sets a new splitTenderPayment
     *
     * @param
     * \net\authorize\api\contract\v1\TransactionResponseType\SplitTenderPaymentsAType\SplitTenderPaymentAType[]
     * $splitTenderPayment
     * @return self
     */
    public function setSplitTenderPayment(array $splitTenderPayment)
    {
        $this->splitTenderPayment = $splitTenderPayment;
        return $this;
    }

}


text:
package org.newdawn.slick.opengl;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import org.lwjgl.BufferUtils;
import org.newdawn.slick.opengl.renderer.Renderer;
import org.newdawn.slick.opengl.renderer.SGL;
import org.newdawn.slick.util.Log;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * A texture to be bound within JOGL. This object is responsible for
 * keeping track of a given OpenGL texture and for calculating the
 * texturing mapping coordinates of the full image.
 *
 * Since textures need to be powers of 2 the actual texture may be
 * considerably bigged that the source image and hence the texture
 * mapping coordinates need to be adjusted to matchup drawing the
 * sprite against the texture.
 *
 * @author Kevin Glass
 * @author Brian Matzon
 */
public class TextureImpl implements Texture {
    /** The renderer to use for all GL operations */
    private static final SGL GL = Renderer.get();

    /** The last texture that was bound to */
    @Nullable
    private static Texture lastBind;

    /**
     * Retrieve the last texture bound through the texture interface
     *
     * @return The last texture bound
     */
    @Nullable
    public static Texture getLastBind() {
        return lastBind;
    }

    /** The GL target type */
    private int target;
    /** The GL texture ID */
    private int textureID = 0;
    /** The height of the image */
    private int height;
    /** The width of the image */
    private int width;
    /** The width of the texture */
    private int texWidth;
    /** The height of the texture */
    private int texHeight;
    /** The ratio of the width of the image to the texture */
    private float widthRatio;
    /** The ratio of the height of the image to the texture */
    private float heightRatio;
    /** The format of this image. */
    private ImageData.Format format;
    /** The reference this texture was loaded from */
    private String ref;
    /** The name the texture has in the cache */
    private String cacheName;

    /** Data used to reload this texture */
    private ReloadData reloadData;

    /**
     * For subclasses to utilise
     */
    TextureImpl() {
    }

    /**
     * Create a new texture
     *
     * @param ref The reference this texture was loaded from
     * @param target The GL target
     * @param textureID The GL texture ID
     */
    public TextureImpl(String ref, int target,int textureID) {
        this.target = target;
        this.ref = ref;
        this.textureID = textureID;
        lastBind = this;
    }

    /**
     * Set the name this texture is stored against in the cache
     *
     * @param cacheName The name the texture is stored against in the cache
     */
    public void setCacheName(String cacheName) {
        this.cacheName = cacheName;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#hasAlpha()
     */
    public boolean hasAlpha() {
        return format.hasAlpha();
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getTextureRef()
     */
    public String getTextureRef() {
        return ref;
    }

  /**
   * Set the format of the image
   *
   * @param imageFormat the format of the image this texture displays
   */
    public void setImageFormat(final ImageData.Format imageFormat) {
      format = imageFormat;
    }

    /**
     * Clear the binding of the texture
     */
    public static void bindNone() {
        lastBind = null;
        GL.glDisable(SGL.GL_TEXTURE_2D);
    }

    /**
     * Clear slick caching of the last bound texture so that an
     * external texture binder can play with the context before returning
     * control to slick.
     */
    public static void unbind() {
        lastBind = null;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#bind()
     */
    public void bind() {
        if (lastBind != this) {
            lastBind = this;
            GL.glEnable(SGL.GL_TEXTURE_2D);
            GL.glBindTexture(target, textureID);
        }
    }

    /**
     * Set the height of the image
     *
     * @param height The height of the image
     */
    public void setHeight(int height) {
        this.height = height;
        setHeight();
    }

    /**
     * Set the width of the image
     *
     * @param width The width of the image
     */
    public void setWidth(int width) {
        this.width = width;
        setWidth();
    }

    public ImageData.Format getImageFormat() {
        return format;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getImageHeight()
     */
    public int getImageHeight() {
        return height;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getImageWidth()
     */
    public int getImageWidth() {
        return width;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getHeight()
     */
    public float getHeight() {
        return heightRatio;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getWidth()
     */
    public float getWidth() {
        return widthRatio;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getTextureHeight()
     */
    public int getTextureHeight() {
        return texHeight;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getTextureWidth()
     */
    public int getTextureWidth() {
        return texWidth;
    }

    /**
     * Set the height of this texture
     *
     * @param texHeight The height of the texture
     */
    public void setTextureHeight(int texHeight) {
        this.texHeight = texHeight;
        setHeight();
    }

    /**
     * Set the width of this texture
     *
     * @param texWidth The width of the texture
     */
    public void setTextureWidth(int texWidth) {
        this.texWidth = texWidth;
        setWidth();
    }

    /**
     * Set the height of the texture. This will update the
     * ratio also.
     */
    private void setHeight() {
        if (texHeight != 0) {
            heightRatio = ((float) height)/texHeight;
        }
    }

    /**
     * Set the width of the texture. This will update the
     * ratio also.
     */
    private void setWidth() {
        if (texWidth != 0) {
            widthRatio = ((float) width)/texWidth;
        }
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#release()
     */
    public void release() {
        if (textureID == 0)
            return;
        InternalTextureLoader.deleteTextureID(textureID);

        if (lastBind == this) {
            bindNone();
        }

        if (cacheName != null) {
            InternalTextureLoader.get().clear(cacheName);
        } else {
            InternalTextureLoader.get().clear(ref);
        }
        textureID = 0;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getTextureID()
     */
    public int getTextureID() {
        return textureID;
    }

    /**
     * Set the OpenGL texture ID for this texture
     *
     * @param textureID The OpenGL texture ID
     */
    void setTextureID(int textureID) {
        this.textureID = textureID;
    }

    /**
     * Creates an integer buffer to hold specified ints
     * - strictly a utility method
     *
     * @param size how many int to contain
     * @return created IntBuffer
     */
    @Nonnull
    protected IntBuffer createIntBuffer(int size) {
      ByteBuffer temp = ByteBuffer.allocateDirect(4 * size);
      temp.order(ByteOrder.nativeOrder());

      return temp.asIntBuffer();
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#getTextureData()
     */
    public byte[] getTextureData() {
        ByteBuffer buffer = BufferUtils.createByteBuffer(format.getColorComponents() * texWidth * texHeight);
        bind();
        GL.glGetTexImage(SGL.GL_TEXTURE_2D, 0, format.getOGLType(), SGL.GL_UNSIGNED_BYTE,
                           buffer);
        byte[] data = new byte[buffer.limit()];
        buffer.get(data);
        buffer.clear();

        return data;
    }

    /**
     * @see org.newdawn.slick.opengl.Texture#setTextureFilter(int)
     */
    public void setTextureFilter(int textureFilter) {
        bind();
        GL.glTexParameteri(target, SGL.GL_TEXTURE_MIN_FILTER, textureFilter);
        GL.glTexParameteri(target, SGL.GL_TEXTURE_MAG_FILTER, textureFilter);
    }

    /**
     * Set the texture data that this texture can be reloaded from
     *
     * @param srcPixelFormat The pixel format
     * @param componentCount The component count
     * @param minFilter The OpenGL minification filter
     * @param magFilter The OpenGL magnification filter
     * @param textureBuffer The texture buffer containing the data for the texture
     */
    public void setTextureData(int srcPixelFormat, int componentCount,
            int minFilter, int magFilter, ByteBuffer textureBuffer) {
        reloadData = new ReloadData();
        reloadData.srcPixelFormat = srcPixelFormat;
        reloadData.componentCount = componentCount;
        reloadData.minFilter = minFilter;
        reloadData.magFilter = magFilter;
        reloadData.textureBuffer = textureBuffer;
    }

    /**
     * Reload this texture if it is holding texture data (release() should be called before this).
     * This is generally done internally (i.e. for use with context switches in Android / OpenGL ES)
     */
    public void reload() {
        if (reloadData != null) {
            textureID = reloadData.reload();
        }
    }

  /**
     * Reload this texture from it's original source data
     */
    private class ReloadData {
        /** The src pixel format */
        private int srcPixelFormat;
        /** The component count */
        private int componentCount;
        /** The OpenGL minification filter */
        private int minFilter;
        /** The OpenGL magnification filter */
        private int magFilter;
        /** The texture buffer of pixel data */
        private ByteBuffer textureBuffer;

        /**
         * Reload this texture
         *
         * @return The new texture ID assigned to this texture
         */
        public int reload() {
            Log.error("Reloading texture: "+ref);
            return InternalTextureLoader.get().reload(TextureImpl.this, srcPixelFormat, componentCount, minFilter, magFilter, textureBuffer);
        }
    }
}


text:
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Streams;

namespace HttpServerWinRT
{
    public sealed class StreamReaderAsync : IInputStreamAsync, IDisposable
    {
        public const uint DefaultBufferSize = 8192;
        public const InputStreamOptions DefaultStreamOptions = InputStreamOptions.Partial;

        uint currentIndex = 0;
        bool headersRead = false;
        readonly IInputStream inputStream;
        readonly StringBuilder stringBuilder;
        readonly Windows.Storage.Streams.Buffer buffer;

        StreamReaderAsync(IInputStream inputStream)
        {
            this.inputStream = inputStream;
            this.stringBuilder = new StringBuilder();
            this.buffer = new Windows.Storage.Streams.Buffer(DefaultBufferSize);
        }

        public static async Task<StreamReaderAsync> Create(IInputStream inputStream)
        {
            var stream = new StreamReaderAsync(inputStream);
            await inputStream.ReadAsync(stream.buffer, stream.buffer.Capacity, DefaultStreamOptions);
            return stream;
        }

        public async Task<int> ReadBytesAsync(byte[] bytes)
        {
            int otherIndex = 0;
            if (currentIndex < buffer.Length)
                for ( ; currentIndex < buffer.Length && otherIndex < bytes.Length; currentIndex++, otherIndex++)
                    bytes[otherIndex] = buffer.GetByte(currentIndex);

            while (!headersRead || (buffer.Length == buffer.Capacity && otherIndex < bytes.Length))
            {
                await inputStream.ReadAsync(buffer, buffer.Capacity, DefaultStreamOptions);
                headersRead = true;

                for (currentIndex = 0; currentIndex < buffer.Length && otherIndex < bytes.Length; currentIndex++, otherIndex++)
                    bytes[otherIndex] = buffer.GetByte(currentIndex);
            }

            return otherIndex;
        }

        void appendStringFromBufferBytes(uint start, uint count)
        {
            if (count > 0)
            {
                var bytes = buffer.ToArray(start, (int)count);
                var str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                stringBuilder.Append(str);
            }
        }

        string scanForNewLine()
        {
            for (uint i = currentIndex; i < buffer.Length - 1; i++)
            {
                if (buffer.GetByte(i) == '\r' && buffer.GetByte(i + 1) == '\n')
                {
                    appendStringFromBufferBytes(currentIndex, i - currentIndex);
                    currentIndex = i + 2;
                    return stringBuilder.ToString();
                }
            }
            appendStringFromBufferBytes(0, buffer.Length);
            currentIndex = buffer.Length;
            return null;
        }

        public async Task<string> ReadLineAsync()
        {
            stringBuilder.Clear();
            if (currentIndex < buffer.Length)
            {
                var str = scanForNewLine();
                if (str != null) { return str; }
            }

            while (!headersRead || buffer.Length == buffer.Capacity)
            {
                await inputStream.ReadAsync(buffer, buffer.Capacity, DefaultStreamOptions);
                headersRead = true;
                currentIndex = 0;

                var str = scanForNewLine();
                if (str != null) { return str; }
            }

            return stringBuilder.ToString();
        }

        public async Task<string> ReadToEndAsync()
        {
            stringBuilder.Clear();
            if (currentIndex < buffer.Length)
                appendStringFromBufferBytes(currentIndex, buffer.Length - currentIndex);

            while (!headersRead || buffer.Length == buffer.Capacity)
            {
                await inputStream.ReadAsync(buffer, buffer.Capacity, DefaultStreamOptions);
                appendStringFromBufferBytes(0, buffer.Length);
                currentIndex = buffer.Length;
                headersRead = true;
            }
            return stringBuilder.ToString();
        }

        public void Dispose()
        {
            this.inputStream.Dispose();
        }
    }

    public sealed class StreamWriterAsync : IOutputStreamAsync, IDisposable
    {
        public readonly IOutputStream Stream;
        public readonly DataWriter DataWriter;

        public StreamWriterAsync(IOutputStream stream)
        {
            this.Stream = stream;
            this.DataWriter = new DataWriter(stream);
        }

        public async Task WriteBytesAsync(byte[] bytes)
        {
            this.DataWriter.WriteBytes(bytes);
            await this.DataWriter.StoreAsync();
        }

        public async Task WriteStringAsync(string str)
        {
            this.DataWriter.WriteString(str);
            await this.DataWriter.StoreAsync();
        }

        public void Dispose()
        {
            this.DataWriter.Dispose();
            this.Stream.Dispose(); // The stream should be disposed with the DataWriter actually
        }
    }
}


text:
package com.intuit.ipp.interceptors;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.intuit.ipp.exception.FMSException;
import com.intuit.ipp.services.CallbackMessage;
import com.intuit.ipp.util.Config;
import com.intuit.ipp.util.Logger;
import com.intuit.ipp.util.StringUtils;
import org.apache.commons.configuration.Configuration;

/**
 * Class to provide the provision to add interceptors in the order those have to be executed.
 *
 */
public class IntuitInterceptorProvider implements Callable<Void> {

	/**
	 * logger instance
	 */
	private static final org.slf4j.Logger LOG = Logger.getLogger();

	/**
	 * variable requestInterceptors is used for keeping the request interceptors
	 */
	private List<Interceptor> requestInterceptors = new ArrayList<Interceptor>();

	/**
	 * variable responseInterceptors is used for keeping the response interceptors
	 */
	private List<Interceptor> responseInterceptors = new ArrayList<Interceptor>();

	/**
	 * variable intuitMessage
	 */
	private IntuitMessage intuitMessage = null;

	/**
	 * Manual configuration properties to be used while executing the interceptors in async mode.
	 */
	private Configuration configuration = null;

	/**
	 * Constructor IntuitInterceptorProvider
	 */
	public IntuitInterceptorProvider() {

		requestInterceptors.add(new PrepareRequestInterceptor());
		requestInterceptors.add(new SerializeInterceptor());
		requestInterceptors.add(new CompressionInterceptor());
		//requestInterceptors.add(new ConnectionInterceptor());
		requestInterceptors.add(getConnectionInterceptor());

		responseInterceptors.add(new DecompressionInterceptor());
		responseInterceptors.add(new DeserializeInterceptor());
		responseInterceptors.add(new HandleResponseInterceptor());
	}

	/**
	 * Method to execute the interceptors (request and response) which are added
	 *
	 * @param intuitMessage the intuit message
	 * @throws FMSException the FMSException
	 */
	public void executeInterceptors(final IntuitMessage intuitMessage) throws FMSException {
		executeRequestInterceptors(intuitMessage);
		executeResponseInterceptors(intuitMessage);
	}

	/**
	 * Method to execute only request interceptors which are added to requestInterceptors list
	 *
	 * @param intuitMessage the intuit message
	 * @throws FMSException the FMSException
	 */
	protected void executeRequestInterceptors(final IntuitMessage intuitMessage) throws FMSException {
		Iterator<Interceptor> itr = requestInterceptors.iterator();
		while (itr.hasNext()) {
			Interceptor interceptor = itr.next();
			interceptor.execute(intuitMessage);
		}
	}

	/**
	 * Method to execute only response interceptors which are added to the responseInterceptors list
	 *
	 * @param intuitMessage the intuit message
	 * @throws FMSException the FMSException
	 */
	protected void executeResponseInterceptors(final IntuitMessage intuitMessage) throws FMSException {
		Iterator<Interceptor> itr = responseInterceptors.iterator();
		while (itr.hasNext()) {
			Interceptor interceptor = itr.next();
			interceptor.execute(intuitMessage);
		}
	}

	/**
	 * Method to execute interceptors in case of Async operations.
	 *
	 * @param intuitMessage the intuit message
	 */
	public void executeAsyncInterceptors(final IntuitMessage intuitMessage) {
		this.intuitMessage = intuitMessage;
		this.configuration = Config.cloneConfigurationOverrides();
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		executorService.submit(this);
	}

	private Interceptor getConnectionInterceptor() {
		String httpTransport = Config.getProperty(Config.HTTP_TRANSPORT);
		if (StringUtils.hasText(httpTransport) && httpTransport.equals(HTTPURLConnectionInterceptor.HTTP_URL_CONNECTION)) {
			return new HTTPURLConnectionInterceptor();
		}
		return new HTTPClientConnectionInterceptor();
	}
	/**
	 * Callable interface method will be executed
	 *
	 * @return Void the Class object representing the Java keyword void
	 * @throws Exception the callable exception
	 */
	@Override
	public Void call() throws FMSException {
		CallbackMessage callbackMessage = new CallbackMessage();
		try {
			// add configuration properties from the caller thread
			Config.addConfigurationOverrides(configuration);
			executeInterceptors(intuitMessage);
		} catch (FMSException e) {
			callbackMessage.setFMSException(e);
			LOG.error("Exception in interceptor flow", e);
		}
		// set callbackMessage
		intuitMessage.getResponseElements().setCallbackMessage(callbackMessage);

		// execute callback handler interceptor
		new CallbackHandlerInterceptor().execute(intuitMessage);

		return null;
	}

    /**
     * Returns current request interceptors.
     * It is used to extend and overwrite existing order
     * @return interceptors list
     */
    protected List<Interceptor> getRequestInterceptors() {
        return requestInterceptors;
    }

    /**
     * Updates interceptors
     * @param requestInterceptors list
     */
    protected void setRequestInterceptors(List<Interceptor> requestInterceptors) {
        this.requestInterceptors = requestInterceptors;
    }

}


text:
  Angra dos Reis

  Aperibé

  Araruama

  Areal

  Armação dos Búzios

  Arraial do Cabo

  Barra do Piraí

  Barra Mansa

  Belford Roxo

  Bom Jardim

  Bom Jesus do Itabapoana

  Cabo Frio

  Cachoeiras de Macacu

  Cambuci

  Campos dos Goytacazes

  Cantagalo

  Carapebus

  Cardoso Moreira

  Carmo

  Casimiro de Abreu

  Comendador Levy Gasparian

  Conceição de Macabu

  Cordeiro

  Duas Barras

  Duque de Caxias

  Engenheiro Paulo de Frontin

  Guapimirim

  Iguaba Grande

  Itaboraí

  Itaguaí

  Italva

  Itaocara

  Itaperuna

  Itatiaia

  Japeri

  Laje do Muriaé

  Macaé

  Macuco

  Magé

  Mangaratiba

  Maricá

  Mendes

  Mesquita

  Miguel Pereira

  Miracema

  Natividade

  Nilópolis

  Niterói

  Nova Friburgo

  Nova Iguaçu

  Paracambi

  Paraíba do Sul

  Paraty

  Paty do Alferes

  Petrópolis

  Pinheiral

  Piraí

  Porciúncula

  Porto Real

  Quatis

  Queimados

  Quissamã

  Resende

  Rio Bonito

  Rio Claro

  Rio das Flores

  Rio das Ostras

  Rio de Janeiro

  Santa Maria Madalena

  Santo Antônio de Pádua

  São Fidélis

  São Francisco de Itabapoana

  São Gonçalo

  São João da Barra

  São João de Meriti

  São José de Ubá

  São José do Vale do Rio Preto

  São Pedro da Aldeia

  São Sebastião do Alto

  Sapucaia

  Saquearema

  Seropédica

  Silva Jardim

  Sumidouro

  Tanguá

  Teresópolis

  Trajano de Moraes

  Três Rios

  Valença

  Varre-Sai

  Vassouras

  Volta Redonda


text:
ACCEPTED

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

#### Published in
Flora of Manchuria and East Mongolia 3: 302 (1928)

#### Original name
Puccinia miscanthi Miura, 1928

### Remarks
null


text:
require 'spec_helper'
require 'trubl/base'

describe Trubl::Base do

  subject{ Trubl::Base.new }

  let(:response){
    resp = double("Response")
    resp.stub(:body).and_return('{"base": {}}')
    resp
  }

  let(:missing_response){
    resp = double("Response")
    resp.stub(:body).and_return('{"error": "resource not found"}')
    resp.stub(:code).and_return(404)
    resp
  }

  let(:error_response){
    resp = double("Response")
    resp.stub(:body).and_return('{"error": "kaboom"}')
    resp.stub(:code).and_return(500)
    resp
  }

  it "inherits from Hash" do
    subject.is_a? Hash
  end

  it "inherits from Hashie::Mash" do
    subject.is_a? Hashie::Mash
  end

  describe "#from_response" do

    it "returns nil if response code is 4xx" do
      missing_response.should_receive(:code)
      instance = subject.from_response(missing_response)
      instance.should be_nil
    end

    it "returns nil if response code is 5xx" do
      error_response.should_receive(:code)
      instance = subject.from_response(error_response)
      instance.should be_nil
    end

    it "parses the response body" do
      response.should_receive(:code)
      subject.should_receive(:parse).with(response)
      subject.from_response(response)
    end

    it "uses the inferred class name" do
      response.should_receive(:code)
      subject.should_receive(:klass_name)
      subject.from_response(response)
    end

    it "re-initializes the instance" do
      response.should_receive(:code)
      subject.should_receive :initialize
      subject.from_response(response)
    end

  end

  describe "#parse" do

    it "parses the response body into a json object" do
       JSON.should_receive(:parse).with(response.body).and_return({})
       subject.parse(response)
    end

  end

  describe "klass_name" do

    it "downcases the class name " do
      subject.klass_name.should == 'base'
    end

  end

end


text:
package test.store.api;

import java.io.File;

import test.util.RandomBytes;

import krati.core.segment.MappedSegmentFactory;
import krati.core.segment.Segment;
import krati.store.ArrayStore;
import krati.store.StaticDataArray;

/**
 * TestStaticDataArrayApi
 *
 * @author jwu
 * 06/06, 2011
 *
 */
public class TestStaticDataArrayApi extends AbstractTestArrayStoreApi {

    @Override
    protected ArrayStore createStore(File homeDir) throws Exception {
        return new StaticDataArray(
                _rand.nextInt(1 << 20), /* length */
                100,                    /* batchSize */
                5,                      /* numSyncBatches */
                homeDir,
                new MappedSegmentFactory(),
                Segment.minSegmentFileSizeMB,
                Segment.defaultSegmentCompactFactor);
    }

    public void testException() throws Exception {
        int index = _store.getIndexStart() + _store.capacity() + _rand.nextInt(100);
        byte[] value = RandomBytes.getBytes();

        try {
            _store.set(index, value, System.currentTimeMillis());
            assertFalse(true);
        } catch(ArrayIndexOutOfBoundsException e) {}

        try {
            _store.get(index);
            assertFalse(true);
        } catch(ArrayIndexOutOfBoundsException e) {}
    }
}


text:
import unittest

from tangled.web import Application, config
from tangled.web import Resource as BaseResource
from tangled.web.resource.config import Config

class TestConfig(unittest.TestCase):

    def setUp(self):
        self.app = Application({})

    def test_no_args_raises_TypeError(self):
        with self.assertRaises(TypeError):
            config('*/*')(type('Resource', (), {}))

    def test_no_defaults(self):

        class Resource(BaseResource):

            @config('text/html', status=303)
            def GET(self):
                pass

        self.app.load_config(Resource)

        resource = Resource(None, None)
        info = Config.for_resource(self.app, resource, 'GET', 'text/html')
        self.assertIsNone(info.type)
        self.assertEqual(info.status, 303)
        self.assertEqual(info.response_attrs, {})
        self.assertEqual(info.representation_args, {})

    def test_defaults(self):

        @config('*/*', status=303)
        class Resource(BaseResource):

            def GET(self):
                pass

        self.app.load_config(Resource)

        resource = Resource(None, None)
        info = Config.for_resource(self.app, resource, 'GET', 'text/html')
        self.assertIsNone(info.type)
        self.assertEqual(info.status, 303)
        self.assertEqual(info.response_attrs, {})
        self.assertEqual(info.representation_args, {})

    def test_override_defaults(self):
        @config(
            '*/*', type='no_content', status=301,
            response_attrs={'status': 204})
        class Resource(BaseResource):

            @config('*/*', status=302)
            @config('application/json', status=303, response_attrs={'x': 'x'})
            @config('text/html', type=None, response_attrs={})
            def GET(self):
                pass

        self.app.load_config(Resource)

        resource = Resource(None, None)
        info = Config.for_resource(self.app, resource, 'GET', 'text/html')
        self.assertIsNone(info.type)
        self.assertEqual(info.status, 302)
        self.assertEqual(info.response_attrs, {})
        self.assertEqual(info.representation_args, {})

        resource = Resource(None, None)
        info = Config.for_resource(
            self.app, resource, 'GET', 'application/json')
        self.assertEqual(info.type, 'no_content')
        self.assertEqual(info.status, 303)
        self.assertEqual(info.response_attrs, {'x': 'x'})
        self.assertEqual(info.representation_args, {})

    def test_add_arg(self):

        class Resource(BaseResource):

            def GET(self):
                pass

        with self.assertRaises(TypeError):
            self.app.load_config(config('*/*', xxx=True)(Resource))

        self.app.add_config_field('*/*', 'xxx', False)
        self.app.load_config(config('*/*', xxx=True)(Resource))

        resource = Resource(None, None)
        info = Config.for_resource(self.app, resource, 'GET', 'text/html')
        self.assertTrue(hasattr(info, 'xxx'))
        self.assertTrue(info.xxx)


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
	<meta http-equiv="X-UA-Compatible" content="chrome=1">
	<title>CVE-2015-5460 – Snorby – 2.6.2 - Stored Cross-site Scripting</title>
	<meta name="description" content="">
	<meta name="author" content="Federico Fazzi">
	<link rel="stylesheet" href="/assets/app-9aa3a0497cf8b7ed5697ebed051cfe57.css">
	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
	<link rel="alternate" type="application/rss+xml" title="" href="/feed.xml">
	<link rel="canonical" href="http://deftcode.ninja/post/CVE-2015-5460-snorby-ids-ui-stored-cross-site-scripting/">

	<button id="toggle" class="standard-width" type="button" data-toggle="collapse">

	</button>

DEFTCODE( 2 )

Posts

Security

About

		GPG - 2048R/6D378CAF

CVE-2015-5460 – Snorby – 2.6.2 - Stored Cross-site Scripting

RELEASED IN WEDNESDAY 15, JULY, 2015

Vendor

https://www.snorby.org/ – 2.6.2

Snorby is a new and modern Snort IDS front-end. The basic fundamental concepts behind snorby are simplicity and power. The project goal is to create a free, open source and highly competitive application for network monitoring for both private and enterprise use.

Description

During my research and testing of new IDS (Intrusion Detection System) like Suricata I've found a Stored Cross-site Scripting (XSS) vulnerability in Snorby that I want to use as web user interface for suricata. The vulnerability exists in the module for adding a new threat classification model where the user input is not correctly sanitized before being saved it on the database or for example the output is not properly filtered, before its rendering in the event/menu code, in this way the vector gets executed.

Vulnerability

CVSS Score: 4.3 (AV:N/AC:M/Au:N/C:N/I:P/A:N)

The XSS vector is triggered in the snorby/app/views/events/_menu.html.erb page by the event/menu:

<% @classifications.each do |cls| %>
    <% if cls.locked && cls.hotkey %>
        <%= drop_down_item "#{cls.name}<span class='shortcut'>#{cls.shortcut}</span>", '#', nil, { :class => 'classification', :"data-classification-id" => cls.id.to_i } %>
    <% else %>
        <%= drop_down_item "#{cls.name}", '#', nil, { :class => 'classification', :"data-classification-id" => cls.id.to_i } %>
    <% end %>
<% end %>

Mitigation

A simple XSS mitigation on rails could be the usage of the sanitize, for example the code below filters the xss vector by removing the onerror attribute from the image tag:

<% @classifications.each do |cls| %
    <% if cls.locked && cls.hotkey %>
        <%= drop_down_item "#{sanitize cls.name}<span class='shortcut'>#{cls.shortcut}</span>", '#', nil, { :class => 'classification', :"data-classification-id" => cls.id.to_i } %>
    <% else %>
        <%= drop_down_item "#{sanitize cls.name}", '#', nil, { :class => 'classification', :"data-classification-id" => cls.id.to_i } %>
    <% end %>
<% end %>

Solution

Update to the latest version on GitHub.

Disclosure:

30-06-2015 – Vendor notification (GitHub Issue-377)

30-06-2015 – CVE id requested

01-07-2015 – Vendor acknowledge

01-07-2015 – Vendor pushed a fix (commit-id: 89d7cbcd3697c8a842f1a61b99e9a78f295798fb)

09-07-2015 – CVE id assigned (CVE-2015-5460)

15-07-2015 – Public disclosure

References

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-5460

http://seclists.org/fulldisclosure/2015/Jul/15

https://github.com/Snorby/snorby/issues/377

Please enable JavaScript to view the comments powered by Disqus.

2016 – MIT License


text:
package org.apache.spark.ui

import java.util.{Timer, TimerTask}

import org.apache.spark._
import org.apache.spark.internal.Logging

/**
 * ConsoleProgressBar shows the progress of stages in the next line of the console. It poll the
 * status of active stages from `sc.statusTracker` periodically, the progress bar will be showed
 * up after the stage has ran at least 500ms. If multiple stages run in the same time, the status
 * of them will be combined together, showed in one line.
 */
private[spark] class ConsoleProgressBar(sc: SparkContext) extends Logging {
  // Carriage return
  private val CR = '\r'
  // Update period of progress bar, in milliseconds
  private val updatePeriodMSec =
    sc.getConf.getTimeAsMs("spark.ui.consoleProgress.update.interval", "200")
  // Delay to show up a progress bar, in milliseconds
  private val firstDelayMSec = 500L

  // The width of terminal
  private val TerminalWidth = if (!sys.env.getOrElse("COLUMNS", "").isEmpty) {
    sys.env.get("COLUMNS").get.toInt
  } else {
    80
  }

  private var lastFinishTime = 0L
  private var lastUpdateTime = 0L
  private var lastProgressBar = ""

  // Schedule a refresh thread to run periodically
  private val timer = new Timer("refresh progress", true)
  timer.schedule(new TimerTask{
    override def run() {
      refresh()
    }
  }, firstDelayMSec, updatePeriodMSec)

  /**
   * Try to refresh the progress bar in every cycle
   */
  private def refresh(): Unit = synchronized {
    val now = System.currentTimeMillis()
    if (now - lastFinishTime < firstDelayMSec) {
      return
    }
    val stageIds = sc.statusTracker.getActiveStageIds()
    val stages = stageIds.flatMap(sc.statusTracker.getStageInfo).filter(_.numTasks() > 1)
      .filter(now - _.submissionTime() > firstDelayMSec).sortBy(_.stageId())
    if (stages.length > 0) {
      show(now, stages.take(3))  // display at most 3 stages in same time
    }
  }

  /**
   * Show progress bar in console. The progress bar is displayed in the next line
   * after your last output, keeps overwriting itself to hold in one line. The logging will follow
   * the progress bar, then progress bar will be showed in next line without overwrite logs.
   */
  private def show(now: Long, stages: Seq[SparkStageInfo]) {
    val width = TerminalWidth / stages.size
    val bar = stages.map { s =>
      val total = s.numTasks()
      val header = s"[Stage ${s.stageId()}:"
      val tailer = s"(${s.numCompletedTasks()} + ${s.numActiveTasks()}) / $total]"
      val w = width - header.length - tailer.length
      val bar = if (w > 0) {
        val percent = w * s.numCompletedTasks() / total
        (0 until w).map { i =>
          if (i < percent) "=" else if (i == percent) ">" else " "
        }.mkString("")
      } else {
        ""
      }
      header + bar + tailer
    }.mkString("")

    // only refresh if it's changed OR after 1 minute (or the ssh connection will be closed
    // after idle some time)
    if (bar != lastProgressBar || now - lastUpdateTime > 60 * 1000L) {
      System.err.print(CR + bar)
      lastUpdateTime = now
    }
    lastProgressBar = bar
  }

  /**
   * Clear the progress bar if showed.
   */
  private def clear() {
    if (!lastProgressBar.isEmpty) {
      System.err.printf(CR + " " * TerminalWidth + CR)
      lastProgressBar = ""
    }
  }

  /**
   * Mark all the stages as finished, clear the progress bar if showed, then the progress will not
   * interweave with output of jobs.
   */
  def finishAll(): Unit = synchronized {
    clear()
    lastFinishTime = System.currentTimeMillis()
  }

  /**
   * Tear down the timer thread.  The timer thread is a GC root, and it retains the entire
   * SparkContext if it's not terminated.
   */
  def stop(): Unit = timer.cancel()
}


text:
package gwen.web.eval.lambda.unit

import gwen.web.eval.WebContext

import gwen.core.behavior.BehaviorType
import gwen.core.eval.lambda.UnitStep
import gwen.core.node.GwenNode
import gwen.core.node.gherkin.Step

import scala.util.chaining._

class WaitForCondition(javascript: String, delayMsecs: Option[Long], timeoutSecs: Option[Long]) extends UnitStep[WebContext] {

  override def apply(parent: GwenNode, step: Step, ctx: WebContext): Step = {
    step tap { _ =>
      checkStepRules(step, BehaviorType.Action, ctx)
      ctx.waitUntil(delayMsecs, timeoutSecs, s"waiting for true return from javascript: $javascript") {
        ctx.evaluateJS(ctx.formatJSReturn(javascript)).asInstanceOf[Boolean]
      }
    }
  }

}


text:
require_relative 'node_util'

# Tacacs Global configuration management
module Cisco
  # TacacsGlobal - node utility class for
  class TacacsGlobal < NodeUtil
    attr_reader :name

    def initialize(name)
      fail TypeError unless name.is_a?(String)
      fail ArgumentError,
           "This provider only accepts an id of 'default'" \
           unless name.eql?('default')
      @name = name
    end

    def self.tacacs_global
      hash = {}
      hash['default'] = TacacsGlobal.new('default')
      hash
    end

    def ==(other)
      name == other.name
    end

    def timeout
      return nil unless Feature.tacacs_enabled?
      config_get('tacacs_global', 'timeout')
    end

    def default_timeout
      config_get_default('tacacs_global', 'timeout')
    end

    def timeout=(val)
      unless val.nil?
        fail ArgumentError, 'timeout must be an Integer' \
          unless val.is_a?(Integer)
      end

      if val.nil?
        fail ArgumentError, 'timeout cannot be unset if TACACS enabled - ' \
        "use default value #{default_timeout}" \
          if Feature.tacacs_enabled?
      else
        Feature.tacacs_enable
        config_set('tacacs_global',
                   'timeout',
                   state:   '',
                   timeout: val)
      end
    end

    def key_format
      match = config_get('tacacs_global', 'key_format')
      match.nil? ? TACACS_GLOBAL_ENC_UNKNOWN : match[0].to_i
    end

    def key
      return nil unless Feature.tacacs_enabled?
      str = config_get('tacacs_global', 'key')
      return TacacsGlobal.default_key if str.empty?
      str[1].strip.gsub(/\"/, '')
    end

    # Get default encryption password
    def self.default_key
      config_get_default('tacacs_global', 'key')
    end

    def encryption_key_set(key_format, key)
      # If we get an empty key - remove default if configured
      if key.nil? || key.to_s.empty?
        key = self.key
        return if key.empty?
        key_format = self.key_format
        config_set('tacacs_server', 'encryption', state: 'no',
                    option: key_format, key: key)
      else
        Feature.tacacs_enable
        key = Utils.add_quotes(key)
        if key_format.nil? || key_format.to_s.empty?
          config_set('tacacs_server', 'encryption', state: '', option: '',
                    key: key)
        else
          config_set('tacacs_server', 'encryption', state: '',
                    option: key_format, key: key)
        end
      end
    end

    # Get default source interface
    def default_source_interface
      config_get_default('tacacs_global', 'source_interface')
    end

    # Set source interface
    def source_interface=(name)
      if name
        Feature.tacacs_enable
        config_set(
          'tacacs_global', 'source_interface',
          state: '', source_interface: name)
      else
        config_set(
          'tacacs_global', 'source_interface',
          state: 'no', source_interface: '')
      end
    end

    # Get source interface
    def source_interface
      return nil unless Feature.tacacs_enabled?
      i = config_get('tacacs_global', 'source_interface')
      i.nil? ? default_source_interface : i.downcase
    end
  end # class
end # module


text:
import React from 'react'
import { NavItem } from 'rebass'
import { FaTasks } from 'react-icons/lib/fa'
import { MdCloud, MdCreditCard, MdPerson, MdPhonelinkSetup, MdTimeline } from 'react-icons/lib/md'

export default (
  <div className='sidebar-icons'>
    <style jsx global>{`
      .icon {
        font-size: 3em;
        padding-right: 0;
      }
    `}</style>
    <NavItem href='/devices' title='Devices'>
      <MdPhonelinkSetup className='icon' />
    </NavItem>
    <NavItem href='/simulations' title='Simulations'>
      <FaTasks className='icon' />
    </NavItem>
    <NavItem href='/runs' title='Runs'>
      <MdCloud className='icon' />
    </NavItem>
    <NavItem href='/reports' title='Reports'>
      <MdTimeline className='icon' />
    </NavItem>
    <NavItem href='/account' title='Account'>
      <MdPerson className='icon' />
    </NavItem>
    <NavItem href='/billing' title='Billing'>
      <MdCreditCard className='icon' />
    </NavItem>
  </div>
)


text:
'use strict';

/**
 * Module dependencies.
*/
var mongoose = require('mongoose'),
	Schema = mongoose.Schema,
	Band = mongoose.model('Band');

var ObjectId = mongoose.Types.ObjectId;

/*convert string to lower case*/
function toLower (v) {
  return v.toLowerCase();
}

/**
 * FeedItem Schema
 */
var FeedItemSchema = new Schema({
	bandID: { type: Schema.ObjectId },
	publisherID: { type: Schema.ObjectId, ref: 'User' },
	itemType: {type: String, trim:true},
	itemID: { type: String, trim:true },
	title: { type: String, trim:true },
	summary: { type: String, trim:true },
	summary_2: { type: String, trim:true },
	description: { type: String, trim:true },
	image:  {type: String},
	link: { type: String, trim:true  },
	state: { type: String, trim:true, lowercase:true, default: 'new' },
	publishedDate: { type: Date, default: Date.now },
	created: { type: Date, default: Date.now },
	updated: { type: Date, default: Date.now },

	//specific fields
	itemStatus: { type: String, trim:true  }, //song, repertoire
	itemScore: { type: Number, default:0  },
	itemQuantity:{ type: Number, default:0  }, //repertoire
	itemDuration:{ type: Number, default:0  }, //repertoire

});

FeedItemSchema.statics.addSongFeed = function(song, user, callback) {

	var itemType = 'song_add';
	var title = 'Added new song';
	var description = 'Song added to the repertoire';
	var publisher = undefined;

	if (song.song_status === 'Backlog' || song.song_status === 'New'){

		publisher = song.user;

		if(song.song_status==='Backlog'){
			publisher = user;
			itemType = 'song_reject';
			title = 'Rejected song';
			description = 'Song placed in to the backlog';
		}

		var _this = new this();

		console.log(song.user);

		_this.bandID = song.band;
		_this.publisherID = publisher;
		_this.itemType = itemType;
		_this.itemID = song._id;
		_this.title = title;
		_this.summary = song.name;
		_this.summary_2 = song.artist;
		_this.description = description ;
		_this.link = '/songs';
		//_this.image = song.song_image;
		//specific fields
		//_this.itemStatus = song.song_status;
		_this.itemScore = song.song_rate;

		//console.log('artist', song.artist);

		//console.log(_this);

		_this.save(function(err) {
			if (err) {
				callback(err, null);
				console.log('feed item save error ' + err);
			}
			else {

				var UserFeed = mongoose.model('UserFeed');
				//FEED CREATED ADD ITEM TO BAND MEMBERS
				Band.getMembers(song.band, function (err, members){

					//loop members
					for (var i = 0; i < members.length; i++) {
						UserFeed.addUserFeed(members[i].member, _this._id, _this.bandID, function(results){
							//console.log('user feed added:', results);
						} );
					}

				}); //band get member callback

				//console.log('feed item saved successfully');
				callback(null, true);
			}
		}); //item.save callback
	}else {
		callback(null, false);
	}
		//end if song

};

FeedItemSchema.index({entryID : 1});
FeedItemSchema.index({bandID : 1});

mongoose.model('FeedItem', FeedItemSchema);

/*FEED COMMENTS */
var feedCommentSchema = new Schema({
	feedItem: { type: Schema.ObjectId, ref: 'FeedItem' },
	authorID: { type: Schema.ObjectId, ref: 'User' },
	publishedDate: { type: Date, default: Date.now },
	comment: {type: String, trim:true }
});

feedCommentSchema.statics.addFeedComment = function(userID, feedItemID, comment, callback) {
	var _this = new this();

	_this.authorID = userID;
	_this.feedItem = feedItemID;
	_this.comment = comment;

	_this.save(function(err) {
		if (err) {
			callback(err,false);
			console.log('feed comment save error ' + err);
		}
		else {
			callback(null, _this);
			console.log('feed comment saved successfully' );
		}
	});
};

feedCommentSchema.index({feedItem : 1});
feedCommentSchema.index({authorID : 1});

mongoose.model('FeedComment', feedCommentSchema);

/*USER x FEED ITEM*/
var UserFeedSchema = new mongoose.Schema({

	userID: { type: Schema.ObjectId },
	feedItemID: { type: Schema.ObjectId, ref: 'FeedItem' },
	bandID: { type: Schema.ObjectId },
	read : { type: Boolean, default: false }

});

UserFeedSchema.statics.addUserFeed = function(userID, feedItemID, bandID, callback) {
	var _this = new this();

	_this.userID = userID;
	_this.feedItemID = feedItemID;
	_this.bandID = bandID;

	_this.save(function(err) {
		if (err) {
			callback(false);
			console.log('user feed item save error ' + err);
		}
		else {
			callback(true);
			console.log('user feed item saved ' );
		}
	});
};

mongoose.model('UserFeed', UserFeedSchema);


text:
<?php

/**
 * Validator Result
 *
 * Value object. Represents a result status from a validator
 * callback. The validator callback is to return this object when
 * called. You can pass an implementation of
 * {@see ValidationErrorMessageInterface} as an error message.
 *
 * To return a valid result after validation:
 *
 *
 * $result = new ValidatorResult(TRUE);
 * return $result;
 *
 *
 * You cannot add an error message if the result is valid. Any
 * calls to {@see addErrorMessage} when the type is valid will be
 * ignored.
 *
 * To return a invalid result after validation:
 *
 *
 * $result = new ValidatorResult(FALSE);
 * $result->addErrorMessage($message);
 * return $result;
 *
 *
 * If your validator method transforms/cleans the validated value,
 * e.g. normalizing a date string, don't forget to put the new
 * value into the object:
 *
 *
 * $result->setValue('date', $formattedDate);
 *
 *
 * The ValidationChain object will check for new value using
 * {@see hasNewValue} after it receives a ValidatorResult object
 * and act accordingly.
 *
 * @author  Ricky Christie <seven.rchristie@gmail.com>
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 *
 */

namespace Carrot\Validation;

use Carrot\Message\ValidationErrorMessageInterface;

class ValidatorResult
{
    /**
     * @var bool If TRUE, then the value passes validation, FALSE otherwise.
     */
    protected $valid;

    /**
     * @var array Contains ValidationErrorMessageInterface instances.
     */
    protected $errorMessages = array();

    /**
     * @var array Contains the new value, transformed/cleaned by the validator.
     */
    protected $value = array();

    /**
     * @var bool TRUE if {@see setValue()} has been called, FALSE otherwise.
     */
    protected $hasNewValue = FALSE;

    /**
     * Constructor.
     *
     * Specify whether the result is valid or not by passing a boolean
     * value on object construction:
     *
     *
     * $validResult = new ValidatorResult(TRUE);
     * $invalidResult = new ValidatorResult(FALSE);
     *
     *
     * @param bool $valid TRUE if passes validation, FALSE otherwise.
     *
     */
    public function __construct($valid)
    {
        $this->valid = (bool) $valid;
    }

    /**
     * Returns TRUE if passes validation, FALSE otherwise.
     *
     * @return bool
     *
     */
    public function isValid()
    {
        return $this->valid;
    }

    /**
     * Set the new value, transformed/cleaned by the validator.
     *
     * This is optional, since not all validator callbacks should
     * transform/clean the value being validated.
     *
     * @param mixed $value The new value.
     *
     */
    public function setValue($value)
    {
        $this->value = $value;
        $this->hasNewValue = TRUE;
    }

    /**
     * Get the newly transformed/cleaned value.
     *
     * @return mixed The new value.
     *
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Returns TRUE if the object contains new tranformed/cleaned value, FALSE otherwise.
     *
     * @return bool
     *
     */
    public function hasNewValue()
    {
        return $this->hasNewValue;
    }

    /**
     * Add an error message to the result.
     *
     * If the state of the result is valid any calls to this method
     * will be ignored.
     *
     * @param ValidationErrorMessageInterface $message The message to add.
     *
     */
    public function addErrorMessage(ValidationErrorMessageInterface $message)
    {
        if ($this->valid)
        {
            return;
        }

        $this->errorMessages[] = $message;
    }

    /**
     * Add an array of error messages to the result.
     *
     * Added for brevity in user's code. This method simply loops
     * through the array and call {@see addErrorMessage()}.
     *
     * If the state of the result is valid any calls to this method
     * will be ignored.
     *
     * @param array $messages Array containing ValidationErrorMessageInterface instances.
     *
     */
    public function addErrorMessages(array $messages)
    {
        if ($this->valid)
        {
            return;
        }

        foreach ($messages as $message)
        {
            $this->addErrorMessage($message);
        }
    }

    /**
     * Get all error messages.
     *
     * @return array Contains instances of ValidationErrorMessageInterface.
     *
     */
    public function getErrorMessages()
    {
        return $this->errorMessages;
    }
}


text:
"""sql_lab_models_database_constraint_updates

Revision ID: 8b841273bec3
Revises: 2ed890b36b94
Create Date: 2022-03-16 21:07:48.768425

"""

# revision identifiers, used by Alembic.
revision = "8b841273bec3"
down_revision = "2ed890b36b94"

import sqlalchemy as sa
from alembic import op

from superset.utils.core import generic_find_fk_constraint_name

def upgrade():
    bind = op.get_bind()
    insp = sa.engine.reflection.Inspector.from_engine(bind)

    with op.batch_alter_table("tab_state") as batch_op:
        table_schema_id_constraint = generic_find_fk_constraint_name(
            "tab_state", {"id"}, "dbs", insp
        )
        if table_schema_id_constraint:
            batch_op.drop_constraint(
                table_schema_id_constraint,
                type_="foreignkey",
            )

        table_schema_id_constraint = generic_find_fk_constraint_name(
            "tab_state", {"client_id"}, "query", insp
        )
        if table_schema_id_constraint:
            batch_op.drop_constraint(
                table_schema_id_constraint,
                type_="foreignkey",
            )

        batch_op.create_foreign_key(
            "tab_state_database_id_fkey",
            "dbs",
            ["database_id"],
            ["id"],
            ondelete="CASCADE",
        )

        batch_op.create_foreign_key(
            "tab_state_latest_query_id_fkey",
            "query",
            ["latest_query_id"],
            ["client_id"],
            ondelete="SET NULL",
        )

    with op.batch_alter_table("table_schema") as batch_op:
        table_schema_id_constraint = generic_find_fk_constraint_name(
            "table_schema", {"id"}, "dbs", insp
        )
        if table_schema_id_constraint:
            batch_op.drop_constraint(
                table_schema_id_constraint,
                type_="foreignkey",
            )

        batch_op.create_foreign_key(
            "table_schema_database_id_fkey",
            "dbs",
            ["database_id"],
            ["id"],
            ondelete="CASCADE",
        )

def downgrade():
    bind = op.get_bind()
    insp = sa.engine.reflection.Inspector.from_engine(bind)

    with op.batch_alter_table("tab_state") as batch_op:
        table_schema_id_constraint = generic_find_fk_constraint_name(
            "tab_state", {"id"}, "dbs", insp
        )
        if table_schema_id_constraint:
            batch_op.drop_constraint(
                table_schema_id_constraint,
                type_="foreignkey",
            )

        table_schema_id_constraint = generic_find_fk_constraint_name(
            "tab_state", {"client_id"}, "query", insp
        )
        if table_schema_id_constraint:
            batch_op.drop_constraint(
                table_schema_id_constraint,
                type_="foreignkey",
            )

        batch_op.create_foreign_key(
            "tab_state_database_id_fkey", "dbs", ["database_id"], ["id"]
        )
        batch_op.create_foreign_key(
            "tab_state_latest_query_id_fkey",
            "query",
            ["latest_query_id"],
            ["client_id"],
        )

    with op.batch_alter_table("table_schema") as batch_op:
        table_schema_id_constraint = generic_find_fk_constraint_name(
            "table_schema", {"id"}, "dbs", insp
        )
        if table_schema_id_constraint:
            batch_op.drop_constraint(
                table_schema_id_constraint,
                type_="foreignkey",
            )

        batch_op.create_foreign_key(
            "table_schema_database_id_fkey", "dbs", ["database_id"], ["id"]
        )


text:
package com.raybritton.autovaluemap;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE, ElementType.FIELD})
public @interface Nullable {
}


text:
package com.datatorrent.stram.engine;

import java.util.Iterator;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.UnhandledException;

import com.datatorrent.api.Operator;
import com.datatorrent.api.Operator.InputPort;
import com.datatorrent.api.Sink;
import com.datatorrent.stram.plan.logical.Operators.PortContextPair;
import com.datatorrent.stram.stream.OiOStream;
import com.datatorrent.stram.tuple.Tuple;

/**
 * OiONode is driver for the OiO (ThreadLocal) operator.
 *
 * It mostly replicates the functionality of the GenericNode but the logic here is a lot simpler as most of the
 * validation is already handled by the upstream operator.
 *
 * @since 0.3.5
 */
public class OiONode extends GenericNode
{
  private long lastResetWindowId = WindowGenerator.MIN_WINDOW_ID - 1;
  private long lastEndStreamWindowId = WindowGenerator.MAX_WINDOW_ID - 1;
  private int expectingEndWindows = 0;

  public OiONode(Operator operator, OperatorContext context)
  {
    super(operator, context);
  }

  class ControlSink implements Sink<Tuple>
  {
    final SweepableReservoir reservoir;

    ControlSink(SweepableReservoir sr)
    {
      reservoir = sr;
    }

    @Override
    public void put(Tuple t)
    {
      switch (t.getType()) {
        case BEGIN_WINDOW:
          expectingEndWindows++;
          if (t.getWindowId() != currentWindowId) {
            currentWindowId = t.getWindowId();
            for (int s = sinks.length; s-- > 0;) {
              sinks[s].put(t);
            }
            controlTupleCount++;

            if (applicationWindowCount == 0) {
              insideWindow = true;
              operator.beginWindow(currentWindowId);
            }
          }
          break;

        case END_WINDOW:
          endWindowDequeueTimes.put(reservoir, System.currentTimeMillis());
          if (--expectingEndWindows == 0) {
            processEndWindow(t);
          }
          break;

        case CHECKPOINT:
          if (lastCheckpointWindowId < t.getWindowId() && !doCheckpoint) {
            if (checkpointWindowCount == 0) {
              checkpoint(t.getWindowId());
              lastCheckpointWindowId = t.getWindowId();
            }
            else {
              doCheckpoint = true;
            }

            for (int s = sinks.length; s-- > 0;) {
              sinks[s].put(t);
            }
            controlTupleCount++;
          }
          break;

        case RESET_WINDOW:
          if (t.getWindowId() != lastResetWindowId) {
            lastResetWindowId = t.getWindowId();
            for (int s = sinks.length; s-- > 0;) {
              sinks[s].put(t);
            }
            controlTupleCount++;
          }
          break;

        case END_STREAM:
          if (lastEndStreamWindowId != t.getWindowId()) {
            lastEndStreamWindowId = t.getWindowId();
            for (Entry<String, SweepableReservoir> e: inputs.entrySet()) {
              PortContextPair<InputPort<?>> pcpair = descriptor.inputPorts.get(e.getKey());
              if (pcpair != null) {
                pcpair.component.setConnected(false);
              }
            }
            inputs.clear();

            Iterator<DeferredInputConnection> dici = deferredInputConnections.iterator();
            while (dici.hasNext()) {
              DeferredInputConnection dic = dici.next();
              if (!inputs.containsKey(dic.portname)) {
                dici.remove();
                connectInputPort(dic.portname, dic.reservoir);
              }
            }

            if (inputs.isEmpty()) {
              if (insideWindow) {
                applicationWindowCount = APPLICATION_WINDOW_COUNT - 1;
                expectingEndWindows = 0;
                endWindowDequeueTimes.put(reservoir, System.currentTimeMillis());
                processEndWindow(null);
              }
              emitEndStream();
            }
          }
          break;

        default:
          throw new UnhandledException("Unrecognized Control Tuple", new IllegalArgumentException(t.toString()));
      }
    }

    @Override
    public int getCount(boolean reset)
    {
      throw new UnsupportedOperationException("Not supported yet.");
    }

  }

  @Override
  public void connectInputPort(String port, SweepableReservoir reservoir)
  {
    ((OiOStream)reservoir).setControlSink(new ControlSink(reservoir));
    super.connectInputPort(port, reservoir);
  }

  @SuppressWarnings("unused")
  private static final Logger logger = LoggerFactory.getLogger(OiONode.class);
}


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Manage I(libvirt) networks.
      class Virt_net < Base
        # @return [String] name of the network being managed. Note that network must be previously defined with xml.
        attribute :name
        validates :name, presence: true, type: String

        # @return [:active, :inactive, :present, :absent, nil] specify which state you want a network to be in. If 'active', network will be started. If 'present', ensure that network is present but do not change its state; if it's missing, you need to specify xml argument. If 'inactive', network will be stopped. If 'undefined' or 'absent', network will be removed from I(libvirt) configuration.
        attribute :state
        validates :state, expression_inclusion: {:in=>[:active, :inactive, :present, :absent], :message=>"%{value} needs to be :active, :inactive, :present, :absent"}, allow_nil: true

        # @return [:define, :create, :start, :stop, :destroy, :undefine, :get_xml, :list_nets, :facts, :info, :status, :modify, nil] in addition to state management, various non-idempotent commands are available. See examples. Modify was added in version 2.1
        attribute :command
        validates :command, expression_inclusion: {:in=>[:define, :create, :start, :stop, :destroy, :undefine, :get_xml, :list_nets, :facts, :info, :status, :modify], :message=>"%{value} needs to be :define, :create, :start, :stop, :destroy, :undefine, :get_xml, :list_nets, :facts, :info, :status, :modify"}, allow_nil: true

        # @return [Symbol, nil] Specify if a given network should be started automatically on system boot.
        attribute :autostart
        validates :autostart, type: Symbol

        # @return [String, nil] libvirt connection uri.
        attribute :uri
        validates :uri, type: String

        # @return [String, nil] XML document used with the define command.
        attribute :xml
        validates :xml, type: String
      end
    end
  end
end


text:
package resources

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/awslabs/goformation/cloudformation/policies"
)

// AWSElasticBeanstalkConfigurationTemplate AWS CloudFormation Resource (AWS::ElasticBeanstalk::ConfigurationTemplate)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html
type AWSElasticBeanstalkConfigurationTemplate struct {

	// ApplicationName AWS CloudFormation Property
	// Required: true
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-applicationname
	ApplicationName string `json:"ApplicationName,omitempty"`

	// Description AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-description
	Description string `json:"Description,omitempty"`

	// EnvironmentId AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-environmentid
	EnvironmentId string `json:"EnvironmentId,omitempty"`

	// OptionSettings AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-optionsettings
	OptionSettings []AWSElasticBeanstalkConfigurationTemplate_ConfigurationOptionSetting `json:"OptionSettings,omitempty"`

	// PlatformArn AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-platformarn
	PlatformArn string `json:"PlatformArn,omitempty"`

	// SolutionStackName AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-solutionstackname
	SolutionStackName string `json:"SolutionStackName,omitempty"`

	// SourceConfiguration AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticbeanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-sourceconfiguration
	SourceConfiguration *AWSElasticBeanstalkConfigurationTemplate_SourceConfiguration `json:"SourceConfiguration,omitempty"`

	// _deletionPolicy represents a CloudFormation DeletionPolicy
	_deletionPolicy policies.DeletionPolicy

	// _dependsOn stores the logical ID of the resources to be created before this resource
	_dependsOn []string

	// _metadata stores structured data associated with this resource
	_metadata map[string]interface{}
}

// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *AWSElasticBeanstalkConfigurationTemplate) AWSCloudFormationType() string {
	return "AWS::ElasticBeanstalk::ConfigurationTemplate"
}

// DependsOn returns a slice of logical ID names this resource depends on.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html
func (r *AWSElasticBeanstalkConfigurationTemplate) DependsOn() []string {
	return r._dependsOn
}

// SetDependsOn specify that the creation of this resource follows another.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html
func (r *AWSElasticBeanstalkConfigurationTemplate) SetDependsOn(dependencies []string) {
	r._dependsOn = dependencies
}

// Metadata returns the metadata associated with this resource.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-metadata.html
func (r *AWSElasticBeanstalkConfigurationTemplate) Metadata() map[string]interface{} {
	return r._metadata
}

// SetMetadata enables you to associate structured data with this resource.
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-metadata.html
func (r *AWSElasticBeanstalkConfigurationTemplate) SetMetadata(metadata map[string]interface{}) {
	r._metadata = metadata
}

// SetDeletionPolicy applies an AWS CloudFormation DeletionPolicy to this resource
// see: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html
func (r *AWSElasticBeanstalkConfigurationTemplate) SetDeletionPolicy(policy policies.DeletionPolicy) {
	r._deletionPolicy = policy
}

// MarshalJSON is a custom JSON marshalling hook that embeds this object into
// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'.
func (r AWSElasticBeanstalkConfigurationTemplate) MarshalJSON() ([]byte, error) {
	type Properties AWSElasticBeanstalkConfigurationTemplate
	return json.Marshal(&struct {
		Type           string
		Properties     Properties
		DependsOn      []string                `json:"DependsOn,omitempty"`
		Metadata       map[string]interface{}  `json:"Metadata,omitempty"`
		DeletionPolicy policies.DeletionPolicy `json:"DeletionPolicy,omitempty"`
	}{
		Type:           r.AWSCloudFormationType(),
		Properties:     (Properties)(r),
		DependsOn:      r._dependsOn,
		Metadata:       r._metadata,
		DeletionPolicy: r._deletionPolicy,
	})
}

// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer
// AWS CloudFormation resource object, and just keeps the 'Properties' field.
func (r *AWSElasticBeanstalkConfigurationTemplate) UnmarshalJSON(b []byte) error {
	type Properties AWSElasticBeanstalkConfigurationTemplate
	res := &struct {
		Type       string
		Properties *Properties
		DependsOn  []string
		Metadata   map[string]interface{}
	}{}

	dec := json.NewDecoder(bytes.NewReader(b))
	dec.DisallowUnknownFields() // Force error if unknown field is found

	if err := dec.Decode(&res); err != nil {
		fmt.Printf("ERROR: %s\n", err)
		return err
	}

	// If the resource has no Properties set, it could be nil
	if res.Properties != nil {
		*r = AWSElasticBeanstalkConfigurationTemplate(*res.Properties)
	}
	if res.DependsOn != nil {
		r._dependsOn = res.DependsOn
	}
	if res.Metadata != nil {
		r._metadata = res.Metadata
	}

	return nil
}


text:
package net.violet.platform.httpclient;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.nutch.net.protocols.HttpDateFormat;

import com.sun.syndication.io.impl.DateParser;

/**
 * A Connection should be created by a ConnectionsManager object. It contains the response received from the server
 * and can be used to read the result's content and/or some information returned by the server.
 *
 * A Connection object is NOT thread-safe and should not be accessed by several threads.
 *
 * Do not forget to close the connection when all required information have been read.
 */
public class Connection {

	private final GetMethod method;
	private final boolean isClosed;

	/**
	 * Can only be used by the ConnectionsManager
	 * @param method
	 */
	Connection(GetMethod method) {
		this.method = method;
		this.isClosed = false;
	}

	/**
	 * Returns the value of the 'Last-Modified' header. Can be null if the server does not provide this information.
	 * @return
	 */
	public String getLastModified() {
		return getHeaderValue("Last-Modified");
	};

	/**
	 * Returns the value of the 'Last-Modified' header as a Date object.
	 * May be null if the server does not provided this information.
	 * @return
	 * @throws ParseException if the given header is not a parsable date format.
	 */
	public Date getLastModifiedAsDate() throws ParseException {
		final String lastModifiedAsString = getLastModified();
		if (lastModifiedAsString == null) {
			return null;
		}

		Date theDate;
		try {
			theDate = HttpDateFormat.toDate(lastModifiedAsString);
		} catch (final ParseException e) {
			theDate = DateParser.parseDate(lastModifiedAsString);
			if (theDate == null) {
				throw new ParseException("Cannot parse " + lastModifiedAsString + " into a date", 0);
			}
		}

		return theDate;
	}

	/**
	 * Returns the Etag. May be null.
	 * @return
	 */
	public String getEtag() {
		return getHeaderValue("ETag");
	}

	public InputStream getInputStream() throws IOException {
		final String encoding = getHeaderValue("Content-Encoding");
		final InputStream responseAsStream = this.method.getResponseBodyAsStream();
		if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) {
			return new GZIPInputStream(responseAsStream);
		} else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) {
			return new InflaterInputStream(responseAsStream, new Inflater(true));
		} else {
			return responseAsStream;
		}
	}

	/**
	 * Closes the connection and release the resources.
	 * Closing an already closed connection does not matter.
	 */
	public void close() {
		if (!this.isClosed) {
			this.method.releaseConnection();
		}
	}

	/**
	 * Returns true if the connection is closed.
	 * If the connection is closed, calling other methods may give unexpected behavior (exceptions or invalid results).
	 * @return
	 */
	public boolean isClosed() {
		return this.isClosed;
	}

	private String getHeaderValue(String key) {
		final Header theHeader = this.method.getResponseHeader(key);
		return theHeader == null ? null : theHeader.getValue();
	}

}


text:
<?php
/**
* Auto generated from DocflowApi.proto
*
 * Diadoc.Api.Proto.Docflow package
 */

namespace Diadoc\Api\Proto\Docflow {
/**
 * GetDocflowRequest message
 */
class GetDocflowRequest extends \ProtobufMessage
{
    /* Field index constants */
    const DOCUMENTID = 1;
    const LASTEVENTID = 2;
    const INJECTENTITYCONTENT = 3;

    /* @var array Field descriptors */
    protected static $fields = array(
        self::DOCUMENTID => array(
            'name' => 'DocumentId',
            'required' => true,
            'type' => '\Diadoc\Api\Proto\DocumentId'
        ),
        self::LASTEVENTID => array(
            'name' => 'LastEventId',
            'required' => false,
            'type' => \ProtobufMessage::PB_TYPE_STRING,
        ),
        self::INJECTENTITYCONTENT => array(
            'default' => false,
            'name' => 'InjectEntityContent',
            'required' => false,
            'type' => \ProtobufMessage::PB_TYPE_BOOL,
        ),
    );

    /**
     * Constructs new message container and clears its internal state
     */
    public function __construct()
    {
        $this->reset();
    }

    /**
     * Clears message values and sets default ones
     *
     * @return null
     */
    public function reset()
    {
        $this->values[self::DOCUMENTID] = null;
        $this->values[self::LASTEVENTID] = null;
        $this->values[self::INJECTENTITYCONTENT] = self::$fields[self::INJECTENTITYCONTENT]['default'];
    }

    /**
     * Returns field descriptors
     *
     * @return array
     */
    public function fields()
    {
        return self::$fields;
    }

    /**
     * Sets value of 'DocumentId' property
     *
     * @param \Diadoc\Api\Proto\DocumentId $value Property value
     *
     * @return null
     */
    public function setDocumentId(\Diadoc\Api\Proto\DocumentId $value=null)
    {
        return $this->set(self::DOCUMENTID, $value);
    }

    /**
     * Returns value of 'DocumentId' property
     *
     * @return \Diadoc\Api\Proto\DocumentId
     */
    public function getDocumentId()
    {
        return $this->get(self::DOCUMENTID);
    }

    /**
     * Sets value of 'LastEventId' property
     *
     * @param string $value Property value
     *
     * @return null
     */
    public function setLastEventId($value)
    {
        return $this->set(self::LASTEVENTID, $value);
    }

    /**
     * Returns value of 'LastEventId' property
     *
     * @return string
     */
    public function getLastEventId()
    {
        $value = $this->get(self::LASTEVENTID);
        return $value === null ? (string)$value : $value;
    }

    /**
     * Sets value of 'InjectEntityContent' property
     *
     * @param boolean $value Property value
     *
     * @return null
     */
    public function setInjectEntityContent($value)
    {
        return $this->set(self::INJECTENTITYCONTENT, $value);
    }

    /**
     * Returns value of 'InjectEntityContent' property
     *
     * @return boolean
     */
    public function getInjectEntityContent()
    {
        $value = $this->get(self::INJECTENTITYCONTENT);
        return $value === null ? (boolean)$value : $value;
    }
}
}


text:
require_relative 'views/mixins/document_view_mixin'
require_relative 'views/mixins/mutable_document_view_mixin'
require_relative 'views/mixins/with_reps_view_mixin'

require_relative 'views/view'
require_relative 'views/view_context'

require_relative 'views/config_view'
require_relative 'views/identifiable_collection_view'
require_relative 'views/item_without_reps_view'
require_relative 'views/item_with_reps_view'
require_relative 'views/item_collection_with_reps_view'
require_relative 'views/item_collection_without_reps_view'
require_relative 'views/item_rep_view'
require_relative 'views/item_rep_collection_view'
require_relative 'views/layout_view'
require_relative 'views/layout_collection_view'
require_relative 'views/mutable_config_view'
require_relative 'views/mutable_identifiable_collection_view'
require_relative 'views/mutable_item_view'
require_relative 'views/mutable_item_collection_view'
require_relative 'views/mutable_layout_view'
require_relative 'views/mutable_layout_collection_view'

require_relative 'views/post_compile_item_view'
require_relative 'views/post_compile_item_collection_view'
require_relative 'views/post_compile_item_rep_view'
require_relative 'views/post_compile_item_rep_collection_view'