text:
package org.beigesoft.uml.ui.swing;

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import org.beigesoft.pojo.HasNameEditable;
import org.beigesoft.ui.widget.swing.AsmEditorHasName;
import org.beigesoft.ui.widget.swing.ButtonSwing;
import org.beigesoft.ui.widget.swing.ListSwingWithEditor;
import org.beigesoft.uml.pojo.UseCaseExtended;
import org.beigesoft.uml.ui.EditorUseCaseExtendedFull;

public class AsmEditorUseCaseExtendedFull<UC extends UseCaseExtended, EDT extends EditorUseCaseExtendedFull<UC, Frame, ActionEvent>> extends AsmEditorUseCaseFull<UC, EDT> {

  private static final long serialVersionUID = -7885727548073395811L;

  protected JList jlistExtPoints;

  protected JButton btAddExtPoint;

  protected JButton btEditExtPoint;

  protected JButton btDelExtPoint;

  private final AsmEditorHasName<HasNameEditable> asmEditorItem;

  public AsmEditorUseCaseExtendedFull(Frame frame, EDT editor, AsmEditorHasName<HasNameEditable> asmEditorItem) {
    super(frame, editor);
    this.asmEditorItem = asmEditorItem;
  }

  @Override
  protected void addWidgets() {
    c.gridwidth = 3;
    super.addWidgets();
    c.gridy++;
    contentPane.add(new JLabel(editor.getSrvEdit().getSrvI18n().getMsg("extension_points")+":"), c);
    jlistExtPoints = new JList();
    jlistExtPoints.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    jlistExtPoints.setLayoutOrientation(JList.VERTICAL);
    jlistExtPoints.setVisibleRowCount(-1);
    JScrollPane scrollPane = new JScrollPane(jlistExtPoints);
    scrollPane.setPreferredSize(new Dimension(editor.getSrvEdit().getSettingsGraphic().getScreenWidthPixels()/4,
        editor.getSrvEdit().getSettingsGraphic().getScreenHeightPixels()/5));
    c.gridy++;
    contentPane.add(scrollPane, c);
    btAddExtPoint = new JButton();
    btAddExtPoint.addActionListener(this);
    c.gridy++;
    c.gridwidth = 1;
    c.weightx = 0.5;
    contentPane.add(btAddExtPoint, c);
    btEditExtPoint = new JButton();
    btEditExtPoint.addActionListener(this);
    c.gridx++;
    contentPane.add(btEditExtPoint, c);
    btDelExtPoint = new JButton();
    btDelExtPoint.addActionListener(this);
    c.gridx++;
    contentPane.add(btDelExtPoint, c);
    editor.setBtAddExtPoint(new ButtonSwing(btAddExtPoint));
    editor.setBtEditExtPoint(new ButtonSwing(btEditExtPoint));
    editor.setBtDelExtPoint(new ButtonSwing(btDelExtPoint));
  }

  @Override
  public void doPostConstruct() {
    super.doPostConstruct();
    editor.setListExtentionPoints(new ListSwingWithEditor<HasNameEditable>(jlistExtPoints, editor.getDialogInstrument(), asmEditorItem));
  }
}


text:
<?php

namespace ZendTest\Stdlib;

use Zend\Stdlib\PriorityList;
use PHPUnit_Framework_TestCase as TestCase;

class PriorityListTest extends TestCase
{
    /**
     * @var PriorityList
     */
    protected $list;

    public function setUp()
    {
        $this->list = new PriorityList();
    }

    public function testInsert()
    {
        $this->list->insert('foo', new \stdClass(), 0);

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

        foreach ($this->list as $key => $value) {
            $this->assertEquals('foo', $key);
        }
    }

    public function testRemove()
    {
        $this->list->insert('foo', new \stdClass(), 0);
        $this->list->insert('bar', new \stdClass(), 0);

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

        $this->list->remove('foo');

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

    public function testRemovingNonExistentRouteDoesNotYieldError()
    {
        $this->list->remove('foo');
    }

    public function testClear()
    {
        $this->list->insert('foo', new \stdClass(), 0);
        $this->list->insert('bar', new \stdClass(), 0);

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

        $this->list->clear();

        $this->assertEquals(0, count($this->list));
        $this->assertSame(false, $this->list->current());
    }

    public function testGet()
    {
        $route = new \stdClass();

        $this->list->insert('foo', $route, 0);

        $this->assertEquals($route, $this->list->get('foo'));
        $this->assertNull($this->list->get('bar'));
    }

    public function testLIFOOnly()
    {
        $this->list->insert('foo',    new \stdClass());
        $this->list->insert('bar',    new \stdClass());
        $this->list->insert('baz',    new \stdClass());
        $this->list->insert('foobar', new \stdClass());
        $this->list->insert('barbaz', new \stdClass());

        $orders = array();

        foreach ($this->list as $key => $value) {
            $orders[] = $key;
        }

        $this->assertEquals(array('barbaz', 'foobar', 'baz', 'bar', 'foo'), $orders);
    }

    public function testPriorityOnly()
    {
        $this->list->insert('foo', new \stdClass(), 1);
        $this->list->insert('bar', new \stdClass(), 0);
        $this->list->insert('baz', new \stdClass(), 2);

        $order = array();

        foreach ($this->list as $key => $value) {
            $orders[] = $key;
        }

        $this->assertEquals(array('baz', 'foo', 'bar'), $orders);
    }

    public function testLIFOWithPriority()
    {
        $this->list->insert('foo', new \stdClass(), 0);
        $this->list->insert('bar', new \stdClass(), 0);
        $this->list->insert('baz', new \stdClass(), 1);

        $orders = array();

        foreach ($this->list as $key => $value) {
            $orders[] = $key;
        }

        $this->assertEquals(array('baz', 'bar', 'foo'), $orders);
    }

    public function testFIFOWithPriority()
    {
        $this->list->isLIFO(false);
        $this->list->insert('foo', new \stdClass(), 0);
        $this->list->insert('bar', new \stdClass(), 0);
        $this->list->insert('baz', new \stdClass(), 1);

        $orders = array();

        foreach ($this->list as $key => $value) {
            $orders[] = $key;
        }

        $this->assertEquals(array('baz', 'foo', 'bar'), $orders);
    }

    public function testFIFOOnly()
    {
        $this->list->isLIFO(false);
        $this->list->insert('foo',    new \stdClass());
        $this->list->insert('bar',    new \stdClass());
        $this->list->insert('baz',    new \stdClass());
        $this->list->insert('foobar', new \stdClass());
        $this->list->insert('barbaz', new \stdClass());

        $orders = array();

        foreach ($this->list as $key => $value) {
            $orders[] = $key;
        }

        $this->assertEquals(array('foo', 'bar', 'baz', 'foobar', 'barbaz'), $orders);
    }

    public function testPriorityWithNegativesAndNull()
    {
        $this->list->insert('foo', new \stdClass(), null);
        $this->list->insert('bar', new \stdClass(), 1);
        $this->list->insert('baz', new \stdClass(), -1);

        $orders = array();

        foreach ($this->list as $key => $value) {
            $orders[] = $key;
        }

        $this->assertEquals(array('bar', 'foo', 'baz'), $orders);
    }

    public function testToArray()
    {
        $this->list->insert('foo', 'foo_value', null);
        $this->list->insert('bar', 'bar_value', 1);
        $this->list->insert('baz', 'baz_value', -1);

        $this->assertEquals(
            array(
                'bar' => 'bar_value',
                'foo' => 'foo_value',
                'baz' => 'baz_value'
            ),
            $this->list->toArray()
        );

        $this->assertEquals(
            array(
                'bar' => array('data' => 'bar_value', 'priority' =>  1, 'serial' => 1),
                'foo' => array('data' => 'foo_value', 'priority' =>  0, 'serial' => 0),
                'baz' => array('data' => 'baz_value', 'priority' => -1, 'serial' => 2),
            ),
            $this->list->toArray(PriorityList::EXTR_BOTH)
        );
    }

    /**
     * @group 6768
     * @group 6773
     */
    public function testBooleanValuesAreValid()
    {
        $this->list->insert('null', null, null);
        $this->list->insert('false', false, null);
        $this->list->insert('string', 'test', 1);
        $this->list->insert('true', true, -1);

        $orders1 = array();
        $orders2 = array();

        foreach ($this->list as $key => $value) {
            $orders1[$this->list->key()] = $this->list->current();
            $orders2[$key] = $value;
        }
        $this->assertEquals($orders1, $orders2);
        $this->assertEquals(
            array(
                'null'   => null,
                'false'  => false,
                'string' => 'test',
                'true'   => true,
            ),
            $orders2
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Threading.Tasks;
using KotoriCore.Commands;
using KotoriCore.Database.DocumentDb.Helpers;
using KotoriCore.Exceptions;
using KotoriCore.Helpers;

namespace KotoriCore.Database.DocumentDb
{
    partial class DocumentDb
    {
        async Task<CommandResult> HandleAsync(DeleteDocumentType command)
        {
            var projectUri = command.ProjectId.ToKotoriProjectUri();
            var project = await FindProjectAsync(command.Instance, projectUri).ConfigureAwait(false);
            var documentTypeUri = command.ProjectId.ToKotoriDocumentTypeUri(command.DocumentType, command.DocumentTypeId);

            if (project == null)
                throw new KotoriProjectException(command.ProjectId, "Project not found.") { StatusCode = System.Net.HttpStatusCode.NotFound };

            var docType = await FindDocumentTypeByIdAsync
                (
                    command.Instance,
                    projectUri,
                    documentTypeUri
                ).ConfigureAwait(false);

            if (docType == null)
                throw new KotoriDocumentTypeException(command.DocumentTypeId, "Document type not found.") { StatusCode = System.Net.HttpStatusCode.NotFound };

            var sql = DocumentDbHelpers.CreateDynamicQueryForDocumentSearch
            (
                command.Instance,
                projectUri,
                documentTypeUri,
                null,
                "count(1) as number",
                null,
                null,
                true,
                true
            );

            var count = await CountDocumentsAsync(sql).ConfigureAwait(false);

            if (count > 0)
                throw new KotoriDocumentTypeException(command.DocumentTypeId, $"{count} document{(count > 1 ? "s" : "")} found of this document type.") { StatusCode = System.Net.HttpStatusCode.NotFound };

            await DeleteDocumentTypeAsync(docType.Id).ConfigureAwait(false);

            return new CommandResult();
        }
    }
}


text:
getStyling
==========

Wraps

props,
context,
pos,
styling,
mandatory,
optional


text:
// <copyright file="SqlServerIdentityMapTests.cs" company="dddlib contributors">
//  Copyright (c) dddlib contributors. All rights reserved.
// </copyright>

namespace dddlib.Persistence.Tests.Integration
{
    using System;
    using dddlib.Persistence.SqlServer;
    using dddlib.Tests.Sdk;
    using FluentAssertions;
    using Xunit;

    public class SqlServerIdentityMapTests : Integration.Database
    {
        public SqlServerIdentityMapTests(SqlServerFixture fixture)
            : base(fixture)
        {
        }

        [Fact]
        public void TryGetWhenIdentityMapDoesNotContainNaturalKey()
        {
            // arrange
            var identityMap = new SqlServerIdentityMap(this.ConnectionString);
            var registration = new Registration(Guid.NewGuid().ToString("N"));
            var identity = default(Guid);

            // act
            var success = identityMap.TryGet(typeof(Car), typeof(Registration), registration, out identity);

            // assert
            success.Should().BeFalse();
        }

        [Fact]
        public void TryGetWhenIdentityMapDoesContainNaturalKey()
        {
            // arrange
            var identityMap = new SqlServerIdentityMap(this.ConnectionString);
            var otherIdentityMap = new SqlServerIdentityMap(this.ConnectionString);
            var registration = new Registration(Guid.NewGuid().ToString("N"));
            var actualIdentity = default(Guid);
            var sameIdentity = default(Guid);

            // act
            var expectedIdentity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);
            var success = otherIdentityMap.TryGet(typeof(Car), typeof(Registration), registration, out actualIdentity);
            var anotherSuccess = otherIdentityMap.TryGet(typeof(Car), typeof(Registration), registration, out sameIdentity);

            // assert
            success.Should().BeTrue();
            actualIdentity.Should().Be(expectedIdentity);
            anotherSuccess.Should().BeTrue();
            sameIdentity.Should().Be(expectedIdentity);
        }

        [Fact]
        public void GetOrAddWhenIdentityMapDoesNotContainNaturalKey()
        {
            // arrange
            var identityMap = new SqlServerIdentityMap(this.ConnectionString);
            var registration = new Registration(Guid.NewGuid().ToString("N"));

            // act
            var identity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);
            var sameIdentity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);

            // assert
            identity.Should().Be(sameIdentity);
        }

        [Fact]
        public void GetOrAddWhenIdentityMapDoesContainNaturalKey()
        {
            // arrange
            var identityMap = new SqlServerIdentityMap(this.ConnectionString);
            var otherIdentityMap = new SqlServerIdentityMap(this.ConnectionString);
            var registration = new Registration(Guid.NewGuid().ToString("N"));

            // act
            var expectedIdentity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);
            var actualIdentity = otherIdentityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);

            // assert
            actualIdentity.Should().Be(expectedIdentity);
        }

