text:
package org.apache.storm.streams;

import java.io.Serializable;

/**
 * A pair of values.
 *
 * @param <T1> the type of the first value
 * @param <T2> the type of the second value
 */
public final class Pair<T1, T2> implements Serializable {
    /**
     * The first value
     */
    public final T1 _1;
    /**
     * The second value
     */
    public final T2 _2;

    /**
     * Constructs a new pair of values
     *
     * @param first  the first value
     * @param second the second value
     */
    private Pair(T1 first, T2 second) {
        _1 = first;
        _2 = second;
    }

    /**
     * Returns the first value in a pair.
     *
     * @return the first value
     */
    public T1 getFirst() {
        return _1;
    }

    /**
     * Returns the second value in a pair.
     *
     * @return the second value
     */
    public T2 getSecond() {
        return _2;
    }

    /**
     * Constructs a new pair of values.
     *
     * @param first  the first value
     * @param second the second value
     * @param <T1>   the type of the first value
     * @param <T2>   the type of the second value
     * @return a new pair of values
     */
    public static <T1, T2> Pair<T1, T2> of(T1 first, T2 second) {
        return new Pair<>(first, second);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Pair<?, ?> pair = (Pair<?, ?>) o;

        if (_1 != null ? !_1.equals(pair._1) : pair._1 != null) return false;
        return _2 != null ? _2.equals(pair._2) : pair._2 == null;

    }

    @Override
    public int hashCode() {
        int result = _1 != null ? _1.hashCode() : 0;
        result = 31 * result + (_2 != null ? _2.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "(" + _1 + ", " + _2 + ')';
    }
}


text:
// projectileIGC.cpp : Implementation of CprojectileIGC
#include "pch.h"
#include "projectileIGC.h"

/////////////////////////////////////////////////////////////////////////////
// CprojectileIGC
CprojectileIGC::CprojectileIGC(void)
	:
	m_launcher(NULL),
	m_projectileType(NULL),
	m_pExplosionData(NULL)
{
}

CprojectileIGC::~CprojectileIGC(void)
{
}

HRESULT CprojectileIGC::Initialize(ImissionIGC* pMission, Time now, const void* data, int dataSize)
{
	TmodelIGC<IprojectileIGC>::Initialize(pMission, now, data, dataSize);

	ZRetailAssert(data && (dataSize == sizeof(DataProjectileIGC)));
	{
		DataProjectileIGC*  dataProjectile = (DataProjectileIGC*)data;

		m_projectileType = pMission->GetProjectileType(dataProjectile->projectileTypeID);
		if (m_projectileType)
		{
			m_projectileType->AddRef();

			DataProjectileTypeIGC*  dataProjectileType = (DataProjectileTypeIGC*)m_projectileType->GetData();
			assert(dataProjectileType);

			//Load the model for the projectile
			if (iswalpha(dataProjectileType->modelName[0]))
			{
				HRESULT hr = Load(0, dataProjectileType->modelName, dataProjectileType->textureName, NULL, c_mtCastRay | c_mtNotPickable);
				assert(SUCCEEDED(hr));
				SetRadius(dataProjectileType->radius);
			}
			else
			{
				HRESULT hr = LoadDecal(dataProjectileType->textureName, NULL,
					Color((float)dataProjectileType->color.r,
					(float)dataProjectileType->color.g,
						(float)dataProjectileType->color.b,
						(float)dataProjectileType->color.a),
					dataProjectileType->bDirectional,
					dataProjectileType->width,
					c_mtCastRay | c_mtNotPickable);
				assert(SUCCEEDED(hr));
				GetHitTest()->SetRadius(0.0f);
				GetThingSite()->SetRadius(dataProjectileType->radius);
			}

			//position set after being initialized
			SetVelocity(dataProjectile->velocity);
			{
				Orientation o(dataProjectile->forward);
				SetOrientation(o);
			}
			{
				Rotation    r(dataProjectile->forward, dataProjectileType->rotation);
				SetRotation(r);
			}
			{
				HitTest*    ht = GetHitTest();

				//lifespan == 0 => immortal projectile that can hit until it gets terminated on the next update; this is bad
				assert(dataProjectile->lifespan > 0.0f);
				ht->SetTimeStart(now);
				ht->SetTimeStop(m_timeExpire = now + dataProjectile->lifespan); //intentional assignment
				assert(m_timeExpire != now);
			}

			SetMass(0.0f);
		}
	}

	return S_OK;
}

void    CprojectileIGC::Terminate(void)
{
	AddRef();

	TmodelIGC<IprojectileIGC>::Terminate();

	if (m_launcher)
	{
		m_launcher->Release();
		m_launcher = NULL;
	}

	if (m_projectileType)
	{
		m_projectileType->Release();
		m_projectileType = NULL;
	}

	Release();
}

void    CprojectileIGC::Update(Time now)
{
	if (GetMyLastUpdate() >= m_timeExpire)
		Terminate();
	else
	{
		if (now >= m_timeExpire)
		{
			float   p = m_projectileType->GetBlastPower();
			if (p != 0.0f)
			{
				m_pExplosionData = GetCluster()->CreateExplosion(m_projectileType->GetDamageType(),
					p * GetSide()->GetGlobalAttributeSet().GetAttribute(c_gaDamageGuns),
					m_projectileType->GetBlastRadius(),
					c_etProjectile,
					m_timeExpire,
					GetPosition() +
					GetVelocity() * (m_timeExpire - GetMyLastUpdate()),
					m_launcher);
			}
		}

		TmodelIGC<IprojectileIGC>::Update(now);
	}
}

int     CprojectileIGC::Export(void*    data)
{
	if (data)
	{
		DataProjectileIGC*  dataProjectile = (DataProjectileIGC*)data;

		dataProjectile->projectileTypeID = m_projectileType->GetObjectID();

		dataProjectile->velocity = GetVelocity();
		dataProjectile->forward = GetOrientation().GetForward();
	}

	return sizeof(DataProjectileIGC);
}

void                 CprojectileIGC::HandleCollision(Time       timeCollision,
	float                  tCollision,
	const CollisionEntry&  entry,
	ImodelIGC* pModel)
{
	if (pModel->GetObjectType() == OT_mine)
	{
		//Ignore collisions with minefields
		return;
	}

	if (pModel->GetObjectType() == OT_asteroid && ((IasteroidIGC*)pModel)->IsDead(GetSide()->GetObjectID()))
		return;				//#358: Ignore collisions with dead asteroids

	//A projectile hit something other than a minefield
	bool    fExplosion;
	Vector position1 = GetPosition() + GetVelocity() * tCollision;
	Vector position2 = pModel->GetPosition() + pModel->GetVelocity()  * tCollision;

	DamageTypeID type = m_projectileType->GetDamageType();
	if (pModel->GetAttributes() & c_mtDamagable)
	{
		//The target can take damage
		IdamageIGC*   pDamage = (IdamageIGC*)pModel;

		pModel->AddRef();

		DamageResult dr = pDamage->ReceiveDamage(type,
			m_projectileType->GetPower() * GetSide()->GetGlobalAttributeSet().GetAttribute(c_gaDamageGuns),
			timeCollision,
			position2,
			position1,
			m_launcher);

		//No explosion because no hull damage, not visible or we killed it.
		fExplosion = (dr <= c_drHullDamage) && pModel->GetVisibleF() && (pModel->GetCluster() != NULL);

		pModel->Release();
	}
	else
		fExplosion = false;

	if (m_pExplosionData)
	{
		//This projectile would have exploded anyway -- change the explosion position & time.
		m_pExplosionData->time = timeCollision;
		m_pExplosionData->position = position1;
	}
	else
	{
		float   p = m_projectileType->GetBlastPower();
		if (p != 0.0f)
		{
			//Area effect weapon: create an explosion (no matter what)
			GetCluster()->CreateExplosion(type,
				p,
				m_projectileType->GetBlastRadius(),
				c_etProjectile,
				timeCollision,
				position1,
				m_launcher);
		}
		else if (fExplosion && ((type & c_dmgidNoDebris) == 0))
		{
			Vector pos = position1 - position2;

			pModel->GetThingSite()->AddHullHit(pos,
				pos.Normalize());
		}
	}

	//In any case, kill the projectile
	Terminate();
}

redpajama_set_name: RedPajamaGithub


text:
require 'simplecov'

SimpleCov.configure do
  filters.clear
  load_profile 'test_frameworks'
end

SimpleCov.start do
  add_filter "/(.rbenv|.rvm)/"
  add_filter 'vendor'
end
require 'rubygems'
require 'bundler'
begin
  Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
  $stderr.puts "#{e.message}\nRun `bundle install` to install missing gems"
  exit e.status_code
end
require 'minitest/autorun'
require 'minitest/spec'

$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'micro_state_machine'

Minitest.autorun


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ed_09;

import Exceptions.NotSupportComparable;
import SortedArrays.ArrayUnorderedList;
import Exceptions.ElementNotFoundException;
import Exceptions.EmptyQueueException;
import Interfaces.QueueADT;
import Queues.LinkedQueue;
import java.util.Iterator;

/**
 *
 * @author navega
 */
/**
 * LinkedBinaryTree implements the BinaryTreeADT interface
 *
 */
public class LinkedBinaryTree<T> implements BinaryTreeADT<T> {

    protected int count;
    protected BinaryTreeNode<T> root;

    /**
     * Creates an empty binary tree.
     */
    public LinkedBinaryTree() {
        count = 0;
        root = null;
    }

    /**
     * Creates a binary tree with the specified element as its root.
     *
     * @param element the element that will become the root of the new binary
     * tree
     */
    public LinkedBinaryTree(T element) {
        count = 1;
        root = new BinaryTreeNode<T>(element);
    }

    @Override
    public T getRoot() {
        return (T) this.root;
    }

    @Override
    public boolean isEmpty() {
        return this.count == 0;
    }

    @Override
    public int size() {
        return this.count;
    }

    @Override
    public boolean contains(T targetElement) throws NotSupportComparable {
        if (targetElement instanceof Comparable) {

            boolean found = false;
            try {
                Iterator i = this.iteratorInOrder();
                while (i.hasNext()) {
                    if (i.next().equals(targetElement)) {
                        found = true;
                    }
                }

            } catch (NotSupportComparable ex) {

            }
            return found;
        } else {
            throw new NotSupportComparable("Not support comparable.");
        }

    }

