text:
namespace local_discovery {

EndpointResolver::EndpointResolver() {
  service_discovery_client_ = ServiceDiscoverySharedClient::GetInstance();
}

EndpointResolver::~EndpointResolver() {}

void EndpointResolver::Start(const std::string& service_name,
                             const ResultCallback& callback) {
  service_resolver_ = service_discovery_client_->CreateServiceResolver(
      service_name, base::Bind(&EndpointResolver::ServiceResolveComplete,
                               base::Unretained(this), callback));
  service_resolver_->StartResolving();
}

void EndpointResolver::ServiceResolveComplete(
    const ResultCallback& callback,
    ServiceResolver::RequestStatus result,
    const ServiceDescription& description) {
  if (result != ServiceResolver::STATUS_SUCCESS)
    return callback.Run(net::IPEndPoint());

  Start(description.address, callback);
}

void EndpointResolver::Start(const net::HostPortPair& address,
                             const ResultCallback& callback) {
#if defined(OS_MACOSX)
  net::IPAddressNumber ip_address;
  if (!net::ParseIPLiteralToNumber(address.host(), &ip_address)) {
    NOTREACHED() << address.ToString();
    // Unexpected, but could be a reason for crbug.com/513505
    base::debug::DumpWithoutCrashing();
    return callback.Run(net::IPEndPoint());
  }

  // OSX already has IP there.
  callback.Run(net::IPEndPoint(ip_address, address.port()));
#else   // OS_MACOSX
  net::AddressFamily address_family = net::ADDRESS_FAMILY_UNSPECIFIED;
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kPrivetIPv6Only)) {
    address_family = net::ADDRESS_FAMILY_IPV6;
  }

  domain_resolver_ = service_discovery_client_->CreateLocalDomainResolver(
      address.host(), address_family,
      base::Bind(&EndpointResolver::DomainResolveComplete,
                 base::Unretained(this), address.port(), callback));
  domain_resolver_->Start();
#endif  // OS_MACOSX
}

void EndpointResolver::DomainResolveComplete(
    uint16_t port,
    const ResultCallback& callback,
    bool success,
    const net::IPAddressNumber& address_ipv4,
    const net::IPAddressNumber& address_ipv6) {
  if (!success)
    return callback.Run(net::IPEndPoint());

  net::IPAddressNumber address = address_ipv4;
  if (address.empty())
    address = address_ipv6;

  DCHECK(!address.empty());

  callback.Run(net::IPEndPoint(address, port));
}

}  // namespace local_discovery

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Nito.Disposables;

namespace Nito.Mvvm
{
    /// <summary>
    /// A command that cancels a <see cref="CancellationToken"/> when it is executed. "Operations" may be started for this command. This command is canceled whenever there are no operations.
    /// </summary>
    public sealed class CancelCommand : ICommand
    {
        /// <summary>
        /// The implementation of <see cref="ICommand.CanExecuteChanged"/>.
        /// </summary>
        private readonly ICanExecuteChanged _canExecuteChanged;

        /// <summary>
        /// The cancellation token source currently controlled by this command. This is <c>null</c> when the current context has been cancelled.
        /// </summary>
        private RefCountedCancellationTokenSource _context;

        /// <summary>
        /// Creates a new cancel command.
        /// </summary>
        /// <param name="canExecuteChangedFactory">The factory for the implementation of <see cref="ICommand.CanExecuteChanged"/>.</param>
        public CancelCommand(Func<object, ICanExecuteChanged> canExecuteChangedFactory)
        {
            _canExecuteChanged = canExecuteChangedFactory(this);
        }

        /// <summary>
        /// Creates a new cancel command.
        /// </summary>
        public CancelCommand()
            : this(CanExecuteChangedFactories.DefaultCanExecuteChangedFactory)
        {
        }

        event EventHandler ICommand.CanExecuteChanged
        {
            add { _canExecuteChanged.CanExecuteChanged += value; }
            remove { _canExecuteChanged.CanExecuteChanged -= value; }
        }

        bool ICommand.CanExecute(object parameter)
        {
            return _context != null;
        }

        void ICommand.Execute(object parameter)
        {
            _context.Cancel();
        }

        private IDisposable StartOperation()
        {
            if (_context == null)
            {
                _context = new RefCountedCancellationTokenSource(this);
                _canExecuteChanged.OnCanExecuteChanged();
            }
            return _context.StartOperation();
        }

        /// <summary>
        /// Called when the context has been cancelled.
        /// </summary>
        /// <param name="context">The context.</param>
        private void Notify(RefCountedCancellationTokenSource context)
        {
            if (_context != context)
                return;
            _context = null;
            _canExecuteChanged.OnCanExecuteChanged();
        }

        /// <summary>
        /// Cancels any current context.
        /// </summary>
        public void Cancel() => _context?.Cancel();

        /// <summary>
        /// Wraps a delegate so it cancels this cancel command and then registers with it. The delegate is passed the <see cref="CancellationToken"/> of this cancel command. Any <see cref="OperationCanceledException"/> exceptions raised by the delegate are silently ignored.
        /// </summary>
        public Func<object, Task> WrapCancel(Func<object, CancellationToken, Task> executeAsync)
        {
            var wrapped = Wrap(executeAsync);
            return async parameter =>
            {
                Cancel();
                await wrapped(parameter).ConfigureAwait(false);
            };
        }

        /// <summary>
        /// Wraps a delegate so it cancels this cancel command and then registers with it. The delegate is passed the <see cref="CancellationToken"/> of this cancel command. Any <see cref="OperationCanceledException"/> exceptions raised by the delegate are silently ignored.
        /// </summary>
        public Func<Task> WrapCancel(Func<CancellationToken, Task> executeAsync)
        {
            var wrapped = Wrap(executeAsync);
            return async () =>
            {
                Cancel();
                await wrapped().ConfigureAwait(false);
            };
        }

        /// <summary>
        /// Wraps a delegate so that it registers with this cancel command. The delegate is passed the <see cref="CancellationToken"/> of this cancel command. Any <see cref="OperationCanceledException"/> exceptions raised by the delegate are silently ignored.
        /// </summary>
        /// <param name="executeAsync">The cancelable delegate.</param>
        public Func<object, Task> Wrap(Func<object, CancellationToken, Task> executeAsync)
        {
            return async parameter =>
            {
                using (StartOperation())
                {
                    try
                    {
                        await executeAsync(parameter, _context.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        // We cannot use `when (ex.CancellationToken == cancellationToken)` on the catch block because the user delegate may be cancelled by a linked CancellationToken.
                    }
                }
            };
        }

        /// <summary>
        /// Wraps a delegate so that it registers with this cancel command. The delegate is passed the <see cref="CancellationToken"/> of this cancel command. Any <see cref="OperationCanceledException"/> exceptions raised by the delegate are silently ignored.
        /// </summary>
        /// <param name="executeAsync">The cancelable delegate.</param>
        public Func<Task> Wrap(Func<CancellationToken, Task> executeAsync)
        {
            var wrapped = Wrap((_, token) => executeAsync(token));
            return () => wrapped(null);
        }

        private sealed class RefCountedCancellationTokenSource
        {
            /// <summary>
            /// The parent <see cref="CancelCommand"/>.
            /// </summary>
            private readonly CancelCommand _parent;

            /// <summary>
            /// The cancellation token source.
            /// </summary>
            private readonly CancellationTokenSource _cts = new CancellationTokenSource();

            /// <summary>
            /// The number of current operations. If this is <c>0</c>, then the cts is canceled.
            /// </summary>
            private int _count;

            public RefCountedCancellationTokenSource(CancelCommand parent)
            {
                _parent = parent;
            }

            public CancellationToken Token => _cts.Token;

            /// <summary>
            /// Decrements the count, and cancels the command if the new count is <c>0</c>.
            /// </summary>
            private void Signal()
            {
                if (--_count != 0)
                    return;
                Cancel();
            }

            /// <summary>
            /// Associates an operation with the cts. The operation is disassociated when disposed.
            /// </summary>
            public IDisposable StartOperation()
            {
                ++_count;
                return new AnonymousDisposable(Signal);
            }

            /// <summary>
            /// Cancels the command immediately.
            /// </summary>
            public void Cancel()
            {
                _cts.Cancel();
                _parent.Notify(this);
            }
        }
    }
}


text:
<?php

namespace LIN3S\AdminBundle\Extension\ListField;

use LIN3S\AdminBundle\Configuration\Model\Entity;
use LIN3S\AdminBundle\Configuration\Type\ListFieldType;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * @author Gorka Laucirica <gorka.lauzirika@gmail.com>
 */
final class StringListFieldType implements ListFieldType
{
    private $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function header($name, Entity $configuration)
    {
        if (!isset($name)) {
            throw new \InvalidArgumentException('Field to be rendered must be passed as string');
        }

        return $this->translator->trans($name);
    }

    public function render($entity, $options, Entity $configuration)
    {
        if (!isset($options['field'])) {
            throw new \InvalidArgumentException('Field to be rendered must be passed as string');
        }

        if (is_array($entity)) {
            $value = $entity[$options['field']];
        } else {
            $properties = explode('.', $options['field']);
            $value = $entity;
            foreach ($properties as $property) {
                $value = $value->$property();
            }
        }

        return $this->translator->trans($value);
    }
}


text:
//////////////////////////////////////////////////////////////////////////
#ifndef DIALOG_H
#define DIALOG_H
//////////////////////////////////////////////////////////////////////////
#pragma once
//////////////////////////////////////////////////////////////////////////
#include "Window.h"

_TIM_BEGIN

class Dialog : public Window
{
public:
	Dialog() : _fModeless(false), _isCreated(false)
	{	_hWnd = NULL;	}

	~Dialog()
	{
		if(_hWnd)
			::SetWindowLongPtr(_hWnd, GWLP_USERDATA, (LONG_PTR)NULL);
		_hWnd = NULL;
		_isCreated = false;
	}

	virtual void create(UINT uID, LPVOID lParam = 0);
	virtual void doModal(UINT uID, LPVOID lParam = 0);

	bool	IsCreated()		{	return _isCreated;	}

	virtual void	destroy()
	{
		if (!_hWnd)	return;

		if (_fModeless)
			::DestroyWindow(_hWnd);
		else
			::EndDialog(_hWnd, _nResult);

		_isCreated = false;
	}

protected:

	static	BOOL CALLBACK dlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
	virtual BOOL CALLBACK runProc(UINT uMsg, WPARAM wParam, LPARAM lParam) = 0;

	void SetDlgIcon(UINT uIconID)
	{
		if (!_hWnd)	return ;
		HINSTANCE hInst = (HINSTANCE)GetWindowLongPtr(GWLP_HINSTANCE);
		HICON hIcon = LoadIcon(hInst, MAKEINTRESOURCE(uIconID));

		sendMsg(WM_SETICON, TRUE,  (LPARAM)hIcon);
		sendMsg(WM_SETICON, FALSE, (LPARAM)hIcon);
	}

	void SetDefaultButton(int id){
		sendMsg(DM_SETDEFID, id);
	}

	LRESULT SendItemMsg(int id, UINT uMsg, WPARAM wParam = 0U, LPARAM lParam = 0L){
		return ::SendDlgItemMessage(_hWnd, id, uMsg, wParam, lParam);
	}

	HWND HwndFromId(int id)	{	return ::GetDlgItem(_hWnd, id);		}	//由控件ID返回句柄

	void ShowCtrl(int id)	{	::ShowWindow(HwndFromId(id), SW_SHOW);	}	//显示控件
	void HideCtrl(int id)	{	::ShowWindow(HwndFromId(id), SW_HIDE);	}	//隐藏控件

	void EnableCtrl(int id)	{	::EnableWindow(HwndFromId(id), TRUE);	}	//控件有效
	void DisableCtrl(int id){	::EnableWindow(HwndFromId(id), FALSE);	}	//控件无效

	void CheckButton(int id)	{	::CheckDlgButton(_hWnd, id, BST_CHECKED);	}
	void UnCheckButton(int id)	{	::CheckDlgButton(_hWnd, id, BST_UNCHECKED);	}

	bool IsButtonChecked(int nIDButton)
		{	return ::IsDlgButtonChecked(_hWnd, nIDButton)==BST_CHECKED ? true : false;	}

	BOOL CheckRadio(int nIDFirstButton, int nIDLastButton, int nIDCheckButton)
		{	return ::CheckRadioButton(_hWnd, nIDFirstButton, nIDLastButton, nIDCheckButton);	}

	void FocusCtrl(int id)	{	::SetFocus(HwndFromId(id));				}	//使控件取得焦点

	TString GetItemText(int id);
	void	SetItemText(int id, const TString &Str)	{	::SetWindowText(HwndFromId(id), Str.c_str());	}
	void	SetLimitText(int id, int max)		{	::SendMessage(HwndFromId(id), EM_SETLIMITTEXT, max, 0);	}
	void	SetLimitText(HWND hEdit, int max)	{	::SendMessage(hEdit, EM_SETLIMITTEXT, max, 0);		}
protected:
	LPVOID _pData;

private:
	bool _fModeless;	//当前对话是无模式还是模式
	INT_PTR _nResult;//创建模式对话框返回的