        [Fact]
        public void RemoveFromIdentityMap()
        {
            // arrange
            var identityMap = new SqlServerIdentityMap(this.ConnectionString);
            var registration = new Registration(Guid.NewGuid().ToString("N"));

            // act
            var identity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);
            identityMap.Remove(identity);
            var otherIdentity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);

            // assert
            identity.Should().NotBe(otherIdentity);
        }

        [Fact]
        public void TryGetWhenIdentityMapHasRemovedNaturalKey()
        {
            // arrange
            var identityMap = new SqlServerIdentityMap(this.ConnectionString);
            var otherIdentityMap = new SqlServerIdentityMap(this.ConnectionString);
            var registration = new Registration(Guid.NewGuid().ToString("N"));
            var somelIdentity = default(Guid);

            // act
            var identity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);
            var sameIdentity = otherIdentityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);
            identityMap.Remove(identity);
            var success = otherIdentityMap.TryGet(typeof(Car), typeof(Registration), registration, out somelIdentity);
            var anotherSuccess = otherIdentityMap.TryGet(typeof(Car), typeof(Registration), registration, out somelIdentity);

            // assert
            success.Should().BeFalse();
            anotherSuccess.Should().BeFalse();
        }

        [Fact]
        public void UseAlternateSchema()
        {
            // arrange
            var identityMap = new SqlServerIdentityMap(this.ConnectionString, "alternate");
            var registration = new Registration(Guid.NewGuid().ToString("N"));
            var actualIdentity = default(Guid);

            // act
            var initialSuccess = identityMap.TryGet(typeof(Car), typeof(Registration), registration, out actualIdentity);
            var expectedIdentity = identityMap.GetOrAdd(typeof(Car), typeof(Registration), registration);
            var subsequentSuccess = identityMap.TryGet(typeof(Car), typeof(Registration), registration, out actualIdentity);

            // assert
            initialSuccess.Should().BeFalse();
            subsequentSuccess.Should().BeTrue();
            actualIdentity.Should().Be(expectedIdentity);
        }

        private class Registration : ValueObject<Registration>
        {
            public Registration(string number)
            {
                Guard.Against.Null(() => number);

                this.Number = number;
            }

            public string Number { get; private set; }
        }

        private class Car : AggregateRoot
        {
            public Registration Registration { get; private set; }
        }
    }
}


text:
class AddRequeuedJobIdToFailedJobs < ActiveRecord::Migration[6.0]
  def change
    add_column :failed_jobs, :requeued_job_id, :integer, limit: 8
  end
end


text:
@charset "UTF-8";
/* CSS Document */

.promo-1{
	position: relative;
	overflow: hidden;
	float: center;
	margin-top: 10px;
	margin-left: 10px;
	background-position: center;
	background-repeat: no-repeat;
}

.promo-2{
	position: relative;
	overflow: hidden;
	float: center;
	margin-top: 10px;
	margin-left: 10px;
	background-position: center;
	background-repeat: no-repeat;
}

.promo-3{
	position: relative;
	overflow: hidden;
	float: center;
	margin-top: 10px;
	margin-left: 10px;
	background-position: center;
	background-repeat: no-repeat;
}

.promo-large{
	position: relative;
	overflow: hidden;
	float: center;
	margin-top: 10px;
	margin-left: 10px;
	background-position: center;
	background-repeat: no-repeat;
}

.promo-body{
	color: #fff;
	position: absolute;
	bottom:5px;
	right:25px;
	margin: 10px 10px 10px 10px;
}

.promo p{
	color: #fff;
	margin: 10px 10px 10px 10px;
	float: right;
}

.promo h2{
	color: #fff;
	margin: 10px 10px 10px 10px;
	float: right;
}

.promo h3{
	color: #fff;
	margin: 10px 10px 10px 10px;
	float: right;
}