    @Override
    public T find(T targetElement) throws ElementNotFoundException {
        BinaryTreeNode<T> current = findAgain(targetElement, root);
        if (current == null) {
            throw new ElementNotFoundException("binary tree");
        }
        return (current.element);
    }

    /**
     * Returns a reference to the specified target element if it is found in
     * this binary tree.
     *
     * @param targetElement the element being sought in this tree
     * @param next the element to begin searching from
     */
    private BinaryTreeNode<T> findAgain(T targetElement, BinaryTreeNode<T> next) {
        if (next == null) {
            return null;
        }
        if (next.element.equals(targetElement)) {
            return next;
        }
        BinaryTreeNode<T> temp = findAgain(targetElement, next.left);
        if (temp == null) {
            temp = findAgain(targetElement, next.right);
        }
        return temp;
    }

    @Override
    public Iterator<T> iteratorInOrder() throws NotSupportComparable {
        ArrayUnorderedList<T> tempList = new ArrayUnorderedList<T>();
        inorder(root, tempList);
        return tempList.iterator();
    }

    @Override
    public Iterator<T> iteratorPreOrder() throws NotSupportComparable {
        ArrayUnorderedList<T> tempList = new ArrayUnorderedList<T>();
        preorder(root, tempList);
        return tempList.iterator();
    }

    @Override
    public Iterator<T> iteratorPostOrder() throws NotSupportComparable {
        ArrayUnorderedList<T> tempList = new ArrayUnorderedList<T>();
        postorder(root, tempList);
        return tempList.iterator();
    }

    @Override
    public Iterator<T> iteratorLevelOrder() throws NotSupportComparable {
        ArrayUnorderedList<T> tempList = new ArrayUnorderedList<T>();
        try {
            levelorder(root, tempList);
        } catch (EmptyQueueException ex) {
        }
        return tempList.iterator();
    }

    /**
     * Performs a recursive inorder traversal.
     *
     * @param node the node to be used as the root for this traversal
     * @param tempList the temporary list for use in this traversal
     */
    protected void inorder(BinaryTreeNode<T> node, ArrayUnorderedList<T> tempList) throws NotSupportComparable {
        if (node != null) {
            inorder(node.left, tempList);
            tempList.addToRear(node.element);
            inorder(node.right, tempList);
        }
    }

    protected void preorder(BinaryTreeNode<T> node, ArrayUnorderedList<T> tempList) throws NotSupportComparable {
        if (node != null) {
            tempList.addToRear(node.element);
            preorder(node.left, tempList);
            preorder(node.right, tempList);
        }
    }

    protected void postorder(BinaryTreeNode<T> node, ArrayUnorderedList<T> tempList) throws NotSupportComparable {
        if (node != null) {
            postorder(node.left, tempList);
            postorder(node.right, tempList);
            tempList.addToRear(node.element);
        }
    }

    protected void levelorder(BinaryTreeNode<T> node, ArrayUnorderedList<T> tempList) throws EmptyQueueException, NotSupportComparable {
        QueueADT<BinaryTreeNode> nodes = new LinkedQueue();
        nodes.enqueue(this.root);

        while (!nodes.isEmpty()) {
            BinaryTreeNode element = (BinaryTreeNode) nodes.dequeue();
            if (element != null) {
                tempList.addToRear(element);
                nodes.enqueue(element.left);
                nodes.enqueue(element.right);
            } else {
                //tempList.addToRear(null);
            }

        }
    }

}


text:
package uk.ac.derby.GameEngine2D;

/** A class defining simple rigid (i.e., non-elastic) 2D physics. */
public class RigidBody2D {

	public static final float _MAXTHRUST = 10.0f;
	public static final float _MINTHRUST = 0.0f;
	public static final float _DTHRUST = 0.01f;
	public static final float _STEERINGFORCE = 3.0f;
	public static final float _LINEARDRAGCOEFFICIENT = 0.3f;
	public static final float _ANGULARDRAGCOEFFICIENT = 5000.0f;

	private float fMass = 10;			// total mass (constant)
	private float fInertia = 10;		// mass moment of inertia in body coordinates (constant)

	private Vector3D vPosition = new Vector3D();	// position in world coordinates
	private Vector3D vVelocity = new Vector3D();	// velocity in world coordinates
	private Vector3D vVelocityBody = new Vector3D();		// velocity in body coordinates
	private Vector3D vAngularVelocity = new Vector3D();	// angular velocity in body coordinates

	private float fOrientation;			// orientation

	private Vector3D vForces = new Vector3D();			// total force on body
	private Vector3D vMoment = new Vector3D();			// total moment (torque) on body (2D: about z-axis only)

	private float driveThrust;			// Magnitude of the thrust force
	private Vector3D portThrust = new Vector3D();	// steering thruster forces
	private Vector3D starboardThrust = new Vector3D();

	private Vector3D centerOfDrag = new Vector3D();		// in body coordinates
	private Vector3D centerPortSteeringThruster = new Vector3D(-1, 1, 0);
	private Vector3D centerStarboardSteeringThruster = new Vector3D(1, 1, 0);

	private float fProjectedArea = 250;	// Projected area causes wind drag

	private Vector3D Fa = new Vector3D();					// other applied force
	private Vector3D Pa = new Vector3D();					// location of other applied force

	/** Create a rigid body. */
	public RigidBody2D() {
	}

	/** Reset all movement and force vectors. */
	public void reset() {
		vVelocity.reset();
		vVelocityBody.reset();
		vAngularVelocity.reset();
		fOrientation = 0;
		vForces.reset();
		vMoment.reset();
		driveThrust = 0;
		portThrust.reset();
		starboardThrust.reset();
		Fa.reset();
		Pa.reset();
	}

	/** Create a rigid body with an initial position. */
	public RigidBody2D(float x, float y) {
		setPosition(new Vector3D(x, y, 0));
	}

	/** Set body mass.  Default = 10 */
	public void setMass(float f) {
		fMass = f;
	}

	/** Get body mass. */
	public float getMass() {
		return fMass;
	}

	/** Set inertia.  Default = 10 */
	public void setInertia(float f) {
		fInertia = f;	// eg 10
	}

	/** Get inertia. */
	public float getInertia() {
		return fInertia;
	}

	/** Set projected (surface) area */
	public void setProjectedArea(float f) {
		fProjectedArea = f;
	}

	/** Get projected area */
	public float getProjectedArea() {
		return fProjectedArea;
	}

	/** Set position in world. */
	public void setPosition(Vector3D v) {
		vPosition = v;
	}

	/** Get position in world. */
	public Vector3D getPosition() {
		return vPosition;
	}

	/** Calculate loads, forces, all that physics stuff. */
	private void calcLoads() {
		Vector3D Fb = new Vector3D();			// stores the sum of forces
		Vector3D Mb = new Vector3D();			// stores the sum of moments
		Vector3D Thrust = new Vector3D();		// thrust vector

		// reset forces and moments:
		vForces.reset();
		vMoment.reset();

		// Define the thrust vector, which acts through the craft's CG
		Thrust = new Vector3D(0.0f, 1.0f, 0.0f);
		Thrust.multiply(driveThrust);

		// Calculate forces and moments in body space:
		// Calculate the aerodynamic drag force:
		// Calculate local velocity:
		// The local velocity includes the velocity due to linear motion of the craft,
		// plus the velocity at each element due to the rotation of the craft.
		Vector3D vLocalVelocity = Vector3D.add(vVelocityBody, Vector3D.crossProduct(vAngularVelocity, centerOfDrag));

		// Calculate local air speed
		float fLocalSpeed = vLocalVelocity.getMagnitude();

		// Find the direction in which drag will act.
		// Drag always acts in line with the relative velocity but in the opposing direction
		if (fLocalSpeed > Utility.nearZero)  {
			vLocalVelocity.normalise();
			Vector3D vDragVector = vLocalVelocity.conjugate();

			// Determine the resultant force on the element.
			double f;
			if (Vector3D.dotProduct(Thrust, vLocalVelocity) / (Thrust.getMagnitude() * vLocalVelocity.getMagnitude()) > 0)
				f = 2;
			else
				f = 1;

			float tmp = 0.5f * Utility.rho * fLocalSpeed * fLocalSpeed * fProjectedArea * (float)f;
			Vector3D vResultant = Vector3D.multiply(Vector3D.multiply(vDragVector, _LINEARDRAGCOEFFICIENT), tmp); // simulate fuselage drag

			// Keep a running total of these resultant forces (total force)
			Fb.add(vResultant);

			// Calculate the moment about the CG of this element's force
			// and keep a running total of these moments (total moment)
			Mb.add(Vector3D.crossProduct(centerOfDrag, vResultant));
		}

		// Calculate the Port & Starboard bow thruster forces:
		// Keep a running total of these resultant forces (total force)
		Fb.add(Vector3D.multiply(3, portThrust));

		// Calculate the moment about the CG of this element's force
		// and keep a running total of these moments (total moment)
		Mb.add(Vector3D.crossProduct(centerPortSteeringThruster, portThrust));

		// Keep a running total of these resultant forces (total force)
		Fb.add(Vector3D.multiply(3, starboardThrust));

		// Calculate the moment about the CG of this element's force
		// and keep a running total of these moments (total moment)
		Mb.add(Vector3D.crossProduct(centerStarboardSteeringThruster, starboardThrust));

		// do other applied forces here
		Fb.add(Fa);
		Mb.add(Vector3D.crossProduct(Pa, Fa));

		// Calculate rotational drag
		if (vAngularVelocity.getMagnitude() > Utility.nearZero) {
			Vector3D vtmp = new Vector3D();
			vtmp.setX(0);
			vtmp.setY(0);
			float tmp = 0.5f * Utility.rho * vAngularVelocity.getZ() * vAngularVelocity.getZ() * fProjectedArea;
			if (vAngularVelocity.getZ() > 0.0)
				vtmp.setZ(-_ANGULARDRAGCOEFFICIENT * tmp);
			else
				vtmp.setZ(_ANGULARDRAGCOEFFICIENT * tmp);
			Mb.add(vtmp);
		}

		// Now add the propulsion thrust
		Fb.add(Thrust); 	// no moment since line of action is through CG

		// Convert forces from model space to world space
		vForces = Vector3D.vRotate2D(fOrientation, Fb);
		vMoment.add(Mb);
	}