	bool _isCreated;
};

_TIM_END

#endif


text:
using System;

class GetLargestNumber
{
    public static int GetMax(int first, int second)
    {
        return Math.Max(first, second);
    }
    static void Main()
    {
        Console.Write("Enter first number: ");
        int first = Convert.ToInt32(Console.ReadLine());
        Console.Write("Enter second number: ");
        int second = Convert.ToInt32(Console.ReadLine());
        Console.Write("Enter third number: ");
        int third = Convert.ToInt32(Console.ReadLine());
        int max = GetMax(first, GetMax(second, third));
        Console.WriteLine(max);
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_console_execl_61b.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-61b.tmpl.c
*/
/*
 * @description
 * CWE: 78 OS Command Injection
 * BadSource: console Read input from the console
 * GoodSource: Fixed string
 * Sinks: execl
 *    BadSink : execute command with execl
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "ls"
#define COMMAND_ARG2 "-la"
#define COMMAND_ARG3 data
#endif

#ifdef _WIN32
#include <process.h>
#define EXECL _execl
#else /* NOT _WIN32 */
#define EXECL execl
#endif

#ifndef OMITBAD

char * CWE78_OS_Command_Injection__char_console_execl_61b_badSource(char * data)
{
    {
        /* Read input from the console */
        size_t dataLen = strlen(data);
        /* if there is room in data, read into it from the console */
        if (100-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgets() */
                dataLen = strlen(data);
                if (dataLen > 0 && data[dataLen-1] == '\n')
                {
                    data[dataLen-1] = '\0';
                }
            }
            else
            {
                printLine("fgets() failed");
                /* Restore NUL terminator if fgets fails */
                data[dataLen] = '\0';
            }
        }
    }
    return data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
char * CWE78_OS_Command_Injection__char_console_execl_61b_goodG2BSource(char * data)
{
    /* FIX: Append a fixed string to data (not user / external input) */
    strcat(data, "*.*");
    return data;
}

#endif /* OMITGOOD */


text:
#include "halApiTestSupport.h"
#include "halAlignment.h"
#include "halGenome.h"
#include "halMetaData.h"
#include <iostream>
#include <string>
extern "C" {
#include "commonC.h"
}

using namespace std;
using namespace hal;

struct MetaDataTest : public AlignmentTest {
    void createCallBack(Alignment *alignment) {
        hal_size_t alignmentSize = alignment->getNumGenomes();
        CuAssertTrue(_testCase, alignmentSize == 0);

        MetaData *meta = alignment->getMetaData();
        CuAssertTrue(_testCase, meta->getMap().empty() == true);
        meta->set("colour", "red");
        meta->set("number", "1");
        meta->set("animal", "cat");
        meta->set("colour", "black");

        CuAssertTrue(_testCase, meta->get("colour") == "black");
        CuAssertTrue(_testCase, meta->get("number") == "1");
        CuAssertTrue(_testCase, meta->get("animal") == "cat");

        CuAssertTrue(_testCase, meta->has("colour") == true);
        CuAssertTrue(_testCase, meta->has("city") == false);

        CuAssertTrue(_testCase, meta->getMap().size() == 3);
    }

    void checkCallBack(const Alignment *alignment) {
        const MetaData *meta = alignment->getMetaData();

        CuAssertTrue(_testCase, meta->get("colour") == "black");
        CuAssertTrue(_testCase, meta->get("number") == "1");
        CuAssertTrue(_testCase, meta->get("animal") == "cat");

        CuAssertTrue(_testCase, meta->has("colour") == true);
        CuAssertTrue(_testCase, meta->has("city") == false);

        CuAssertTrue(_testCase, meta->getMap().size() == 3);
    }
};

static void halMetaDataTest(CuTest *testCase) {
    MetaDataTest tester;
    tester.check(testCase);
}

static CuSuite *halMetaDataTestSuite(void) {
    CuSuite *suite = CuSuiteNew();
// FIXME: commented this out till we implement this for mmap.
    if (false) {
        SUITE_ADD_TEST(suite, halMetaDataTest);
    }
    return suite;
}

int main(int argc, char *argv[]) {
    return runHalTestSuite(argc, argv, halMetaDataTestSuite());
}


text:
<!DOCTYPE html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<canvas>
  <object id="f"></object>
</canvas>
<script>
test(function() {
  f.focus();
}, "crbug.com/587263 focusing plugin object in canvas fallback may dereference nullptr");
</script>


text:
package org.ovirt.engine.ui.frontend;

import org.ovirt.engine.core.common.businessentities.IVdcQueryable;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.EventDefinition;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.ObservableCollection;

public final class RegistrationResult
{
    /**
     Raised once when a first result retrievement occurs.

    */
    private Event privateRetrievedEvent;

    public Event getRetrievedEvent()
    {
        return privateRetrievedEvent;
    }

    private void setRetrievedEvent(Event value)
    {
        privateRetrievedEvent = value;
    }

    public static EventDefinition RetrievedEventDefinition;

    private Guid privateId = new Guid();

    public Guid getId()
    {
        return privateId;
    }

    private void setId(Guid value)
    {
        privateId = value;
    }

    private ObservableCollection<IVdcQueryable> privateData;

    public ObservableCollection<IVdcQueryable> getData()
    {
        return privateData;
    }

    private void setData(ObservableCollection<IVdcQueryable> value)
    {
        privateData = value;
    }

    private int privateRetrievementCount;

    public int getRetrievementCount()
    {
        return privateRetrievementCount;
    }

    public void setRetrievementCount(int value)
    {
        privateRetrievementCount = value;
    }

    static
    {
        RetrievedEventDefinition = new EventDefinition("RetrievedEvent", RegistrationResult.class); //$NON-NLS-1$
    }

    public RegistrationResult(Guid id, ObservableCollection<IVdcQueryable> data)
    {
        setRetrievedEvent(new Event(RetrievedEventDefinition));

        setId(id);
        setData(data);
    }

    public void NotifyRetrieved()
    {
        getRetrievedEvent().raise(this, EventArgs.Empty);
    }
}


text:
{% extends "base.html" %} {% block content %}

For publishers

Key benefits

 Be seen to be helping institutions in their long-standing aspiration to capture and disseminate copies of the outputs of their researchers.

 Help UK institutions comply with the policy of open access and the REF, and mandates and policies from other bodies.

 Help institutions accurately capture and respect your licensing terms, including any embargo periods.

How to join

Please contact us on pubrouter@jisc.ac.uk if you would like to find out more.

How it works

Publications router aims to pass notifications about research articles to UK institutions matching the affiliations of the authors, including all the co-authors, or their ORCIDs.

One of its key aims is to assist institutions in their compliance with the policy on open access and the REF.

An ideal workflow would consist of two notifications for each article, one at acceptance and another at publication. This can be varied depending on your workflow and turn-around times from acceptance to publication.

 Upon acceptance the notification should include basic metadata about the article accompanied, if possible, by the accepted manuscript:

 The article's DOI

 The article's title (even if still subject to change)

 The full list of (co-)authors and, crucially, their affiliations (and ORCIDs if available). (Note that publications router will not cause these affiliations to be displayed anywhere. It will only use them to match to the appropriate institutions, so unedited, "back office" information is all that is required here.)

 The title of the journal.

 Upon publication the notification should include finalised metadata:

 The article's DOI

 The article's title

 The full list of (co-)authors and, crucially, their affiliations (and ORCIDs if available)

 The full bibliographic details (including year of publication, journal title, volume, page numbers)

 The details of any embargo period that may apply to any version you have sent us (accepted manuscript and/or version of record). This could be encoded using NISO ALI metadata, for example.

The metadata can be supplied as JATS (or NLM) XML, for example, though other formats may well be possible. We are open to discussion on the details of this.

We are actively exploring additional options for ingesting notifications more flexibly, especially at acceptance.

Publications router takes no view on what the embargo period or licensing terms should be, but undertakes to pass these on to the institutions if you provide them. If you supply embargoed content and metadata specifying an embargo end-date that applies to it, we will require institutions to respect the embargo that you stipulate in this way. This commitment forms part of a contract between Jisc and participating institutions, and between Jisc and participating publishers.

More detail on how you can transmit this information to publications router is given in the technical documentation listed below.

Technical Information

Please see here for details of publications router architecture and how to connect to it.

{% endblock %} {% block extra_js_bottom %} {% endblock extra_js_bottom
%}


text:
using System;
using Cairo;
using Gtk;

namespace Pinta.Core
{
	public class PasteHistoryItem : BaseHistoryItem
	{
		private Gdk.Pixbuf paste_image;
		private DocumentSelection old_selection;

		public override bool CausesDirty { get { return true; } }

		public PasteHistoryItem (Gdk.Pixbuf pasteImage, DocumentSelection oldSelection)
		{
			Text = Translations.GetString ("Paste");
			Icon = Resources.StandardIcons.EditPaste;

			paste_image = pasteImage;
			old_selection = oldSelection;
		}

		public override void Redo ()
		{
			Document doc = PintaCore.Workspace.ActiveDocument;

			// Copy the paste to the temp layer
			doc.Layers.CreateSelectionLayer ();
			doc.Layers.ShowSelectionLayer = true;

			using (Cairo.Context g = new Cairo.Context (doc.Layers.SelectionLayer.Surface)) {
				g.DrawPixbuf (paste_image, new Cairo.Point (0, 0));
			}

			Swap ();

			PintaCore.Workspace.Invalidate ();
			PintaCore.Tools.SetCurrentTool ("MoveSelectedTool");
		}

		public override void Undo ()
		{
			var doc = PintaCore.Workspace.ActiveDocument;

			Swap ();

			doc.Layers.DestroySelectionLayer ();
			PintaCore.Workspace.Invalidate ();
		}

		public override void Dispose ()
		{
			if (paste_image != null)
				(paste_image as IDisposable).Dispose ();

			if (old_selection != null)
				old_selection.Dispose ();
		}

		private void Swap ()
		{
			// Swap the selection paths, and whether the
			// selection path should be visible
			Document doc = PintaCore.Workspace.ActiveDocument;

			DocumentSelection swap_selection = doc.Selection;
			doc.Selection = old_selection;
			old_selection = swap_selection;
		}
	}
}


text:
<?php

declare(strict_types=1);

namespace LIN3S\SharedKernel\Infrastructure\Persistence\Doctrine\DBAL\Domain\Model\Iban\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\TextType;
use LIN3S\SharedKernel\Domain\Model\Iban\Iban;

/**
 * @author Rubén García <ruben@lin3s.com>
 */
class IbanType extends TextType
{
    public function convertToDatabaseValue($value, AbstractPlatform $platform) : ?string
    {
        if ($value instanceof Iban) {
            return $value->iban();
        }

        return $value;
    }

    public function convertToPHPValue($value, AbstractPlatform $platform) : ?Iban
    {
        if (null === $value) {
            return null;
        }

        return Iban::from($value);
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform) : bool
    {
        return true;
    }

    public function getName()
    {
        return 'iban';
    }
}


text:
"""The environment_variables component."""

import logging
import os

import voluptuous as vol

from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType

DOMAIN = "environment_variables"

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
    {DOMAIN: {cv.string:cv.string}}, extra=vol.ALLOW_EXTRA
)

async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the environment_variables component."""
    conf = config.get(DOMAIN, {})

    for name in conf:
        os.environ[name] = conf.get(name)
        _LOGGER.warning("Set environment variable: %s=%s", name, conf.get(name))
    return True


text:
<?php

declare(strict_types=1);

namespace Artisanry\Database\Repositories\Criteria;

use Artisanry\Database\Contracts\Repositories\Repository;
use Illuminate\Database\Eloquent\Model;

class WithRelations extends Criterion
{
    private $relations;

    public function __construct($relations)
    {
        $this->relations = $relations;
    }

    public function apply(Model $model, Repository $repository)
    {
        return $model->with($this->relations);
    }
}


text:
<?php

/*
 * slim-routing (https://github.com/juliangut/slim-routing).
 * Slim framework routing.
 *
 * @license BSD-3-Clause
 * @link https://github.com/juliangut/slim-routing
 * @author Julián Gutiérrez <juliangut@gmail.com>
 */

declare(strict_types=1);

namespace Jgut\Slim\Routing\Tests\Naming;

use Jgut\Slim\Routing\Naming\SnakeCase;
use PHPUnit\Framework\TestCase;

/**
 * Snake case route naming strategy tests.
 */
class SnakeCaseTest extends TestCase
{
    /**
     * @var SnakeCase
     */
    protected $naming;

    /**
     * {@inheritdoc}
     */
    protected function setUp(): void
    {
        $this->naming = new SnakeCase();
    }

    public function testSinglePartName(): void
    {
        static::assertEquals('name', $this->naming->combine(['name']));
    }

    public function testMultiPartName(): void
    {
        static::assertEquals('multi_part_name', $this->naming->combine(['multi', 'part', 'name']));
    }
}


text:
using Devsense.PHP.Syntax;
using Devsense.PHP.Text;
using System.Collections.Generic;
using System.Text;

namespace UnitTests.TestImplementation
{
    class EmptyComposer : ITokenComposer
    {
        public StringBuilder Code { get { /*ProcessWhitespaces(Tokens.T_INLINE_HTML, new Span(int.MaxValue, 0));*/ return _builder; } }
        private StringBuilder _builder = new StringBuilder();

        public List<ISourceToken> Processed => _processed;
        private List<ISourceToken> _processed = new List<ISourceToken>();

        private Tokens _previousToken = Tokens.END;
        private Span _previous = Span.Invalid;
        ISourceTokenProvider _tokens;

        public EmptyComposer(ISourceTokenProvider tokens)
        {
            _tokens = tokens;
        }

        private void ProcessToken(Tokens token, string text, Span position)
        {
            var start = position.Start;
            var end = start + text.Length;
            //if (start >= 0 && text.Length >= 0)
            {
                _builder.Append(text);
                _processed.Add(new SourceToken(token, position));
            }
        }

        public void ConsumeToken(Tokens token, string text, Span position)
        {
            ProcessWhitespaces(token, position);
            ProcessToken(token, _tokens.GetTokenText(new SourceToken(token, position), text), position);
            _previousToken = token;
            _previous = position;
        }

        private void ProcessWhitespaces(Tokens token, Span position)
        {
            if ((_previousToken == Tokens.END || _previousToken == Tokens.T_INLINE_HTML) && token != Tokens.T_INLINE_HTML)
            {
                ProcessToken(_previousToken = Tokens.T_OPEN_TAG, "<?php", _previous.IsValid ? _previous = new Span(_previous.End, 5) : Span.Invalid);
                ProcessToken(_previousToken = Tokens.T_WHITESPACE, " ", _previous.IsValid ? _previous = new Span(_previous.End, 1) : Span.Invalid);
            }
            else if (_previousToken != Tokens.END && _previousToken != Tokens.T_INLINE_HTML && token == Tokens.T_INLINE_HTML)
            {
                ProcessToken(_previousToken = Tokens.T_CLOSE_TAG, "?>", _previous.IsValid ? _previous = new Span(_previous.End, 2) : Span.Invalid);
            }
            else if (_previousToken != Tokens.END && _previousToken != Tokens.T_INLINE_HTML && token != Tokens.T_END_HEREDOC)
            {
                ProcessToken(Tokens.T_WHITESPACE, _previousToken == Tokens.T_END_HEREDOC ? "\n" : " ", _previous.IsValid ? _previous = new Span(_previous.End, 1) : Span.Invalid);
                _previousToken = Tokens.T_WHITESPACE;
            }
        }
    }
}


text:
using System;

namespace DiscUtils.Nfs
{
    public sealed class Nfs3AccessResult : Nfs3CallResult
    {
        public Nfs3AccessResult()
        {
        }

        internal Nfs3AccessResult(XdrDataReader reader)
        {
            Status = (Nfs3Status)reader.ReadInt32();
            if (reader.ReadBool())
            {
                ObjectAttributes = new Nfs3FileAttributes(reader);
            }

            Access = (Nfs3AccessPermissions)reader.ReadInt32();
        }

        public Nfs3AccessPermissions Access { get; set; }

        public Nfs3FileAttributes ObjectAttributes { get; set; }

        public override void Write(XdrDataWriter writer)
        {
            writer.Write((int)Status);
            writer.Write(ObjectAttributes != null);
            if (ObjectAttributes != null)
            {
                ObjectAttributes.Write(writer);
            }
            writer.Write((int)Access);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as Nfs3AccessResult);
        }

        public bool Equals(Nfs3AccessResult other)
        {
            if (other == null)
            {
                return false;
            }

            return other.Access == Access
                && object.Equals(other.ObjectAttributes, ObjectAttributes)
                && other.Status == Status;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Access, ObjectAttributes, Status);
        }
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/dom/interfaces/base/nsIDOMPerformance.idl
 */

#ifndef __gen_nsIDOMPerformance_h__
#define __gen_nsIDOMPerformance_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMPerformanceTiming; /* forward declaration */

class nsIDOMPerformanceNavigation; /* forward declaration */

/* starting interface:    nsIDOMPerformance */
#define NS_IDOMPERFORMANCE_IID_STR "446faf26-000b-4e66-a5fd-ae37c5ed6beb"

#define NS_IDOMPERFORMANCE_IID \
  {0x446faf26, 0x000b, 0x4e66, \
    { 0xa5, 0xfd, 0xae, 0x37, 0xc5, 0xed, 0x6b, 0xeb }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMPerformance : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMPERFORMANCE_IID)

  /* readonly attribute nsIDOMPerformanceTiming timing; */
  NS_SCRIPTABLE NS_IMETHOD GetTiming(nsIDOMPerformanceTiming * *aTiming) = 0;

  /* readonly attribute nsIDOMPerformanceNavigation navigation; */
  NS_SCRIPTABLE NS_IMETHOD GetNavigation(nsIDOMPerformanceNavigation * *aNavigation) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMPerformance, NS_IDOMPERFORMANCE_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMPERFORMANCE \
  NS_SCRIPTABLE NS_IMETHOD GetTiming(nsIDOMPerformanceTiming * *aTiming); \
  NS_SCRIPTABLE NS_IMETHOD GetNavigation(nsIDOMPerformanceNavigation * *aNavigation);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMPERFORMANCE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetTiming(nsIDOMPerformanceTiming * *aTiming) { return _to GetTiming(aTiming); } \
  NS_SCRIPTABLE NS_IMETHOD GetNavigation(nsIDOMPerformanceNavigation * *aNavigation) { return _to GetNavigation(aNavigation); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMPERFORMANCE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetTiming(nsIDOMPerformanceTiming * *aTiming) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTiming(aTiming); } \
  NS_SCRIPTABLE NS_IMETHOD GetNavigation(nsIDOMPerformanceNavigation * *aNavigation) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNavigation(aNavigation); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsDOMPerformance : public nsIDOMPerformance
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMPERFORMANCE

  nsDOMPerformance();

private:
  ~nsDOMPerformance();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMPerformance, nsIDOMPerformance)

nsDOMPerformance::nsDOMPerformance()
{
  /* member initializers and constructor code */
}

nsDOMPerformance::~nsDOMPerformance()
{
  /* destructor code */
}

/* readonly attribute nsIDOMPerformanceTiming timing; */
NS_IMETHODIMP nsDOMPerformance::GetTiming(nsIDOMPerformanceTiming * *aTiming)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute nsIDOMPerformanceNavigation navigation; */
NS_IMETHODIMP nsDOMPerformance::GetNavigation(nsIDOMPerformanceNavigation * *aNavigation)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIDOMPerformance_h__ */


text:
package com.sergiopino.ars.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sergiopino.ars.dao.user.UserDao;
import com.sergiopino.ars.entity.User;

@Service("userService")
public class UserService implements UserDetailsService
{

	@Autowired
	private UserDao userDao;

	@Override
	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
	{
		User user = userDao.findByName(username);
		if (null == user) {
			throw new UsernameNotFoundException("The user with name " + username + " was not found");
		}

		return user;
	}

}


text:
IMPLEMENT_MANAGED(Material)

MaterialID material::create()
{
	MaterialID ret = gMaterialManager.add();
	Material& m = getMaterial(ret);

	m.states.depthTest = true;
	m.states.writeDepth = true;

	m._valuecount = 0;
	m._texturecount = 0;
	m._flags = 0;

	return ret;
}

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

void material::setShader(MaterialID material, ShaderID shader)
{
	Material& m = getMaterial(material);

	m._shader = shader;
	m._valuecount = 0;
	m._texturecount = 0;
}

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

//--- value MUST HAVE the size needed for the param name
void material::setValue(MaterialID mat, const char* name, void* value, int size)
{
	Material& m = getMaterial(mat);
	int idx = shader::getParameterIndex(m._shader, name);

	if(idx == -1)
	{
		//printf("Couldn't find : %s in shader\n", name);
		return;
	}

	int existingId = -1;

	for(int i = 0; i < m._valuecount; ++i)
	{
		if(m._values[i].paramIdx == idx)
		{
			existingId = i;
			break;
		}
	}

	if(existingId == -1)
	{//first time we set that param, insert it in array
		m._values[m._valuecount].paramIdx = idx;
		existingId = m._valuecount;
		m._valuecount += 1;
	}

	int correctedSize = std::min<int>(16 * sizeof(float), size);
	memcpy(m._values[existingId].value, value, correctedSize);
}

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

void material::setTexture(MaterialID mat, const char* name, TextureID tex)
{
	Material& m = getMaterial(mat);
	Texture& t = getTexture(tex);

	int idx = shader::getParameterIndex(m._shader, name);

	if(idx == -1)
	{
		printf("Couldn't find texture : %s in shader\n", name);
		return;
	}

	int existingId = -1;

	for(int i = 0; i < m._texturecount; ++i)
	{
		if(m._textures[i].paramIdx == idx)
		{
			existingId = i;
			break;
		}
	}

	if(existingId == -1)
	{//first time we set that param, insert it in array
		m._textures[m._texturecount].paramIdx = idx;
		existingId = m._texturecount;
		m._texturecount += 1;
	}

	m._textures[existingId].textureHandle = t._native;
}

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

void material::setFlag(MaterialID mat, unsigned int flags)
{
	Material& m = getMaterial(mat);
	m._flags = flags;

	switch(flags)
	{
	case MAT_TRANSPARENT:
		m.states.depthTest = true;
		m.states.writeDepth = false;
		break;
	default:
		break;
	}
}

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

void material::bind(MaterialID material)
{
	Material& m = getMaterial(material);
	for(int i = 0; i < m._valuecount; ++i)
	{
		shader::setParameter(m._shader, m._values[i].paramIdx, m._values[i].value);
	}

	for(int i = 0; i < m._texturecount; ++i)
	{
		shader::setTexture(m._shader, m._textures[i].paramIdx, m._textures[i].textureHandle, i);
	}
}

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


text:
dojo.provide("MainAssistant");
dojo.require("dojox.mobile.app.SceneAssistant");

dojo.declare("MainAssistant", dojox.mobile.app.SceneAssistant, {
	setup: function(){
		console.log("In main assistant setup");

		this.controller.parse();

		var scenes = [
		  {
		    label: "Simple ImageView Test",
			scene: "image-view"
		  },
		  {
		    label: "Flickr ImageView Test",
			scene: "flickr-image-view"
		  },
		  {
		    label: "Browse Flickr",
			scene: "flickr-search-selection"
		  }
		];

		var listWidget = dijit.byId("listWidget");
		listWidget.set("items", scenes);

		var _this = this;

		dojo.connect(listWidget, "onSelect", function(data, index, rowNode){
		  _this.controller.stageController.pushScene(data.scene);
		});
  },

  activate: function(){
    console.log("In main assistant activate");

  }
});


text:
using System.Collections.Generic;
using UnityEngine;
using VFWExamples;

namespace Vexe.Runtime.Types
{
	[DefineCategories("Actions", "Funcs", "Collections")]
	public class DelegatesExample : BetterBehaviour
	{
		const string Actions     = "Actions";
		const string Funcs       = "Funcs";
		const string Collections = "Collections";

		[Category(Actions)] public uAction action0;
		[Category(Actions)] public uAction<string> Action1 { get; set; }
		[Category(Actions)] public uAction<GameObject, Vector3> action2;
		[Category(Actions)] public uAction<ITest, Transform, float> Action3 { get; set; }

		[Category(Funcs)] public uFunc<string> func0;
		[Category(Funcs)] public uFunc<int, bool> Func1 { get; set; }
		[Category(Funcs)] public uFunc<GameObject, Vector3, string> func2;
		[Category(Funcs)] public uFunc<ITest, Transform, float, string> Func3 { get; set; }

		[Category(Collections)] public uAction[] actions0;
		[Category(Collections)] public List<uAction<string>> actions1;
		[Category(Collections)] public Dictionary<string, List<uAction>> dict;

		public uDelegate kickass;

		[Hide]
		public void Action0Method0()
		{
			LogFormat("Action0Method0");

			action0.Add(Action0Method1);
			action0.Invoke();
		}

		public void Action0Method1()
		{
			LogFormat("Action0Method1");
		}

		public void Action1Method(string arg0)
		{
			LogFormat("Action1Method {0}", arg0);
		}

		public void Action2Method(GameObject arg0, Vector3 arg1)
		{
			LogFormat("Action0Method {0}, {1}", arg0, arg1);
		}

		public void Action3Method(ITest arg0, Transform arg1, float arg2)
		{
			LogFormat("Action1Method {0}, {1}, {2}", arg0, arg1, arg2);
		}

		public string Func0Method()
		{
			LogFormat("Func0Method");
			return string.Empty;
		}

		public bool Func1Method(int arg0)
		{
			LogFormat("Func1Method {0}", arg0);
			return arg0 > 0;
		}

		public string Func2Method(GameObject arg0, Vector3 arg1)
		{
			LogFormat("Func0Method {0}, {1}", arg0, arg1);
			return arg1.ToString();
		}

		public string Func3Method(ITest arg0, Transform arg1, float arg2)
		{
			LogFormat("Func1Method {0}, {1}, {2}", arg0, arg1, arg2);
			return arg2.ToString();
		}
	}
}


text:
/** @jsx React.DOM */
/*global React*/

var FluxChildMixin = require('fluxxor').FluxChildMixin(React);

var DateTimePicker = require('./DateTimePicker');
var CravingItem = require('./CravingItem');

var CravingItems = React.createClass({

  mixins: [FluxChildMixin],

  propTypes: {
    cravings: React.PropTypes.object.isRequired
  },

  getInitialState: function() {
    return {
      editing: null
    };
  },

  handleSave: function(payload) {
  },

  handleClose: function() {
    this.refs.editModal.hide();
  },

  render: function() {

    return (

            <form className="form-inline" role="form">

                When
                <DateTimePicker placeholder="When" ref="whenDatePicker" />

                Strength
                <input ref="strengthInput" type="number" className="form-control input-sm" id="strengthInput" placeholder="Strength" />

              <button className="btn btn-sm btn-default" onClick={this.addCraving}>Add Craving</button>
            </form>

                  When
                  Strength

                { this.props.cravings.map(function(craving, i) {
                  return (
                  <CravingItem
                    key={i}
                    craving={craving}
                    editing={this.state.editing}
                    onEditClick={this.handleEditing}
                    onCancelClick={this.handleCancel}
                    onSaveClick={this.saveCraving}
                    onDeleteClick={this.deleteCraving} />
                  );
                }.bind(this)) }

    );

  },

  addCraving: function(e) {
    e.preventDefault();
    var craving = {
      when: this.refs.whenDatePicker.getValue(),
      strength: this.refs.strengthInput.getDOMNode().value
    };
    this.getFlux().actions.addCraving(craving);
    this.refs.whenDatePicker.setValue("");
    this.refs.strengthInput.getDOMNode().value = "";
  },

  handleEditing: function(key) {
    this.setState({
      editing: key
    });
  },

  handleCancel: function() {
    this.setState({
      editing: null
    });
  },

  saveCraving: function(craving, values) {
    this.getFlux().actions.saveCraving(craving, values);
    this.setState({
      editing: null
    });
  },

  deleteCraving: function(craving) {
    this.getFlux().actions.deleteCraving(craving);
  }

});

module.exports = CravingItems;


text:
package org.apereo.cas.bucket4j.consumer;

import java.util.concurrent.TimeUnit;

/**
 * This is {@link BucketConsumer}.
 *
 * @author Misagh Moayyed
 * @since 6.5.0
 */
@FunctionalInterface
public interface BucketConsumer {
    /**
     * Header value to indicate available tokens.
     */
    String HEADER_NAME_X_RATE_LIMIT_REMAINING = "X-Rate-Limit-Remaining";

    /**
     * Header value to indicate available tokens once capacity is consumed..
     */
    String HEADER_NAME_X_RATE_LIMIT_RETRY_AFTER_SECONDS = "X-Rate-Limit-Retry-After-Seconds";

    /**
     * limit of time(in nanoseconds) which thread can wait for a blocking call.
     */
    long MAX_WAIT_NANOS = TimeUnit.HOURS.toNanos(1);

    /**
     * Permit all bucket consumer.
     *
     * @return the bucket consumer
     */
    static BucketConsumer permitAll() {
        return key -> BucketConsumptionResult.builder().consumed(true).build();
    }

    /**
     * Consume bucket and return consumption result.
     *
     * @param key the key
     * @return the bucket consumption result
     */
    BucketConsumptionResult consume(String key);
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System;

namespace Microsoft.Owin.Security.Notifications
{
    public class AuthenticationFailedNotification<TMessage, TOptions> : BaseNotification<TOptions>
    {
        public AuthenticationFailedNotification(IOwinContext context, TOptions options)
            : base(context, options)
        {
        }

        public TMessage ProtocolMessage { get; set; }

        public Exception Exception { get; set; }
    }
}


text:
=head1 LICENSE

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

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

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

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

=head1 CONTACT

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

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

=head1 NAME

Bio::EnsEMBL::Funcgen::ArrayChip - A simple module to represent the concept/template of
a chip/slide within an array,  of which the physical manifestation is an ExperimentalChip.

=head1 SYNOPSIS

 use Bio::EnsEMBL::Funcgen::ArrayChip;

 my $ec = Bio::EnsEMBL::Funcgen::ArrayChip->new(
                    							 -ARRAY_ID  => $array->dbID(),
					                    		 -NAME      => $desc,
                                                 -DESIGN_ID => $design_id,
							                   );

#add more methods here?

=head1 DESCRIPTION

An ArrayChip object represent the concept of an array chip/slide withing a given array/chipset.
The data for ArrayChips is stored in the array_chip table.

=head1 SEE ALSO

Bio::EnsEMBL::Funcgen::DBSQL::ArrayChipAdaptor
Bio::EnsEMBL::Funcgen::Array

=cut

package Bio::EnsEMBL::Funcgen::ArrayChip;

use strict;
use warnings;
use Bio::EnsEMBL::Utils::Argument  qw( rearrange );
use Bio::EnsEMBL::Utils::Exception qw( throw );

use base qw(Bio::EnsEMBL::Funcgen::Storable);

=head2 new

  Arg [-ARRAY_ID]  : Int - the dbID of the parent array
  Arg [-ARRAY]     : Bio::EnsEMBL::Funcgen::Array
  Arg [-DESIGN_ID] : String - the unqiue deisng ID defined by the array vendor
  Arg [-NAME]      : String - the name of the array chip

  Example    : my $array_chip = Bio::EnsEMBL::Funcgen::ArrayChip->new
                 (
							    -ARRAY_ID  => $array->dbID(),
							    -NAME      => $desc,
                  -DESIGN_ID => $design_id,
							   );
  Description: Creates a new Bio::EnsEMBL::Funcgen::ArrayChip object.
  Returntype : Bio::EnsEMBL::Funcgen::ArrayChip
  Exceptions : Throws if mandatory parameters are not set.
  Caller     : General
  Status     : Stable

=cut

sub new {
  my $caller = shift;
  my $class  = ref($caller) || $caller;
  my $self   = $class->SUPER::new(@_);

  my ($array_id, $name,  $design_id, $array)
    = rearrange( ['ARRAY_ID', 'NAME', 'DESIGN_ID', 'ARRAY'], @_ );

  #Remove array_id so we can remove checking below?

  throw("Must define a name($name) and design_id($design_id)") if(! $name || ! $design_id);

  #Make these mutually exclusive to avoid checking
  if($array_id && $array){
    throw('Must provide either -array or -array_id but not both');
  }

  if(defined $array){

    if(!(ref($array) && $array->isa('Bio::EnsEMBL::Funcgen::Array'))){
      throw('Array paramter must be a valid Bio::EnsEMBL::Funcgen::Array');
    }

    $self->{array} = $array;
  }

  $self->{array_id}  = $array_id;
  $self->{name}      = $name;
  $self->{design_id} = $design_id;

  return $self;
}

=head2 array_id

  Example    : my $array_id = $array_chip->array_id();
  Description: Getter array_id attribute.
  Returntype : Int
  Exceptions : None
  Caller     : General
  Status     : Stable

=cut

sub array_id {
    my $self     = shift;
    my $array_id = shift;

    if (defined $array_id) {
      $self->{'array_id'} = $array_id;
    }
    return $self->{'array_id'};
}

=head2 name

  Example    : my $ac_name = $array_chip->name();
  Description: Getter for the name attribute
  Returntype : String
  Exceptions : None
  Caller     : General
  Status     : Stable

=cut

sub name { return shift->{name}; }

=head2 design_id

  Example    : my $design_id = $array_chip->design_id();
  Description: Getter for the design_id attribute
  Returntype : String
  Exceptions : None
  Caller     : General
  Status     : Stable

=cut

sub design_id {  return shift->{design_id}; }

=head2 get_Array

  Example    : my $array = $array_chip->get_array();
  Description: Getter for the array attribute
  Returntype : Bio::EnsEMBL::Funcgen::Array
  Exceptions : None
  Caller     : General
  Status     : At Risk

=cut

sub get_Array {
  my $self = shift;

  if(! defined $self->{'array'}){
    $self->{'array'} = $self->adaptor->db->get_ArrayAdaptor()->fetch_by_dbID($self->array_id());
  }

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

1;


text:
                @include('partials.app.breadcrumbs')

{!! $content !!}


text:
<?php

namespace Kunstmaan\MediaBundle\Repository;

use Doctrine\ORM\EntityNotFoundException;
use Doctrine\ORM\EntityRepository;
use Kunstmaan\MediaBundle\Entity\Media;

/**
 * MediaRepository
 */
class MediaRepository extends EntityRepository
{
    /**
     * @param Media $media
     */
    public function save(Media $media)
    {
        $em = $this->getEntityManager();
        $em->persist($media);
        $em->flush();
    }

    /**
     * @param Media $media
     */
    public function delete(Media $media)
    {
        $em = $this->getEntityManager();
        $media->setDeleted(true);
        $em->persist($media);
        $em->flush();
    }

    /**
     * @param int $mediaId
     *
     * @return object
     * @throws EntityNotFoundException
     */
    public function getMedia($mediaId)
    {
        $media = $this->find($mediaId);
        if (!$media) {
            throw new EntityNotFoundException();
        }

        return $media;
    }

    /**
     * @param integer $pictureId
     *
     * @return object
     * @throws EntityNotFoundException
     */
    public function getPicture($pictureId)
    {
        $em = $this->getEntityManager();

        $picture = $em->getRepository('KunstmaanMediaBundle:Image')->find($pictureId);
        if (!$picture) {
            throw new EntityNotFoundException();
        }

        return $picture;
    }

    /**
     * Finds all Media  that has their deleted flag set to 1
     * and have their remove_from_file_system flag set to 0
     *
     * @return object[]
     */
    public function findAllDeleted()
    {
        return $this->findBy(array('deleted' => true, 'removedFromFileSystem' => false));
    }
}


text:
(function () {
    'use strict';
    angular.module(APPNAME)
        .controller('layoutController', LayoutController);
    LayoutController.$inject = ['$scope', '$window', '$baseController', 'timecardEntryService', '$sabio', '$location', '$timeout', '$anchorScroll'];

    function LayoutController($scope, $window, $baseController, timecardEntryService, $sabio, $location, $timeout, $anchorScroll) {
        // Administrative stuff
        var vm = this;
        vm.$scope = $scope;
        vm.$sabio = $sabio;
        // Simulate inheritance to add
        // $document, $log, $route, $routeParams, $systemEventService, $alertService, $sabio services
        // to our controller.
        vm.$location = $location;
        $baseController.merge(vm, $baseController);
        vm.timecardEntryService = timecardEntryService;
        vm.$window = $window;
        vm.logout = _logout;
        vm.item = null;
        vm.model = $sabio.model;
        vm.isAdmin = vm.model.isAdmin;

        _navBehavior();

        function _navBehavior() {
            $('ul.navbar-right>li.dropdown>a.dropdown-toggle').on('mouseenter', function () {
                $(this).click();
            });
        }

        //Logout Functions
        function _logout() {
            sabio.services.user.getLogout(_logoutSuccess, _logoutError);
        }

        function _logoutSuccess() {
            window.location.href = "/";
        }

        function _logoutError() {
            toastr.error("Failed to logout");
        }
    }

})();


text:
x=2
x=3 if x='a' or
  false
# What's weird here is we get two stops on line 4 and both times x is
# 4. In Ruby 1.9 we don't get *any* line traces.


text:
Bridge.merge(new System.Globalization.CultureInfo("fi", true), {
    englishName: "Finnish",
    nativeName: "suomi",

    numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), {
        nanSymbol: "epäluku",
        negativeSign: "-",
        positiveSign: "+",
        negativeInfinitySymbol: "-∞",
        positiveInfinitySymbol: "∞",
        percentSymbol: "%",
        percentGroupSizes: [3],
        percentDecimalDigits: 2,
        percentDecimalSeparator: ",",
        percentGroupSeparator: " ",
        percentPositivePattern: 0,
        percentNegativePattern: 0,
        currencySymbol: "€",
        currencyGroupSizes: [3],
        currencyDecimalDigits: 2,
        currencyDecimalSeparator: ",",
        currencyGroupSeparator: " ",
        currencyNegativePattern: 8,
        currencyPositivePattern: 3,
        numberGroupSizes: [3],
        numberDecimalDigits: 2,
        numberDecimalSeparator: ",",
        numberGroupSeparator: " ",
        numberNegativePattern: 1
    }),

    dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), {
        abbreviatedDayNames: ["su","ma","ti","ke","to","pe","la"],
        abbreviatedMonthGenitiveNames: ["tammik.","helmik.","maalisk.","huhtik.","toukok.","kesäk.","heinäk.","elok.","syysk.","lokak.","marrask.","jouluk.",""],
        abbreviatedMonthNames: ["tammi","helmi","maalis","huhti","touko","kesä","heinä","elo","syys","loka","marras","joulu",""],
        amDesignator: "ap.",
        dateSeparator: ".",
        dayNames: ["sunnuntai","maanantai","tiistai","keskiviikko","torstai","perjantai","lauantai"],
        firstDayOfWeek: 1,
        fullDateTimePattern: "dddd d. MMMM yyyy H.mm.ss",
        longDatePattern: "dddd d. MMMM yyyy",
        longTimePattern: "H.mm.ss",
        monthDayPattern: "d. MMMM",
        monthGenitiveNames: ["tammikuuta","helmikuuta","maaliskuuta","huhtikuuta","toukokuuta","kesäkuuta","heinäkuuta","elokuuta","syyskuuta","lokakuuta","marraskuuta","joulukuuta",""],
        monthNames: ["tammikuu","helmikuu","maaliskuu","huhtikuu","toukokuu","kesäkuu","heinäkuu","elokuu","syyskuu","lokakuu","marraskuu","joulukuu",""],
        pmDesignator: "ip.",
        rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
        shortDatePattern: "d.M.yyyy",
        shortestDayNames: ["su","ma","ti","ke","to","pe","la"],
        shortTimePattern: "H.mm",
        sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
        sortableDateTimePattern1: "yyyy'-'MM'-'dd",
        timeSeparator: ".",
        universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
        yearMonthPattern: "MMMM yyyy",
        roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz"
    }),

    TextInfo: Bridge.merge(new System.Globalization.TextInfo(), {
        ANSICodePage: 1252,
        CultureName: "fi-FI",
        EBCDICCodePage: 20278,
        IsRightToLeft: false,
        LCID: 1035,
        listSeparator: ";",
        MacCodePage: 10000,
        OEMCodePage: 850,
        IsReadOnly: true
    })
});


text:
package com.amazonaws.services.elasticbeanstalk.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.elasticbeanstalk.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * PlatformFramework StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PlatformFrameworkStaxUnmarshaller implements Unmarshaller<PlatformFramework, StaxUnmarshallerContext> {

    public PlatformFramework unmarshall(StaxUnmarshallerContext context) throws Exception {
        PlatformFramework platformFramework = new PlatformFramework();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return platformFramework;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("Name", targetDepth)) {
                    platformFramework.setName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("Version", targetDepth)) {
                    platformFramework.setVersion(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return platformFramework;
                }
            }
        }
    }

    private static PlatformFrameworkStaxUnmarshaller instance;

    public static PlatformFrameworkStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new PlatformFrameworkStaxUnmarshaller();
        return instance;
    }
}


text:
package com.alta189.simple.gallery.objects;

public enum MessagePosition {
	TOP_CENTER("top-center"),
	TOP_LEFT("top-left"),
	TOP_RIGHT("top-right"),
	BOTTOM_CENTER("bottom-center"),
	BOTTOM_LEFT("bottom-left"),
	BOTTOM_RIGHT("bottom-right");

	private final String value;

	MessagePosition(String value) {
		this.value = value;
	}

	public static MessagePosition fromValue(String value) {
		for (MessagePosition position : values()) {
			if (position.getValue().equalsIgnoreCase(value)) {
				return position;
			}
		}
		return TOP_RIGHT; // default value
	}

	public String getValue() {
		return value;
	}
}


text:
package com.haulmont.cuba.web.widgets.addons.dragdroplayouts.drophandlers;

import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.shared.ui.dd.HorizontalDropLocation;
import com.vaadin.shared.ui.dd.VerticalDropLocation;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.SingleComponentContainer;

import com.haulmont.cuba.web.widgets.addons.dragdroplayouts.DDCssLayout;
import com.haulmont.cuba.web.widgets.addons.dragdroplayouts.DDCssLayout.CssLayoutTargetDetails;
import com.haulmont.cuba.web.widgets.addons.dragdroplayouts.events.LayoutBoundTransferable;

/**
 * Default CSS Layout drop handler
 *
 * @author John Ahlroos / www.jasoft.fi
 * @since 0.7.0
 *
 */
@SuppressWarnings("serial")
public class DefaultCssLayoutDropHandler
        extends AbstractDefaultLayoutDropHandler {

    @Override
    protected void handleComponentReordering(DragAndDropEvent event) {
        // Component re-ordering
        LayoutBoundTransferable transferable = (LayoutBoundTransferable) event
                .getTransferable();
        CssLayoutTargetDetails details = (CssLayoutTargetDetails) event
                .getTargetDetails();
        DDCssLayout layout = (DDCssLayout) details.getTarget();
        Component comp = transferable.getComponent();
        int idx = details.getOverIndex();
        Component over = details.getOverComponent();

        // Detach from old source
        Component source = transferable.getSourceComponent();
        if (source instanceof ComponentContainer) {
            ((ComponentContainer) source).removeComponent(comp);
        } else if (source instanceof SingleComponentContainer) {
            ((SingleComponentContainer) source).setContent(null);
        }

        // Add component
        if (idx >= 0 && idx < layout.getComponentCount()) {
            layout.addComponent(comp, idx);
        } else {
            layout.addComponent(comp);
        }
    }

    @Override
    protected void handleDropFromLayout(DragAndDropEvent event) {
        LayoutBoundTransferable transferable = (LayoutBoundTransferable) event
                .getTransferable();
        CssLayoutTargetDetails details = (CssLayoutTargetDetails) event
                .getTargetDetails();
        DDCssLayout layout = (DDCssLayout) details.getTarget();
        HorizontalDropLocation hl = details.getHorizontalDropLocation();
        VerticalDropLocation vl = details.getVerticalDropLocation();
        Component source = event.getTransferable().getSourceComponent();
        int idx = (details).getOverIndex();
        Component comp = transferable.getComponent();
        Component over = details.getOverComponent();

        if (over == layout) {
            if (vl == VerticalDropLocation.TOP
                    || hl == HorizontalDropLocation.LEFT) {
                idx = 0;
            } else if (vl == VerticalDropLocation.BOTTOM
                    || hl == HorizontalDropLocation.RIGHT) {
                idx = -1;
            }
        } else {
            if (vl == VerticalDropLocation.BOTTOM
                    || hl == HorizontalDropLocation.RIGHT) {
                idx++;
            }
        }

        // Check that we are not dragging an outer layout into an inner
        // layout
        Component parent = layout.getParent();
        while (parent != null) {
            if (parent == comp) {
                return;
            }
            parent = parent.getParent();
        }

        // If source is an instance of a component container then remove
        // it
        // from there,
        // the component cannot have two parents.
        if (source instanceof ComponentContainer) {
            ComponentContainer sourceLayout = (ComponentContainer) source;
            sourceLayout.removeComponent(comp);
        }

        // Add component
        if (idx >= 0 && idx < layout.getComponentCount()) {
            layout.addComponent(comp, idx);
        } else {
            layout.addComponent(comp);
        }
    }

    @Override
    protected void handleHTML5Drop(DragAndDropEvent event) {
        CssLayoutTargetDetails details = (CssLayoutTargetDetails) event
                .getTargetDetails();
        Component over = details.getOverComponent();
        DDCssLayout layout = (DDCssLayout) details.getTarget();
        int idx = (details).getOverIndex();
        HorizontalDropLocation hl = details.getHorizontalDropLocation();
        VerticalDropLocation vl = details.getVerticalDropLocation();

        if (over == layout) {
            if (vl == VerticalDropLocation.TOP
                    || hl == HorizontalDropLocation.LEFT) {
                idx = 0;
            } else if (vl == VerticalDropLocation.BOTTOM
                    || hl == HorizontalDropLocation.RIGHT) {
                idx = -1;
            }
        } else {
            if (vl == VerticalDropLocation.BOTTOM
                    || hl == HorizontalDropLocation.RIGHT) {
                idx++;
            }
        }

        if (idx >= 0 && idx < layout.getComponentCount()) {
            layout.addComponent(resolveComponentFromHTML5Drop(event), idx);
        } else {
            layout.addComponent(resolveComponentFromHTML5Drop(event));
        }
    }

    @Override
    public Class<CssLayout> getTargetLayoutType() {
        return CssLayout.class;
    }
}


text:
import { ChangeDetectionStrategy, Component, EventEmitter, Inject, Input, OnInit, Output } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import {
  ErrorsExtractor,
  IBaseEntityModalOptions,
  ModalsService,
  Permission,
  PERMISSIONS_CONFIG_TOKEN,
  translate
} from '@rucken/core';
import { DynamicRepository, IRestProviderOptions } from 'ngx-repository';
import { PermissionsGridModalComponent } from '../permissions-grid-modal/permissions-grid-modal.component';
import { PermissionsGridComponent } from '../permissions-grid/permissions-grid.component';
import { BindIoInner } from 'ngx-bind-io';

@BindIoInner()
@Component({
  selector: 'permission-input',
  templateUrl: './permission-input.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PermissionInputComponent extends PermissionsGridComponent implements OnInit {
  @Output()
  select = new EventEmitter<Permission>();
  @Input()
  modalAppendFromGrid: IBaseEntityModalOptions = {
    component: PermissionsGridModalComponent,
    initialState: {
      title: translate('Select permission'),
      yesTitle: translate('Select')
    }
  };

  constructor(
    modalsService: ModalsService,
    protected errorsExtractor: ErrorsExtractor,
    protected translateService: TranslateService,
    protected dynamicRepository: DynamicRepository,
    @Inject(PERMISSIONS_CONFIG_TOKEN) protected permissionsConfig: IRestProviderOptions<Permission>
  ) {
    super(modalsService, errorsExtractor, translateService, dynamicRepository, permissionsConfig);
  }
  ngOnInit() {
    this.mockedItems = [];
    this.useMock({
      items: this.mockedItems,
      ...this.permissionsConfig
    });
    this.mockedItemsChange.subscribe(items => this.onSelect(items[0]));
  }
  onSelect(item: Permission) {
    this.select.emit(item);
  }
}


text:
require "spec_helper"

describe Huckleberry::Calorie do
  it { should validate_presence_of(:nutrient_databank_number) }
  it { should validate_presence_of(:calories) }
  it { should belong_to(:ingredient) }
end


text:
package io.crate.action.sql.parser;

import org.elasticsearch.ElasticsearchException;

/**
 * An exception thrown if the XContent source of a request cannot be parsed.
 */
public class SQLParseSourceException extends ElasticsearchException {

    public SQLParseSourceException(SQLXContentSourceContext context, String msg) {
        super("Parse Failure [" + msg + "]");
    }
}


text:
import java.io.Console;
// June 2017, JMI
// program asks user to type their favorite color and then prints acknowledgment, among other things
public class FavoriteColor {
    public static void main(String[] args) {
        Console myConsole = System.console();

        System.out.println("What's your favorite color?"); // prints to console, requests user input
        String favoriteColor = myConsole.readLine();  // reads console input (stdin)
        favoriteColor = favoriteColor.trim().toUpperCase(); // trims whitespace and converts to upper case

        System.out.println("What's your next favorite color?");
        String nextFavorite = myConsole.readLine();
        nextFavorite = nextFavorite.trim().toUpperCase();
        favoriteColor = favoriteColor.concat(" and ").concat(nextFavorite); // takes the input from console and adds "concats" that to the first answer, inserting "and" between

        System.out.println("The class of the variable 'favoriteColor' is "+ favoriteColor.getClass()); // check to see which class (String, Integer, etc) favoriteColor belongs to and print the result
        System.out.println("Your favoite colors are "+favoriteColor+"!");
        System.out.println("Haha! Your new favoite color, as dicatated by me, is " + favoriteColor.replaceAll(favoriteColor, "Unicorn Poop.")); // replace the user's favorite color with unicorn poop
    }
}


text:
+++
Title = "Antonio García"
image = "antonio-garcia.jpg"
type = "speaker"
linktitle = "antonio-garcia"
Twitter = "agcandil"
+++

Mi mayor hobby es poder compartir el tiempo con mi familia y amigos, disfrutar cada día con mi mujer y mis hijos. Profesionalmente, me gusta afrontar todos los retos que se me planteen, desde hacer un pequeño script hasta formar parte de un proceso de transformación. Llevo más de nueve años trabajando en atSistemas, lo que me ha permitido estar implicado en numerosos proyectos de mejora y automatización a nivel de Metodología, Organización, CI/CD, Monitorización,... He podido ver los pasos que se han ido dado en todo tipo de organizaciones, desde pequeñas empresas hasta las grandes cuentas que dominan en España cualquier sector (Banca, Retail, telco,...) en su intento de modernizarse y prepararse para la revolución digital que estamos viviendo.


text:
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
    return dict(initial_formation="template5", path_list=[
        [TestAction.create_mini_vm, "vm1", 'data_volume=false', 'cpu=2', 'memory=2', 'provisiong=thick'],
        [TestAction.create_vm_backup, "vm1", "backup1"],
        [TestAction.create_mini_vm, "vm2", 'data_volume=false', 'cpu=2', 'memory=2', 'provisiong=thick'],
        [TestAction.migrate_vm, "vm1"],
        [TestAction.migrate_vm, "vm2"],
        [TestAction.create_volume, "volume1", "=scsi,thin"],
        [TestAction.attach_volume, "vm1", "volume1"],
        [TestAction.create_mini_vm, "vm3", 'data_volume=false', 'cpu=2', 'memory=2', 'network=random',
         'provisiong=thin'],
        [TestAction.create_volume, "volume2", "=scsi,thick"],
        [TestAction.add_image, "image1", 'root', "http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2"],
        [TestAction.stop_vm, "vm1"],
        [TestAction.use_vm_backup, "backup1"],
        [TestAction.start_vm, "vm1"],
        [TestAction.delete_image, "image1"],
        [TestAction.expunge_image, "image1"],
        [TestAction.create_vm_backup, "vm1", "backup2"],
        [TestAction.create_vm_backup, "vm2", "backup3"],
        [TestAction.create_mini_vm, "vm3", 'data_volume=false', 'cpu=2', 'memory=2', 'provisiong=thick'],
        [TestAction.resize_data_volume, "volume1", 5 * 1024 * 1024],
        [TestAction.resize_data_volume, "volume2", 5 * 1024 * 1024],
        [TestAction.create_volume, "volume3", "flag=scsi,thick", "size=random"],
        [TestAction.delete_volume, "volume2"],
        [TestAction.recover_volume, "volume2"],
        [TestAction.stop_vm, "vm1"],
        [TestAction.stop_vm, "vm2"],
        [TestAction.stop_vm, "vm3"],
        [TestAction.start_vm, "vm1"],
        [TestAction.start_vm, "vm2"],
        [TestAction.start_vm, "vm3"],
        [TestAction.add_image, "image2", 'root', "http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2"],
        [TestAction.delete_volume, "volume3"],
        [TestAction.expunge_volume, "volume3"],
        [TestAction.reboot_vm, "vm1"],
        [TestAction.reboot_vm, "vm2"],
        [TestAction.reboot_vm, "vm3"],
        [TestAction.create_volume_backup, "volume1", "backup4"],
        [TestAction.resize_data_volume, "volume1", 5 * 1024 * 1024],
        [TestAction.resize_data_volume, "volume2", 5 * 1024 * 1024],
        [TestAction.delete_image, "image2"],
        [TestAction.stop_vm, "vm1"],
        [TestAction.use_volume_backup, "backup4"],
        [TestAction.start_vm, "vm1"],
        [TestAction.add_image, "image3", 'root', "http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2"],
        [TestAction.attach_volume, "vm2", "volume2"]])


text:
package ws.rocket.config.test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertSame;

import java.io.ByteArrayInputStream;
import org.testng.annotations.Test;
import ws.rocket.config.ConfigException;
import ws.rocket.config.ConfigModel;
import ws.rocket.config.Messages;

/**
 * Tests the minimum: a configuration with no sections, both model construction and parsing.
 *
 * @author Martti Tamm
 */
public final class ConfigModelEmptyTest {

  /**
   * Creates a configuration model with no sections. Afterwards parses an empty stream and verifies that an instance of
   * configuration bean is created.
   */
  @Test
  public void testModel() {
    ConfigModel<Object> model = ConfigModel.expect(Object.class).ready();
    verifyModel(model);
    verifyParse(model);
    verifyToString(model);
  }

  private void verifyModel(ConfigModel<Object> model) {
    assertNotNull(model, "Model object");

    assertSame(model.getConfigBeanType(), Object.class, "Model bean type.");

    assertNotNull(model.getSections(), "Model sections array");
    assertEquals(model.getSections().length, 0, "Model sections count");
  }

  private void verifyParse(ConfigModel<Object> model) {
    try {
      Object data = model.parse(new ByteArrayInputStream(new byte[0]));

      assertNotNull(data, "Configuration object");
      assertEquals(data.getClass(), Object.class, "Configuration object type");

    } catch (ConfigException e) {
      Messages msgs = e.getMessages();
      msgs.writeTo(System.out);

      assertNotNull(msgs, "Messages must be (always) defined");
      assertFalse(msgs.hasWarnings(), "No warnings expected (should be correct model).");
      assertFalse(msgs.hasErrors(), "No errors expected (should be correct model).");
    }
  }

  private void verifyToString(ConfigModel<Object> model) {
    System.out.println(model.toString());
  }

}


text:
<?php

//注册插件
RegisterPlugin("LinkCentre", "ActivePlugin_LinkCentre");

function ActivePlugin_LinkCentre()
{
    Add_Filter_Plugin('Filter_Plugin_Admin_Header', 'LinkCentre_Head');
    Add_Filter_Plugin('Filter_Plugin_Admin_CategoryMng_SubMenu', 'LinkCentre_AddMenu');
    Add_Filter_Plugin('Filter_Plugin_Admin_PageMng_SubMenu', 'LinkCentre_AddMenu');
    Add_Filter_Plugin('Filter_Plugin_Admin_ModuleMng_SubMenu', 'LinkCentre_ModuleMenu');
    Add_Filter_Plugin('Filter_Plugin_Zbp_BuildTemplate', 'LinkCentre_BuidTemp');
}
function LinkCentre_BuidTemp(&$templates)
{
    // global $zbp;
    // if (is_file(LinkCentre_Path("u-temp"))) {
    $templates['Links_defend'] = file_get_contents(LinkCentre_Path("u-temp"));
    // }
    $templates['Links_admin'] = file_get_contents(LinkCentre_Path("tr"));
}
function LinkCentre_ModuleMenu()
{
    global $zbp;

    $array = $zbp->GetModuleList(
        array('*')
    );
    $mods = array();
    foreach ($array as $mod) {
        if ($mod->Type == 'ul') {
            if ($mod->Source == 'system' && !in_array($mod->HtmlID, array('navbar', 'link', 'misc', 'favorite'))) {
                continue;
            }
            $mods[] = $mod->FileName;
        }
    }

    $str = '新建链接模块';

    $url = LinkCentre_Path("main", "host");
    $mod = LinkCentre_Path("bakfile") . '|' . implode('|', $mods);
    $str .= "<input class=\"js-mod\" type=\"hidden\" value=\"{$mod}\">";
    echo $str;
}
function LinkCentre_Head()
{
    echo "<link rel=\"stylesheet\" href=\"" . LinkCentre_Path("style", "host") . "\">";
    echo "";
}
function LinkCentre_AddMenu()
{
    global $zbp;
    echo '导航管理';
}
function LinkCentre_Path($file, $t = "path")
{
    global $zbp;
    $result = $zbp->$t . "zb_users/plugin/LinkCentre/";
    switch ($file) {
        case "u-temp":
            return $result . "usr/li.html";
            break;
        case "v-temp":
            return $result . "var/li.html";
            break;
        case "tr":
            return $result . "var/tr.html";
            break;
        case "style":
            return $result . "var/style.css";
            break;
        case "script":
            return $result . "var/script.js";
            break;
        case "usr":
            return $result . "usr/";
            break;
        case "bakdir":
            return $result . "backup/";
            break;
        case "bakfile":
            return 'navbar|favorite|link';
            break;
        case "main":
            return $result . "main.php";
            break;
        default:
            return $result . $file;
    }
}
function InstallPlugin_LinkCentre()
{
}

function UninstallPlugin_LinkCentre()
{
}


text:
package com.blackducksoftware.integration.hub.detect.detector.gradle;

import java.io.File;

import com.blackducksoftware.integration.hub.detect.detector.Detector;
import com.blackducksoftware.integration.hub.detect.detector.DetectorEnvironment;
import com.blackducksoftware.integration.hub.detect.detector.DetectorException;
import com.blackducksoftware.integration.hub.detect.detector.DetectorType;
import com.blackducksoftware.integration.hub.detect.detector.ExtractionId;
import com.blackducksoftware.integration.hub.detect.workflow.extraction.Extraction;
import com.blackducksoftware.integration.hub.detect.workflow.file.DetectFileFinder;
import com.blackducksoftware.integration.hub.detect.workflow.file.DirectoryManager;
import com.blackducksoftware.integration.hub.detect.workflow.search.result.DetectorResult;
import com.blackducksoftware.integration.hub.detect.workflow.search.result.ExecutableNotFoundDetectorResult;
import com.blackducksoftware.integration.hub.detect.workflow.search.result.FileNotFoundDetectorResult;
import com.blackducksoftware.integration.hub.detect.workflow.search.result.InspectorNotFoundDetectorResult;
import com.blackducksoftware.integration.hub.detect.workflow.search.result.PassedDetectorResult;

public class GradleInspectorDetector extends Detector {
    public static final String BUILD_GRADLE_FILENAME = "build.gradle";

    private final DirectoryManager directoryManager;
    private final DetectFileFinder fileFinder;
    private final GradleExecutableFinder gradleFinder;
    private final GradleInspectorManager gradleInspectorManager;
    private final GradleInspectorExtractor gradleInspectorExtractor;

    private String gradleExe;
    private String gradleInspector;

    public GradleInspectorDetector(final DetectorEnvironment environment, final DirectoryManager directoryManager, final DetectFileFinder fileFinder,
        final GradleExecutableFinder gradleFinder, final GradleInspectorManager gradleInspectorManager,
        final GradleInspectorExtractor gradleInspectorExtractor) {
        super(environment, "Gradle Inspector", DetectorType.GRADLE);
        this.directoryManager = directoryManager;
        this.fileFinder = fileFinder;
        this.gradleFinder = gradleFinder;
        this.gradleInspectorManager = gradleInspectorManager;
        this.gradleInspectorExtractor = gradleInspectorExtractor;
    }

    @Override
    public DetectorResult applicable() {
        final File buildGradle = fileFinder.findFile(environment.getDirectory(), BUILD_GRADLE_FILENAME);
        if (buildGradle == null) {
            return new FileNotFoundDetectorResult(BUILD_GRADLE_FILENAME);
        }

        return new PassedDetectorResult();
    }

    @Override
    public DetectorResult extractable() throws DetectorException {
        gradleExe = gradleFinder.findGradle(environment);
        if (gradleExe == null) {
            return new ExecutableNotFoundDetectorResult("gradle");
        }

        gradleInspector = gradleInspectorManager.getGradleInspector();
        if (gradleInspector == null) {
            return new InspectorNotFoundDetectorResult("gradle");
        }

        return new PassedDetectorResult();
    }

    @Override
    public Extraction extract(final ExtractionId extractionId) {
        File outputDirectory = directoryManager.getExtractionOutputDirectory(extractionId);
        return gradleInspectorExtractor.extract(environment.getDirectory(), gradleExe, gradleInspector, outputDirectory);
    }

}


text:
var searchData=
[
  ['historytextfield_2eh',['HistoryTextField.h',['../d1/da2/_history_text_field_8h.html',1,'']]],
  ['historytextfield_2em',['HistoryTextField.m',['../d8/de8/_history_text_field_8m.html',1,'']]],
  ['horizontalspliviewdelegate_2eh',['HorizontalSpliViewDelegate.h',['../d6/d87/_horizontal_spli_view_delegate_8h.html',1,'']]],
  ['horizontalspliviewdelegate_2em',['HorizontalSpliViewDelegate.m',['../d4/d62/_horizontal_spli_view_delegate_8m.html',1,'']]]
];


text:
package main

import (
	"fmt"

	ogcli "github.com/opsgenie/opsgenie-go-sdk/client"
	hb "github.com/opsgenie/opsgenie-go-sdk/heartbeat"
	samples "github.com/opsgenie/opsgenie-go-sdk/_samples"
	"github.com/opsgenie/opsgenie-go-sdk/_samples/constants"
)

func main() {
	cli := new(ogcli.OpsGenieClient)
	cli.SetAPIKey(constants.APIKey)

	hbCli, cliErr := cli.Heartbeat()

	if cliErr != nil {
		panic(cliErr)
	}

	// create the hb
	enabled := true
	req := hb.AddHeartbeatRequest{
		Name: samples.RandStringWithPrefix("Test", 4),
		IntervalUnit:"minutes",
		Enabled: &enabled,
		Interval:5,
		Description:"Heartbeat description"}
	response, hbErr := hbCli.Add(req)

	if hbErr != nil {
		panic(hbErr)
	}

	fmt.Printf("Heartbeat added\n")
	fmt.Printf("---------------\n")
	fmt.Printf("name: %s\n", response.Name)
	fmt.Printf("status: %s\n", response.Status)
	fmt.Printf("code: %d\n", response.Code)

	// send heart beat request
	pingRequest := hb.PingHeartbeatRequest{Name: response.Name}
	pingResponse, sendErr := hbCli.Ping(pingRequest)

	if sendErr != nil {
		panic(sendErr)
	}

	fmt.Println()
	fmt.Printf("Heartbeat request sent\n")
	fmt.Printf("----------------------\n")
	fmt.Printf("RequestId: %s\n", pingResponse.RequestID)
	fmt.Printf("Response Time: %f\n", pingResponse.ResponseTime)
}


text:
$(function() {
    const generateButton = $('#generate-button');
    const myPrivate = $('#my-private');
    const myPublic = $('#my-public');
    const partnerPublic = $('#partner-public');
    const sharedKey = $('#shared-key');
    let myKey;

    // let myKey = ec.genKeyPair();
    //
    // myPrivate.val(myKey.getPrivate().toString('hex'));
    // myPublic.val(myKey.getPublic().encode('hex'));

    $("input:text").focus(function() {
        $(this).select();
    }).on('input propertychange', function() {
        updateKeys();
    });

    function generateMyKey() {
        myKey = ec.genKeyPair();
        myPrivate.val(myKey.getPrivate().toString('hex'));
    }

    function updateKeys() {
        myKey = ec.keyFromPrivate(myPrivate.val());
        myPublic.val(myKey.getPublic().encode('hex'));

        if (myPublic.val().length > 0 && partnerPublic.val().length > 0) {
            let partnerKey = ec.keyFromPublic(partnerPublic.val(), 'hex');
            sharedKey.val(myKey.derive(partnerKey.getPublic()).toString(16));
        }
    }

    generateButton.on('click', function() {
        generateMyKey();
        updateKeys();
    });

    myPrivate.tooltip({
        container: 'body',
        placement: 'top',
        title: "Paste an existing private key here or click \"Generate\". Keep this key secret."
    });

    myPublic.tooltip({
        container: 'body',
        placement: 'top',
        title: "Send your public key to your partner."
    });

    partnerPublic.tooltip({
        container: 'body',
        placement: 'top',
        title: "Paste your partner's public key here."
    });

    sharedKey.tooltip({
        container: 'body',
        placement: 'top',
        title: "This shared secret is private between you and your partner."
    });

    generateMyKey();
    updateKeys();
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Discom. Bohem. (Prague) 268 (1934)

#### Original name
Arachnopeziza corcontica Velen.

### Remarks
null


text:
package org.apache.streams.local.test.providers;

import org.apache.streams.core.StreamsDatum;
import org.apache.streams.core.StreamsProvider;
import org.apache.streams.core.StreamsResultSet;
import org.apache.streams.util.ComponentUtils;
import org.joda.time.DateTime;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class NumericMessageProviderMetaData implements StreamsProvider {
    protected int startNumber = 0;
    protected int numMessages;

    public NumericMessageProviderMetaData() {
        this.numMessages = 0;
    }

    public NumericMessageProviderMetaData(int numMessages) {
        this.numMessages = numMessages;
    }

    public NumericMessageProviderMetaData(int startNumber, int numMessages) {
        this.startNumber = startNumber;
        this.numMessages = numMessages;
    }

    public void startStream() {
        // no op
    }

    public StreamsResultSet readCurrent() {
        return new ResultSet();
    }

    public StreamsResultSet readNew(BigInteger sequence) {
        return new ResultSet();
    }

    public StreamsResultSet readRange(DateTime start, DateTime end) {
        return new ResultSet();
    }

    public void prepare(Object configurationObject) {

    }

    public void cleanUp() {

    }

    private class ResultSet extends StreamsResultSet {

        private ResultSet() {
            super(new ConcurrentLinkedQueue<StreamsDatum>());
            for(int i = 0; i < numMessages; i++) {
                final Integer sequence = i;
                final String className = this.getClass().getCanonicalName();
                StreamsDatum datum = new StreamsDatum(new NumericMessageObject(startNumber + i));
                datum.setMetadata(new HashMap<String, Object>() {{
                    put("sequence", sequence);
                    put("class", className);
                }});
                ComponentUtils.offerUntilSuccess(datum, this.getQueue());
            }
        }
    }
}