.promo img{

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="Open Knowledge">
    <meta name="description" content="Read our user stories on the 2014 Open Data Index">
    <meta name="keywords" content="Open Government, Open Data, Government Transparency, Open Knowledge">
    <meta property="og:type" content="website"/>
    <meta property="og:title" content="Open Data Index - Open Knowledge"/>
    <meta property="og:site_name" content="Open Data Index"/>
    <meta property="og:description"
          content="The Global Open Data Index assesses the state of open government data around the world."/>
    <meta property="og:image" content="/static/images/favicon.ico"/>
    <title>Read our user stories on the 2014 Open Data Index | Global Open Data Index by Open Knowledge</title>
    <base href="/">

    <link rel="stylesheet" href="/static/css/site.css">
    <link rel="icon" href="/static/images/favicon.ico">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                            data-target="#navbar-collapse">
                        Toggle navigation

                    </button>

                            Global
Open Data Index

                                Places

                                Datasets

                                Download

                                Insights

                                Methodology

                                About

                                Press

                        Home

Stories

Americas

Global Open Data Index stories from Americas

            We invited the community to send in their 2014 open data index stories.

            Do you have a case study you would like to contribute? Send us an email

            Chile / Daniela Tejada

This version is translated from the original Spanish version.

Open Data and Open Government policies have had a breakthrough the last years in Chile. The ...

        Read more

            Paraguay / Juan Pane

Earlier this year I proposed to the teach an Open Data course, lasting the whole semester, for the Computer Science (Informatics Engineering) curriculum at the ...

        Read more

                        –

                        Data License (Public
                            Domain)

    This service is run by Open Knowledge

Open Knowledge

What is
                    Open Data?

Run your
                    own Index

Source Code

Home

Download

Methodology

FAQ

About

Contact

Press


text:
<?php

namespace Grido\Translations;

/**
 * Simple file translator.
 *
 * @package     Grido
 * @subpackage  Translations
 * @author      Petr Bugyík
 */
class FileTranslator extends \Nette\Object implements \Nette\Localization\ITranslator
{
    public $dictionary = array();

    /**
     * @param string $lang
     * @param array $dictionary
     */
    public function __construct($lang = NULL, array $dictionary = array())
    {
        if ($lang) {
            require_once __DIR__ . "/$lang.php";
            $dictionary = $dictionary + $dict;
        }

        $this->dictionary = $dictionary;
    }

    /**
     * Sets language of translation.
     * @param string $lang
     */
    public function setLang($lang)
    {
        require_once __DIR__ . "/$lang.php";
        $this->dictionary = $dict;
    }

    /************************* interface \Nette\Localization\ITranslator **************************/

    /**
     * @param string $message
     * @param int $count plural
     * @return type
     */
    public function translate($message, $count = NULL)
    {
        if (is_array($message)) {
            $tmp = array_shift($message);
            $args = $message;
            $message = $tmp;
        }

        if (!isset($args)) {
            $args = func_get_args();
            array_shift($args);
        }

        if (isset($this->dictionary[$message])) {
            if (is_array($this->dictionary[$message])) {
                if (count($args) > 0) {
                    if (isset($this->dictionary[$message][pluralIndex($args[0])])) {
                        $message = $this->dictionary[$message][pluralIndex($args[0])];
                    }
                }
            } else {
                $message = $this->dictionary[$message];
            }
        }

        if (count($args) > 0) {
            return vsprintf($message, $args);
        }

        return $message;
    }
}


text:
<?php

/**
 * Caches fetched definitions so they don't have to be read from the original source
 * for each use.
 *
 * The cache is typically used to wrap around another ezcPersistentDefinitionManager
 * of your choice.
 *
 * @version //autogen//
 * @package PersistentObject
 */
class ezcPersistentCacheManager extends ezcPersistentDefinitionManager
{
    /**
     * Holds the manager that fetches definitions.
     *
     * @var ezcPersistentDefinitionManager
     */
    private $manager;

    /**
     * Holds the persistent object definitions that are currently cached.
     *
     * @var array($className=>ezcPersistentObjectDefinition)
     */
    private $cache = array();

    /**
     * Constructs a new definition cache.
     *
     * @param ezcPersistentDefinitionManager $manager
     */
    public function __construct( ezcPersistentDefinitionManager $manager )
    {
        $this->manager = $manager;
    }

    /**
     * Returns the definition of the persistent object with the class $class.
     *
     * If a definition has been requested already the definition will be served from
     * the cache.
     *
     * @throws ezcPersistentDefinitionNotFoundException if no such definition can be found.
     * @param string $class
     * @return ezcPersistentObjectDefinition
     */
    public function fetchDefinition( $class )
    {
        if ( isset( $this->cache[$class] ) )
        {
            return $this->cache[$class];
        }

        $def = $this->manager->fetchDefinition( $class );

        // cache it
        $this->cache[$class] = $def;
        return $def;
    }
}
?>


text:
<?php

namespace Besearcher;

class Auth {
	private static $mSessionName;
	private static $mRequireAuth;

	public static function init($theSessionName, $theRequireAuth = false) {
		self::$mSessionName = $theSessionName;
		self::$mRequireAuth = $theRequireAuth;
		session_start();
		session_name(self::$mSessionName);
	}

	public static function credentialsMatch($theUser, $thePassword) {
		$aUser = WebApp::users()->getByLogin($theUser);
		$aValid = $aUser !== false && password_verify($thePassword, $aUser['password']);

		return $aValid;
	}

	public static function login($theUserLogin) {
		$aUser = WebApp::users()->getByLogin($theUserLogin);

		if($aUser == false) {
			throw new \Exception('Unable to authenticate invalid user.');
		}

		$_SESSION['authenticaded'] = true;
		$_SESSION['user'] = $aUser['id'];
	}

	public static function allowAuthenticated() {
		if(!self::isAuthenticated()) {
			header('Location: login.php');
			exit();
		}
	}

	public static function allowNonAuthenticated() {
		if(self::isAuthenticated()) {
			header('Location: index.php');
			exit();
		}
	}

	public static function user() {
		$aUser = false;

		if(isset($_SESSION['user'])) {
			$aUser = WebApp::users()->getById($_SESSION['user']);
		}

		return $aUser;
	}

	public static function logout() {
		unset($_SESSION);
		session_destroy();
	}

	public static function isAuthenticated() {
		return !self::$mRequireAuth || (isset($_SESSION['authenticaded']) && $_SESSION['authenticaded']);
	}
}

?>


text:
package org.eclipse.rdf4j.sparqlbuilder.core;

import org.eclipse.rdf4j.sparqlbuilder.rdf.Rdf;
import org.junit.Assert;
import org.junit.Test;

public class PrefixDeclarationsTest {
	@Test
	public void testReplaceInQuery_nothing() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals("nothing to replace",
				pd.replacePrefixesInQuery("nothing to replace"));
	}

	@Test
	public void testReplaceInQuery_justTheNamespace() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals("label: to replace",
				pd.replacePrefixesInQuery("<http://example.org/ns#> to replace"));
	}

	@Test
	public void testReplaceInQuery_atStart() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals("label:local to replace",
				pd.replacePrefixesInQuery("<http://example.org/ns#local> to replace"));
	}

	@Test
	public void testReplaceInQuery_atEnd() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals("replace label:local",
				pd.replacePrefixesInQuery("replace <http://example.org/ns#local>"));
	}

	@Test
	public void testReplaceInQuery_middle() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals("replace label:local in the middle",
				pd.replacePrefixesInQuery("replace <http://example.org/ns#local> in the middle"));
	}

	@Test
	public void testReplaceInQuery_middle_with_angled_brackets() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals("<replace <> <label:local> <in> the middle",
				pd.replacePrefixesInQuery("<replace <> <<http://example.org/ns#local>> <in> the middle"));
	}

	@Test
	public void testReplaceInQuery_multiple_long_shared_substring() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		pd.addPrefix(new Prefix("label2", Rdf.iri("http://example.org/ns2#")));
		Assert.assertEquals("<replace <> <label:local> <in> the middle followed by label2:local",
				pd.replacePrefixesInQuery(
						"<replace <> <<http://example.org/ns#local>> <in> the middle followed by <http://example.org/ns2#local>"));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_in_string() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace \"<http://example.org/ns#local>\" because it's in a string, but replace label:local here.",
				pd.replacePrefixesInQuery(
						"Do not replace \"<http://example.org/ns#local>\" because it's in a string, but replace <http://example.org/ns#local> here."));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_in_string_enclosed_with_multiline_quotes() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace \"in String even if enclosed in quotes:'''<http://example.org/ns#local>'''\", but replace label:local here.",
				pd.replacePrefixesInQuery(
						"Do not replace \"in String even if enclosed in quotes:'''<http://example.org/ns#local>'''\", but replace <http://example.org/ns#local> here."));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_in_string_enclosed_with_escaped_double_quotes() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace \"in String even if enclosed in quotes:\\\"<http://example.org/ns#local>\\\"\", but replace label:local here.",
				pd.replacePrefixesInQuery(
						"Do not replace \"in String even if enclosed in quotes:\\\"<http://example.org/ns#local>\\\"\", but replace <http://example.org/ns#local> here."));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_in_multiline_string() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace '''<http://example.org/ns#local>\n\\n''' because it's in a string, but replace label:local here.",
				pd.replacePrefixesInQuery(
						"Do not replace '''<http://example.org/ns#local>\n\\n''' because it's in a string, but replace <http://example.org/ns#local> here."));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_in_multiline_string_with_nested_quotes() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace '''<http://example.org/ns#local>\nEven with a nested '\"'\n''' because it's in a string, but replace label:local here.",
				pd.replacePrefixesInQuery(
						"Do not replace '''<http://example.org/ns#local>\nEven with a nested '\"'\n''' because it's in a string, but replace <http://example.org/ns#local> here."));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_in_multiline_string_enclosed_with_double_quotes() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace '''in String even if enlosed in quotes: \"<http://example.org/ns#local>\"''', but replace label:local here.",
				pd.replacePrefixesInQuery(
						"Do not replace '''in String even if enlosed in quotes: \"<http://example.org/ns#local>\"''', but replace <http://example.org/ns#local> here."));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_in_multiline_string_enclosed_with_escaped_double_quotes() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace '''in String even if enlosed in quotes: \\\"<http://example.org/ns#local>\\\"''', but replace label:local here.",
				pd.replacePrefixesInQuery(
						"Do not replace '''in String even if enlosed in quotes: \\\"<http://example.org/ns#local>\\\"''', but replace <http://example.org/ns#local> here."));
	}

	@Test
	public void testReplaceInQuery_do_not_replace_if_continuation_is_not_localname() {
		PrefixDeclarations pd = new PrefixDeclarations();
		pd.addPrefix(new Prefix("label", Rdf.iri("http://example.org/ns#")));
		Assert.assertEquals(
				"Do not replace <http://example.org/ns#not/a/localname> because a prefix must be followed by a localname",
				pd.replacePrefixesInQuery(
						"Do not replace <http://example.org/ns#not/a/localname> because a prefix must be followed by a localname"));
	}
}


text:
namespace seed
{
    Emitter::Emitter()
    {
        m_blend = onut::SpriteBatch::eBlendMode::Add;
        m_filter = onut::SpriteBatch::eFiltering::Linear;
        m_emitWorld = true;
    }

    Emitter::~Emitter()
    {

    }

    Node* Emitter::Duplicate(onut::Pool<true>& in_pool, NodeVect& in_pooledNodes) const
    {
        Emitter* newNode = in_pool.alloc<Emitter>();
        Copy(newNode);
        in_pooledNodes.push_back(newNode);
        DuplicateChildren(newNode, in_pool, in_pooledNodes);
        return newNode;
    }

    Node* Emitter::Duplicate() const
    {
        Emitter* newNode = new Emitter();
        Copy(newNode);
        DuplicateChildren(newNode);
        return newNode;
    }

    void Emitter::Copy(Node* in_copy) const
    {
        Node::Copy(in_copy);
        Emitter* copy = (Emitter*)in_copy;

        copy->m_fxName = m_fxName;
        copy->m_filter = m_filter;
        copy->m_blend = m_blend;
        copy->m_emitWorld = m_emitWorld;

        if (m_emitter.isPlaying())
        {
            copy->Start();
        }
    }

    void Emitter::Init(const string& in_fxName)
    {
        m_fxName = in_fxName;
    }

    void Emitter::Update()
    {
        Node::Update();

        if (m_emitWorld)
        {
            m_emitter.setTransform(GetTransform().Translation());
        }
    }

    void Emitter::Render(Matrix* in_parentMatrix, float in_parentAlpha)
    {
        if (!m_visible)
        {
            return;
        }

        // generate our matrix
        Matrix transform = Matrix::Identity;
        transform *= Matrix::CreateScale(m_scale.get().x, m_scale.get().y, 1.f);
        transform *= Matrix::CreateRotationZ(DirectX::XMConvertToRadians(m_angle));
        transform *= Matrix::CreateTranslation(m_position.get().x, m_position.get().y, 0);

        if (in_parentMatrix)
        {
            transform = transform * *in_parentMatrix;
        }

        // render bg children
        RenderChildren(m_bgChildren, &transform, m_color.get().w * in_parentAlpha);

        // render ourself
        if (m_emitWorld)
        {
            OSpriteBatch->changeBlendMode(m_blend);
            OSpriteBatch->changeFiltering(m_filter);
            m_emitter.render();
        }
        else
        {
            OSpriteBatch->end();
            Matrix spriteBatchTransform = OSpriteBatch->getTransform();
            OSpriteBatch->begin(transform * spriteBatchTransform);

            OSpriteBatch->changeBlendMode(m_blend);
            OSpriteBatch->changeFiltering(m_filter);
            m_emitter.setTransform(Vector3::Zero);
            m_emitter.render();

            OSpriteBatch->end();
            OSpriteBatch->begin(spriteBatchTransform);
        }

        // render fg children
        RenderChildren(m_fgChildren, &transform, m_color.get().w * in_parentAlpha);
    }

    void Emitter::Start()
    {
        if (m_emitWorld)
        {
            m_emitter = OEmitPFX(m_fxName.c_str(), GetTransform().Translation());
        }
        else
        {
            m_emitter = OEmitPFX(m_fxName.c_str(), Vector3::Zero);
        }
        m_emitter.setRenderEnabled(false);
    }

    void Emitter::Stop()
    {
        m_emitter.stop();
    }

    void Emitter::SetFilter(onut::SpriteBatch::eFiltering in_filter)
    {
        m_filter = in_filter;
    }

    onut::SpriteBatch::eFiltering Emitter::GetFilter() const
    {
        return m_filter;
    }

    void Emitter::SetBlend(onut::SpriteBatch::eBlendMode in_blend)
    {
        m_blend = in_blend;
    }

    onut::SpriteBatch::eBlendMode Emitter::GetBlend() const
    {
        return m_blend;
    }

    bool Emitter::GetEmitWorld() const
    {
        return m_emitWorld;
    }