	/** Update body position given a relative change in time. */
	public void updateBodyEuler(double dt) {
		// Calculate forces and moments:
		calcLoads();

		// Integrate linear equation of motion:
		vVelocity.add(Vector3D.multiply(Vector3D.divide(vForces, fMass), (float)dt));
		vPosition.add(Vector3D.multiply(vVelocity, (float)dt));
		vAngularVelocity.setZ(vAngularVelocity.getZ() + vMoment.getZ() / fInertia * (float)dt);
		fOrientation += Utility.radiansToDegrees(vAngularVelocity.getZ() * (float)dt);
		// Misc. calculations:
		vVelocityBody = Vector3D.vRotate2D(-fOrientation, vVelocity);
	}

	/** Obtain velocity in world space. */
	public float getVelocity() {
		return vVelocity.getMagnitude();
	}

	/** Obtain velocity in world space as a vector. */
	public Vector3D getVelocityVector() {
		return vVelocity;
	}

	/** Obtain body orientation in degrees. */
	public float getOrientationInDegrees() {
		Vector3D v = new Vector3D(vVelocity);
		Vector3D v2 = Vector3D.multiply(v, 2);
		return (float)v.orientTo(v2);
	}

	/** Obtain position in world. */
	public float getX() {
		return vPosition.getX();
	}

	/** Obtain position in world. */
	public float getY() {
		return vPosition.getY();
	}

	public void setSteeringThrusters(boolean port, boolean starboard) {
		portThrust.setX(0);
		portThrust.setY(0);
		starboardThrust.setX(0);
		starboardThrust.setY(0);
		if (port)
			portThrust.setX(-_STEERINGFORCE);
		if (starboard)
			starboardThrust.setX(_STEERINGFORCE);
	}

	public void setThrust(boolean up) {
		driveThrust += up ? _DTHRUST : -_DTHRUST;
		if (driveThrust > _MAXTHRUST) driveThrust = _MAXTHRUST;
		if (driveThrust < _MINTHRUST) driveThrust = _MINTHRUST;
	}

	public void setThrust(float thrust) {
		driveThrust = thrust;
		if (driveThrust > _MAXTHRUST) driveThrust = _MAXTHRUST;
		if (driveThrust < _MINTHRUST) driveThrust = _MINTHRUST;
	}

	/** Set additional applied force. */
	public void setAppliedForce(Vector3D fA) {
		Fa = fA;
	}

	/** Get additional applied force. */
	public Vector3D getAppliedForce() {
		return Fa;
	}

	/** Set body position of additional applied force. */
	public void setAppliedForcePosition(Vector3D pA) {
		Pa = pA;
	}

	/** Get body position of additional applied force. */
	public Vector3D getAppliedForcePosition() {
		return Pa;
	}
}


text:
<!-- Explain the expected behaviour. -->

### Actual behaviour

<!-- Explain the actual behaviour. -->

### Steps to reproduce

<!-- If applicable, please include a minimum reproducable code sample. -->


text:
//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//

#include "pch.h"
#include <experimental\resumable>
#include <ppl.h>
#include <pplawait.h>
#include <ppltasks.h>

#include "MainPage.xaml.h"
#include "ExplorerPage.xaml.h"
#include "OneDriveService.h"
#include "FileOpen.h"

using namespace OneDriveAccess;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::Web::Http;
using namespace Windows::Data::Json;
using namespace concurrency;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

using namespace Windows::Security;

using namespace Windows::Storage::Pickers;
using namespace Windows::UI::Xaml::Media::Imaging;
using namespace Windows::Web::Http;

MainPage::MainPage()
{
	InitializeComponent();
}

void MainPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
	(void) e;	// Unused parameter

	// TODO: Prepare page for display here.

	// TODO: If your application contains multiple pages, ensure that you are
	// handling the hardware Back button by registering for the
	// Windows::Phone::UI::Input::HardwareButtons.BackPressed event.
	// If you are using the NavigationHelper provided by some templates,
	// this event is handled for you.
	UpdateSigninStatus();
	UpdateProgress();

}
void MainPage::UpdateSigninStatus()
{
	UserName->Text = L"";
	SignInOutButton->Content = L"Sign-in";

	OneDriveAccess::App^ app = safe_cast<OneDriveAccess::App^>(OneDriveAccess::App::Current);
	OneDriveAccess::OneDriveService^ service = app->GetOneDriveService();
	if (!service)
		return;

	UserName->Text = service->GetUserName();
	String^ token = service->GetAccessToken();
	if (token)
	{
		SignInOutButton->Content = L"Sign-out";
	}

}
void MainPage::UpdateProgress()
{
	ProgressRing->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
	ProgressRing->IsActive = false;

	OneDriveAccess::App^ app = safe_cast<OneDriveAccess::App^>(OneDriveAccess::App::Current);
	OneDriveAccess::OneDriveService^ service = app->GetOneDriveService();
	if (!service)
		return;

	if (service->IsBusy())
	{
		ProgressRing->Visibility = Windows::UI::Xaml::Visibility::Visible;
		ProgressRing->IsActive = true;
	}
}
void MainPage::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
	// Called when a page is no longer the active page in a frame.
	int a = 0;

}

void MainPage::LoginButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
	String^ token = nullptr;
	OneDriveAccess::App^ app = safe_cast<OneDriveAccess::App^>(OneDriveAccess::App::Current);
	OneDriveAccess::OneDriveService^ service = app->GetOneDriveService();

	if (!service)
		return;

	token = service->GetAccessToken();

	if (token)
	{
		service->SignOut();
	}
	else
	{
		service->SignIn();
	}

}

void MainPage::ExploreFoldersButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{

	OneDriveAccess::App^ app = safe_cast<OneDriveAccess::App^>(OneDriveAccess::App::Current);
	OneDriveAccess::OneDriveService^ service = app->GetOneDriveService();
	if (!service)
		return;

	String^ token = service->GetAccessToken();
	if (!token)
	{
		return;
	}
	service->RequestFolder(nullptr);
}


text:
#pragma once

#include <quic/QuicException.h>
#include <quic/congestion_control/CongestionControlFunctions.h>
#include <quic/congestion_control/CongestionController.h>
#include <quic/state/AckEvent.h>
#include <quic/state/StateData.h>

namespace quic {

constexpr float kCubicHystartPacingGain = 2.0f;
constexpr float kCubicRecoveryPacingGain = 1.25f;

enum class CubicStates : uint8_t {
  Hystart,
  Steady,
  FastRecovery,
};

/**
 *
 *  |--------|                              |-----|
 *  |      [Ack]                          [Ack]   |
 *  |        |                              |     |
 *  -->Hystart------------[Ack]---------->Cubic<--|
 *        |                                 |     |
 *        |                                 |     |
 *        |                ->[ACK/Loss]     |     |
 *        |                |     |          |     |
 *        |                |     |          |     |
 *        -[Loss]---->Fast Recovery<--[Loss]-     |
 *                             |                  |
 *                             |                  |
 *                             |                  |
 *                             |->-----[Ack]------|
 *
 */

class Cubic : public CongestionController {
 public:
  static constexpr uint64_t INIT_SSTHRESH =
      std::numeric_limits<uint64_t>::max();
  /**
   * initSsthresh:      the initial value of ssthresh
   * ssreduction:       how should cwnd be reduced when loss happens during slow
   *                    start
   * tcpFriendly:       if cubic cwnd calculation should be friendly to Reno TCP
   * spreadacrossRtt:   if the pacing bursts should be spread across RTT or all
   *                    close to the beginning of an RTT round
   */
  explicit Cubic(
      QuicConnectionStateBase& conn,
      uint64_t initCwndBytes = 0,
      uint64_t initSsthresh = INIT_SSTHRESH,
      bool tcpFriendly = true,
      bool ackTrain = false);

  CubicStates state() const noexcept;

  enum class ExitReason : uint8_t {
    SSTHRESH,
    EXITPOINT,
  };

  // if hybrid slow start exit point is found
  enum class HystartFound : uint8_t {
    No,
    FoundByAckTrainMethod,
    FoundByDelayIncreaseMethod
  };

  void onPacketAckOrLoss(
      const AckEvent* FOLLY_NULLABLE,
      const LossEvent* FOLLY_NULLABLE) override;
  void onPacketAckOrLoss(
      folly::Optional<AckEvent> ack,
      folly::Optional<LossEvent> loss) {
    onPacketAckOrLoss(ack.get_pointer(), loss.get_pointer());
  }
  void onRemoveBytesFromInflight(uint64_t) override;
  void onPacketSent(const OutstandingPacket& packet) override;

  uint64_t getWritableBytes() const noexcept override;
  uint64_t getCongestionWindow() const noexcept override;
  void setAppIdle(bool idle, TimePoint eventTime) noexcept override;
  void setAppLimited() override;

  void setBandwidthUtilizationFactor(
      float /*bandwidthUtilizationFactor*/) noexcept override {}

  bool isInBackgroundMode() const noexcept override {
    return false;
  }

  bool isAppLimited() const noexcept override;

  void getStats(CongestionControllerStats& stats) const override;

  void handoff(
      uint64_t newCwnd,
      uint64_t ssthresh = INIT_SSTHRESH,
      TimePoint lastReductionTime = Clock::now()) noexcept;

  CongestionControlType type() const noexcept override;

  void setExperimental(bool experimental) override {
    experimental_ = experimental;
  }

 protected:
  CubicStates state_{CubicStates::Hystart};

 private:
  bool isAppIdle() const noexcept;
  void onPacketAcked(const AckEvent& ack);
  void onPacketAckedInHystart(const AckEvent& ack);
  void onPacketAckedInSteady(const AckEvent& ack);
  void onPacketAckedInRecovery(const AckEvent& ack);

