text:
package armnetwork_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v2"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/LoadBalancerNetworkInterfaceListSimple.json
func ExampleLoadBalancerNetworkInterfacesClient_NewListPager_loadBalancerNetworkInterfaceListSimple() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armnetwork.NewLoadBalancerNetworkInterfacesClient("subid", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListPager("testrg", "lb", nil)
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/LoadBalancerNetworkInterfaceListVmss.json
func ExampleLoadBalancerNetworkInterfacesClient_NewListPager_loadBalancerNetworkInterfaceListVmss() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armnetwork.NewLoadBalancerNetworkInterfacesClient("subid", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListPager("testrg", "lb", nil)
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}


text:
package com.google.common.truth;

import static com.google.common.truth.Fact.fact;
import static com.google.common.truth.Fact.simpleFact;

import com.google.common.base.Optional;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Propositions for Guava {@link Optional} subjects.
 *
 *
If you are looking for a {@code java.util.Optional} subject, please read
 * faq#java8
 *
 * @author Christian Gruber
 */
public final class GuavaOptionalSubject extends Subject {
  private final Optional<?> actual;

  GuavaOptionalSubject(
      FailureMetadata metadata, @Nullable Optional<?> actual, @Nullable String typeDescription) {
    super(metadata, actual, typeDescription);
    this.actual = actual;
  }

  /** Fails if the {@link Optional}{@code <T>} is absent or the subject is null. */
  public void isPresent() {
    if (actual == null) {
      failWithActual(simpleFact("expected present optional"));
    } else if (!actual.isPresent()) {
      failWithoutActual(simpleFact("expected to be present"));
    }
  }

  /** Fails if the {@link Optional}{@code <T>} is present or the subject is null. */
  public void isAbsent() {
    if (actual == null) {
      failWithActual(simpleFact("expected absent optional"));
    } else if (actual.isPresent()) {
      failWithoutActual(
          simpleFact("expected to be absent"), fact("but was present with value", actual.get()));
    }
  }

  /**
   * Fails if the {@link Optional}{@code <T>} does not have the given value or the subject is null.
   *
   *
To make more complex assertions on the optional's value split your assertion in two:
   *
   *
{@code
   * assertThat(myOptional).isPresent();
   * assertThat(myOptional.get()).contains("foo");
   * }

   */
  public void hasValue(Object expected) {
    if (expected == null) {
      throw new NullPointerException("Optional cannot have a null value.");
    }
    if (actual == null) {
      failWithActual("expected an optional with value", expected);
    } else if (!actual.isPresent()) {
      failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent"));
    } else {
      checkNoNeedToDisplayBothValues("get()").that(actual.get()).isEqualTo(expected);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
extern crate delix;

mod helper;

use delix::node::request;

#[test]
#[allow(unused_variables)]
fn registration_over_incoming_connection() {
    helper::set_up();

    let (node_one, metric_one) = helper::build_node("localhost:3001", &[], None);
    node_one.register("echo", Box::new(|request| Ok(request)))
            .unwrap();

    let (node_two, metric_two) = helper::build_node("localhost:3002", &["localhost:3001"], None);

    helper::wait_for_joined(&[&metric_one, &metric_two]);
    helper::wait_for_services(&[&metric_one, &metric_two], 1);
}

#[test]
#[allow(unused_variables)]
fn registration_over_outgoing_connection() {
    helper::set_up();

    let (node_one, metric_one) = helper::build_node("localhost:3011", &[], None);

    let (node_two, metric_two) = helper::build_node("localhost:3012", &["localhost:3011"], None);
    node_two.register("echo", Box::new(|request| Ok(request)))
            .unwrap();

    helper::wait_for_joined(&[&metric_one, &metric_two]);
    helper::wait_for_services(&[&metric_one, &metric_two], 1);
}

#[test]
#[allow(unused_variables)]
fn registration_in_joined_network() {
    helper::set_up();

    let (node_one, metric_one) = helper::build_node("localhost:3021", &[], None);
    let (node_two, metric_two) = helper::build_node("localhost:3022", &["localhost:3021"], None);

    helper::wait_for_joined(&[&metric_one, &metric_two]);

    helper::wait_for_services(&[&metric_one, &metric_two], 0);
    node_one.register("echo", Box::new(|request| Ok(request)))
            .unwrap();
    helper::wait_for_services(&[&metric_one, &metric_two], 1);
}

#[test]
fn deregistration() {
    helper::set_up();

    let (node, metric) = helper::build_node("localhost:3031", &[], None);
    node.register("echo", Box::new(|request| Ok(request)))
        .unwrap();

    helper::wait_for_services(&[&metric], 1);
    node.deregister("echo").unwrap();
    helper::wait_for_services(&[&metric], 0);
}

#[test]
fn deregistration_in_joined_network() {
    helper::set_up();

    let (node_one, metric_one) = helper::build_node("localhost:3041", &[], None);
    node_one.register("echo", Box::new(|request| Ok(request)))
            .unwrap();

    let (node_two, metric_two) = helper::build_node("localhost:3042", &["localhost:3041"], None);

    helper::wait_for_joined(&[&metric_one, &metric_two]);

    helper::wait_for_services(&[&metric_one, &metric_two], 1);
    node_one.deregister("echo").unwrap();
    helper::wait_for_services(&[&metric_one, &metric_two], 0);

    assert_eq!(Err(request::Error::NoService), node_two.request_bytes("echo", b"test"));
}


text:
/**
 */
package com.example.example.with.group.unchanged.impl;

import com.example.example.with.group.unchanged.Element3;
import com.example.example.with.group.unchanged.UnchangedPackage;

import java.util.Collection;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import org.eclipse.emf.ecore.util.EDataTypeEList;

/**
 *
 * An implementation of the model object 'Element3'.
 *
 *

 * The following features are implemented:
 *

 *
{@link com.example.example.with.group.unchanged.impl.Element3Impl#getRepeatableElement1 Repeatable Element1}

 *
{@link com.example.example.with.group.unchanged.impl.Element3Impl#getRepeatableElement2 Repeatable Element2}

 *
{@link com.example.example.with.group.unchanged.impl.Element3Impl#getRepeatableElement3 Repeatable Element3}

 *

 *

 *
 * @generated
 */
public class Element3Impl extends MinimalEObjectImpl.Container implements Element3 {
	/**
	 * The cached value of the '{@link #getRepeatableElement1() Repeatable Element1}' attribute list.
	 *
	 *
	 * @see #getRepeatableElement1()
	 * @generated
	 * @ordered
	 */
	protected EList<String> repeatableElement1;

	/**
	 * The default value of the '{@link #getRepeatableElement2() Repeatable Element2}' attribute.
	 *
	 *
	 * @see #getRepeatableElement2()
	 * @generated
	 * @ordered
	 */
	protected static final String REPEATABLE_ELEMENT2_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getRepeatableElement2() Repeatable Element2}' attribute.
	 *
	 *
	 * @see #getRepeatableElement2()
	 * @generated
	 * @ordered
	 */
	protected String repeatableElement2 = REPEATABLE_ELEMENT2_EDEFAULT;

	/**
	 * The default value of the '{@link #getRepeatableElement3() Repeatable Element3}' attribute.
	 *
	 *
	 * @see #getRepeatableElement3()
	 * @generated
	 * @ordered
	 */
	protected static final String REPEATABLE_ELEMENT3_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getRepeatableElement3() Repeatable Element3}' attribute.
	 *
	 *
	 * @see #getRepeatableElement3()
	 * @generated
	 * @ordered
	 */
	protected String repeatableElement3 = REPEATABLE_ELEMENT3_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected Element3Impl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return UnchangedPackage.Literals.ELEMENT3;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EList<String> getRepeatableElement1() {
		if (repeatableElement1 == null) {
			repeatableElement1 = new EDataTypeEList<String>(String.class, this, UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT1);
		}
		return repeatableElement1;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getRepeatableElement2() {
		return repeatableElement2;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setRepeatableElement2(String newRepeatableElement2) {
		String oldRepeatableElement2 = repeatableElement2;
		repeatableElement2 = newRepeatableElement2;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT2, oldRepeatableElement2, repeatableElement2));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getRepeatableElement3() {
		return repeatableElement3;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setRepeatableElement3(String newRepeatableElement3) {
		String oldRepeatableElement3 = repeatableElement3;
		repeatableElement3 = newRepeatableElement3;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT3, oldRepeatableElement3, repeatableElement3));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT1:
				return getRepeatableElement1();
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT2:
				return getRepeatableElement2();
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT3:
				return getRepeatableElement3();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT1:
				getRepeatableElement1().clear();
				getRepeatableElement1().addAll((Collection<? extends String>)newValue);
				return;
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT2:
				setRepeatableElement2((String)newValue);
				return;
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT3:
				setRepeatableElement3((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT1:
				getRepeatableElement1().clear();
				return;
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT2:
				setRepeatableElement2(REPEATABLE_ELEMENT2_EDEFAULT);
				return;
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT3:
				setRepeatableElement3(REPEATABLE_ELEMENT3_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT1:
				return repeatableElement1 != null && !repeatableElement1.isEmpty();
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT2:
				return REPEATABLE_ELEMENT2_EDEFAULT == null ? repeatableElement2 != null : !REPEATABLE_ELEMENT2_EDEFAULT.equals(repeatableElement2);
			case UnchangedPackage.ELEMENT3__REPEATABLE_ELEMENT3:
				return REPEATABLE_ELEMENT3_EDEFAULT == null ? repeatableElement3 != null : !REPEATABLE_ELEMENT3_EDEFAULT.equals(repeatableElement3);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (repeatableElement1: ");
		result.append(repeatableElement1);
		result.append(", repeatableElement2: ");
		result.append(repeatableElement2);
		result.append(", repeatableElement3: ");
		result.append(repeatableElement3);
		result.append(')');
		return result.toString();
	}

} //Element3Impl


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Developer's Guide - Creating Custom Widgets - Google Web Toolkit - Google Code</title>

<link href="/css/codesite.pack.04102009.css" type="text/css" rel="stylesheet">

<link rel="search" type="application/opensearchdescription+xml" title="Google Code" href="/osd.xml">

    <link href="/css/semantic_headers.css" rel="stylesheet" type="text/css" />
       <link href="/webtoolkit/css/local_extensions.css" rel="stylesheet" type="text/css"/>

    My favorites ▼
    |

    English ▼

    | Sign in

  Skip to page content
  Skip to main navigation

      <form id="cse" action="http://www.google.com/cse" accept-charset="utf-8" class="gsc-search-box" onsubmit="executeGSearch(document.getElementById('gsearchInput').value); return false;">

      <input type="hidden" name="cref" value="http://code.google.com/cse/googlecode-context.xml">

        <input id="gsearchInput" type="text" name="q" maxlength="2048" class="gsc-input" autocomplete="off" title="Google Code Search" style="width:345px">

        <input title="Search" id="gsearchButton" class="gsc-search-button" name="sa" value="Search" type="submit">

e.g. "ajax apis" or "open source"

      </form>

Google Web Toolkit

      Home

      Docs

      Blog

      Community

      Terms

      Download

Downloads

Learn More

Overview

Business Apps

SDK

Speed Tracer

Plugin for Eclipse

Examples

Get Started

SDK

Set up Eclipse

Speed Tracer

Tutorials

Get Started

Create a GWT Project

Design the Application

Build the User Interface

Manage Events on the Client

Code Functionality on the Client

Debug a GWT Application

Apply Style

Compile a GWT Application

Internationalization

Client-Server Communication

GWT RPC

JSON

JSON - PHP

Cross-Site

JUnit Testing

Google App Engine

MVP Architecture

Documentation

What's Coming in 2.1?

Release Notes

Organize Projects

Compile & Debug

Coding Basics

Client-Side Code

Compatibility with the Java Language and Libraries

History

Number and Date Formatting

Programming Delayed Logic

Working with JSON

Working with XML

JavaScript Native Interface (JSNI)

JavaScript Overlay Types

Deferred Binding

Build User Interfaces

Cross-Browser Support

Layout Using Panels

Widgets

Creating Custom Widgets

Working with the DOM

Events and Handlers

Working with CSS

Declarative UI with UiBinder

Bundling Image Resources

Accessibility

Internationalization

Locale

Constants

Messages

Plural Forms

UiBinder

Communicate with a Server

Test with JUnit

HtmlUnit

Remote Testing

Code Coverage

Deploy

Optimize

Code Splitting

Compile Report

Client Bundle

Lightweight Metrics

Reference

SDK API Reference (Javadoc)

JRE Emulation Reference

Widget List

FAQ

Get Started

Debug and Compile

Build the User Interface

Develop Client-side Code

Communicate with a Server

Troubleshoot

Glossary

Docs for Previous Versions

Tools

Plugin for Eclipse

SDK Command-line Tools

Speed Tracer

Getting Started

Examples

Hints

Data Dump Format

Logging API

FAQ

GWT Designer

WindowBuilder Pro

WindowTester Pro

CodePro AnalytiX

Resources

Articles

Books

Community

App Gallery

Developer Spotlight

Google API Libraries

Tools & Libraries

Presentations

Making GWT Better

Issue Tracking

        More Google Web Toolkit resource links

Developer's Guide - Creating Custom Widgets

GWT makes it easy to create custom user interface elements. There are three general strategies to follow:

Create a widget that is a composite of existing widgets.

Create an entirely new widget written in the Java language.

Create a widget that wraps JavaScript using JSNI methods.

There are numerous third party libraries that provide widgets you can integrate into your GWT module that were created using the strategies listed above.

Building Composites

The most effective way to create new widgets is to extend the Composite class. A composite is a
specialized widget that can contain another component (typically, a Panel) but behaves as if it were its contained widget.
You can easily combine groups of existing widgets into a composite that is itself a reusable widget. Some of the UI components provided in GWT are composites:
for example, the TabPanel (a composite of a TabBar and a DeckPanel) and the
SuggestBox.

Rather than create complex widgets by subclassing Panel or another
Widget type,
it's better to create a composite because a composite usually wants to control which methods are publicly accessible without exposing those methods that it
would inherit from its Panel superclass.

Example Composite Widget

The following code snippet shows how to create a composite widget composed of a TextBox widget and a
CheckBox widget laid out in a VerticalPanel.

package com.google.gwt.examples;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class CompositeExample implements EntryPoint {

  /**
   * A composite of a TextBox and a CheckBox that optionally enables it.
   */
  private static class OptionalTextBox extends Composite implements
      ClickHandler {

    private TextBox textBox = new TextBox();
    private CheckBox checkBox = new CheckBox();

    /**
     * Constructs an OptionalTextBox with the given caption on the check.
     *
     * @param caption the caption to be displayed with the check box
     */
    public OptionalTextBox(String caption) {
      // Place the check above the text box using a vertical panel.
      VerticalPanel panel = new VerticalPanel();
      panel.add(checkBox);
      panel.add(textBox);

      // Set the check box's caption, and check it by default.
      checkBox.setText(caption);
      checkBox.setChecked(true);
      checkBox.addClickHandler(this);

      // All composites must call initWidget() in their constructors.
      initWidget(panel);

      // Give the overall composite a style name.
      setStyleName("example-OptionalCheckBox");
    }

    public void onClick(ClickEvent event) {
      Object sender = event.getSource();
      if (sender == checkBox) {
        // When the check box is clicked, update the text box's enabled state.
        textBox.setEnabled(checkBox.isChecked());
      }
    }

    /**
     * Sets the caption associated with the check box.
     *
     * @param caption the check box's caption
     */
    public void setCaption(String caption) {
      // Note how we use the use composition of the contained widgets to provide
      // only the methods that we want to.
      checkBox.setText(caption);
    }

    /**
     * Gets the caption associated with the check box.
     *
     * @return the check box's caption
     */
    public String getCaption() {
      return checkBox.getText();
    }
  }

  public void onModuleLoad() {
    // Create an optional text box and add it to the root panel.
    OptionalTextBox otb = new OptionalTextBox("Check this to enable me");
    RootPanel.get().add(otb);
  }
}

From Scratch in Java Code

It is also possible to create a widget from scratch, although it is trickier since you have to write code at a lower level. Many of the basic widgets are written this way, such
as Button and TextBox. Please refer to the implementations of these
widgets to understand how to create your own.

To understand how to create your own, refer to the implementations of these widgets in the com.google.gwt.user.client.ui package. The source code is in gwt-user.jar.

Using JavaScript

When implementing a custom widget that derives directly from the Widget base class, you may also write some of
the widget's methods using JavaScript. This should generally only be done as a last resort, as it becomes necessary to consider the cross-browser implications
of the native methods that you write, and also becomes more difficult to debug. For an example of this pattern in practice, see the
TextBox widget and the underlying JavaScript implementation of some of its methods in the TextBoxImpl class.
You should use deferred binding to isolate browser specific code.

  Except as otherwise noted,
  the content of this page is licensed under the Creative Commons
  Attribution 3.0 License.

    ©2010 Google -
    Code Home -
    Terms of Service -
    Privacy Policy -
    Site Directory

    Google Code offered in:
    English -
    Español -
    日本語 -
    한국어 -
    Português -
    Pусский -
    中文(简体) -
    中文(繁體)


text:
<?php

namespace ReCaptcha;

use PHPUnit\Framework\TestCase;

class ReCaptchaTest extends TestCase
{

    /**
     * @expectedException \RuntimeException
     * @dataProvider invalidSecretProvider
     */
    public function testExceptionThrownOnInvalidSecret($invalid)
    {
        $rc = new ReCaptcha($invalid);
    }

    public function invalidSecretProvider()
    {
        return array(
            array(''),
            array(null),
            array(0),
            array(new \stdClass()),
            array(array()),
        );
    }

    public function testVerifyReturnsErrorOnMissingResponse()
    {
        $rc = new ReCaptcha('secret');
        $response = $rc->verify('');
        $this->assertFalse($response->isSuccess());
        $this->assertEquals(array(Recaptcha::E_MISSING_INPUT_RESPONSE), $response->getErrorCodes());
    }

    private function getMockRequestMethod($responseJson)
    {
        $method = $this->getMockBuilder(\ReCaptcha\RequestMethod::class)
            ->disableOriginalConstructor()
            ->setMethods(array('submit'))
            ->getMock();
        $method->expects($this->any())
            ->method('submit')
            ->with($this->callback(function ($params) {
                return true;
            }))
            ->will($this->returnValue($responseJson));
        return $method;
    }

    public function testVerifyReturnsResponse()
    {
        $method = $this->getMockRequestMethod('{"success": true}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->verify('response');
        $this->assertTrue($response->isSuccess());
    }

    public function testVerifyReturnsInitialResponseWithoutAdditionalChecks()
    {
        $method = $this->getMockRequestMethod('{"success": true}');
        $rc = new ReCaptcha('secret', $method);
        $initialResponse = $rc->verify('response');
        $this->assertEquals($initialResponse, $rc->verify('response'));
    }

    public function testVerifyHostnameMatch()
    {
        $method = $this->getMockRequestMethod('{"success": true, "hostname": "host.name"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setExpectedHostname('host.name')->verify('response');
        $this->assertTrue($response->isSuccess());
    }

    public function testVerifyHostnameMisMatch()
    {
        $method = $this->getMockRequestMethod('{"success": true, "hostname": "host.NOTname"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setExpectedHostname('host.name')->verify('response');
        $this->assertFalse($response->isSuccess());
        $this->assertEquals(array(ReCaptcha::E_HOSTNAME_MISMATCH), $response->getErrorCodes());
    }

    public function testVerifyApkPackageNameMatch()
    {
        $method = $this->getMockRequestMethod('{"success": true, "apk_package_name": "apk.name"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setExpectedApkPackageName('apk.name')->verify('response');
        $this->assertTrue($response->isSuccess());
    }

    public function testVerifyApkPackageNameMisMatch()
    {
        $method = $this->getMockRequestMethod('{"success": true, "apk_package_name": "apk.NOTname"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setExpectedApkPackageName('apk.name')->verify('response');
        $this->assertFalse($response->isSuccess());
        $this->assertEquals(array(ReCaptcha::E_APK_PACKAGE_NAME_MISMATCH), $response->getErrorCodes());
    }

    public function testVerifyActionMatch()
    {
        $method = $this->getMockRequestMethod('{"success": true, "action": "action/name"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setExpectedAction('action/name')->verify('response');
        $this->assertTrue($response->isSuccess());
    }

    public function testVerifyActionMisMatch()
    {
        $method = $this->getMockRequestMethod('{"success": true, "action": "action/NOTname"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setExpectedAction('action/name')->verify('response');
        $this->assertFalse($response->isSuccess());
        $this->assertEquals(array(ReCaptcha::E_ACTION_MISMATCH), $response->getErrorCodes());
    }

    public function testVerifyAboveThreshold()
    {
        $method = $this->getMockRequestMethod('{"success": true, "score": "0.9"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setScoreThreshold('0.5')->verify('response');
        $this->assertTrue($response->isSuccess());
    }

    public function testVerifyBelowThreshold()
    {
        $method = $this->getMockRequestMethod('{"success": true, "score": "0.1"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setScoreThreshold('0.5')->verify('response');
        $this->assertFalse($response->isSuccess());
        $this->assertEquals(array(ReCaptcha::E_SCORE_THRESHOLD_NOT_MET), $response->getErrorCodes());
    }

    public function testVerifyWithinTimeout()
    {
        // Responses come back like 2018-07-31T13:48:41Z
        $challengeTs = date('Y-M-d\TH:i:s\Z', time());
        $method = $this->getMockRequestMethod('{"success": true, "challenge_ts": "'.$challengeTs.'"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setChallengeTimeout('1000')->verify('response');
        $this->assertTrue($response->isSuccess());
    }

    public function testVerifyOverTimeout()
    {
        // Responses come back like 2018-07-31T13:48:41Z
        $challengeTs = date('Y-M-d\TH:i:s\Z', time() - 600);
        $method = $this->getMockRequestMethod('{"success": true, "challenge_ts": "'.$challengeTs.'"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setChallengeTimeout('60')->verify('response');
        $this->assertFalse($response->isSuccess());
        $this->assertEquals(array(ReCaptcha::E_CHALLENGE_TIMEOUT), $response->getErrorCodes());
    }

    public function testVerifyMergesErrors()
    {
        $method = $this->getMockRequestMethod('{"success": false, "error-codes": ["initial-error"], "score": "0.1"}');
        $rc = new ReCaptcha('secret', $method);
        $response = $rc->setScoreThreshold('0.5')->verify('response');
        $this->assertFalse($response->isSuccess());
        $this->assertEquals(array('initial-error', ReCaptcha::E_SCORE_THRESHOLD_NOT_MET), $response->getErrorCodes());
    }
}


text:
#region MIT
//
// Gorgon.
// Copyright (C) 2016 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: June 29, 2016 8:13:58 PM
//
#endregion

using System;
using System.Collections.Generic;
using Gorgon.Collections.Specialized;
using Gorgon.Properties;

namespace Gorgon.Configuration
{
    /// <summary>
    /// Provides a functionality for setting and reading various options from a predefined option bag.
    /// </summary>
    public sealed class GorgonOptionBag
        : GorgonNamedObjectList<IGorgonOption>, IGorgonOptionBag
    {
        #region Methods.
        /// <summary>
        /// Function to retrieve the value for an option.
        /// </summary>
        /// <typeparam name="T">The type of data for the option.</typeparam>
        /// <param name="optionName">The name of the option.</param>
        /// <returns>The value stored with the option.</returns>
        public T GetOptionValue<T>(string optionName) => GetItemByName(optionName).GetValue<T>();

        /// <summary>
        /// Function to assign a value for an option.
        /// </summary>
        /// <typeparam name="T">The type of data for the option.</typeparam>
        /// <param name="optionName">The name of the option.</param>
        /// <param name="value">The value to assign to the option.</param>
        public void SetOptionValue<T>(string optionName, T value)
        {
            if (!Contains(optionName))
            {
                throw new KeyNotFoundException();
            }

            GetItemByName(optionName).SetValue(value);
        }
        #endregion

        #region Constructor.
        /// <summary>
        /// Initializes a new instance of the <see cref="GorgonOptionBag"/> class.
        /// </summary>
        /// <param name="options">Values and types used to initialize the options.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="options"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentException">Thrown when the <paramref name="options"/> contains a value that is already in this option bag.</exception>
        public GorgonOptionBag(IEnumerable<IGorgonOption> options)
            : base(false)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            foreach (IGorgonOption option in options)
            {
                // Don't allow duplicates.
                if ((Contains(option.Name))
                    || (Contains(option)))
                {
                    throw new ArgumentException(string.Format(Resources.GOR_ERR_OPTION_ALREADY_EXISTS, option.Name), nameof(options));
                }

                Add(option);
            }
        }
        #endregion
    }
}


text:
import {
  PresubmitRunId,
} from '@/services/cluster';
import {
  Changelist,
  ClusterId,
  Variant,
  variantAsPairs,
} from '@/services/shared_models';

export const linkToCluster = (project: string, c: ClusterId): string => {
  if (c.algorithm.startsWith('rules-') || c.algorithm == 'rules') {
    return linkToRule(project, c.id);
  } else {
    const projectEncoded = encodeURIComponent(project);
    const algorithmEncoded = encodeURIComponent(c.algorithm);
    const idEncoded = encodeURIComponent(c.id);
    return `/p/${projectEncoded}/clusters/${algorithmEncoded}/${idEncoded}`;
  }
};

export const linkToRule = (project: string, ruleId: string): string => {
  const projectEncoded = encodeURIComponent(project);
  const ruleIdEncoded = encodeURIComponent(ruleId);
  return `/p/${projectEncoded}/rules/${ruleIdEncoded}`;
};

export const invocationName = (invocationId: string): string => {
  if (invocationId.startsWith('build-')) {
    return invocationId.slice('build-'.length);
  }
  return invocationId;
};

export const failureLink = (invocationId: string, testId: string): string => {
  const query = `ID:${testId} `;
  if (invocationId.startsWith('build-')) {
    return `https://ci.chromium.org/ui/b/${invocationId.slice('build-'.length)}/test-results?q=${encodeURIComponent(query)}`;
  }
  return `https://ci.chromium.org/ui/inv/${invocationId}/test-results?q=${encodeURIComponent(query)}`;
};

export const clLink = (cl: Changelist): string => {
  return `https://${cl.host}/c/${cl.change}/${cl.patchset}`;
};

export const clName = (cl: Changelist): string => {
  const host = cl.host.replace('-review.googlesource.com', '');
  return `${host}/${cl.change}/${cl.patchset}`;
};

export const presubmitRunLink = (runId: PresubmitRunId): string => {
  return `https://luci-change-verifier.appspot.com/ui/run/${runId.id}`;
};

export const testHistoryLink = (project: string, testId: string, partialVariant?: Variant): string => {
  const query = variantAsPairs(partialVariant).map((vp) => {
    return 'V:' + encodeURIComponent(vp.key || '') + '=' + encodeURIComponent(vp.value);
  }).join(' ');
  return `https://ci.chromium.org/ui/test/${encodeURIComponent(project)}/${encodeURIComponent(testId)}?q=${encodeURIComponent(query)}`;
};

// loginLink constructs a URL to login to LUCI Analysis, with a redirect to
// the given absolute URL (which should start with "/").
export const loginLink = (redirectTarget: string): string => {
  return window.loginUrl + '?r=' + encodeURIComponent(redirectTarget);
};

// logoutLink constructs a URL to logout from LUCI Analysis, with a redirect to
// the given absolute URL (which should start with "/").
export const logoutLink = (redirectTarget: string): string => {
  return window.logoutUrl + '?r=' + encodeURIComponent(redirectTarget);
};


text:
var _ggazzi$category_diagram_editor$Native_MeasureText = function() {

  var canvasContext = document.createElement('canvas').getContext('2d');

  var measureText = function(font, text) {
    canvasContext.font = font;
    return canvasContext.measureText(text).width;
  }

  return {
    'measureText': F2(measureText)
  };
}();


text:
package com.bt.pi.app.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Calendar;
import java.util.Locale;

import javax.security.auth.x500.X500Principal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.springframework.stereotype.Component;

@Component
public class SecurityUtils {
    private static final Log LOG = LogFactory.getLog(SecurityUtils.class);
    private static final String PROVIDER = "BC";
    private static final int FIVE = 5;

    public SecurityUtils() {
    }

    public KeyPair getNewKeyPair(String keyAlgorithm, int keySize) throws GeneralSecurityException {
        LOG.debug(String.format("getNewKeyPair(%s, %d)", keyAlgorithm, keySize));
        KeyPairGenerator keyGen = null;
        keyGen = KeyPairGenerator.getInstance(keyAlgorithm);
        SecureRandom random = new SecureRandom();
        random.setSeed(System.currentTimeMillis());
        keyGen.initialize(keySize, random);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    }

    public String getFingerPrint(Key key) {
        LOG.debug(String.format("getFingerPrint(%s)", key));
        byte[] fp = HashDigest.SHA1.getMessageDigest().digest(key.getEncoded());
        StringBuffer sb = new StringBuffer();
        for (byte b : fp)
            sb.append(String.format("%02X:", b));
        return sb.substring(0, sb.length() - 1).toLowerCase(Locale.ENGLISH);
    }

    public byte[] getPemBytes(final Object o) throws IOException {
        LOG.debug(String.format("getPemBytes(%s)", o));
        ByteArrayOutputStream pemByteOut = new ByteArrayOutputStream();
        PEMWriter pemOut = new PEMWriter(new OutputStreamWriter(pemByteOut));
        pemOut.writeObject(o);
        pemOut.close();
        return pemByteOut.toByteArray();
    }

    public X509Certificate getNewCertificate(String certDn, String keyAlgorithm, String keySigningAlgorithm, int keySize) throws GeneralSecurityException {
        return getNewCertificate(certDn, keySigningAlgorithm, getNewKeyPair(keyAlgorithm, keySize));
    }

    public X509Certificate getNewCertificate(String certDn, String keySigningAlgorithm, KeyPair keyPair) throws GeneralSecurityException {
        LOG.debug(String.format("getNewCertificate(%s, %s, %s)", certDn, keySigningAlgorithm, keyPair));
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        X500Principal dnName = new X500Principal(certDn);

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(dnName);
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

        Calendar cal = Calendar.getInstance();
        certGen.setNotBefore(cal.getTime());
        cal.add(Calendar.YEAR, FIVE);
        certGen.setNotAfter(cal.getTime());
        certGen.setSubjectDN(dnName);
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm(keySigningAlgorithm);
        return certGen.generate(keyPair.getPrivate(), PROVIDER);
    }

    public PrivateKey getPrivateKeyFromEncoded(byte[] bytes) throws GeneralSecurityException {
        LOG.debug(String.format("getPrivateKeyFromEncoded(%s)", bytes));
        return KeyFactory.getInstance("RSA", PROVIDER).generatePrivate(new PKCS8EncodedKeySpec(bytes));
    }

    public Certificate getCertificateFromEncoded(byte[] data) throws GeneralSecurityException {
        LOG.debug(String.format("getCertificateFromEncoded(%s)", data));
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return certificateFactory.generateCertificate(new ByteArrayInputStream(data));
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Commencement.Controllers.Services;
using Commencement.Core.Domain;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Core.Utils;

namespace Commencement.Controllers.ViewModels
{
    public class RegistrationDataViewModel
    {
        public IList<RegistrationData> RegistrationData { get; set; }

        public static RegistrationDataViewModel Create(IRepository repository, ICeremonyService ceremonyService, string userId, TermCode termCode)
        {
            Check.Require(repository != null, "Repository is required.");

            //var viewModel = new RegistrationDataViewModel();
            //viewModel.RegistrationData = new List<RegistrationData>();

            //var ceremonies = ceremonyService.GetCeremonies(userId, termCode);

            //viewModel.RegistrationData = ceremonies.Select(a => new RegistrationData()
            //                                      {
            //                                          TermCode = a.TermCode,
            //                                          Ceremony = a,
            //                                          Registrants = a.RegistrationParticipations.Count(),
            //                                          CancelledRegistrants = a.RegistrationParticipations.Count(),
            //                                          RegistrationPetitionsSubmitted = a.RegistrationPetitions.Count,
            //                                          RegistrationPetitionsApproved =
            //                                              a.RegistrationPetitions.Where(
            //                                                  b => b.IsApproved && !b.IsPending).Count(),
            //                                          TicketsRequested = a.ProjectedTicketCount,
            //                                          ExtraTicketsRequested = a.ProjectedTicketCount,
            //                                          TotalTickets = a.TotalTickets
            //                                      }).ToList();

            //return viewModel;

            var viewModel = new RegistrationDataViewModel();

            // load all ceremonies that a user has access to
            var ceremonies = ceremonyService.GetCeremonies(userId);

            viewModel.RegistrationData = (from a in ceremonies
                       select new RegistrationData()
                                  {
                                      TermCode = a.TermCode,
                                      Ceremony = a,
                                      Registrants = a.RegistrationParticipations.Where(b => !b.Cancelled).Count(),
                                      CancelledRegistrants = a.RegistrationParticipations.Where(b => b.Cancelled).Count(),
                                      RegistrationPetitionsSubmitted = a.RegistrationPetitions.Count,
                                      RegistrationPetitionsApproved = a.RegistrationPetitions.Where(b => b.IsApproved).Count(),
                                      ExtraTicketPetitionsSubmitted = a.RegistrationParticipations.Where(b => b.ExtraTicketPetition != null).Count(),
                                      ExtraTicketPetitionsApproved = a.RegistrationParticipations.Where(b => b.ExtraTicketPetition != null && b.ExtraTicketPetition.IsApproved).Count(),
                                      TicketsPavilion = a.TicketCount,
                                      TicketsBallroom = a.TicketStreamingCount,
                                      TicketsByPetition = a.RegistrationParticipations.Where(b => b.ExtraTicketPetition != null && b.ExtraTicketPetition.IsApprovedCompletely).Sum(b => b.ExtraTicketPetition.TotalTickets)
                                  }).ToList();

            return viewModel;
        }
    }

    public class RegistrationData
    {
        public TermCode TermCode { get; set; }
        public Ceremony Ceremony { get; set; }
        /// <summary>
        /// # of registrants
        /// </summary>
        public int Registrants { get; set; }
        /// <summary>
        /// # of cancelled registrants
        /// </summary>
        public int CancelledRegistrants { get; set; }
        /// <summary>
        /// # of registration petitions submitted
        /// </summary>
        public int RegistrationPetitionsSubmitted { get; set; }
        /// <summary>
        /// # of registration petitions approved
        /// </summary>
        public int RegistrationPetitionsApproved { get; set; }
        /// <summary>
        /// # of extra ticket petitions submitted
        /// </summary>
        public int ExtraTicketPetitionsSubmitted { get; set; }
        /// <summary>
        /// # of extra ticket petitions approved
        /// </summary>
        public int ExtraTicketPetitionsApproved { get; set; }
        /// <summary>
        /// # of tickets to the Pavilion
        /// </summary>
        public int TicketsPavilion { get; set; }
        /// <summary>
        /// # of tickets to the ballroom
        /// </summary>
        public int? TicketsBallroom { get; set; }
        /// <summary>
        /// # of tickets to either pavilion or ballroom by petition
        /// </summary>
        public int TicketsByPetition { get; set; }

        ///// <summary>
        ///// # of tickets requested by original request
        ///// </summary>
        //public int TicketsRequested { get; set; }
        ///// <summary>
        ///// # of tickets requested by extra request
        ///// </summary>
        //public int ExtraTicketsRequested { get; set; }
        ///// <summary>
        ///// # of total tickets approved
        ///// </summary>
        //public int TotalTickets { get; set; }
    }
}


text:
using Monkeyspeak.Lexical;
using System;
using System.Collections.Generic;

namespace Monkeyspeak
{
    public abstract class AbstractLexer : IDisposable
    {
        protected readonly SStreamReader reader;

        protected AbstractLexer(MonkeyspeakEngine engine, SStreamReader reader)
        {
            this.reader = reader;
            Engine = engine;
        }

        /// <summary>
        /// Gets the engine.
        /// </summary>
        /// <value>
        /// The engine.
        /// </value>
        public virtual MonkeyspeakEngine Engine { get; private set; }

        /// <summary>
        /// Gets the current source position.
        /// </summary>
        /// <value>
        /// The current source position.
        /// </value>
        public virtual SourcePosition CurrentSourcePosition
        {
            get;
        }

        /// <summary>
        /// Advances one character in the reader.
        /// </summary>
        /// <param name="steps">Length of chars to read</param>
        public abstract int Next(int length = 1);

        /// <summary>
        /// Reads the tokens from the reader.  Used by the Parser.
        /// </summary>
        /// <returns></returns>
        public abstract IEnumerable<Token> ReadToEnd();

        /// <summary>
        /// Reads the specified start position in stream.  Used by the Token to read the token's value.
        /// </summary>
        /// <param name="startPosInStream">The start position in stream.</param>
        /// <param name="length">The length.</param>
        /// <returns></returns>
        public abstract char[] Read(long startPosInStream, int length);

        /// <summary>
        /// Looks ahead a specified number of chars and returns the result.
        /// </summary>
        /// <param name="amount">The amount.</param>
        /// <returns></returns>
        public abstract int LookAhead(int amount);

        /// <summary>
        /// Looks back a specified number of chars and returns the result.
        /// </summary>
        /// <param name="amount">The amount.</param>
        /// <returns></returns>
        public abstract int LookBack(int amount);

        /// <summary>
        /// Checks if the next input is a match to <paramref name="c"/>.
        /// </summary>
        /// <param name="c">The c.</param>
        /// <exception cref="MonkeyspeakException" />
        public abstract bool CheckMatch(int c);

        /// <summary>
        /// Checks if the next input is a match to <paramref name="c"/>.
        /// </summary>
        /// <param name="c">The c.</param>
        /// <exception cref="MonkeyspeakException" />
        public abstract bool CheckMatch(char c);

        /// <summary>
        /// Checks if the next input is a match to <paramref name="str"/>.
        /// </summary>
        /// <param name="str">The string.</param>
        /// <exception cref="MonkeyspeakException" />
        public abstract bool CheckMatch(string str);

        /// <summary>
        /// Checks if <paramref name="c"/> is a number.
        /// </summary>
        /// <param name="c">The c.</param>
        /// <exception cref="MonkeyspeakException" />
        public abstract bool CheckIsDigit(char c = '\0');

        /// <summary>
        /// Checks if the next input results in End of File.
        /// </summary>
        /// <param name="c">The c.</param>
        /// <exception cref="MonkeyspeakException" />
        public abstract bool CheckEOF(int c);

        /// <summary>
        /// Resets this instance.
        /// </summary>
        public abstract void Reset();

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            reader.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}


text:
Why this matters is listed below.

===============================================================================================

#### Overview

Instead of coding add_image_size() and set_post_thumbnail_size(), now you simply configure an array and pass that to this class / methods. Here's an example of what that array looks like:

- https://github.com/WPezBoilerStrap/wp-ezboilerstrap-uno/blob/master/setup/uno/class-wp-ezboilerstrap-add-image-size.php

Note: This example also has settings (1) for:

- https://github.com/WPezPlugins/wp-ezplugins-templates-picturefill-js

- https://github.com/WPezClasses/class-wp-ezclasses-templates-picturefill-js

(1) The settings are simply an example of what's possible. The Picturefill plugin / class uses its own settings (for now) so that example remains free-standing. In an ideal WP dev world you'd lean on a single array that defines all your WP image needs. Why sprawl if you don't have to?

===============================================================================================

#### "Why is this a better way to think about WordPress themes and how to implement additional custom images?"

- Less actual code, a lot less. This is (mostly) simply configuring an array and using a couple methods.

- Centralization: All the key WP theme image stuff wrapped up in one.

- Flexibility: An example: Set the width, pick an (aspect) ratio, and the height will be calculated for you.

- Simplicity: New project / theme, same widths / breakpoints, set different ratios (to achieve a slightly differnt look)...Done.

- Pair it with Class_WP_ezClasses_Templates_Picturefill_js and dev life gets even better.

- Dumb it down: Your new designer isn't all that WP savvy (yet); so give him / her your boilerplate widths and request they stick to the predefined ratios. Chance are 400 x 300 is just a good as 400 x 293 (or some close but none the less custom ratio).

- Control: Fully custom width and height are still possible. Possibilities have not been removed, just automated and supplemented.

===============================================================================================

##### Get Social

- **https://github.com/WPezClasses**
    - https://twitter.com/WPezClasses
    - https://www.facebook.com/WPezClasses
- **https://github.com/WPezPlugins**
    - https://twitter.com/WPezPlugins
    - https://www.facebook.com/WPezPlugins
- **https://github.com/WPezDeveloper**
    - https://twitter.com/WPezDeveloper
    - https://www.facebook.com/WPezDeveloper
- **https://github.com/WPezBoilerStrap**
    - https://twitter.com/WPezBoilerStrap
    - https://www.facebook.com/WPezBoilerStrap


text:
<?xml version="1.0" encoding="UTF-8"?>
<site>
   <description url="http://rajendarreddyj.github.io/eclipse-weblogic-plugin/update-site">
      Eclipse Update Site for Eclipse Weblogic plugin
   </description>
   <feature url="features/com.rajendarreddyj.eclipse.plugins.weblogic.feature_1.1.0.jar" id="com.rajendarreddyj.eclipse.plugins.weblogic.feature" version="1.1.0">
      <category name="Eclipse Weblogic Plugin"/>
   </feature>
   <category-def name="Eclipse Weblogic Plugin" label="Eclipse Weblogic Plugin">
      <description>
         A Simple Weblogic Plugin to Start/Stop Weblogic Server. With Remote Control.
      </description>
   </category-def>
</site>


text:
package com.wxweven.cache.guavatest;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * CallableCache demo
 *
 * @author wxweven
 * @date 2017/7/13
 */
public class GuavaCallableCache {

    public static void main(String[] args) {
        final String key = "github";
        Cache<String, Optional<String>> cache = CacheBuilder.newBuilder()
                                                            .expireAfterWrite(3, TimeUnit.SECONDS)
                                                            .removalListener(notification ->
                                                                    System.out.println("cache expired, remove key : " + notification.getKey())
                                                            )
                                                            .build();
        try {
            Optional<String> optional;

            String cacheSting1 = cache.get(key, () -> Optional.ofNullable(MockDB.loadFromPersistence(key))).orElse("empty");
            System.out.println("load from cache once : " + cacheSting1);
            Thread.sleep(2000);

            System.out.println("load from cache twice : " + cache.get(key, () -> Optional.ofNullable(MockDB.loadFromPersistence(key))).orElse(null));
            Thread.sleep(2000);

            System.out.println("load from cache third : " + cache.get(key, () -> Optional.ofNullable(MockDB.loadFromPersistence(key))).orElse(null));
            Thread.sleep(2000);

            final String nullKey = "email";
            optional = cache.get(nullKey, () -> Optional.ofNullable(MockDB.loadFromPersistence(nullKey)));
            System.out.println("load not exist key from cache : " + optional.orElse(null));
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
/*
@author: j.n.magee 11/11/96
updated: daniel.sykes 2013
*/

package concurrency;

import java.awt.*;
import java.applet.*;
import concurrency.display.*;

public class JoinDemo extends Applet {

    ThreadPanel ms;
    ThreadPanel sl;
    SlotCanvas resultdisp;

    public void init() {
        add(ms =new ThreadPanel("Master",Color.blue,true));
        add(resultdisp = new SlotCanvas("res",Color.cyan,1));
        add(sl =new ThreadPanel("Slave",Color.blue,true));
		setBackground(Color.lightGray);
     }

    public void start() {
        ms.start(new Master(sl,resultdisp));
    }

    public void stop() {
        ms.stop();
    }

}

/*******************MASTER************************/

class Master implements Runnable {

  ThreadPanel slaveDisplay;
  SlotCanvas  resultDisplay;

  Master(ThreadPanel tp, SlotCanvas sc)
    {slaveDisplay=tp; resultDisplay=sc;}

  public void run() {
    try {
      String res=null;
      while(true) {
        while (!ThreadPanel.rotate());
        if (res!=null) resultDisplay.leave(res);
        // create new slave thread
        Slave s = new Slave();
        Thread st = slaveDisplay.start(s,false);
        // continue execution
        while (ThreadPanel.rotate());
        // wait for slave termination
        st.join();
        // get and display result from slave
        res = String.valueOf(s.result());
        resultDisplay.enter(res);
      }
    } catch (InterruptedException e){}
  }
}

/*******************SLAVE************************/

class Slave implements Runnable {
  int rotations = 0;

  public void run() {
    try {
      while (!ThreadPanel.rotate()) ++rotations;
    } catch (InterruptedException e){}
  }

  int result(){
    return rotations;
  }
}


text:
label.checkbox input[type='checkbox']{margin:0;}
.side {left: 20px; position: absolute; width: 160px; transition: all 0.3s ease 0s;}
.side-handle {background: #fff none repeat scroll 0 0; border: 1px solid #d5d5d5; color: #666; cursor: pointer; line-height: 34px; padding: 0; position: absolute; right: 0; text-align: center; top: 0; transition: all 0.3s ease 0s; width: 15px; z-index: 99; }
.side-handle:hover {background: #e5e5e5 none repeat scroll 0 0; color: #141414; }
.side-body {overflow: hidden;}
.main{transition: all 0.3s ease 0s; margin-left: 180px; margin-right: 0;}
.side-body .panel {min-width: 160px;}
.hide-side .side {border: 0 none; width: 0;}
.hide-side .side .side-handle {right: -10px;}
.with-side.hide-side .main, .with-side.hide-side .side + form, .with-side .side + table {margin-left: 0;}
.side-body .tree .active{font-weight: bold;}
.side-body .tree li{margin-right: 0; padding-right: 0;}
.table-footer{transition: all 0.3s ease 0s;}


text:
*trace* - enables OpenTracing-based tracing of DNS requests as they go through the plugin chain.

## Description

With *trace* you enable OpenTracing of how a request flows through CoreDNS.

## Syntax

The simplest form is just:

~~~
trace [ENDPOINT-TYPE] [ENDPOINT]
~~~

* **ENDPOINT-TYPE** is the type of tracing destination. Currently only `zipkin` is supported
  and that is what it defaults to.
* **ENDPOINT** is the tracing destination, and defaults to `localhost:9411`. For Zipkin, if
  ENDPOINT does not begin with `http`, then it will be transformed to `http://ENDPOINT/api/v1/spans`.

With this form, all queries will be traced.

Additional features can be enabled with this syntax:

~~~
trace [ENDPOINT-TYPE] [ENDPOINT] {
	every AMOUNT
	service NAME
	client_server
}
~~~

* `every` **AMOUNT** will only trace one query of each AMOUNT queries. For example, to trace 1 in every
  100 queries, use AMOUNT of 100. The default is 1.
* `service` **NAME** allows you to specify the service name reported to the tracing server.
  Default is `coredns`.
* `client_server` will enable the `ClientServerSameSpan` OpenTracing feature.

## Zipkin
You can run Zipkin on a Docker host like this:

```
docker run -d -p 9411:9411 openzipkin/zipkin
```

## Examples

Use an alternative Zipkin address:

~~~
trace tracinghost:9253
~~~

or

~~~ corefile
. {
    trace zipkin tracinghost:9253
}
~~~

If for some reason you are using an API reverse proxy or something and need to remap
the standard Zipkin URL you can do something like:

~~~
trace http://tracinghost:9411/zipkin/api/v1/spans
~~~

Trace one query every 10000 queries, rename the service, and enable same span:

~~~
trace tracinghost:9411 {
	every 10000
	service dnsproxy
	client_server
}
~~~


text:
layout: post
title:  "Welcome to IT Sky!"
date:   2017-5-25
categories: hanggle update
---

#  MarkDown
this is a very beautiful tool for us.
```
public static void main(String [] args){
    System.out.println("Edited by MarkDown !")
}
```
l like this style.


text:
package org.jamel.j7zip.archive.sevenZip;

import org.jamel.j7zip.common.ByteBuffer;
import org.jamel.j7zip.common.ObjectVector;

class StreamSwitch {
    InArchive _archive;
    boolean _needRemove;

    public StreamSwitch() {
        _needRemove = false;
    }

    public void close() {
        remove();
    }

    void remove() {
        if (_needRemove) {
            _archive.deleteByteStream();
            _needRemove = false;
        }
    }

    void set(InArchive archive, ByteBuffer byteBuffer) {
        remove();
        _archive = archive;
        _archive.addByteStream(byteBuffer.data(), byteBuffer.GetCapacity());
        _needRemove = true;
    }

    void set(InArchive archive, ObjectVector<ByteBuffer> dataVector) throws java.io.IOException {
        remove();
        int external = archive.readByte();
        if (external != 0) {
            int dataIndex = archive.readNum();
            set(archive, dataVector.get(dataIndex));
        }
    }
}


text:
package org.fugerit.java.core.web.servlet.helper;

import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;

public class ApplicationMapHelper {

	public static int getTotalContextMapSize( ServletContext context ) {
		SerializedAttSizeFunction fun = new SerializedAttSizeFunction();
		applyFunctionOnContextAttributes( context , fun );
		return fun.getTotalSize();
	}

	public static int getTotalRequestMapSize( ServletRequest request ) {
		SerializedAttSizeFunction fun = new SerializedAttSizeFunction();
		applyFunctionOnRequestAttributes( request , fun );
		return fun.getTotalSize();
	}

	public static int getTotalSessionMapSize( HttpSession session ) {
		SerializedAttSizeFunction fun = new SerializedAttSizeFunction();
		applyFunctionOnSessionAttributes( session , fun );
		return fun.getTotalSize();
	}

	public static int applyFunctionOnContextAttributes( ServletContext context, AttributeFunction fun ) {
		int res = 0;
		Enumeration<String> keys = context.getAttributeNames();
		while ( keys.hasMoreElements() ) {
			String key = keys.nextElement();
			Object value = context.getAttribute( key );
			if ( fun.apply( key, value ).isResultOk() ) {
				res ++;
			}
		}
		return res;
	}

	public static int applyFunctionOnRequestAttributes( ServletRequest request, AttributeFunction fun ) {
		int res = 0;
		Enumeration<String> keys = request.getAttributeNames();
		while ( keys.hasMoreElements() ) {
			String key = keys.nextElement();
			Object value = request.getAttribute( key );
			if ( fun.apply( key, value ).isResultOk() ) {
				res ++;
			}
		}
		return res;
	}

	public static int applyFunctionOnSessionAttributes( HttpSession session, AttributeFunction fun ) {
		int res = 0;
		Enumeration<String> keys = session.getAttributeNames();
		while ( keys.hasMoreElements() ) {
			String key = keys.nextElement();
			Object value = session.getAttribute( key );
			if ( fun.apply( key, value ).isResultOk() ) {
				res ++;
			}
		}
		return res;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectCodeStyleSettingsManager">
    <option name="PER_PROJECT_SETTINGS">
      <value>
        <option name="USE_SAME_INDENTS" value="true" />
        <option name="IGNORE_SAME_INDENTS_FOR_LANGUAGES" value="true" />
        <option name="OTHER_INDENT_OPTIONS">
          <value>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="2" />
            <option name="TAB_SIZE" value="2" />
            <option name="USE_TAB_CHARACTER" value="false" />
            <option name="SMART_TABS" value="false" />
            <option name="LABEL_INDENT_SIZE" value="0" />
            <option name="LABEL_INDENT_ABSOLUTE" value="false" />
            <option name="USE_RELATIVE_INDENTS" value="false" />
          </value>
        </option>
        <option name="LINE_SEPARATOR" value="
" />
        <option name="FIELD_NAME_PREFIX" value="my" />
        <XML>
          <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
        </XML>
        <ADDITIONAL_INDENT_OPTIONS fileType="scala">
          <option name="INDENT_SIZE" value="2" />
          <option name="TAB_SIZE" value="2" />
        </ADDITIONAL_INDENT_OPTIONS>
        <codeStyleSettings language="Groovy">
          <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="2" />
            <option name="TAB_SIZE" value="2" />
          </indentOptions>
        </codeStyleSettings>
        <codeStyleSettings language="JAVA">
          <option name="ELSE_ON_NEW_LINE" value="true" />
          <option name="IF_BRACE_FORCE" value="1" />
          <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="2" />
            <option name="TAB_SIZE" value="2" />
          </indentOptions>
        </codeStyleSettings>
        <codeStyleSettings language="XML">
          <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="2" />
            <option name="TAB_SIZE" value="2" />
          </indentOptions>
        </codeStyleSettings>
      </value>
    </option>
    <option name="USE_PER_PROJECT_SETTINGS" value="true" />
  </component>
</project>


text:
import * as Constants from '../../constants/tracker2'
import * as Kb from '../../common-adapters'
import * as React from 'react'
import * as Styles from '../../styles'

const maxBio = 255

type Props = {
  bio: string
  fullname: string
  location: string
  title: string
  onCancel: () => void
  onSubmit: (bio: string, fullname: string, location: string) => void
}

type State = {
  bio: string
  fullname: string
  location: string
}

class EditProfile extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = {
      bio: props.bio,
      fullname: props.fullname,
      location: props.location,
    }
  }

  _disabled = () => {
    return (
      (this.state.bio === this.props.bio &&
        this.state.fullname === this.props.fullname &&
        this.state.location === this.props.location) ||
      this.state.bio.length >= maxBio
    )
  }

  _updateFullname = fullname => this.setState({fullname})
  _updateBio = bio => this.setState({bio})
  _updateLocation = location => this.setState({location})

  _submit = () => {
    this.props.onSubmit(this.state.bio, this.state.fullname, this.state.location)
  }

  // TODO use NewInput when that supports better border radius changes
  render() {
    return (
      <Kb.PopupWrapper onCancel={this.props.onCancel} title={this.props.title}>
        <Kb.ScrollView>
          <Kb.Box2 fullWidth={true} direction="vertical" style={styles.container}>
            {Styles.isMobile ? null : (
              <Kb.Text type="Header" style={styles.header}>
                Edit Profile
              </Kb.Text>
            )}
            <Kb.RoundedBox side="top">
              <Kb.PlainInput
                value={this.state.fullname}
                placeholder="Full name"
                autoFocus={true}
                onChangeText={this._updateFullname}
              />
            </Kb.RoundedBox>
            <Kb.RoundedBox side="middle">
              <Kb.PlainInput
                value={this.state.bio}
                placeholder="Bio"
                multiline={true}
                rowsMin={7}
                rowsMax={7}
                onChangeText={this._updateBio}
              />
            </Kb.RoundedBox>
            <Kb.RoundedBox side="bottom">
              <Kb.PlainInput
                value={this.state.location}
                placeholder="Location"
                onChangeText={this._updateLocation}
                onEnterKeyDown={this._submit}
              />
            </Kb.RoundedBox>
            <Kb.Box2 direction="vertical" style={styles.gap} />
            <Kb.WaitingButton
              waitingKey={Constants.waitingKey}
              label="Save"
              disabled={this._disabled()}
              onClick={this._submit}
            />
            {this.state.bio.length > maxBio && <Kb.Text type="BodySmallError">Bio too long, sorry</Kb.Text>}
          </Kb.Box2>
        </Kb.ScrollView>
      </Kb.PopupWrapper>
    )
  }
}

const styles = Styles.styleSheetCreate(() => ({
  bio: {
    maxHeight: undefined,
  },
  container: Styles.platformStyles({
    common: {
      padding: Styles.globalMargins.small,
    },
    isElectron: {
      height: 450,
      width: 350,
    },
  }),
  gap: {flexGrow: 1, minHeight: Styles.globalMargins.small},
  header: {marginBottom: Styles.globalMargins.small},
}))

export default EditProfile


text:
Filters out repeated lines in a file or input

## Why is it useful?
When looking for duplicates or generating a unique list without duplicates.

## Basic usage
`uniq [file]`

## Example
`sort names.txt | uniq` Returns the unique entries in the names.txt file

`sort names.txt | uniq -c` Returns the unique entries in the names.txt file proceeded by the number of times each entry occurred.


text:
package com.savoirfairelinux.jmeter.openstack.lib;

/**
 * @author Julien Bonjean <julien.bonjean@savoirfairelinux.com>
 */
public interface JMeterParameter {
	public String getDefaultValue();

	public String name();
}


text:
import {Factory} from 'immutable-di/define'
import LoadTodoLists from 'todomvc/todo/loaders/LoadTodoLists'

function UserInfoPageFacet({
    loadTodoLists,
    todoLists,
    user
}) {
    loadTodoLists()
    return {todoLists, user}
}

export default Factory({
    loadTodoLists: LoadTodoLists,
    user: ['user', 'current'],
    todoLists: ['todo', 'todoLists']
})(UserInfoPageFacet)


text:
require 'me2day/error/client_error'

module Me2day
  class Error
    # Raised when Me2day returns the HTTP status code 403
    class Forbidden < Me2day::Error::ClientError
      HTTP_STATUS_CODE = 403
    end
  end
end


text:
<?php
namespace Beanbun\Queue;

interface QueueInterface
{
    public function add($url);

    public function queued($url);

    public function next();

    public function count();

    public function queuedCount();

    public function isQueued($url);

    public function clean();
}


text:
from .contract import Contract
from .document import Document
from .addendum import Addendum
from .ticket import Ticket


text:
  CreateMemCpy((dst), (src), (size), (algn))
#define CREATE_MEMCPY_VOLATILE(dst, src, size, algn)                           \
  CreateMemCpy((dst), (src), (size), (algn), true)
#elif LLVM_VERSION_MAJOR >= 7 && LLVM_VERSION_MAJOR < 10
#define CREATE_MEMCPY(dst, src, size, algn)                                    \
  CreateMemCpy((dst), (algn), (src), (algn), (size))
#define CREATE_MEMCPY_VOLATILE(dst, src, size, algn)                           \
  CreateMemCpy((dst), (algn), (src), (algn), (size), true)
#elif LLVM_VERSION_MAJOR >= 10
#define CREATE_MEMCPY(dst, src, size, algn)                                    \
  CreateMemCpy((dst), MaybeAlign(algn), (src), MaybeAlign(algn), (size))
#define CREATE_MEMCPY_VOLATILE(dst, src, size, algn)                           \
  CreateMemCpy((dst), MaybeAlign(algn), (src), MaybeAlign(algn), (size), true)
#else
#error Unsupported LLVM version
#endif

#if LLVM_VERSION_MAJOR >= 10
#define CREATE_MEMSET(ptr, val, size, align)                                   \
  CreateMemSet((ptr), (val), (size), MaybeAlign((align)))
#else
#define CREATE_MEMSET(ptr, val, size, align)                                   \
  CreateMemSet((ptr), (val), (size), (align))
#endif

namespace bpftrace {
namespace ast {

using namespace llvm;

class IRBuilderBPF : public IRBuilder<>
{
public:
  IRBuilderBPF(LLVMContext &context, Module &module, BPFtrace &bpftrace);

  AllocaInst *CreateAllocaBPF(llvm::Type *ty, const std::string &name="");
  AllocaInst *CreateAllocaBPF(const SizedType &stype, const std::string &name="");
  AllocaInst *CreateAllocaBPFInit(const SizedType &stype, const std::string &name);
  AllocaInst *CreateAllocaBPF(llvm::Type *ty, llvm::Value *arraysize, const std::string &name="");
  AllocaInst *CreateAllocaBPF(const SizedType &stype, llvm::Value *arraysize, const std::string &name="");
  AllocaInst *CreateAllocaBPF(int bytes, const std::string &name="");
  llvm::Type *GetType(const SizedType &stype);
  llvm::ConstantInt *GetIntSameSize(uint64_t C, llvm::Value *expr);
  llvm::ConstantInt *GetIntSameSize(uint64_t C, llvm::Type *ty);
  CallInst *CreateBpfPseudoCallId(int mapid);
  CallInst *CreateBpfPseudoCallId(Map &map);
  CallInst *CreateBpfPseudoCallValue(int mapid);
  CallInst *CreateBpfPseudoCallValue(Map &map);
  Value *CreateMapLookupElem(Value *ctx,
                             Map &map,
                             Value *key,
                             const location &loc);
  Value *CreateMapLookupElem(Value *ctx,
                             int mapid,
                             Value *key,
                             SizedType &type,
                             const location &loc);
  void CreateMapUpdateElem(Value *ctx,
                           Map &map,
                           Value *key,
                           Value *val,
                           const location &loc);
  void CreateMapDeleteElem(Value *ctx,
                           Map &map,
                           Value *key,
                           const location &loc);
  void CreateProbeRead(Value *ctx,
                       Value *dst,
                       llvm::Value *size,
                       Value *src,
                       AddrSpace as,
                       const location &loc);
  // Emits a bpf_probe_read call in which the size is derived from the SizedType
  // argument. Has special handling for certain types such as pointers where the
  // size depends on the host system as well as the probe type.
  // If provided, the optional AddrSpace argument is used instead of the type's
  // address space (which may not always be set).
  void CreateProbeRead(Value *ctx,
                       Value *dest,
                       const SizedType &type,
                       Value *src,
                       const location &loc,
                       std::optional<AddrSpace> addrSpace = std::nullopt);
  // Emits the load instruction the type of which is derived from the provided
  // SizedType. Used to access elements from structures that ctx points to, or
  // those that have already been pulled onto the BPF stack. Correctly handles
  // pointer size differences (see CreateProbeRead).
  llvm::Value *CreateDatastructElemLoad(
      const SizedType &type,
      llvm::Value *ptr,
      bool isVolatile = false,
      std::optional<AddrSpace> addrSpace = std::nullopt);
  CallInst *CreateProbeReadStr(Value *ctx,
                               Value *dst,
                               llvm::Value *size,
                               Value *src,
                               AddrSpace as,
                               const location &loc);
  CallInst *CreateProbeReadStr(Value *ctx,
                               Value *dst,
                               size_t size,
                               Value *src,
                               AddrSpace as,
                               const location &loc);
  Value *CreateUSDTReadArgument(Value *ctx,
                                AttachPoint *attach_point,
                                int usdt_location_index,
                                int arg_name,
                                Builtin &builtin,
                                pid_t pid,
                                AddrSpace as,
                                const location &loc);
  Value *CreateStrncmp(Value *str1,
                       uint64_t str1_size,
                       Value *str2,
                       uint64_t str2_size,
                       uint64_t n,
                       bool inverse);
  CallInst *CreateGetNs(bool boot_time, const location &loc);
  CallInst *CreateGetPidTgid(const location &loc);
  CallInst *CreateGetCurrentCgroupId(const location &loc);
  CallInst *CreateGetUidGid(const location &loc);
  CallInst *CreateGetNumaId(const location &loc);
  CallInst *CreateGetCpuId(const location &loc);
  CallInst *CreateGetCurrentTask(const location &loc);
  CallInst *CreateGetRandom(const location &loc);
  CallInst   *CreateGetStackId(Value *ctx, bool ustack, StackType stack_type, const location& loc);
  CallInst   *CreateGetJoinMap(Value *ctx, const location& loc);
  CallInst *CreateHelperCall(libbpf::bpf_func_id func_id,
                             FunctionType *helper_type,
                             ArrayRef<Value *> args,
                             const Twine &Name,
                             const location *loc = nullptr);
  CallInst *createCall(FunctionType *callee_type,
                       Value *callee,
                       ArrayRef<Value *> args,
                       const Twine &Name);
  void        CreateGetCurrentComm(Value *ctx, AllocaInst *buf, size_t size, const location& loc);
  void CreatePerfEventOutput(Value *ctx,
                             Value *data,
                             size_t size,
                             const location *loc = nullptr);
  void CreateTracePrintk(Value *fmt,
                         Value *fmt_size,
                         const std::vector<Value *> &values,
                         const location &loc);
  void        CreateSignal(Value *ctx, Value *sig, const location &loc);
  void        CreateOverrideReturn(Value *ctx, Value *rc);
  void        CreateHelperError(Value *ctx, Value *return_value, libbpf::bpf_func_id func_id, const location& loc);
  void        CreateHelperErrorCond(Value *ctx, Value *return_value, libbpf::bpf_func_id func_id, const location& loc, bool compare_zero=false);
  StructType *GetStructType(std::string name, const std::vector<llvm::Type *> & elements, bool packed = false);
  AllocaInst *CreateUSym(llvm::Value *val, const location &loc);
  Value *CreateRegisterRead(Value *ctx, const std::string &builtin);
  Value *CreateRegisterRead(Value *ctx, int offset, const std::string &name);
  Value      *CreatKFuncArg(Value *ctx, SizedType& type, std::string& name);
  CallInst *CreateSkbOutput(Value *skb,
                            Value *len,
                            AllocaInst *data,
                            size_t size);
  void CreatePath(Value *ctx,
                  AllocaInst *buf,
                  Value *path,
                  const location &loc);
  void CreateSeqPrintf(Value *ctx,
                       Value *fmt,
                       Value *fmt_size,
                       Value *data,
                       Value *data_len,
                       const location &loc);

  StoreInst *createAlignedStore(Value *val, Value *ptr, unsigned align);
  // moves the insertion point to the start of the function you're inside,
  // invokes functor, then moves the insertion point back to its original
  // position. this enables you to emit instructions at the start of your
  // function. you might want to "hoist" an alloca to make it available to
  // blocks that do not follow from yours, for example to make $a accessible in
  // both branches here:
  // BEGIN { if (nsecs > 0) { $a = 1 } else { $a = 2 } print($a); exit() }
  void hoist(const std::function<void()> &functor);
  int helper_error_id_ = 0;

  // Returns the integer type used to represent pointers in traced code.
  llvm::Type *getPointerStorageTy(AddrSpace as);

private:
  Module &module_;
  BPFtrace &bpftrace_;

  Value *CreateUSDTReadArgument(Value *ctx,
                                struct bcc_usdt_argument *argument,
                                Builtin &builtin,
                                AddrSpace as,
                                const location &loc);
  CallInst *createMapLookup(int mapid, Value *key);
  libbpf::bpf_func_id selectProbeReadHelper(AddrSpace as, bool str);

  llvm::Type *getKernelPointerStorageTy();
  llvm::Type *getUserPointerStorageTy();

  std::map<std::string, StructType *> structs_;
};

} // namespace ast
} // namespace bpftrace


text:
package credentials

import (
	"encoding/xml"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

// AssumedRoleUser - The identifiers for the temporary security credentials that
// the operation returns. Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumedRoleUser
type AssumedRoleUser struct {
	Arn           string
	AssumedRoleID string `xml:"AssumeRoleId"`
}

// AssumeRoleWithClientGrantsResponse contains the result of successful AssumeRoleWithClientGrants request.
type AssumeRoleWithClientGrantsResponse struct {
	XMLName          xml.Name           `xml:"https://sts.amazonaws.com/doc/2011-06-15/ AssumeRoleWithClientGrantsResponse" json:"-"`
	Result           ClientGrantsResult `xml:"AssumeRoleWithClientGrantsResult"`
	ResponseMetadata struct {
		RequestID string `xml:"RequestId,omitempty"`
	} `xml:"ResponseMetadata,omitempty"`
}

// ClientGrantsResult - Contains the response to a successful AssumeRoleWithClientGrants
// request, including temporary credentials that can be used to make MinIO API requests.
type ClientGrantsResult struct {
	AssumedRoleUser AssumedRoleUser `xml:",omitempty"`
	Audience        string          `xml:",omitempty"`
	Credentials     struct {
		AccessKey    string    `xml:"AccessKeyId" json:"accessKey,omitempty"`
		SecretKey    string    `xml:"SecretAccessKey" json:"secretKey,omitempty"`
		Expiration   time.Time `xml:"Expiration" json:"expiration,omitempty"`
		SessionToken string    `xml:"SessionToken" json:"sessionToken,omitempty"`
	} `xml:",omitempty"`
	PackedPolicySize             int    `xml:",omitempty"`
	Provider                     string `xml:",omitempty"`
	SubjectFromClientGrantsToken string `xml:",omitempty"`
}

// ClientGrantsToken - client grants token with expiry.
type ClientGrantsToken struct {
	Token  string
	Expiry int
}

// A STSClientGrants retrieves credentials from MinIO service, and keeps track if
// those credentials are expired.
type STSClientGrants struct {
	Expiry

	// Required http Client to use when connecting to MinIO STS service.
	Client *http.Client

	// MinIO endpoint to fetch STS credentials.
	stsEndpoint string

	// getClientGrantsTokenExpiry function to retrieve tokens
	// from IDP This function should return two values one is
	// accessToken which is a self contained access token (JWT)
	// and second return value is the expiry associated with
	// this token. This is a customer provided function and
	// is mandatory.
	getClientGrantsTokenExpiry func() (*ClientGrantsToken, error)
}

// NewSTSClientGrants returns a pointer to a new
// Credentials object wrapping the STSClientGrants.
func NewSTSClientGrants(stsEndpoint string, getClientGrantsTokenExpiry func() (*ClientGrantsToken, error)) (*Credentials, error) {
	if stsEndpoint == "" {
		return nil, errors.New("STS endpoint cannot be empty")
	}
	if getClientGrantsTokenExpiry == nil {
		return nil, errors.New("Client grants access token and expiry retrieval function should be defined")
	}
	return New(&STSClientGrants{
		Client: &http.Client{
			Transport: http.DefaultTransport,
		},
		stsEndpoint:                stsEndpoint,
		getClientGrantsTokenExpiry: getClientGrantsTokenExpiry,
	}), nil
}

func getClientGrantsCredentials(clnt *http.Client, endpoint string,
	getClientGrantsTokenExpiry func() (*ClientGrantsToken, error)) (AssumeRoleWithClientGrantsResponse, error) {

	accessToken, err := getClientGrantsTokenExpiry()
	if err != nil {
		return AssumeRoleWithClientGrantsResponse{}, err
	}

	v := url.Values{}
	v.Set("Action", "AssumeRoleWithClientGrants")
	v.Set("Token", accessToken.Token)
	v.Set("DurationSeconds", fmt.Sprintf("%d", accessToken.Expiry))
	v.Set("Version", "2011-06-15")

	u, err := url.Parse(endpoint)
	if err != nil {
		return AssumeRoleWithClientGrantsResponse{}, err
	}
	u.RawQuery = v.Encode()

	req, err := http.NewRequest("POST", u.String(), nil)
	if err != nil {
		return AssumeRoleWithClientGrantsResponse{}, err
	}
	resp, err := clnt.Do(req)
	if err != nil {
		return AssumeRoleWithClientGrantsResponse{}, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return AssumeRoleWithClientGrantsResponse{}, errors.New(resp.Status)
	}

	a := AssumeRoleWithClientGrantsResponse{}
	if err = xml.NewDecoder(resp.Body).Decode(&a); err != nil {
		return AssumeRoleWithClientGrantsResponse{}, err
	}
	return a, nil
}

// Retrieve retrieves credentials from the MinIO service.
// Error will be returned if the request fails.
func (m *STSClientGrants) Retrieve() (Value, error) {
	a, err := getClientGrantsCredentials(m.Client, m.stsEndpoint, m.getClientGrantsTokenExpiry)
	if err != nil {
		return Value{}, err
	}

	// Expiry window is set to 10secs.
	m.SetExpiration(a.Result.Credentials.Expiration, DefaultExpiryWindow)

	return Value{
		AccessKeyID:     a.Result.Credentials.AccessKey,
		SecretAccessKey: a.Result.Credentials.SecretKey,
		SessionToken:    a.Result.Credentials.SessionToken,
		SignerType:      SignatureV4,
	}, nil
}


text:
import { Tag } from './Tag';

/**
 * @access public
 */
export class CapabilityTag extends Tag {
    static readonly Type = 'capability';

    constructor(capability: string) {
        super(capability, CapabilityTag.Type);
    }
}


text:
datarouter-aws-elb provides tools to monitor amazon's elastic-load-balancer configurations for the application.

## Installation with Maven

```xml
<dependency>
	<groupId>io.datarouter</groupId>
	<artifactId>datarouter-aws-elb</artifactId>
	<version>0.0.117</version>
</dependency>
```

## Installation with Datarouter

You can install this module by adding its plugin to the `WebappBuilder`.

```java
.addJobPlugin(new DatarouterAwsElbPlugin())
```

## License

This library is licensed under the Apache License, Version 2.0 - see [LICENSE](../LICENSE) for details.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<resources>
  <string name="app_name">c:geo - calendario (complemento)</string>
  <string name="calendars">Calendarios</string>
  <string name="event_success">Evento añadido al calendario</string>
  <string name="event_fail">Error al añadir el evento al calendario</string>
</resources>


text:
<?php echo get_sympal_content_slot('title', array('type' => 'Text')) ?>

<?php echo get_sympal_content_slot('body', array('type' => 'Markdown')) ?>


text:
import pytest
from radosgw_agent.util import network
import random

def valid_ipv6_addr(ports=False, brackets=False, addresses=20):
    max_rand_int = 16**4

    def generate(brackets, ports):
        address = ":".join(
            ("%x" % random.randint(0, max_rand_int) for i in range(8))
        )
        if brackets:
            address =  '[%s]' % address
        if ports:
            address = '%s:8080' % address
        return address
    return [generate(brackets, ports) for i in range(addresses)]

def invalid_ipv6_addr():
    return [
        '',
        1,
        'some address',
        '192.1.1.1',
        '::!',
    ]

class TestIsIPV6(object):

    @pytest.mark.parametrize('address', valid_ipv6_addr())
    def test_passes_valid_addresses(self, address):
        assert network.is_ipv6(address) is True

    @pytest.mark.parametrize('address', valid_ipv6_addr(brackets=True))
    def test_passes_valid_addresses_with_brackets(self, address):
        assert network.is_ipv6(address) is True

    @pytest.mark.parametrize('address', invalid_ipv6_addr())
    def test_catches_invalid_addresses(self, address):
        assert network.is_ipv6(address) is False

    @pytest.mark.parametrize('address', valid_ipv6_addr(ports=True, brackets=True))
    def test_passes_valid_addresses_with_brackets_and_ports(self, address):
        assert network.is_ipv6(address) is True


text:
from .dummypart import DummyPart  # noqa

# Expose all the classes
__all__ = sorted(k for k, v in globals().items() if type(v) == type)


text:
#region License

// Copyright 2011 Linquize
//
// 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.
//
// The latest version of this file can be found at http://github.com/Linquize/git-dot-aspx

#endregion

using System;
using GitAspx.Lib;
using GitAspx.ViewModels;
using GitSharp;

namespace GitAspx.Controllers
{
    public class TreeViewController : WebBrowsingBaseController<TreeViewModel>
    {
        public TreeViewController(RepositoryService repositories) : base(repositories) { }

        public override void Browse()
        {
            Tree loTree = Model.RootTree;
            Tree loTree2 = null;
            if (Model.PathSegments.Length > 0)
                loTree2 = Model.RootTree[string.Join("/", Model.PathSegments)] as Tree;
            if (loTree2 != null)
                loTree = loTree2;
            Model.Directories = loTree.Trees;
            Model.Files = loTree.Leaves;
        }
    }
}


text:
{% block body %}

Thanks!

Your account has been activated, if you need calcel it follow this link:

            {{ base_url}}/cancel-account/{{ cancel_token }}

See later.

{% endblock %}

{% block footer %}

    The Taiga development team.

{% endblock %}


text:
package io.scigraph.owlapi.cases;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import io.scigraph.neo4j.GraphUtil;
import io.scigraph.owlapi.OwlRelationships;

import org.hamcrest.collection.IsIterableWithSize;
import org.junit.Test;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;

/***
 * See https://github.com/SciCrunch/SciGraph/wiki/MappingToOWL#subclassof-axioms
 *
 */
public class TestSubObjectPropertyOf extends OwlTestCase {

  @Test
  public void testSubclass() {
    Node subp = getNode("http://example.org/subproperty");
    Node superp = getNode("http://example.org/superproperty");
    assertThat("subclass should be a directed relationship",
        GraphUtil.getRelationships(subp, superp, OwlRelationships.RDFS_SUB_PROPERTY_OF),
        is(IsIterableWithSize.<Relationship> iterableWithSize(1)));
  }

}


text:
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta charset="UTF-8" />
  <title>App</title>
  <link rel="stylesheet" href="css-ext-import.css" />
</head>
<body>
body
</body>
</html>


text:
require 'results/dibs_result.rb'
require 'results/authorize.rb'
require 'results/capture.rb'