    void Emitter::SetEmitWorld(bool in_emitWorld)
    {
        m_emitWorld = in_emitWorld;
    }

    OEmitterInstance& Emitter::GetEmitterInstance()
    {
        return m_emitter;
    }

    const string& Emitter::GetFxName() const
    {
        return m_fxName;
    }

    extern std::unordered_map<onut::SpriteBatch::eFiltering, string> filteringMap;
    extern std::unordered_map<onut::SpriteBatch::eBlendMode, string> blendMap;

    tinyxml2::XMLElement* Emitter::Serialize(tinyxml2::XMLDocument* in_xmlDoc) const
    {
        tinyxml2::XMLElement *xmlNode = Node::Serialize(in_xmlDoc);

        xmlNode->SetName("Emitter");
        xmlNode->SetAttribute("fx", GetFxName().c_str());
        xmlNode->SetAttribute("filter", filteringMap[GetFilter()].c_str());
        xmlNode->SetAttribute("blend", blendMap[GetBlend()].c_str());
        xmlNode->SetAttribute("emitWorld", m_emitWorld);

        return xmlNode;
    }

    void Emitter::Deserialize(View* view, tinyxml2::XMLElement* in_xmlNode)
    {
        Node::Deserialize(view, in_xmlNode);

        const char* filter = in_xmlNode->Attribute("filter");
        for (auto &kv : filteringMap) if (kv.second == filter) SetFilter(kv.first);

        const char* blend = in_xmlNode->Attribute("blend");
        for (auto &kv : blendMap) if (kv.second == blend) SetBlend(kv.first);

        in_xmlNode->QueryBoolAttribute("emitWorld", &m_emitWorld);
    }
}


text:
package org.jboss.weld.tests.extensions.lifecycle.atd;

import javax.annotation.Priority;
import javax.enterprise.inject.Alternative;

@Priority(2501)
@Alternative
public class BravoAlternative {

}


text:
from typing import Any, Callable, Dict, List

class EventSummarizer:
    """Utility that aggregates related log messages to reduce log spam."""

    def __init__(self):
        self.events_by_key: Dict[str, int] = {}

    def add(self, template: str, *, quantity: Any,
            aggregate: Callable[[Any, Any], Any]) -> None:
        """Add a log message, which will be combined by template.

        Args:
            template (str): Format string with one placeholder for quantity.
            quantity (Any): Quantity to aggregate.
            aggregate (func): Aggregation function used to combine the
                quantities. The result is inserted into the template to
                produce the final log message.
        """
        # Enforce proper sentence structure.
        if not template.endswith("."):
            template += "."
        if template in self.events_by_key:
            self.events_by_key[template] = aggregate(
                self.events_by_key[template], quantity)
        else:
            self.events_by_key[template] = quantity

    def summary(self) -> List[str]:
        """Generate the aggregated log summary of all added events."""
        out = []
        for template, quantity in self.events_by_key.items():
            out.append(template.format(quantity))
        return out

    def clear(self) -> None:
        """Clear the events added."""
        self.events_by_key.clear()


text:
require 'spec_helper'
require 'xezat/detector/libQt5Core-devel'

describe Xezat::Detector::Libqt5coreDevel do
  it 'inherits qt5-qmake' do
    detector = Xezat::Detector::Libqt5coreDevel.new
    expect(detector.detect(_qt5_qmake_CYGCLASS_: '1')).to be_truthy
  end
  it 'does not inherit qt5-qmake' do
    detector = Xezat::Detector::Libqt5coreDevel.new
    expect(detector.detect({})).to be_falsey
  end
end


text:
import { IConfigSettings } from '../../common';
import { Hash } from '../services/hash';
import { IVersionInfoService } from '../version/IVersionInfoService';
import { IServer } from './../IServer';
import { IResource } from './IResource';
import { IResourceManager } from './IResourceManager';
import { UriTemplate } from './UriTemplate';

import * as _ from 'lodash';

export class Resource implements IResource {
  public name = 'metadata';
  public uriTemplate = '?hash={hash}';
  public templateName = 'metadataTemplate';
  public type = 'client';

  private configSettings: IConfigSettings;
  private resourceManager: IResourceManager;
  private versionInfoService: IVersionInfoService;

  constructor(server: IServer) {
    this.configSettings = server.providers.configSettings;
    this.resourceManager = server.providers.resourceManager;
    this.versionInfoService = server.providers.versionInfoService;
  }

  public invoke(req, res) {
    const baseUri = UriTemplate.getBaseUri(this.configSettings, req);

    const resources = _(this.resourceManager.resources)
      .reduce<{ [key: string]: string }>(
      (result, resource) => {
        result[resource.name] = UriTemplate.fromResource(baseUri, resource);
        return result;
      },
      {});

    const resourceHash = Hash.hashObject(resources);

    const metadata = {
      versions: this.versionInfoService.allInfo,
      resources,
      hash: resourceHash,
      experimentalMode: this.configSettings.getBoolean('enable.experimental.features', false),
    };

    res.json(metadata);
  }
}


text:
package com.griddynamics.jagger.engine.e1.collector.testgroup;

import com.griddynamics.jagger.engine.e1.Provider;
import com.griddynamics.jagger.engine.e1.services.ServicesAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* begin: following section is used for docu generation - example of the test group listener */

/** Example of the test group listener
 * @author Andrey Badaev
 * @n
 * @par Details:
 * @details
 * Does nothing but logging at test group execution start and stop
 *
 * @ingroup Main_Listeners_group */
public class ExampleTestGroupListener extends ServicesAware implements Provider<TestGroupListener> {

    private final static Logger log = LoggerFactory.getLogger(ExampleTestGroupListener.class);

    @Override
    protected void init() {
        super.init();
    }

    @Override
    public TestGroupListener provide() {
        return new TestGroupListener() {
            @Override
            public void onStart(TestGroupInfo infoStart) {
                log.info("Started {} test group execution", infoStart.getTestGroup().getTaskName());
            }

            @Override
            public void onStop(TestGroupInfo infoStop) {
                log.info("{} test group execution took {}ms", infoStop.getTestGroup().getTaskName(), infoStop.getDuration());
            }
        };
    }
}

/* end: following section is used for docu generation - example of the test group listener */


text:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
        <gradient android:startColor="#10f3d465" android:endColor="#00000000"
            android:angle="270"/>
    <stroke android:width="1dp" android:color="#FFE3AE00"/>
    <corners android:radius="0dp"/>
    <padding android:left="6dp" android:top="2dp"
            android:right="6dp" android:bottom="2dp" />
</shape>


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { firebaseConnect, getVal } from 'react-redux-firebase'
import { path } from 'ramda'
import firebaseTools from 'decorators/firebaseTools'
// Components
import { Button } from 'react-bootstrap'
// Selectors
import {
  answerActiveSelector,
  currentPlaySelector,
  currentPlayerAnswerSelector,
  questionActiveSelector,
} from 'redux/selectors/plays'
import { currentTourSelector } from 'redux/selectors/tours'
// Consts
import {
  ABCD_QUESTIONS_PATH,
} from 'consts/firebasePaths'
// Styles
import styles from './Question.scss'

@firebaseConnect(({ questionKey }) => ([
  `${ABCD_QUESTIONS_PATH}/${questionKey}`,
]))
@connect(
  (state, { questionKey }) => ({
    isAnswerActive: answerActiveSelector(state),
    isQuestionActive: questionActiveSelector(state),
    play: currentPlaySelector(state),
    playerAnswer: currentPlayerAnswerSelector(state),
    question: getVal(state.firebase, `data/${ABCD_QUESTIONS_PATH}/${questionKey}`),
    tour: currentTourSelector(state),
  }),
)
@firebaseTools()
class Question extends Component {
  static propTypes = {
    isAnswerActive: PropTypes.bool,
    isQuestionActive: PropTypes.bool,
    playerAnswer: PropTypes.string,
    question: PropTypes.object,
    questionKey: PropTypes.string,
    updatePlayerQuestion: PropTypes.func,
  }

  handleAnswerClick = (answer) => {
    const { playerAnswer, question } = this.props
    if (playerAnswer) {
      return
    }
    const correct = answer === path(['answer'], question)
    this.props.updatePlayerQuestion({
      answer,
      correct,
    })
  }

  renderOptions() {
    const { question, playerAnswer } = this.props
    const options = path(['options'], question) || {}

    return (

        {Object.keys(options).map(key => (

            <Button
              block
              className={key === playerAnswer ? styles.active : ''}
              bsSize="large"
              onClick={() => this.handleAnswerClick(key)}>

                {key}.{' '}

              {options[key]}

            </Button>

        ))}

    )
  }

  render() {
    const { isAnswerActive, isQuestionActive, question } = this.props
    const text = path(['text'], question)
    return (

          {isQuestionActive &&

            {text}

}
          {isQuestionActive && !isAnswerActive &&

            {this.renderOptions()}

}

    )
  }
}

export default Question


text:
function displayFriends() {
	var getURL = "/friends/all";
	$.get(getURL, displayFriendsCallback);
}

function displayFriendsCallback(result) {
	var header ='

	' +
							'
	' +
							'
friends
	' +
							'
	' +
							'
edit
';
	var headerTemplate = Handlebars.compile(header);
	var headerHTML = headerTemplate(result);
	$('header').html(headerHTML);

	var main = 	'
	' +
							'		<form id="addFriendForm" role="form" method="get" action="/friends/edit/friendAdd" class="container">	' +
 						  '  		First Name:	' +
							'  		<input type="text" class="form-control" id="firstname" placeholder="first name" name="firstname">	' +
  						'  		Last Name: ' +
							'  		<input type="text" class="form-control" id="lastname" placeholder="last name" name="lastname">	' +
  						'  		Email: ' +
							'  		<input type="text" class="form-control" id="email" placeholder="email" name="email">	' +
							'
	' +
							'			<input type="submit" id="submitBtn" class="btn btn-success" value="Add friend"></input>	' +
							'		</form>	' +
							'
	' +
							'
	' +
							'		+	' +
							'
	' +
							'	{{#each friends}}	' +
							'
	' +
							'
	' +
							'			<text class="list-name">{{first-name}} {{last-name}}</text>	' +
							'			<text class="list-description">{{email}}</text>	' +
							'
	' +
							'
	' +
							'
delete
	' +
							'
	' +
							'
	' +
							'	{{/each}}';
	var mainTemplate = Handlebars.compile(main);
	var mainHTML = mainTemplate(result);
	$('.main').html(mainHTML);

	displayFriendsJQuery();
}