  void onPacketLoss(const LossEvent& loss);
  void onPacketLossInRecovery(const LossEvent& loss);
  void onPersistentCongestion();

  float pacingGain() const noexcept;

  void startHystartRttRound(TimePoint time) noexcept;

  void cubicReduction(TimePoint lossTime) noexcept;
  void updateTimeToOrigin() noexcept;
  int64_t calculateCubicCwndDelta(TimePoint timePoint) noexcept;
  uint64_t calculateCubicCwnd(int64_t delta) noexcept;

  bool isRecovered(TimePoint packetSentTime) noexcept;

  QuicConnectionStateBase& conn_;
  uint64_t cwndBytes_;
  // the value of cwndBytes_ at last loss event
  folly::Optional<uint64_t> lossCwndBytes_;
  // the value of ssthresh_ at the last loss event
  folly::Optional<uint64_t> lossSsthresh_;
  uint64_t ssthresh_;

  struct HystartState {
    // If AckTrain method will be used to exit SlowStart
    bool ackTrain{false};
    // If we are currently in a RTT round
    bool inRttRound{false};
    // If we have found the exit point
    HystartFound found{HystartFound::No};
    // The starting timestamp of a RTT round
    TimePoint roundStart;
    // Last timestamp when closed space Ack happens
    TimePoint lastJiffy;
    // The minimal of sampled RTT in current RTT round. Hystart only samples
    // first a few RTTs in a round
    folly::Optional<std::chrono::microseconds> currSampledRtt;
    // End value of currSampledRtt at the end of a RTT round:
    folly::Optional<std::chrono::microseconds> lastSampledRtt;
    // Estimated minimal delay of a path
    folly::Optional<std::chrono::microseconds> delayMin;
    // Ack sampling count
    uint8_t ackCount{0};
    // When a packet with sent time >= rttRoundEndTarget is acked, end the
    // current RTT round
    TimePoint rttRoundEndTarget;
  };

  struct SteadyState {
    // time takes for cwnd to increase to lastMaxCwndBytes
    double timeToOrigin{0.0};
    // The cwnd value that timeToOrigin is calculated based on
    folly::Optional<uint64_t> originPoint;
    bool tcpFriendly{true};
    folly::Optional<TimePoint> lastReductionTime;
    // This is Wmax, it could be different from lossCwndBytes if cwnd never
    // reaches last lastMaxCwndBytes before loss event:
    folly::Optional<uint64_t> lastMaxCwndBytes;
    uint64_t estRenoCwnd;
    // cache reduction/increase factors based on numEmulatedConnections_
    float reductionFactor{kDefaultCubicReductionFactor};
    float lastMaxReductionFactor{kDefaultLastMaxReductionFactor};
    float tcpEstimationIncreaseFactor{kCubicTCPFriendlyEstimateIncreaseFactor};
  };

  struct RecoveryState {
    // The time point after which Quic will no longer be in current recovery
    folly::Optional<TimePoint> endOfRecovery;
  };

  // if quiescenceStart_ has a value, then the connection is app limited
  folly::Optional<TimePoint> quiescenceStart_;

  HystartState hystartState_;
  SteadyState steadyState_;
  RecoveryState recoveryState_;
  bool experimental_{false};
};

folly::StringPiece cubicStateToString(CubicStates state);

} // namespace quic


text:
require_relative 'streaming'

module RubyTDMS
	class File < ::File
		include Streaming

		class << self
			def parse(filename)
				Document.new open(filename, 'rb')
			end
		end
	end
end


text:
"""Creates the virtual machine."""

COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'