function displayFriendsJQuery() {
	var headerHeight = $('header').height();
	var footerHeight = $('footer').height();

	// make sure content fits within middle section
	$('.main').css('margin-top', headerHeight);
	$('.main').css('margin-bottom', footerHeight);

	$('.add').css('top', headerHeight);
	$('.add-form').css('top', headerHeight + $('.add').height());

	$('.edit').css('height', $('.element').height());
	$('.menu-right').click(function() {
		function hideEdit(callback) {
			$('.add-form').hide();
			callback();
		}

		hideEdit(function() {
			$('.add').toggle('slide', {direction: 'up'});
		});

		if (parseInt($('.main').css('margin-top')) == headerHeight) {
			$('.main').animate({'margin-top': headerHeight + $('.add').height()});
		} else {
			$('.main').animate({'margin-top': headerHeight});
		}

  	$('.edit').toggle('slide', {direction: 'right'});
		$('.menu-right').text($(this).text() == 'edit' ? 'done' : 'edit');
	});

	$('.add').click(function() {
		$('.add-form').toggle();
	});
}


text:
import { sum } from 'namedSum';

const add2 = (val) => sum(val, 2);

export default add2;


text:
char replace(std::string& s, unsigned index, char x) {
    char result;
    boost::contract::old_ptr<char> old_y; // Null, old value copied later...
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(index < s.size());
        })
        .old([&] { // ...after preconditions (and invariants) checked.
            old_y = BOOST_CONTRACT_OLDOF(s[index]);
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(s[index] == x);
            BOOST_CONTRACT_ASSERT(result == *old_y);
        })
    ;

    result = s[index];
    s[index] = x;
    return result;
}
//]

int main() {
    std::string s = "abc";
    char r = replace(s, 1, '_');
    assert(s == "a_c");
    assert(r == 'b');
    return 0;
}


text: A Twitter bot made to create Markov chains from classic literature


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>X-Index</title>
<meta name="date" content="2013-10-01">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M O P Q R S T U V W X Y Z

X

X - Variable in class edu.cmu.cs.lane.algorithmicEngine.SimulatedData

X - Variable in class edu.cmu.cs.lane.datatypes.GFLasso.GFLassoDataInput

XLabels - Variable in class edu.cmu.cs.lane.datatypes.GFLasso.GFLassoDataInput

A B C D E F G H I L M O P Q R S T U V W X Y Z

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php

namespace Concrete\Core\Navigation\Item;

use Concrete\Core\Page\Page;

class PageItem extends Item
{

    /**
     * @var int
     */
    protected $pageID;

    /**
     * @var string
     */
    protected $keywords = '';

    /**
     * Item constructor.
     * @param string $url
     * @param string $name
     * @param bool $isActive
     */
    public function __construct(Page $page = null, bool $isActive = false)
    {
        if ($page) {
            $this->pageID = $page->getCollectionID();
            $this->keywords = (string)$page->getAttribute("meta_keywords");
            parent::__construct($page->getCollectionLink(), t($page->getCollectionName()), $isActive);
        }
        if ($this->keywords === null) {
            $this->keywords = '';
        }
    }

    /**
     * @return PageItem[]
     */
    public function getChildren(): array
    {
        return parent::getChildren(); // TODO: Change the autogenerated stub
    }

    /**
     * @return int
     */
    public function getPageID(): int
    {
        return $this->pageID;
    }

    /**
     * @param int $pageID
     */
    public function setPageID(int $pageID): void
    {
        $this->pageID = $pageID;
    }

    /**
     * @return string
     */
    public function getKeywords(): string
    {
        return $this->keywords;
    }

    /**
     * @param string $keywords
     * @return PageItem
     */
    public function setKeywords(string $keywords): PageItem
    {
        $this->keywords = $keywords;
        return $this;
    }

    public function jsonSerialize()
    {
        $data = parent::jsonSerialize();
        $data['pageID'] = $this->getPageID();
        $data['keywords'] = $this->getKeywords();
        return $data;
    }

}


text:
export { default } from './Badge';

export * from './constants';


text:
package org.jboss.weld.tests.category;

/**
 * Marker Interface for JUnit Category marking Broken tests
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
public interface Broken {

}


text:
from argparse import ArgumentParser
from multiprocessing import Pool, Manager
from tests import faker

import datetime
import json
import time
import uuid
import sys
import random

INSTANCE_TEMPLATE = { 'uuid':'uuid_replace',
               'display_name':'display_name_replace',
               'host':'h1',
               'power_state':1,
               'vm_state':'active',
               'vcpus':2,
               'memory_mb':10,
               'disk_gb':1,
               'key_name':'key1',
               'launched_at':'replace',
               'user_id':'u1',
               'project_id':'p1',
               'image_ref':'i1',
               'flavor_name':'flavor1',
               'ip':'0.0.0.0' }

COMPUTENODE_TEMPLATE = { 'id':-1, #replace
        'local_gb': 259,
        'vcpus_used': 0,
        'deleted': 0,
        'hypervisor_type': 'powervm',
        'created_at': '2013-04-01T00:27:06.000000',
        'local_gb_used': 0,
        'updated_at': '2013-04-03T00:35:41.000000',
        'hypervisor_hostname': 'hostname_replace',
        'memory_mb_used': 512,
        'memory_mb': 131072,
        'current_workload': 0,
        'vcpus': 16,
        'cpu_info': 'ppc64,powervm,3940',
        'running_vms': 0,
        'free_disk_gb': 259,
        'service_id': 7,
        'hypervisor_version': 7,
        'disk_available_least': 265856,
        'deleted_at': None,
        'free_ram_mb': 130560 }

STATE_MAP = {
    0: 'pending',
    1: 'active',
    3: 'paused',
    4: 'shutdown',
    6: 'crashed',
    7: 'suspended',
    9: 'building',
}

DATA_BATCH = 1000
MAX_PROCESSES = 10
HOST_TO_VM_RATIO = 20

class ScaleDataProvider():

    def __init__(self, file_names):
        self.file_names = file_names

    def execute(self, query):
        def datetime_hook(data):
            if 'launched_at' in data:
                # expensive translation that causes a 4x multiple in data read time. Necessary to keep InstanceHandler happy.
                data['launched_at'] = datetime.datetime.strptime(data['launched_at'],'%Y-%m-%d %H:%M:%S.%f') if '.' in data['launched_at'] else datetime.datetime.strptime(data['launched_at'],'%Y-%m-%d %H:%M:%S')
            return data
        data = []
        for file_name in self.file_names :
            with open(file_name, "r") as data_file :
                file_data = json.load(data_file, object_hook= datetime_hook)
                data.extend(file_data)
        return data

def ensure_dir(dirname):
    import os
    if not os.path.exists(dirname):
        print 'Creating %s.' % dirname
        os.makedirs(dirname)

def _generate_instance_batch(file_name, data_range, host_names):
    #start_time = time.time()
    #print 'Writing to %s range[%d, %d] in proc %d.' % (file_name, data_range[0], data_range[0] + len(data_range), os.getpid())
    sys.stdout.write('.')
    host_names_index = 0
    projects = faker.firstname(10)
    with open(file_name, 'w') as data_file:
        add_separator = False
        data_file.write('[')
        for index in data_range:
            INSTANCE_TEMPLATE['uuid'] = str(uuid.uuid4())
            INSTANCE_TEMPLATE['display_name'] = 'i-%d.' % index + faker.domain()
            INSTANCE_TEMPLATE['launched_at'] = str(datetime.datetime.now())
            INSTANCE_TEMPLATE['host'] = host_names[host_names_index]
            INSTANCE_TEMPLATE['flavor_name'] = random.sample(("m1.tiny", "m1.small", "m1.medium", "m1.large", "m1.xlarge"), 1)[0]
            INSTANCE_TEMPLATE['power_state'] = random.sample((1,1,1,3,7), 1)[0]
            INSTANCE_TEMPLATE['vm_state'] = STATE_MAP[INSTANCE_TEMPLATE['power_state']]
            INSTANCE_TEMPLATE['vcpus'] = random.randint(1, 4)
            INSTANCE_TEMPLATE['memory_mb'] = random.randint(1, 2048)
            INSTANCE_TEMPLATE['disk_gb'] = random.randint(1, 256)
            INSTANCE_TEMPLATE['project_id'] = 'p' + str(random.randint(0, 9))
            INSTANCE_TEMPLATE['user_id'] = 'u' + str(random.randint(0, 9))
            INSTANCE_TEMPLATE['image_ref'] = 'i' + str(random.randint(0, 9))
            INSTANCE_TEMPLATE['ip'] = faker.ip()

            if add_separator:
                data_file.write(',\n')
            else :
                add_separator = True
            json.dump(INSTANCE_TEMPLATE, data_file)
            # even host distribution
            host_names_index = host_names_index + 1
            host_names_index = 0 if host_names_index == len(host_names) else host_names_index
        data_file.write(']')
    #print 'Process %d done writing to %s in %f.' % (os.getpid(), file_name, time.time() - start_time)

def _generate_instance_data(location, size, host_names):
    instance_location = '%s/%s' % (location, 'instance')
    ensure_dir(instance_location)
    sys.stdout.write('generating instance data')
    file_names = []
    num_file = size / DATA_BATCH
    if (size % DATA_BATCH) :
        num_file = num_file + 1
    HOST_BATCH = DATA_BATCH / HOST_TO_VM_RATIO
    pp = Pool(processes=MAX_PROCESSES)
    for file_index in range(num_file):
        file_name = '%s/data_%d.dat' % (instance_location, file_index)
        file_names.append(file_name)
        data_start_index = file_index * DATA_BATCH
        is_last_page = (size - data_start_index) <= DATA_BATCH
        data_end_index = size if is_last_page else data_start_index + DATA_BATCH
        # Even batch distribution
        pp.apply_async(_generate_instance_batch,
                       args=(file_name, range(data_start_index, data_end_index),
                       host_names[file_index*HOST_BATCH:file_index*HOST_BATCH + HOST_BATCH]))
    pp.close()
    pp.join()
    sys.stdout.write('\n')
    return file_names

def _generate_computenode_batch(file_name, data_range, host_names):
    #start_time = time.time()
    #print 'Writing to %s range[%d, %d] in proc %d.' % (file_name, data_range[0], data_range[0] + len(data_range), os.getpid())
    sys.stdout.write('.')
    with open(file_name, 'w') as data_file:
        add_separator = False
        data_file.write('[')
        for index in data_range:
            COMPUTENODE_TEMPLATE['id'] = index
            host_name = faker.domain()
            COMPUTENODE_TEMPLATE['hypervisor_hostname'] = host_name
            vcpus = random.randint(8, 24)
            COMPUTENODE_TEMPLATE['vcpus'] = vcpus
            COMPUTENODE_TEMPLATE['memory_mb'] = random.randint(32768, 98304)
            COMPUTENODE_TEMPLATE['local_gb'] = random.randint(1, 2048)
            # TODO: find a way to compute vcpus_used, vcpus_assignred, memory_active,
            # memory_assigned, storage_used and storage_free. All of them should be calculated
            # after all vm's for the particular host are generated.
            COMPUTENODE_TEMPLATE['vcpus_used'] = random.randint(30, 5 * vcpus + 20)
            COMPUTENODE_TEMPLATE['memory_mb_used'] = random.randint(1, 3 * COMPUTENODE_TEMPLATE['memory_mb'])
            COMPUTENODE_TEMPLATE['local_gb_used'] = random.randint(1, COMPUTENODE_TEMPLATE['local_gb'])
            COMPUTENODE_TEMPLATE['free_disk_gb'] = COMPUTENODE_TEMPLATE['local_gb'] - COMPUTENODE_TEMPLATE['local_gb_used']

            host_names.append(host_name)
            if add_separator:
                data_file.write(',\n')
            else :
                add_separator = True
            json.dump(COMPUTENODE_TEMPLATE, data_file)
        data_file.write(']')
    #print 'Process %d done writing to %s in %f.' % (os.getpid(), file_name, time.time() - start_time)

def _generate_computenode_data(location, size):
    computenode_location = '%s/%s' % (location, 'computenode')
    ensure_dir(computenode_location)
    sys.stdout.write('generating computenode data')
    file_names = []
    num_file = size / DATA_BATCH
    if (size % DATA_BATCH) :
        num_file = num_file + 1
    # manager holds the host_names list and allows other process to manipulate this via proxy.
    # initial testing suggests this to be thread/process safe.
    manager = Manager()
    host_names = manager.list()
    pp = Pool(processes=MAX_PROCESSES)
    for file_index in range(num_file):
        file_name = '%s/data_%d.dat' % (computenode_location, file_index)
        file_names.append(file_name)
        data_start_index = file_index * DATA_BATCH
        is_last_page = (size - data_start_index) <= DATA_BATCH
        data_end_index = size if is_last_page else data_start_index + DATA_BATCH
        pp.apply_async(_generate_computenode_batch, args=(file_name, range(data_start_index, data_end_index), host_names))
    pp.close()
    pp.join()
    sys.stdout.write('\n')
    return (file_names, host_names)

def generate_data(location, size):
    # generate computenode data
    computenode_size = size / HOST_TO_VM_RATIO + (1 if size % HOST_TO_VM_RATIO > 0 else 0)
    start_time = time.time()
    computenodes_files, host_names = _generate_computenode_data(location, computenode_size)
    print 'generated %s compute_nodes in %f.' % (len(host_names), time.time() - start_time)
    #generate instance data
    start_time = time.time()
    instances_files = _generate_instance_data(location, size, host_names)
    print 'generated %s instance_nodes in %f.' % (size, time.time() - start_time)
    return (computenodes_files, instances_files)

def main():
    parser = ArgumentParser()
    parser.add_argument("-l", "--location", help="location of the file.")
    parser.add_argument("-n", "--number", help="number of resources.")
    args = parser.parse_args()

    computenodes_files, instances_files = generate_data(args.location, int(args.number))

#     if len(file_names) > 0:
#         #print file_names
#         print 'reading from %d file(s).' % len(file_names)
#         provider = ScaleDataProvider(file_names)
#         start_time = time.time()
#         data = provider.execute("")
#         print 'read %d(%d bytes) instance_nodes from all files in %f.' % (len(data), sys.getsizeof(data), time.time() - start_time)

if __name__ == '__main__':
    main()


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class vpnintranetapplication(base_resource) :
	""" Configuration for SSLVPN intranet application resource. """
	def __init__(self) :
		self._intranetapplication = ""
		self._protocol = ""
		self._destip = ""
		self._netmask = ""
		self._iprange = ""
		self._hostname = ""
		self._clientapplication = []
		self._spoofiip = ""
		self._destport = ""
		self._interception = ""
		self._srcip = ""
		self._srcport = 0
		self._ipaddress = ""
		self.___count = 0

	@property
	def intranetapplication(self) :
		"""Name of the intranet application.
Minimum length =  1
Maximum length =  31.
		"""
		try :
			return self._intranetapplication
		except Exception as e:
			raise e

	@intranetapplication.setter
	def intranetapplication(self, intranetapplication) :
		"""Name of the intranet application.
Minimum length =  1
Maximum length =  31
		"""
		try :
			self._intranetapplication = intranetapplication
		except Exception as e:
			raise e

	@property
	def protocol(self) :
		"""Protocol used by the intranet application. If protocol is set to BOTH, TCP and UDP traffic is allowed.
Possible values = TCP, UDP, ANY.
		"""
		try :
			return self._protocol
		except Exception as e:
			raise e

	@protocol.setter
	def protocol(self, protocol) :
		"""Protocol used by the intranet application. If protocol is set to BOTH, TCP and UDP traffic is allowed.
Possible values = TCP, UDP, ANY
		"""
		try :
			self._protocol = protocol
		except Exception as e:
			raise e

	@property
	def destip(self) :
		"""Destination IP address, IP range, or host name of the intranet application. This address is the server IP address.
Minimum length =  1.
		"""
		try :
			return self._destip
		except Exception as e:
			raise e

	@destip.setter
	def destip(self, destip) :
		"""Destination IP address, IP range, or host name of the intranet application. This address is the server IP address.
Minimum length =  1
		"""
		try :
			self._destip = destip
		except Exception as e:
			raise e

	@property
	def netmask(self) :
		"""Destination subnet mask for the intranet application.
		"""
		try :
			return self._netmask
		except Exception as e:
			raise e

	@netmask.setter
	def netmask(self, netmask) :
		"""Destination subnet mask for the intranet application.
		"""
		try :
			self._netmask = netmask
		except Exception as e:
			raise e

	@property
	def iprange(self) :
		"""If you have multiple servers in your network, such as web, email, and file shares, configure an intranet application that includes the IP range for all the network applications. This allows users to access all the intranet applications contained in the IP address range.
Minimum length =  1.
		"""
		try :
			return self._iprange
		except Exception as e:
			raise e

	@iprange.setter
	def iprange(self, iprange) :
		"""If you have multiple servers in your network, such as web, email, and file shares, configure an intranet application that includes the IP range for all the network applications. This allows users to access all the intranet applications contained in the IP address range.
Minimum length =  1
		"""
		try :
			self._iprange = iprange
		except Exception as e:
			raise e

	@property
	def hostname(self) :
		"""Name of the host for which to configure interception. The names are resolved during interception when users log on with the NetScaler Gateway Plug-in.
Minimum length =  1.
		"""
		try :
			return self._hostname
		except Exception as e:
			raise e

	@hostname.setter
	def hostname(self, hostname) :
		"""Name of the host for which to configure interception. The names are resolved during interception when users log on with the NetScaler Gateway Plug-in.
Minimum length =  1
		"""
		try :
			self._hostname = hostname
		except Exception as e:
			raise e

	@property
	def clientapplication(self) :
		"""Names of the client applications, such as PuTTY and Xshell.
Minimum length =  1.
		"""
		try :
			return self._clientapplication
		except Exception as e:
			raise e

	@clientapplication.setter
	def clientapplication(self, clientapplication) :
		"""Names of the client applications, such as PuTTY and Xshell.
Minimum length =  1
		"""
		try :
			self._clientapplication = clientapplication
		except Exception as e:
			raise e

	@property
	def spoofiip(self) :
		"""IP address that the intranet application will use to route the connection through the virtual adapter.
Default value: ON
Possible values = ON, OFF.
		"""
		try :
			return self._spoofiip
		except Exception as e:
			raise e

	@spoofiip.setter
	def spoofiip(self, spoofiip) :
		"""IP address that the intranet application will use to route the connection through the virtual adapter.
Default value: ON
Possible values = ON, OFF
		"""
		try :
			self._spoofiip = spoofiip
		except Exception as e:
			raise e

	@property
	def destport(self) :
		"""Destination TCP or UDP port number for the intranet application. Use a hyphen to specify a range of port numbers, for example 90-95.
Minimum length =  1.
		"""
		try :
			return self._destport
		except Exception as e:
			raise e

	@destport.setter
	def destport(self, destport) :
		"""Destination TCP or UDP port number for the intranet application. Use a hyphen to specify a range of port numbers, for example 90-95.
Minimum length =  1
		"""
		try :
			self._destport = destport
		except Exception as e:
			raise e

	@property
	def interception(self) :
		"""Interception mode for the intranet application or resource. Correct value depends on the type of client software used to make connections. If the interception mode is set to TRANSPARENT, users connect with the NetScaler Gateway Plug-in for Windows. With the PROXY setting, users connect with the NetScaler Gateway Plug-in for Java.
Possible values = PROXY, TRANSPARENT.
		"""
		try :
			return self._interception
		except Exception as e:
			raise e

	@interception.setter
	def interception(self, interception) :
		"""Interception mode for the intranet application or resource. Correct value depends on the type of client software used to make connections. If the interception mode is set to TRANSPARENT, users connect with the NetScaler Gateway Plug-in for Windows. With the PROXY setting, users connect with the NetScaler Gateway Plug-in for Java.
Possible values = PROXY, TRANSPARENT
		"""
		try :
			self._interception = interception
		except Exception as e:
			raise e

	@property
	def srcip(self) :
		"""Source IP address. Required if interception mode is set to PROXY. Default is the loopback address, 127.0.0.1.
Minimum length =  1.
		"""
		try :
			return self._srcip
		except Exception as e:
			raise e

	@srcip.setter
	def srcip(self, srcip) :
		"""Source IP address. Required if interception mode is set to PROXY. Default is the loopback address, 127.0.0.1.
Minimum length =  1
		"""
		try :
			self._srcip = srcip
		except Exception as e:
			raise e

	@property
	def srcport(self) :
		"""Source port for the application for which the NetScaler Gateway virtual server proxies the traffic. If users are connecting from a device that uses the NetScaler Gateway Plug-in for Java, applications must be configured manually by using the source IP address and TCP port values specified in the intranet application profile. If a port value is not set, the destination port value is used.
Minimum length =  1.
		"""
		try :
			return self._srcport
		except Exception as e:
			raise e

	@srcport.setter
	def srcport(self, srcport) :
		"""Source port for the application for which the NetScaler Gateway virtual server proxies the traffic. If users are connecting from a device that uses the NetScaler Gateway Plug-in for Java, applications must be configured manually by using the source IP address and TCP port values specified in the intranet application profile. If a port value is not set, the destination port value is used.
Minimum length =  1
		"""
		try :
			self._srcport = srcport
		except Exception as e:
			raise e

	@property
	def ipaddress(self) :
		"""The IP address for the application. This address is the real application server IP address.
		"""
		try :
			return self._ipaddress
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(vpnintranetapplication_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.vpnintranetapplication
		except Exception as e :
			raise e

	def _get_object_name(self) :
		""" Returns the value of object identifier argument
		"""
		try :
			if (self.intranetapplication) :
				return str(self.intranetapplication)
			return None
		except Exception as e :
			raise e

	@classmethod
	def add(cls, client, resource) :
		""" Use this API to add vpnintranetapplication.
		"""
		try :
			if type(resource) is not list :
				addresource = vpnintranetapplication()
				addresource.intranetapplication = resource.intranetapplication
				addresource.protocol = resource.protocol
				addresource.destip = resource.destip
				addresource.netmask = resource.netmask
				addresource.iprange = resource.iprange
				addresource.hostname = resource.hostname
				addresource.clientapplication = resource.clientapplication
				addresource.spoofiip = resource.spoofiip
				addresource.destport = resource.destport
				addresource.interception = resource.interception
				addresource.srcip = resource.srcip
				addresource.srcport = resource.srcport
				return addresource.add_resource(client)
			else :
				if (resource and len(resource) > 0) :
					addresources = [ vpnintranetapplication() for _ in range(len(resource))]
					for i in range(len(resource)) :
						addresources[i].intranetapplication = resource[i].intranetapplication
						addresources[i].protocol = resource[i].protocol
						addresources[i].destip = resource[i].destip
						addresources[i].netmask = resource[i].netmask
						addresources[i].iprange = resource[i].iprange
						addresources[i].hostname = resource[i].hostname
						addresources[i].clientapplication = resource[i].clientapplication
						addresources[i].spoofiip = resource[i].spoofiip
						addresources[i].destport = resource[i].destport
						addresources[i].interception = resource[i].interception
						addresources[i].srcip = resource[i].srcip
						addresources[i].srcport = resource[i].srcport
				result = cls.add_bulk_request(client, addresources)
			return result
		except Exception as e :
			raise e

	@classmethod
	def delete(cls, client, resource) :
		""" Use this API to delete vpnintranetapplication.
		"""
		try :
			if type(resource) is not list :
				deleteresource = vpnintranetapplication()
				if type(resource) !=  type(deleteresource):
					deleteresource.intranetapplication = resource
				else :
					deleteresource.intranetapplication = resource.intranetapplication
				return deleteresource.delete_resource(client)
			else :
				if type(resource[0]) != cls :
					if (resource and len(resource) > 0) :
						deleteresources = [ vpnintranetapplication() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].intranetapplication = resource[i]
				else :
					if (resource and len(resource) > 0) :
						deleteresources = [ vpnintranetapplication() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].intranetapplication = resource[i].intranetapplication
				result = cls.delete_bulk_request(client, deleteresources)
			return result
		except Exception as e :
			raise e

	@classmethod
	def get(cls, client, name="", option_="") :
		""" Use this API to fetch all the vpnintranetapplication resources that are configured on netscaler.
		"""
		try :
			if not name :
				obj = vpnintranetapplication()
				response = obj.get_resources(client, option_)
			else :
				if type(name) != cls :
					if type(name) is not list :
						obj = vpnintranetapplication()
						obj.intranetapplication = name
						response = obj.get_resource(client, option_)
					else :
						if name and len(name) > 0 :
							response = [vpnintranetapplication() for _ in range(len(name))]
							obj = [vpnintranetapplication() for _ in range(len(name))]
							for i in range(len(name)) :
								obj[i] = vpnintranetapplication()
								obj[i].intranetapplication = name[i]
								response[i] = obj[i].get_resource(client, option_)
			return response
		except Exception as e :
			raise e

	@classmethod
	def get_filtered(cls, client, filter_) :
		""" Use this API to fetch filtered set of vpnintranetapplication resources.
		filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = vpnintranetapplication()
			option_ = options()
			option_.filter = filter_
			response = obj.getfiltered(client, option_)
			return response
		except Exception as e :
			raise e

	@classmethod
	def count(cls, client) :
		""" Use this API to count the vpnintranetapplication resources configured on NetScaler.
		"""
		try :
			obj = vpnintranetapplication()
			option_ = options()
			option_.count = True
			response = obj.get_resources(client, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e :
			raise e

	@classmethod
	def count_filtered(cls, client, filter_) :
		""" Use this API to count filtered the set of vpnintranetapplication resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = vpnintranetapplication()
			option_ = options()
			option_.count = True
			option_.filter = filter_
			response = obj.getfiltered(client, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e :
			raise e

	class Spoofiip:
		ON = "ON"
		OFF = "OFF"

	class Protocol:
		TCP = "TCP"
		UDP = "UDP"
		ANY = "ANY"

	class Interception:
		PROXY = "PROXY"
		TRANSPARENT = "TRANSPARENT"

class vpnintranetapplication_response(base_response) :
	def __init__(self, length=1) :
		self.vpnintranetapplication = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.vpnintranetapplication = [vpnintranetapplication() for _ in range(length)]


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.tools.ant.taskdefs.optional.ejb (Apache Ant API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.tools.ant.taskdefs.optional.ejb package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

org.apache.tools.ant.taskdefs.optional.ejb

Interfaces

EJBDeploymentTool

Classes

BorlandDeploymentTool

BorlandGenerateClient

DescriptorHandler

EjbJar

EjbJar.CMPVersion

EjbJar.DTDLocation

EjbJar.NamingScheme

GenericDeploymentTool

InnerClassFilenameFilter

IPlanetDeploymentTool

IPlanetEjbc

IPlanetEjbcTask

JbossDeploymentTool

JonasDeploymentTool

WeblogicDeploymentTool

WeblogicTOPLinkDeploymentTool

WebsphereDeploymentTool


text:
import sys

try:
    import simplejson as json
except ImportError:
    import json

from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import urlparse
from libcloud.utils.py3 import parse_qsl

from libcloud.common.types import LibcloudError
from libcloud.loadbalancer.types import Provider
from libcloud.loadbalancer.providers import get_driver
from libcloud.loadbalancer.base import LoadBalancer, Member, Algorithm
from libcloud.loadbalancer.drivers.cloudstack import CloudStackLBDriver

from libcloud.test import unittest
from libcloud.test import MockHttpTestCase
from libcloud.test.file_fixtures import LoadBalancerFileFixtures

class CloudStackLBTests(unittest.TestCase):
    def setUp(self):
        CloudStackLBDriver.connectionCls.conn_classes = \
            (None, CloudStackMockHttp)

        CloudStackLBDriver.path = '/test/path'
        CloudStackLBDriver.type = -1
        CloudStackLBDriver.name = 'CloudStack'
        self.driver = CloudStackLBDriver('apikey', 'secret')
        CloudStackMockHttp.fixture_tag = 'default'
        self.driver.connection.poll_interval = 0.0

    def test_user_must_provide_host_and_path(self):
        CloudStackLBDriver.path = None
        CloudStackLBDriver.type = Provider.CLOUDSTACK

        expected_msg = 'When instantiating CloudStack driver directly ' + \
                       'you also need to provide host and path argument'
        cls = get_driver(Provider.CLOUDSTACK)

        self.assertRaisesRegexp(Exception, expected_msg, cls,
                                'key', 'secret')

        try:
            cls('key', 'secret', True, 'localhost', '/path')
        except Exception:
             self.fail('host and path provided but driver raised an exception')

    def test_list_supported_algorithms(self):
        algorithms = self.driver.list_supported_algorithms()

        self.assertTrue(Algorithm.ROUND_ROBIN in algorithms)
        self.assertTrue(Algorithm.LEAST_CONNECTIONS in algorithms)

    def test_list_balancers(self):
        balancers = self.driver.list_balancers()
        for balancer in balancers:
            self.assertTrue(isinstance(balancer, LoadBalancer))

    def test_create_balancer(self):
        members = [Member(1, '1.1.1.1', 80), Member(2, '1.1.1.2', 80)]
        balancer = self.driver.create_balancer('fake', members)
        self.assertTrue(isinstance(balancer, LoadBalancer))

    def test_destroy_balancer(self):
        balancer = self.driver.list_balancers()[0]
        self.driver.destroy_balancer(balancer)

    def test_balancer_attach_member(self):
        balancer = self.driver.list_balancers()[0]
        member = Member(id=1234, ip='1.1.1.1', port=80)
        balancer.attach_member(member)

    def test_balancer_detach_member(self):
        balancer = self.driver.list_balancers()[0]
        member = balancer.list_members()[0]
        balancer.detach_member(member)

    def test_balancer_list_members(self):
        balancer = self.driver.list_balancers()[0]
        members = balancer.list_members()
        for member in members:
            self.assertTrue(isinstance(member, Member))
            self.assertEquals(member.balancer, balancer)

class CloudStackMockHttp(MockHttpTestCase):
    fixtures = LoadBalancerFileFixtures('cloudstack')
    fixture_tag = 'default'

    def _load_fixture(self, fixture):
        body = self.fixtures.load(fixture)
        return body, json.loads(body)

    def _test_path(self, method, url, body, headers):
        url = urlparse.urlparse(url)
        query = dict(parse_qsl(url.query))

        self.assertTrue('apiKey' in query)
        self.assertTrue('command' in query)
        self.assertTrue('response' in query)
        self.assertTrue('signature' in query)

        self.assertTrue(query['response'] == 'json')

        del query['apiKey']
        del query['response']
        del query['signature']
        command = query.pop('command')

        if hasattr(self, '_cmd_' + command):
            return getattr(self, '_cmd_' + command)(**query)
        else:
            fixture = command + '_' + self.fixture_tag + '.json'
            body, obj = self._load_fixture(fixture)
            return (httplib.OK, body, obj, httplib.responses[httplib.OK])

    def _cmd_queryAsyncJobResult(self, jobid):
        fixture = 'queryAsyncJobResult' + '_' + str(jobid) + '.json'
        body, obj = self._load_fixture(fixture)
        return (httplib.OK, body, obj, httplib.responses[httplib.OK])

if __name__ == "__main__":
    sys.exit(unittest.main())


text:
import React,{Component} from 'react';
import {connect} from 'react-redux';
import TodoAction from '../Action/TodoAction';
import TodoHeader from './TodoHeader';

class TodoHeaderController extends Component {

    constructor(props){
        super(props);
        this.state = {};
    }

    render() {
        return (
            <TodoHeader onKeyDown={(e) => {
                let keyCode = e.keyCode;
                if (keyCode === 13) {
                    let title= e.target.value;
                    this.props.createItem(title);
                    e.target.value = "";
                }
            }}/>
        );
    }

}

export default connect (undefined,{

    createItem:TodoAction.createItem

})(TodoHeaderController);


text:
@implementation MKAnalytics

#pragma mark - Life Cycle

+ (MKAnalytics *)defaultAnalytics
{
    static dispatch_once_t onceToken;
    static MKAnalytics *sharedInstance = nil;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MKAnalytics alloc] init];
    });
    return sharedInstance;
}

+ (instancetype)analyticsWithServices:(NSArray <id<MKAnalyticsService>> *)services
{
    MKAnalytics *const analytics = [[MKAnalytics alloc] init];
    analytics.analyticsServices = services;
    return analytics;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _analyticsServices = (NSArray <id<MKAnalyticsService>> *) @[];
    }
    return self;
}

#pragma mark - Public Implementation

- (void)identifyUserWithId:(NSString *)userId
{
    [self identifyUserWithId:userId properties:nil];
}

- (void)trackScreen:(NSString *)screenName
{
    [self trackScreen:screenName properties:nil];
}

- (void)trackEvent:(NSString *)event
{
    [self trackEvent:event properties:nil];
}

#pragma mark - MKAnalyticsService

- (void)identifyUserWithId:(NSString *)userId properties:(NSDictionary<NSString *, id> *)properties
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service identifyUserWithId:userId properties:properties];
    }
}

- (void)aliasUser:(NSString *)alias
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service aliasUser:alias];
    }
}

- (void)setUserProperties:(NSDictionary<NSString *, id> *)properties
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service setUserProperties:properties];
    }
}

- (void)resetIdentification
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service resetIdentification];
    }
}

- (void)trackAppLaunched
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service trackAppLaunched];
    }
}

- (void)trackScreen:(NSString *)screenName properties:(NSDictionary<NSString *, id> *)properties
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service trackScreen:screenName properties:properties];
    }
}

- (void)trackEvent:(NSString *)event properties:(NSDictionary<NSString *, id> *)properties
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service trackEvent:event properties:properties];
    }
}

- (void)startTimingForEvent:(NSString *)event
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service startTimingForEvent:event];
    }
}

- (void)trackPurchase:(NSString *)item amount:(CGFloat)amount currency:(NSString *)currency
{
    for (id<MKAnalyticsService> const service in [NSArray arrayWithArray:self.analyticsServices]) {
        [service trackPurchase:item amount:amount currency:currency];
    }
}

@end


text:
/**
 * Created by ralphy on 18/02/17.
 */