def GenerateConfig(unused_context):
  """Creates the first virtual machine."""

  resources = [{
      'name': 'the-first-vm',
      'type': 'compute.v1.instance',
      'properties': {
          'zone': 'us-central1-f',
          'machineType': ''.join([COMPUTE_URL_BASE, 'projects/MY_PROJECT',
                                  '/zones/us-central1-f/',
                                  'machineTypes/f1-micro']),
          'disks': [{
              'deviceName': 'boot',
              'type': 'PERSISTENT',
              'boot': True,
              'autoDelete': True,
              'initializeParams': {
                  'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/',
                                          'debian-cloud/global/',
                                          'images/family/debian-11'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.a-new-network.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}


text:
'use strict';

function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }

var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');

var FlexWrap = function (_Declaration) {
    _inherits(FlexWrap, _Declaration);

    function FlexWrap() {
        _classCallCheck(this, FlexWrap);

        return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
    }

    /**
     * Don't add prefix for 2009 spec
     */
    FlexWrap.prototype.set = function set(decl, prefix) {
        var spec = flexSpec(prefix)[0];
        if (spec !== 2009) {
            return _Declaration.prototype.set.call(this, decl, prefix);
        }
        return undefined;
    };

    return FlexWrap;
}(Declaration);

Object.defineProperty(FlexWrap, 'names', {
    enumerable: true,
    writable: true,
    value: ['flex-wrap']
});

module.exports = FlexWrap;


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.cango.palmcartreasure.customview.SateLliteMenu
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#ccc"
        app:exampleColor="#33b5e5"
        app:exampleDimension="24sp"
        app:exampleDrawable="@android:drawable/ic_menu_add"
        app:exampleString="Hello, SateLliteMenu" />

</FrameLayout>


text:
import { expect } from 'chai';
import { sharethroughAdapterSpec, sharethroughInternal } from 'modules/sharethroughBidAdapter';
import { newBidder } from 'src/adapters/bidderFactory';

const spec = newBidder(sharethroughAdapterSpec).getSpec();
const bidRequests = [
  {
    bidder: 'sharethrough',
    bidId: 'bidId1',
    sizes: [[600, 300]],
    placementCode: 'foo',
    params: {
      pkey: 'aaaa1111'
    },
    userId: { tdid: 'fake-tdid' }
  },
  {
    bidder: 'sharethrough',
    bidId: 'bidId2',
    sizes: [[700, 400]],
    placementCode: 'bar',
    params: {
      pkey: 'bbbb2222',
      iframe: true
    }
  },
  {
    bidder: 'sharethrough',
    bidId: 'bidId3',
    sizes: [[700, 400]],
    placementCode: 'coconut',
    params: {
      pkey: 'cccc3333',
      iframe: true,
      iframeSize: [500, 500]
    },
  },
];

const prebidRequests = [
  {
    method: 'GET',
    url: document.location.protocol + '//btlr.sharethrough.com' + '/WYu2BXv1/v1',
    data: {
      bidId: 'bidId',
      placement_key: 'pKey'
    },
    strData: {
      skipIframeBusting: false,
      sizes: []
    }
  },
  {
    method: 'GET',
    url: document.location.protocol + '//btlr.sharethrough.com' + '/WYu2BXv1/v1',
    data: {
      bidId: 'bidId',
      placement_key: 'pKey'
    },
    strData: {
      skipIframeBusting: true,
      sizes: [[300, 250], [300, 300], [250, 250], [600, 50]]
    }
  },
  {
    method: 'GET',
    url: document.location.protocol + '//btlr.sharethrough.com' + '/WYu2BXv1/v1',
    data: {
      bidId: 'bidId',
      placement_key: 'pKey'
    },
    strData: {
      skipIframeBusting: true,
      iframeSize: [500, 500],
      sizes: [[300, 250], [300, 300], [250, 250], [600, 50]]
    }
  },
  {
    method: 'GET',
    url: document.location.protocol + '//btlr.sharethrough.com' + '/WYu2BXv1/v1',
    data: {
      bidId: 'bidId',
      placement_key: 'pKey'
    },
    strData: {
      skipIframeBusting: false,
      sizes: [[0, 0]]
    }
  },
  {
    method: 'GET',
    url: document.location.protocol + '//btlr.sharethrough.com' + '/WYu2BXv1/v1',
    data: {
      bidId: 'bidId',
      placement_key: 'pKey'
    },
    strData: {
      skipIframeBusting: false,
      sizes: [[300, 250], [300, 300], [250, 250], [600, 50]]
    }
  },
];

const bidderResponse = {
  body: {
    'adserverRequestId': '40b6afd5-6134-4fbb-850a-bb8972a46994',
    'bidId': 'bidId1',
    'version': 1,
    'creatives': [{
      'auctionWinId': 'b2882d5e-bf8b-44da-a91c-0c11287b8051',
      'cpm': 12.34,
      'creative': {
        'deal_id': 'aDealId',
        'creative_key': 'aCreativeId',
        'title': '✓ à la mode'
      }
    }],
    'stxUserId': ''
  },
  header: { get: (header) => header }
};

const setUserAgent = (str) => {
  window.navigator['__defineGetter__']('userAgent', function () {
    return str;
  });
};

describe('sharethrough internal spec', function () {
  let windowSpy, windowTopSpy;

  beforeEach(function() {
    windowSpy = sinon.spy(window.document, 'getElementsByTagName');
    windowTopSpy = sinon.spy(window.top.document, 'getElementsByTagName');
  });

  afterEach(function() {
    windowSpy.restore();
    windowTopSpy.restore();
    window.STR = undefined;
    window.top.STR = undefined;
  });

  describe('we cannot access top level document', function () {
    beforeEach(function() {
      window.lockedInFrame = true;
    });

    afterEach(function() {
      window.lockedInFrame = false;
    });

    it('appends sfp.js to the safeframe', function () {
      sharethroughInternal.handleIframe();
      expect(windowSpy.calledOnce).to.be.true;
    });

    it('does not append anything if sfp.js is already loaded in the safeframe', function () {
      window.STR = { Tag: true };
      sharethroughInternal.handleIframe();
      expect(windowSpy.notCalled).to.be.true;
      expect(windowTopSpy.notCalled).to.be.true;
    });
  });

  describe('we are able to bust out of the iframe', function () {
    it('appends sfp.js to window.top', function () {
      sharethroughInternal.handleIframe();
      expect(windowSpy.calledOnce).to.be.true;
      expect(windowTopSpy.calledOnce).to.be.true;
    });

    it('only appends sfp-set-targeting.js if sfp.js is already loaded on the page', function () {
      window.top.STR = { Tag: true };
      sharethroughInternal.handleIframe();
      expect(windowSpy.calledOnce).to.be.true;
      expect(windowTopSpy.notCalled).to.be.true;
    });
  });
});

describe('sharethrough adapter spec', function () {
  describe('.code', function () {
    it('should return a bidder code of sharethrough', function () {
      expect(spec.code).to.eql('sharethrough');
    });
  });

  describe('.isBidRequestValid', function () {
    it('should return false if req has no pkey', function () {
      const invalidBidRequest = {
        bidder: 'sharethrough',
        params: {
          notPKey: 'abc123'
        }
      };
      expect(spec.isBidRequestValid(invalidBidRequest)).to.eql(false);
    });

    it('should return false if req has wrong bidder code', function () {
      const invalidBidRequest = {
        bidder: 'notSharethrough',
        params: {
          notPKey: 'abc123'
        }
      };
      expect(spec.isBidRequestValid(invalidBidRequest)).to.eql(false);
    });

    it('should return true if req is correct', function () {
      expect(spec.isBidRequestValid(bidRequests[0])).to.eq(true);
      expect(spec.isBidRequestValid(bidRequests[1])).to.eq(true);
    })
  });

  describe('.buildRequests', function () {
    it('should return an array of requests', function () {
      const builtBidRequests = spec.buildRequests(bidRequests);

      expect(builtBidRequests[0].url).to.eq(
        'http://btlr.sharethrough.com/WYu2BXv1/v1');
      expect(builtBidRequests[1].url).to.eq(
        'http://btlr.sharethrough.com/WYu2BXv1/v1');
      expect(builtBidRequests[0].method).to.eq('GET');
    });

    it('should set the instant_play_capable parameter correctly based on browser userAgent string', function () {
      setUserAgent('Android Chrome/60');
      let builtBidRequests = spec.buildRequests(bidRequests);
      expect(builtBidRequests[0].data.instant_play_capable).to.be.true;

      setUserAgent('iPhone Version/11');
      builtBidRequests = spec.buildRequests(bidRequests);
      expect(builtBidRequests[0].data.instant_play_capable).to.be.true;

      setUserAgent('iPhone CriOS/60');
      builtBidRequests = spec.buildRequests(bidRequests);
      expect(builtBidRequests[0].data.instant_play_capable).to.be.true;

      setUserAgent('Android Chrome/50');
      builtBidRequests = spec.buildRequests(bidRequests);
      expect(builtBidRequests[0].data.instant_play_capable).to.be.false;

      setUserAgent('Android Chrome');
      builtBidRequests = spec.buildRequests(bidRequests);
      expect(builtBidRequests[0].data.instant_play_capable).to.be.false;

      setUserAgent(undefined);
      builtBidRequests = spec.buildRequests(bidRequests);
      expect(builtBidRequests[0].data.instant_play_capable).to.be.false;
    });

    it('should add consent parameters if gdprConsent is present', function () {
      const gdprConsent = { consentString: 'consent_string123', gdprApplies: true };
      const bidderRequest = { gdprConsent: gdprConsent };
      const bidRequest = spec.buildRequests(bidRequests, bidderRequest)[0];
      expect(bidRequest.data.consent_required).to.eq(true);
      expect(bidRequest.data.consent_string).to.eq('consent_string123');
    });

    it('should handle gdprConsent is present but values are undefined case', function () {
      const gdprConsent = { consent_string: undefined, gdprApplies: undefined };
      const bidderRequest = { gdprConsent: gdprConsent };
      const bidRequest = spec.buildRequests(bidRequests, bidderRequest)[0];
      expect(bidRequest.data).to.not.include.any.keys('consent_string')
    });

    it('should add the ttduid parameter if a bid request contains a value for Unified ID from The Trade Desk', function () {
      const bidRequest = spec.buildRequests(bidRequests)[0];
      expect(bidRequest.data.ttduid).to.eq('fake-tdid');
    });

    it('should add Sharethrough specific parameters', function () {
      const builtBidRequests = spec.buildRequests(bidRequests);
      expect(builtBidRequests[0]).to.deep.include({
        strData: {
          skipIframeBusting: undefined,
          iframeSize: undefined,
          sizes: [[600, 300]]
        }
      });
    });

    it('should add a supply chain parameter if schain is present', function() {
      // shallow copy of the first bidRequest obj, so we don't mutate
      const bidRequest = Object.assign({}, bidRequests[0]);
      bidRequest['schain'] = {
        ver: '1.0',
        complete: 1,
        nodes: [
          {
            asi: 'directseller.com',
            sid: '00001',
            rid: 'BidRequest1',
            hp: 1
          }
        ]
      };

      const builtBidRequest = spec.buildRequests([bidRequest])[0];
      expect(builtBidRequest.data.schain).to.eq(JSON.stringify(bidRequest.schain));
    });

    it('should not add a supply chain parameter if schain is missing', function() {
      const bidRequest = spec.buildRequests(bidRequests)[0];
      expect(bidRequest.data).to.not.include.any.keys('schain');
    });

    it('should include the bidfloor parameter if it is present in the bid request', function() {
      const bidRequest = Object.assign({}, bidRequests[0]);
      bidRequest['bidfloor'] = 0.50;
      const builtBidRequest = spec.buildRequests([bidRequest])[0];
      expect(builtBidRequest.data.bidfloor).to.eq(0.5);
    });

    it('should not include the bidfloor parameter if it is missing in the bid request', function() {
      const bidRequest = Object.assign({}, bidRequests[0]);
      const builtBidRequest = spec.buildRequests([bidRequest])[0];
      expect(builtBidRequest.data).to.not.include.any.keys('bidfloor');
    });
  });

  describe('.interpretResponse', function () {
    it('returns a correctly parsed out response', function () {
      expect(spec.interpretResponse(bidderResponse, prebidRequests[0])[0]).to.include(
        {
          width: 1,
          height: 1,
          cpm: 12.34,
          creativeId: 'aCreativeId',
          dealId: 'aDealId',
          currency: 'USD',
          netRevenue: true,
          ttl: 360,
        });
    });

    it('returns a correctly parsed out response with largest size when strData.skipIframeBusting is true', function () {
      expect(spec.interpretResponse(bidderResponse, prebidRequests[1])[0]).to.include(
        {
          width: 300,
          height: 300,
          cpm: 12.34,
          creativeId: 'aCreativeId',
          dealId: 'aDealId',
          currency: 'USD',
          netRevenue: true,
          ttl: 360,
        });
    });

    it('returns a correctly parsed out response with explicitly defined size when strData.skipIframeBusting is true and strData.iframeSize is provided', function () {
      expect(spec.interpretResponse(bidderResponse, prebidRequests[2])[0]).to.include(
        {
          width: 500,
          height: 500,
          cpm: 12.34,
          creativeId: 'aCreativeId',
          dealId: 'aDealId',
          currency: 'USD',
          netRevenue: true,
          ttl: 360,
        });
    });

    it('returns a correctly parsed out response with explicitly defined size when strData.skipIframeBusting is false and strData.sizes contains [0, 0] only', function () {
      expect(spec.interpretResponse(bidderResponse, prebidRequests[3])[0]).to.include(
        {
          width: 0,
          height: 0,
          cpm: 12.34,
          creativeId: 'aCreativeId',
          dealId: 'aDealId',
          currency: 'USD',
          netRevenue: true,
          ttl: 360,
        });
    });

    it('returns a correctly parsed out response with explicitly defined size when strData.skipIframeBusting is false and strData.sizes contains multiple sizes', function () {
      expect(spec.interpretResponse(bidderResponse, prebidRequests[4])[0]).to.include(
        {
          width: 300,
          height: 300,
          cpm: 12.34,
          creativeId: 'aCreativeId',
          dealId: 'aDealId',
          currency: 'USD',
          netRevenue: true,
          ttl: 360,
        });
    });

    it('returns a blank array if there are no creatives', function () {
      const bidResponse = { body: { creatives: [] } };
      expect(spec.interpretResponse(bidResponse, prebidRequests[0])).to.be.an('array').that.is.empty;
    });

    it('returns a blank array if body object is empty', function () {
      const bidResponse = { body: {} };
      expect(spec.interpretResponse(bidResponse, prebidRequests[0])).to.be.an('array').that.is.empty;
    });

    it('returns a blank array if body is null', function () {
      const bidResponse = { body: null };
      expect(spec.interpretResponse(bidResponse, prebidRequests[0])).to.be.an('array').that.is.empty;
    });

    it('correctly generates ad markup when skipIframeBusting is false', function () {
      const adMarkup = spec.interpretResponse(bidderResponse, prebidRequests[0])[0].ad;
      let resp = null;

      expect(() => btoa(JSON.stringify(bidderResponse))).to.throw();
      expect(() => resp = sharethroughInternal.b64EncodeUnicode(JSON.stringify(bidderResponse))).not.to.throw();
      expect(adMarkup).to.match(
        /data-str-native-key="pKey" data-stx-response-name=\"str_response_bidId\"/);
      expect(!!adMarkup.indexOf(resp)).to.eql(true);

      // insert functionality to autodetect whether or not in safeframe, and handle JS insertion
      expect(adMarkup).to.match(/isLockedInFrame/);
      expect(adMarkup).to.match(/handleIframe/);
    });

    it('correctly generates ad markup when skipIframeBusting is true', function () {
      const adMarkup = spec.interpretResponse(bidderResponse, prebidRequests[1])[0].ad;
      let resp = null;

      expect(() => btoa(JSON.stringify(bidderResponse))).to.throw();
      expect(() => resp = sharethroughInternal.b64EncodeUnicode(JSON.stringify(bidderResponse))).not.to.throw();
      expect(adMarkup).to.match(
        /data-str-native-key="pKey" data-stx-response-name=\"str_response_bidId\"/);
      expect(!!adMarkup.indexOf(resp)).to.eql(true);
      expect(adMarkup).to.match(
        /<script src="\/\/native.sharethrough.com\/assets\/sfp.js"><\/script>/);
    });
  });

  describe('.getUserSyncs', function () {
    const cookieSyncs = ['cookieUrl1', 'cookieUrl2', 'cookieUrl3'];
    const serverResponses = [{ body: { cookieSyncUrls: cookieSyncs } }];

    it('returns an array of correctly formatted user syncs', function () {
      const syncArray = spec.getUserSyncs({ pixelEnabled: true }, serverResponses);
      expect(syncArray).to.deep.equal([
        { type: 'image', url: 'cookieUrl1' },
        { type: 'image', url: 'cookieUrl2' },
        { type: 'image', url: 'cookieUrl3' }]
      );
    });

    it('returns an empty array if serverResponses is empty', function () {
      const syncArray = spec.getUserSyncs({ pixelEnabled: true }, []);
      expect(syncArray).to.be.an('array').that.is.empty;
    });

    it('returns an empty array if the body is null', function () {
      const syncArray = spec.getUserSyncs({ pixelEnabled: true }, [{ body: null }]);
      expect(syncArray).to.be.an('array').that.is.empty;
    });

    it('returns an empty array if the body.cookieSyncUrls is missing', function () {
      const syncArray = spec.getUserSyncs({ pixelEnabled: true }, [{ body: { creatives: ['creative'] } }]);
      expect(syncArray).to.be.an('array').that.is.empty;
    });

    it('returns an empty array if pixels are not enabled', function () {
      const syncArray = spec.getUserSyncs({ pixelEnabled: false }, serverResponses);
      expect(syncArray).to.be.an('array').that.is.empty;
    });
  });
});


text:
{# addon, version, request #}

      {{ _('Version {0}', 'addon_display_header_version')|f(version.version) }}

        <time datetime="{{ version.created|isotime }}">
          {# L10n: {0} is a timestamp, such as September 28, 2011. #}
          {{ _('Released {0}')|f(version.created|datetime) }}
        </time>
        {% if version.has_files %}

            {{ version.all_files[0].size|filesizeformat }}

        {% endif %}

      {% if version.compatible_apps %}

          {# L10n: This refers to this version's compatible applications, such as Firefox 8.0 #}
          {{ _('Works with') }}
          {% for app, compat in version.compatible_apps_ordered -%}
            {% if not loop.first %}, {% endif %}
            {{ compat }}
          {%- endfor %}

      {% endif %}

      {{ version.releasenotes|nl2br }}

    {% if version.license %}
      {% set license = version.license %}

          {% if license.url %}
            {% trans url = license.url,
                     name = license.name if license.builtin else _('Custom License') %}
              Source code released under {{ name }}
            {% endtrans %}
          {% else %}
            {% trans url = version.license_url(),
                     name = license.name if license.builtin else _('Custom License') %}
              Source code released under {{ name }}
            {% endtrans %}
          {% endif %}

            {{ _("What's this?", 'addons_display_a_license_what') }}

    {% endif %}
    {% if addon.view_source and version.has_files and
          addon.status in amo.REVIEWED_STATUSES %}

          {{ _('View the source') }}

    {% endif %}

    {{ install_button(addon, version=version, impala=impala) }}


text:
package org.parboiled.scala
package testing

import util.DynamicVariable
import org.parboiled.support.ParseTreeUtils
import org.parboiled.errors.{ParseError, ErrorUtils}
import org.parboiled.Node

/**
 * A trait simplifying the creation of tests for "parboiled for scala" parsers.
 * It can be mixed into any test class that defines a fail(string) method (e.g. all the scalatest Suites).
 */
trait ParboiledTest {
  this: {def fail(msg: String)(implicit pos: org.scalactic.source.Position): Nothing} =>

  /**
   * The type of the root value object created by the parser.
   */
  type Result

  protected val pResult = new DynamicVariable[ParsingResult[_ <: Result]](null)
  protected val pRunner = new DynamicVariable[ParseRunner[_ <: Result]](null)

  /**
   * Runs the given parse runner against the given input and executes the given block upon a successful parsing run.
   * If the parsing run is not successful, i.e. the input did not match the grammar, the test fails will a respective
   * error message.
   */
  def parse(runner: ParseRunner[_ <: Result], input: Input)(f: => Unit): Unit = {
    pRunner.withValue(runner) {
      val res = runner.run(input)
      if (!res.matched) {
        fail(ErrorUtils.printParseErrors(res))
      }
      pResult.withValue(res)(f)
    }
  }

  /**
   * Runs the given parse runner against the given input and executes the given block upon an UNSUCCESSFUL parsing run.
   * If the parsing run is successful, i.e. the input did match the grammar, the test fails will a respective
   * error message.
   */
  def failParse(runner: ParseRunner[_ <: Result], input: Input)(f: => Unit): Unit = {
    pRunner.withValue(runner) {
      val res = runner.run(input)
      if (res.matched) {
        fail("Test unexpectedly succeeded")
      }
      pResult.withValue(res)(f)
    }
  }

  def parsingResult: ParsingResult[Result] = pResult.value

  def matched: Boolean = parsingResult.matched

  def result: Option[Result] = parsingResult.result

  def parseErrors: List[ParseError] = parsingResult.parseErrors

  def parseTreeRoot: Node[Result] = parsingResult.parseTreeRoot

  def errors: String = ErrorUtils.printParseErrors(parsingResult)

  def parseTree: String = ParseTreeUtils.printNodeTree(parsingResult)
}


text:
package com.thinkaurelius.titan.blueprints;

import com.thinkaurelius.titan.graphdb.blueprints.TitanBlueprintsGraph;
import com.tinkerpop.blueprints.*;
import com.tinkerpop.blueprints.impls.GraphTest;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * (c) Matthias Broecheler (me@matthiasb.com)
 */

public class TransactionalTitanGraphTestSuite extends TransactionalGraphTestSuite {

    public TransactionalTitanGraphTestSuite(final GraphTest graphTest) {
        super(graphTest);
    }

    @Override
    public void testCompetingThreads() {
        TitanBlueprintsGraph graph = (TitanBlueprintsGraph) graphTest.generateGraph();
        //Need to define types before hand to avoid deadlock in transactions

        graph.makeType().name("friend").makeEdgeLabel();
        graph.makeType().name("test").dataType(Long.class).makePropertyKey();
        graph.makeType().name("blah").dataType(Float.class).makePropertyKey();
        graph.makeType().name("bloop").dataType(Integer.class).makePropertyKey();

        graph.stopTransaction(TransactionalGraph.Conclusion.SUCCESS);
        graph.shutdown();
        super.testCompetingThreads();
    }

}


text:
#!/usr/bin/env python
from __future__ import unicode_literals, print_function

import sys, os

import pybindgen
from pybindgen import typehandlers
from pybindgen.typehandlers import codesink
from pybindgen.typehandlers.base import Parameter, ReturnValue
from pybindgen.function import Function
from pybindgen.module import Module
from pybindgen import cppclass
from pybindgen.typehandlers.base import NotSupportedError

import pybindgen.settings
pybindgen.settings.deprecated_virtuals = False

import re

stdint_rx = re.compile(".*int\\d+_t.*")

class MyReverseWrapper(typehandlers.base.ReverseWrapperBase):
    def generate_python_call(self):
        params = ['NULL'] # function object to call
        build_params = self.build_params.get_parameters()
        if build_params[0][0] == '"':
            build_params[0] = '(char *) ' + build_params[0]
        params.extend(build_params)
        self.before_call.write_code('py_retval = PyObject_CallFunction(%s);' % (', '.join(params),))
        self.before_call.write_error_check('py_retval == NULL')
        self.before_call.add_cleanup_code('Py_DECREF(py_retval);')

def type_blacklisted(type_name):
    if type_name.startswith('Glib::'):
        return True
    return False

def test():
    code_out = codesink.FileCodeSink(sys.stdout)
    pybindgen.write_preamble(code_out)
    sys.stdout.write("""
#include <string>
#include <stdint.h>
""")
    ## Declare a dummy class
    sys.stdout.write('''
class Foo
{
    std::string m_datum;
public:
    Foo () : m_datum ("")
        {}
    Foo (std::string datum) : m_datum (datum)
        {}
    std::string get_datum () const { return m_datum; }

    Foo (Foo const & other) : m_datum (other.get_datum ())
        {}
};
''')

    module = Module("foo")

    ## Register type handlers for the class
    Foo = module.add_class('Foo')
    Foo.add_constructor([Parameter.new("const Foo&", "foo")])
    #Foo.full_name = Foo.name # normally adding the class to a module would take care of this
    Foo.generate_forward_declarations(code_out, module)

    wrapper_number = 0

    ## test return type handlers of reverse wrappers
    for return_type, return_handler in list(typehandlers.base.return_type_matcher.items()):
        if type_blacklisted(return_type):
            continue
        if os.name == 'nt':
            if stdint_rx.search(return_type):
                continue # win32 does not support the u?int\d+_t types (defined in <stdint.h>)

        code_out.writeln("/* Test %s (%s) return type  */" % (return_type, return_handler))
        if issubclass(return_handler, (cppclass.CppClassPtrReturnValue,
                                       typehandlers.pyobjecttype.PyObjectReturnValue)):
            for caller_owns_return in True, False:
                retval = return_handler(return_type, caller_owns_return=caller_owns_return)
                wrapper = MyReverseWrapper(retval, [])
                wrapper_number += 1
                try:
                    wrapper.generate(code_out,
                                     '_test_wrapper_number_%i' % (wrapper_number,),
                                     ['static'])
                except NotImplementedError:
                    sys.stderr.write("ReverseWrapper %s(void) (caller_owns_return=%r)"
                                     " could not be generated: not implemented\n"
                                     % (retval.ctype, caller_owns_return))
                sys.stdout.write("\n")
        else:
            retval = return_handler(return_type)
            try:
                wrapper = MyReverseWrapper(retval, [])
            except NotSupportedError:
                continue
            except NotImplementedError:
                sys.stderr.write("ReverseWrapper %s(void) could not be generated: not implemented\n"
                                 % (retval.ctype))
                continue
            wrapper_number += 1
            memsink = codesink.MemoryCodeSink()
            try:
                wrapper.generate(memsink,
                                 '_test_wrapper_number_%i' % (wrapper_number,),
                                 ['static'])
            except NotImplementedError:
                sys.stderr.write("ReverseWrapper %s xxx (void) could not be generated: not implemented\n"
                                 % (retval.ctype,))
                continue
            except NotSupportedError:
                continue
            else:
                memsink.flush_to(code_out)
            sys.stdout.write("\n")

    ## test parameter type handlers of reverse wrappers
    for param_type, param_handler in list(typehandlers.base.param_type_matcher.items()):
        if type_blacklisted(param_type):
            continue
        if os.name == 'nt':
            if stdint_rx.search(param_type):
                continue # win32 does not support the u?int\d+_t types (defined in <stdint.h>)
        for direction in param_handler.DIRECTIONS:
            if direction == (Parameter.DIRECTION_IN):
                param_name = 'param'
            elif direction == (Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT):
                param_name = 'param_inout'
            elif direction == (Parameter.DIRECTION_OUT):
                param_name = 'param_out'

                def try_wrapper(param, wrapper_number):
                    if 'const' in param.ctype and direction&Parameter.DIRECTION_OUT:
                        return
                    code_out.writeln("/* Test %s (%s) param type  */" % (param_type, param_handler))
                    wrapper = MyReverseWrapper(ReturnValue.new('void'), [param])
                    try:
                        wrapper.generate(code_out,
                                         '_test_wrapper_number_%i' % (wrapper_number,),
                                         ['static'])
                    except NotImplementedError:
                        sys.stderr.write("ReverseWrapper void(%s) could not be generated: not implemented"
                                         % (param.ctype))
                    sys.stdout.write("\n")

                if issubclass(param_handler, (cppclass.CppClassPtrParameter,
                                              typehandlers.pyobjecttype.PyObjectParam)):
                    for transfer_ownership in True, False:
                        try:
                            param = param_handler(param_type, param_name, transfer_ownership=transfer_ownership)
                        except TypeError:
                            sys.stderr.write("ERROR -----> param_handler(param_type=%r, "
                                             "transfer_ownership=%r, is_const=%r)\n"
                                             % (param_type, transfer_ownership, is_const))
                        wrapper_number += 1
                        try_wrapper(param, wrapper_number)
                else:
                    param = param_handler(param_type, param_name, direction)
                    wrapper_number += 1
                    try_wrapper(param, wrapper_number)

    ## test generic forward wrappers, and module

    for return_type, return_handler in list(typehandlers.base.return_type_matcher.items()):
        if type_blacklisted(return_type):
            continue
        if os.name == 'nt':
            if stdint_rx.search(return_type):
                continue # win32 does not support the u?int\d+_t types (defined in <stdint.h>)
        wrapper_number += 1
        function_name = 'foo_function_%i' % (wrapper_number,)
        ## declare a fake prototype
        sys.stdout.write("%s %s(void);\n\n" % (return_type, function_name))

        if issubclass(return_handler, (cppclass.CppClassPtrReturnValue,
                                       typehandlers.pyobjecttype.PyObjectReturnValue)):
            retval = return_handler(return_type, caller_owns_return=True)
        else:
            retval = return_handler(return_type)

        module.add_function(function_name, retval, [])

    for param_type, param_handler in list(typehandlers.base.param_type_matcher.items()):
        if type_blacklisted(param_type):
            continue
        if os.name == 'nt':
            if stdint_rx.search(param_type):
                continue # win32 does not support the u?int\d+_t types (defined in <stdint.h>)

        for is_const in [True, False]:
            for direction in param_handler.DIRECTIONS:
                if direction == (Parameter.DIRECTION_IN):
                    param_name = 'param'
                elif direction == (Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT):
                    param_name = 'param_inout'
                elif direction == (Parameter.DIRECTION_OUT):
                    param_name = 'param_out'

                if is_const and direction & Parameter.DIRECTION_OUT:
                    continue # const and output parameter makes no sense

                if is_const:
                    if '&' in param_type: # const references not allowed
                        continue
                    param_type_with_const = "const %s" % (param_type,)
                else:
                    param_type_with_const = param_type

                if issubclass(param_handler, (cppclass.CppClassPtrParameter,
                                              typehandlers.pyobjecttype.PyObjectParam)):
                    for transfer_ownership in True, False:
                        name = param_name + (transfer_ownership and '_transfer' or '_notransfer')
                        try:
                            param = param_handler(param_type, name, transfer_ownership=transfer_ownership)
                        except TypeError:
                            sys.stderr.write("ERROR -----> param_handler(param_type=%r, "
                                             "name=%r, transfer_ownership=%r, is_const=%r)\n"
                                             % (param_type, name, transfer_ownership, is_const))
                        wrapper_number += 1
                        function_name = 'foo_function_%i' % (wrapper_number,)
                        ## declare a fake prototype
                        sys.stdout.write("void %s(%s %s);\n\n" % (function_name, param_type_with_const, name))
                        module.add_function(function_name, ReturnValue.new('void'), [param])
                else:
                    param = param_handler(param_type, param_name, direction)
                    wrapper_number += 1
                    function_name = 'foo_function_%i' % (wrapper_number,)
                    ## declare a fake prototype
                    sys.stdout.write("void %s(%s);\n\n" % (function_name, param_type_with_const))
                    module.add_function(function_name, ReturnValue.new('void'), [param])

    module.generate(code_out)

if __name__ == '__main__':
    test()


text:
[See html formatted version](https://huasofoundries.github.io/google-maps-documentation/Data.StylingFunction.html)

Data.StylingFunction typedef
----------------------------

google.maps.Data.StylingFunction typedef

A function that computes the appearance of a feature.

The Data.setStyle() method can accept a styling function. Use this when features should appear differently depending on their properties. You can find more information about styling features in the [developer's guide](https://developers.google.com/maps/documentation/javascript/datalayer#style_geojson_data).

function([Data.Feature](Data.Feature.md)): [Data.StyleOptions](Data.StyleOptions.md)


text:
package com.laytonsmith.abstraction.enums.bukkit;

import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.abstraction.enums.EnumConvertor;
import com.laytonsmith.abstraction.enums.MCTargetReason;
import com.laytonsmith.annotations.abstractionenum;
import org.bukkit.event.entity.EntityTargetEvent.TargetReason;

/**
 *
 *
 */
@abstractionenum(
		implementation = Implementation.Type.BUKKIT,
forAbstractEnum = MCTargetReason.class,
forConcreteEnum = TargetReason.class)
public class BukkitMCTargetReason extends EnumConvertor<MCTargetReason, TargetReason> {
	private static com.laytonsmith.abstraction.enums.bukkit.BukkitMCTargetReason instance;

	public static com.laytonsmith.abstraction.enums.bukkit.BukkitMCTargetReason getConvertor() {
		if (instance == null) {
			instance = new com.laytonsmith.abstraction.enums.bukkit.BukkitMCTargetReason();
		}
		return instance;
	}
}


text:
#ifndef _SF_INTERNAL_JOINING_TYPE_H
#define _SF_INTERNAL_JOINING_TYPE_H

#include "SFBase.h"

enum {
    SFJoiningTypeNil = 0x00,
    SFJoiningTypeU   = 0x01, /**< Non Joining */
    SFJoiningTypeL   = 0x02, /**< Left Joining */
    SFJoiningTypeR   = 0x03, /**< Right Joining */
    SFJoiningTypeD   = 0x04, /**< Dual Joining */
    SFJoiningTypeC   = 0x05, /**< Join Causing */
    SFJoiningTypeT   = 0x06, /**< Transparent */
    SFJoiningTypeF   = 0x07  /**< Unavailable */
};
typedef SFUInt8 SFJoiningType;

#endif


text:
// This software is part of OpenMono, see http://developer.openmono.com
// Released under the MIT license, see LICENSE.txt

#ifndef on_off_button_view_h
#define on_off_button_view_h

#include <abstract_button_view.h>
#include <text_label_view.h>

namespace mono { namespace ui {

    class OnOffButtonView : public AbstractButtonView
    {
    protected:
        bool state;

        display::Color backgroundColor, borderColor, enabledColor, highlightColor;

        TextLabelView onLbl, offLbl;

        uint16_t buttonSeparation;

        virtual void touchEnd(TouchEvent &event);

    public:

        /**
         *
         *
         */
        OnOffButtonView();

        /**
         *
         *
         */
        OnOffButtonView(geo::Rect rct);

        /**
         *
         *
         */
        void setBackground(display::Color c);

        /**
         *
         *
         */
        void setBorder(display::Color c);

        /**
         *
         *
         */
        void setHighlight(display::Color c);

        void setState(bool on, bool fireClickHandler = false);

        display::Color BackgroundColor() const;

        display::Color HighlightColor() const;

        display::Color BorderColor() const;

        bool isActive() const;

        void repaint();
    };

} }

#endif /* on_off_button_view_h */


text:
var request = require('request');
function getWeather(location){
  return new Promise( function (resolve, reject){
    var endocdedLocation = encodeURIComponent(location);
    var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + endocdedLocation + '&appid=2de143494c0b295cca9337e1e96b00e0&units=imperial';

    if(!location){
      return reject('No location provided!');
    }

    request({
      url: url,
      json: true,
    }, function (error, response, body){
      if(error){
        reject('Unable to fetch weather...Sorry I failed you');
      }else {
        resolve('It\'s ' + body.main.temp + 'F in ' + body.name + '!');
      }
    });
  });
}

getWeather('san francisco').then(function(currentWeather){
  console.log(currentWeather);
}, function(error){
  console.log(error);
});


text:
package unimelb.mf.client.util;

import java.util.logging.Logger;

import arc.xml.XmlStringWriter;
import unimelb.mf.client.session.MFSession;

public class AssetNamespaceUtils {

    public static void createAssetNamespace(MFSession session, String ns, Logger logger) throws Throwable {
        if (!assetNamespaceExists(session, ns)) {
            try {
                if (logger != null) {
                    logger.info("Creating asset namespace: '" + ns + "'");
                }
                XmlStringWriter w = new XmlStringWriter();
                w.add("namespace", ns);
                session.execute("asset.namespace.create", w.document());
            } catch (Throwable e) {
                String msg = e.getMessage();
                if (msg != null && (msg.contains("already exists") || msg.contains("not accessible"))) {
                    if (logger != null) {
                        logger.info("Asset namespace: '" + ns + "' already exists.");
                    }
                } else {
                    throw e;
                }
            }
        }
    }

    public static boolean assetNamespaceExists(MFSession session, String ns) throws Throwable {
        XmlStringWriter w = new XmlStringWriter();
        w.add("namespace", ns);
        return session.execute("asset.namespace.exists", w.document()).booleanValue("exists");
    }
}


text:
Configuración de Portsentry

Portsentry es un programa diseñado para detectar y responder en tiempo real
a los escaneos de puertos contra una máquina. Puede hacerlo de dos maneras
- escuchando en un conjunto de puertos seleccionados (modo básico), o
monitorizando todos los puertos por debajo de uno dado. Cuando se detecta
una conexión a uno de los puertos monitorizados, Portsentry registra el
evento en los historiales y (opcionalmente) ejecuta una acción para
bloquear en el futuro cualquier tráfico desde la máquina atacante.

Las opciones de esta página soLas opciones de esta página son :

Puertos TCP que monitorizar

    En modo básico, Portsentry escuchará en todos los puertos TCP listados
    en la primera línea de esta opción. En modo avanzado, escuchará en
    todos los puertos por debajo del indicado en la segunda línea,
    excluyendo aquellos listados en el campo 'excepto'.

UDP ports to monitor

    Like the TCP ports option, but controls which UDP ports are monitored.

Bloquear los sondeos TCP

    Esta opción controla qué acción llevará a cabo Portsentry cuando
    detecte una conexión TCP a uno de los puertos monitorizados. Las
    opciones son 'Sí' (bloquear las futuras conexiones desde la máquina),
    'No' (no hacer nada), o 'Ejecutar comando asesino' (ejecutar un comando
    especificado en el fichero de configuración). En todos los casos la
    conexión se registrará en los históricos del sistema.

Bloquear sondeos UDP

    Como la opción de bloquear los sondeos TCP, pero controla qué sucede
    cuando se detecta una "conexión" UDP.

Mensaje para las conexiones bloqueadas

    Cuando Portsentry está escuchando en un puerto, cualquier conexión que
    se establezca será respondida con este mensaje antes de cerrar la
    conexión.

Número de conexiones antes de activar el bloqueo

    El número de conexiones 'de gracia' que una máquina tiene permitido
    hacer a un puerto monitorizado antes de ser bloqueada. Si se pone a
    cero, la primera conexión activará el bloqueo de la máquina.

Máquinas cuyo tráfico ignorar

    Las direcciones IP, nombres de máquina, o dirección/máscara de las
    máquinas y redes cuyo tráfico ignorar.

En la parte inferior de la página hay un botón para iniciar Portsentry (de
no estar ejecutando) o pararlo (si está en ejecución). Puesto que
Portsentry ejecuta un par de procesos en segundo plano (demonios), si no
está ejecutando no se hará ninguna monitorización de escaneos de puertos.


text:
package com.amazonaws.services.machinelearning.model;

import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 */
public class CreateEvaluationRequest extends AmazonWebServiceRequest implements
        Serializable, Cloneable {

    /**
     *

     * A user-supplied ID that uniquely identifies the Evaluation.
     *

     */
    private String evaluationId;
    /**
     *

     * A user-supplied name or description of the Evaluation.
     *

     */
    private String evaluationName;
    /**
     *

     * The ID of the MLModel to evaluate.
     *

     *

     * The schema used in creating the MLModel must match the
     * schema of the DataSource used in the Evaluation
     * .
     *

     */
    private String mLModelId;
    /**
     *

     * The ID of the DataSource for the evaluation. The schema of
     * the DataSource must match the schema used to create the
     * MLModel.
     *

     */
    private String evaluationDataSourceId;

    /**
     *

     * A user-supplied ID that uniquely identifies the Evaluation.
     *

     *
     * @param evaluationId
     *        A user-supplied ID that uniquely identifies the
     *        Evaluation.
     */
    public void setEvaluationId(String evaluationId) {
        this.evaluationId = evaluationId;
    }

    /**
     *

     * A user-supplied ID that uniquely identifies the Evaluation.
     *

     *
     * @return A user-supplied ID that uniquely identifies the
     *         Evaluation.
     */
    public String getEvaluationId() {
        return this.evaluationId;
    }

    /**
     *

     * A user-supplied ID that uniquely identifies the Evaluation.
     *

     *
     * @param evaluationId
     *        A user-supplied ID that uniquely identifies the
     *        Evaluation.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public CreateEvaluationRequest withEvaluationId(String evaluationId) {
        setEvaluationId(evaluationId);
        return this;
    }

    /**
     *

     * A user-supplied name or description of the Evaluation.
     *

     *
     * @param evaluationName
     *        A user-supplied name or description of the Evaluation
     *        .
     */
    public void setEvaluationName(String evaluationName) {
        this.evaluationName = evaluationName;
    }

    /**
     *

     * A user-supplied name or description of the Evaluation.
     *

     *
     * @return A user-supplied name or description of the
     *         Evaluation.
     */
    public String getEvaluationName() {
        return this.evaluationName;
    }

    /**
     *

     * A user-supplied name or description of the Evaluation.
     *

     *
     * @param evaluationName
     *        A user-supplied name or description of the Evaluation
     *        .
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public CreateEvaluationRequest withEvaluationName(String evaluationName) {
        setEvaluationName(evaluationName);
        return this;
    }

    /**
     *

     * The ID of the MLModel to evaluate.
     *

     *

     * The schema used in creating the MLModel must match the
     * schema of the DataSource used in the Evaluation
     * .
     *

     *
     * @param mLModelId
     *        The ID of the MLModel to evaluate.

     *

     *        The schema used in creating the MLModel must match
     *        the schema of the DataSource used in the
     *        Evaluation.
     */
    public void setMLModelId(String mLModelId) {
        this.mLModelId = mLModelId;
    }

    /**
     *

     * The ID of the MLModel to evaluate.
     *

     *

     * The schema used in creating the MLModel must match the
     * schema of the DataSource used in the Evaluation
     * .
     *

     *
     * @return The ID of the MLModel to evaluate.

     *

     *         The schema used in creating the MLModel must match
     *         the schema of the DataSource used in the
     *         Evaluation.
     */
    public String getMLModelId() {
        return this.mLModelId;
    }

    /**
     *

     * The ID of the MLModel to evaluate.
     *

     *

     * The schema used in creating the MLModel must match the
     * schema of the DataSource used in the Evaluation
     * .
     *

     *
     * @param mLModelId
     *        The ID of the MLModel to evaluate.

     *

     *        The schema used in creating the MLModel must match
     *        the schema of the DataSource used in the
     *        Evaluation.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public CreateEvaluationRequest withMLModelId(String mLModelId) {
        setMLModelId(mLModelId);
        return this;
    }

    /**
     *

     * The ID of the DataSource for the evaluation. The schema of
     * the DataSource must match the schema used to create the
     * MLModel.
     *

     *
     * @param evaluationDataSourceId
     *        The ID of the DataSource for the evaluation. The
     *        schema of the DataSource must match the schema used
     *        to create the MLModel.
     */
    public void setEvaluationDataSourceId(String evaluationDataSourceId) {
        this.evaluationDataSourceId = evaluationDataSourceId;
    }

    /**
     *

     * The ID of the DataSource for the evaluation. The schema of
     * the DataSource must match the schema used to create the
     * MLModel.
     *

     *
     * @return The ID of the DataSource for the evaluation. The
     *         schema of the DataSource must match the schema used
     *         to create the MLModel.
     */
    public String getEvaluationDataSourceId() {
        return this.evaluationDataSourceId;
    }

    /**
     *

     * The ID of the DataSource for the evaluation. The schema of
     * the DataSource must match the schema used to create the
     * MLModel.
     *

     *
     * @param evaluationDataSourceId
     *        The ID of the DataSource for the evaluation. The
     *        schema of the DataSource must match the schema used
     *        to create the MLModel.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public CreateEvaluationRequest withEvaluationDataSourceId(
            String evaluationDataSourceId) {
        setEvaluationDataSourceId(evaluationDataSourceId);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getEvaluationId() != null)
            sb.append("EvaluationId: " + getEvaluationId() + ",");
        if (getEvaluationName() != null)
            sb.append("EvaluationName: " + getEvaluationName() + ",");
        if (getMLModelId() != null)
            sb.append("MLModelId: " + getMLModelId() + ",");
        if (getEvaluationDataSourceId() != null)
            sb.append("EvaluationDataSourceId: " + getEvaluationDataSourceId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreateEvaluationRequest == false)
            return false;
        CreateEvaluationRequest other = (CreateEvaluationRequest) obj;
        if (other.getEvaluationId() == null ^ this.getEvaluationId() == null)
            return false;
        if (other.getEvaluationId() != null
                && other.getEvaluationId().equals(this.getEvaluationId()) == false)
            return false;
        if (other.getEvaluationName() == null
                ^ this.getEvaluationName() == null)
            return false;
        if (other.getEvaluationName() != null
                && other.getEvaluationName().equals(this.getEvaluationName()) == false)
            return false;
        if (other.getMLModelId() == null ^ this.getMLModelId() == null)
            return false;
        if (other.getMLModelId() != null
                && other.getMLModelId().equals(this.getMLModelId()) == false)
            return false;
        if (other.getEvaluationDataSourceId() == null
                ^ this.getEvaluationDataSourceId() == null)
            return false;
        if (other.getEvaluationDataSourceId() != null
                && other.getEvaluationDataSourceId().equals(
                        this.getEvaluationDataSourceId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getEvaluationId() == null) ? 0 : getEvaluationId()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getEvaluationName() == null) ? 0 : getEvaluationName()
                        .hashCode());
        hashCode = prime * hashCode
                + ((getMLModelId() == null) ? 0 : getMLModelId().hashCode());
        hashCode = prime
                * hashCode
                + ((getEvaluationDataSourceId() == null) ? 0
                        : getEvaluationDataSourceId().hashCode());
        return hashCode;
    }

    @Override
    public CreateEvaluationRequest clone() {
        return (CreateEvaluationRequest) super.clone();
    }
}