/**
 * Created by ralphy on 24/01/17.
 * this spell will increase the ambiant lighting
 * duration : 30 seconds
 * @class MANSION.SPELLS.Light
 */

O2.createClass('MANSION.SPELLS.Light', {
    run: function(g) {
        var eDark = new Effect.Bonus('sight');
        var p = g.oLogic.getPlayerSoul();
        eDark.setSource(p);
        eDark.setTarget(p);
        eDark.setLevel(25);
        eDark.setDuration(MANSION.CONST.SPELL_DURATION_MEDIUM);
        var ep = g.oLogic.getEffectProcessor();
        ep.applyEffect(eDark);
    }
});


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var abstractFormatter_1 = require("../language/formatter/abstractFormatter");
var Formatter = /** @class */ (function (_super) {
    tslib_1.__extends(Formatter, _super);
    function Formatter() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /* tslint:enable:object-literal-sort-keys */
    Formatter.prototype.format = function (failures) {
        failures = this.sortFailures(failures);
        return this.mapToMessages(failures).join("\n") + "\n";
    };
    Formatter.prototype.mapToMessages = function (failures) {
        return failures.map(function (failure) {
            var fileName = failure.getFileName();
            var failureString = failure.getFailure();
            var ruleName = failure.getRuleName();
            var lineAndCharacter = failure.getStartPosition().getLineAndCharacter();
            var positionTuple = "[" + (lineAndCharacter.line + 1) + ", " + (lineAndCharacter.character + 1) + "]";
            return failure.getRuleSeverity().toUpperCase() + ": (" + ruleName + ") " + fileName + positionTuple + ": " + failureString;
        });
    };
    /* tslint:disable:object-literal-sort-keys */
    Formatter.metadata = {
        formatterName: "verbose",
        description: "The human-readable formatter which includes the rule name in messages.",
        descriptionDetails: "The output is the same as the prose formatter with the rule name included",
        sample: "ERROR: (semicolon) myFile.ts[1, 14]: Missing semicolon",
        consumer: "human",
    };
    return Formatter;
}(abstractFormatter_1.AbstractFormatter));
exports.Formatter = Formatter;


text:
package com.jayantkrish.jklol.util;

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

import com.google.common.collect.Lists;

/**
 * Heap data structure for finding the K highest-scoring
 * elements of a collection of items.
 *
 * @author jayantk
 *
 * @param <T>
 */
public class KbestQueue<T> implements SearchQueue<T> {
  private double[] values;
  private T[] keys;
  private int size;
  private int maxElements;

  public KbestQueue(int maxElements, T[] keyType) {
    values = new double[maxElements + 1];
    keys = Arrays.copyOf(keyType, maxElements + 1);
    size = 0;
    this.maxElements = maxElements;
  }

  public static <T> KbestQueue<T> create(int maxElements, T[] keyType) {
    return new KbestQueue<T>(maxElements, keyType);
  }

  /**
   * Add {@code toQueue} to this with {@code score}.
   * Calling this method may remove the lowest-scoring
   * element if adding the new element causes the size of
   * {@code this} to exceed {@code this.maxElements}.
   *
   * @param toQueue
   * @param score
   * @return the removed element if an element was removed,
   * {@code null} otherwise.
   */
  public final T offer(T toQueue, double score) {
    HeapUtils.offer(keys, values, size, toQueue, score);
    size++;

    if (size > maxElements) {
      return removeMin();
    } else {
      return null;
    }
  }

  public final T removeMin() {
    T min = keys[0];
    HeapUtils.removeMin(keys, values, size);
    size--;
    return min;
  }

  public int size() {
    return size;
  }

  public T[] getItems() {
    return keys;
  }

  public double[] getScores() {
    return values;
  }

  /**
   * Pops all of the items in this queue and places them
   * into a list sorted in descending score order (i.e.,
   * with the highest scoring item first). This queue
   * will be empty after calling this method.
   *
   * @param queue
   * @return
   */
  public List<T> toSortedList() {
    List<T> sortedItems = Lists.newArrayList();
    while (size() > 0) {
      sortedItems.add(removeMin());
    }
    Collections.reverse(sortedItems);
    return sortedItems;
  }

  public void clear() {
    this.size = 0;
  }
}


text:
jest.mock("../src/libs/s3Client.js");
jest.mock("@aws-sdk/client-s3");

// Get service clients module and commands.
import 'regenerator-runtime/runtime'
import { run, bucketParams } from "../src/s3_putbucketacl.js";
import { s3Client } from "../src/libs/s3Client";

describe("@aws-sdk/client-s3 mock", () => {
  it("should successfully mock S3 client", async () => {
    s3Client.send.mockResolvedValue({ isMock: true });
    const response = await run(bucketParams);
    expect(response.isMock).toEqual(true);
  });
});


text:
using System;
using System.Globalization;
using BenchmarkDotNet.Attributes;
using Light.GuardClauses.Exceptions;

namespace Light.GuardClauses.Performance.StringAssertions
{
    public class MustBeSubstringOfBenchmark
    {
        public string Other = "I shall wear this as a badge of honor.";
        public string Substring = "wear this";

        [Benchmark(Baseline = true)]
        public string ImperativeVersion()
        {
            if (Substring == null) throw new ArgumentNullException(nameof(Substring));
            if (!Other.Contains(Substring)) throw new SubstringException(nameof(Substring));

            return Substring;
        }

        [Benchmark]
        public string ImperativeVersionCustomComparisonType()
        {
            if (Substring == null) throw new ArgumentNullException(nameof(Substring));
            if (Other.IndexOf(Substring, StringComparison.CurrentCultureIgnoreCase) < 0) throw new SubstringException(nameof(Substring));

            return Substring;
        }

        [Benchmark]
        public string LightGuardClauses() => Substring.MustBeSubstringOf(Other, nameof(Substring));

        [Benchmark]
        public string LightGuardClausesCustomComparisonType() => Substring.MustBeSubstringOf(Other, StringComparison.CurrentCultureIgnoreCase);

        [Benchmark]
        public string LightGuardClausesCustomException() => Substring.MustBeSubstringOf(Other, (s1, s2) => new Exception($"Where is your honor, {s1}?"));

        [Benchmark]
        public string LightGuardClausesCustomExceptionCustomComparisonType() =>
            Substring.MustBeSubstringOf(Other, StringComparison.CurrentCultureIgnoreCase, (x, y, c) => new Exception($"Where is your honor, {x}? ({c})"));

        [Benchmark]
        public string OldVersion() => Substring.OldMustBeSubstringOf(Other, parameterName: nameof(Other));
    }

    public static class MustBeSubstringOfExtensions
    {
        public static string OldMustBeSubstringOf(this string parameter, string text, IgnoreCaseInfo ignoreCase = default, string parameterName = null, string message = null, Func<Exception> exception = null)
        {
            parameter.MustNotBeNull(parameterName);
            text.MustNotBeNull(nameof(text));

            if (text.IsContaining(parameter, ignoreCase)) return parameter;

            throw exception?.Invoke() ?? new StringException(message ?? $"\"{parameter}\" must be a substring of \"{text}\", but it is not.", parameterName);
        }

        public static bool IsContaining(this string @string, string text, IgnoreCaseInfo ignoreCase = default)
        {
            @string.MustNotBeNull(nameof(@string));
            text.MustNotBeNull(nameof(text));

            return ignoreCase.StringContains(@string, text);
        }
    }

    public readonly struct IgnoreCaseInfo
    {
        public readonly CultureInfo CultureInfo;

        public readonly CompareOptions CompareOptions;

        public IgnoreCaseInfo(CultureInfo cultureInfo, CompareOptions compareOptions)
        {
            CultureInfo = cultureInfo.MustNotBeNull(nameof(cultureInfo));
            CompareOptions = compareOptions.MustBeValidEnumValue(nameof(compareOptions));
        }

        public static implicit operator IgnoreCaseInfo(bool ignoreCase)
        {
            return ignoreCase ? new IgnoreCaseInfo(CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase) : new IgnoreCaseInfo();
        }

        public static implicit operator IgnoreCaseInfo(CultureInfo cultureInfo)
        {
            return new IgnoreCaseInfo(cultureInfo, CompareOptions.OrdinalIgnoreCase);
        }

        public bool StringContains(string @string, string substring)
        {
            if (CultureInfo == null)
                return @string.MustNotBeNull(nameof(@string)).Contains(substring);

            return CultureInfo.CompareInfo.IndexOf(@string, substring, CompareOptions) != -1;
        }
    }
}