text:
package org.squbs.pipeline

import akka.actor.ActorSystem
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.stream.scaladsl._
import akka.stream.BidiShape
import akka.testkit.TestKit
import akka.util.ByteString
import com.typesafe.config.ConfigFactory
import org.scalatest.flatspec.AnyFlatSpecLike
import org.scalatest.matchers.should.Matchers
import org.squbs.pipeline.Timeouts.awaitMax

import scala.concurrent.Await
import scala.util.{Success, Try}

class PipelineExtensionSpec extends TestKit(ActorSystem("PipelineExtensionSpec", PipelineExtensionSpec.config))
  with AnyFlatSpecLike with Matchers {

  val pipelineExtension = PipelineExtension(system)
  val dummyEndpoint = Flow[RequestContext].map { r =>
    r.withResponse(Try(HttpResponse(entity = s"${r.request.headers.sortBy(_.name).mkString(",")}")))
  }

  it should "build the flow with defaults" in {
    val pipelineFlow = pipelineExtension.getFlow((Some("dummyFlow1"), Some(true)), Context("dummy", ServerPipeline))

    pipelineFlow should not be (None)
    val httpFlow = pipelineFlow.get.join(dummyEndpoint)
    val future = Source.single(RequestContext(HttpRequest(), 0)).runWith(httpFlow.toMat(Sink.head)(Keep.right))
    val rc = Await.result(future, awaitMax)

    rc.response should not be (None)
    val Some(Success(httpResponse)) = rc.response
    httpResponse.headers.sortBy(_.name) should equal(Seq(RawHeader("keyD", "valD"),
                                                         RawHeader("keyPreOutbound", "valPreOutbound"),
                                                         RawHeader("keyPostOutbound", "valPostOutbound")).sortBy(_.name))
    import system.dispatcher
    val actualEntity = Await.result(httpResponse.entity.dataBytes.runFold(ByteString(""))(_ ++ _) map(_.utf8String), awaitMax)
    val expectedEntity = Seq( RawHeader("keyA", "valA"),
                              RawHeader("keyB", "valB"),
                              RawHeader("keyC", "valC"),
                              RawHeader("keyPreInbound", "valPreInbound"),
                              RawHeader("keyPostInbound", "valPostInbound")).sortBy(_.name).mkString(",")
    actualEntity should equal(expectedEntity)
  }

  it should "build the flow without defaults when defaults are turned off" in {
    val pipelineFlow = pipelineExtension.getFlow((Some("dummyFlow1"), Some(false)), Context("dummy", ServerPipeline))

    pipelineFlow should not be (None)
    val httpFlow = pipelineFlow.get.join(dummyEndpoint)
    val future = Source.single(RequestContext(HttpRequest(), 0)).runWith(httpFlow.toMat(Sink.head)(Keep.right))
    val rc = Await.result(future, awaitMax)

    rc.response should not be (None)
    val Some(Success(httpResponse)) = rc.response
    httpResponse.headers should equal(Seq(RawHeader("keyD", "valD")))
    import system.dispatcher
    val actualEntity = Await.result(httpResponse.entity.dataBytes.runFold(ByteString(""))(_ ++ _) map(_.utf8String), awaitMax)
    val expectedEntity = Seq( RawHeader("keyA", "valA"),
                              RawHeader("keyB", "valB"),
                              RawHeader("keyC", "valC")).sortBy(_.name).mkString(",")
    actualEntity should equal(expectedEntity)
  }

  it should "throw IllegalArgumentException when getFlow is called with a bad flow name" in {
    intercept[IllegalArgumentException] {
      pipelineExtension.getFlow((Some("badPipelineName"), Some(true)), Context("dummy", ServerPipeline))
    }
  }

  it should "return None when no custom flow exists and defaults are off" in {
    pipelineExtension.getFlow((None, Some(false)), Context("dummy", ServerPipeline)) should be (None)
  }

  it should "build the flow with defaults when defaultsOn param is set to None" in {
    pipelineExtension.getFlow((None, None), Context("dummy", ServerPipeline)) should not be (None)
  }
}

object PipelineExtensionSpec {
  val config = ConfigFactory.parseString(
    s"""
       |dummyFlow1 {
       |  type = squbs.pipelineflow
       |  factory = org.squbs.pipeline.DummyFlow1
       |}
       |
       |preFlow {
       |  type = squbs.pipelineflow
       |  factory = org.squbs.pipeline.PreFlow
       |}
       |
       |postFlow {
       |  type = squbs.pipelineflow
       |  factory = org.squbs.pipeline.PostFlow
       |}
       |
       |squbs.pipeline.server.default {
       |  pre-flow =  preFlow
       |  post-flow = postFlow
       |}
    """.stripMargin
  )
}

class PipelineExtensionSpec2 extends TestKit(ActorSystem("PipelineExtensionSpec2", ConfigFactory.parseString(
  s"""
     |notExists {
     |  type = squbs.pipelineflow
     |  factory = org.squbs.pipeline.NotExists
     |}
   """.stripMargin))) with AnyFlatSpecLike with Matchers {

  it should "throw ClassNotFoundException when a squbs.pipelineflow factory class does not exist." in {
    intercept[ClassNotFoundException] {
      PipelineExtension(system)
    }
  }
}

class PipelineExtensionSpec3 extends TestKit(ActorSystem("PipelineExtensionSpec3", ConfigFactory.parseString(
  s"""
     |dummyFlow1 {
     |  type = squbs.pipelineflow
     |  factory = org.squbs.pipeline.DummyFlow1
     |}
   """.stripMargin))) with AnyFlatSpecLike with Matchers {

  val pipelineExtension = PipelineExtension(system)
  val dummyEndpoint = Flow[RequestContext].map { r =>
    r.withResponse(Try(HttpResponse(entity = s"${r.request.headers.sortBy(_.name).mkString(",")}")))
  }

  it should "return None when no custom flow exists and no defaults specified in config" in {
    pipelineExtension.getFlow((None, Some(true)), Context("dummy", ServerPipeline)) should be (None)
  }

  it should "be able to build the flow when no defaults are specified in config" in {
    val pipelineFlow = pipelineExtension.getFlow((Some("dummyFlow1"), Some(true)), Context("dummy", ServerPipeline))

    pipelineFlow should not be (None)
    val httpFlow = pipelineFlow.get.join(dummyEndpoint)
    val future = Source.single(RequestContext(HttpRequest(), 0)).runWith(httpFlow.toMat(Sink.head)(Keep.right))
    val rc = Await.result(future, awaitMax)

    rc.response should not be (None)
    val Some(Success(httpResponse)) = rc.response
    httpResponse.headers should equal(Seq(RawHeader("keyD", "valD")))
    import system.dispatcher
    val entity = Await.result(httpResponse.entity.dataBytes.runFold(ByteString(""))(_ ++ _) map(_.utf8String), awaitMax)
    entity should equal("keyA: valA,keyB: valB,keyC: valC")
  }
}

class DummyFlow1 extends PipelineFlowFactory {

  override def create(context: Context)(implicit system: ActorSystem): PipelineFlow = {

    BidiFlow.fromGraph(GraphDSL.create() { implicit b =>
      import GraphDSL.Implicits._

      val stageA = b.add(Flow[RequestContext].map { rc => rc.withRequestHeaders(RawHeader("keyA", "valA")) })
      val stageB = b.add(Flow[RequestContext].map { rc => rc.withRequestHeaders(RawHeader("keyB", "valB")) })
      val stageC = b.add(dummyBidi)
      val stageD = b.add(Flow[RequestContext].map { rc => rc.withResponseHeaders(RawHeader("keyD", "valD")) })

      stageA ~> stageB ~> stageC.in1
      stageD <~           stageC.out2

      BidiShape(stageA.in, stageC.out1, stageC.in2, stageD.out)
    })
  }

  val dummyBidi = BidiFlow.fromGraph(GraphDSL.create() { implicit b =>
    val requestFlow = b.add(Flow[RequestContext].map { rc => rc.withRequestHeaders(RawHeader("keyC", "valC")) } )
    val responseFlow = b.add(Flow[RequestContext])
    BidiShape.fromFlows(requestFlow, responseFlow)
  })
}

class PreFlow extends PipelineFlowFactory {

  override def create(context: Context)(implicit system: ActorSystem): PipelineFlow = {

    BidiFlow.fromGraph(GraphDSL.create() { implicit b =>
      val inbound = b.add(Flow[RequestContext].map { rc => rc.withRequestHeaders(RawHeader("keyPreInbound", "valPreInbound")) })
      val outbound = b.add(Flow[RequestContext].map { rc => rc.withResponseHeaders(RawHeader("keyPreOutbound", "valPreOutbound")) })
      BidiShape.fromFlows(inbound, outbound)
    })
  }
}

class PostFlow extends PipelineFlowFactory {

  override def create(context: Context)(implicit system: ActorSystem): PipelineFlow = {

    BidiFlow.fromGraph(GraphDSL.create() { implicit b =>
      val inbound = b.add(Flow[RequestContext].map { rc => rc.withRequestHeaders(RawHeader("keyPostInbound", "valPostInbound")) })
      val outbound = b.add(Flow[RequestContext].map { rc => rc.withResponseHeaders(RawHeader("keyPostOutbound", "valPostOutbound")) })
      BidiShape.fromFlows(inbound, outbound)
    })
  }
}


text:
<?php

namespace chillerlan\Authenticator;

use chillerlan\Settings\SettingsContainerAbstract;

/**
 * @property int    $digits
 * @property int    $period
 * @property int    $secret_length
 * @property string $algorithm
 * @property string $mode
 * @property int    $adjacent
 */
class AuthenticatorOptions extends SettingsContainerAbstract{
	use AuthenticatorOptionsTrait;
}

redpajama_set_name: RedPajamaGithub


text:
#include "YGJNIVanilla.h"
#include "common.h"

using namespace facebook::yoga;

jint JNI_OnLoad(JavaVM* vm, void*) {
  JNIEnv* env;
  jint ret = vanillajni::ensureInitialized(&env, vm);
  YGJNIVanilla::registerNatives(env);
  return ret;
}


text:
package trademark

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// QueryQrCodeUploadStatus invokes the trademark.QueryQrCodeUploadStatus API synchronously
// api document: https://help.aliyun.com/api/trademark/queryqrcodeuploadstatus.html
func (client *Client) QueryQrCodeUploadStatus(request *QueryQrCodeUploadStatusRequest) (response *QueryQrCodeUploadStatusResponse, err error) {
	response = CreateQueryQrCodeUploadStatusResponse()
	err = client.DoAction(request, response)
	return
}

// QueryQrCodeUploadStatusWithChan invokes the trademark.QueryQrCodeUploadStatus API asynchronously
// api document: https://help.aliyun.com/api/trademark/queryqrcodeuploadstatus.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) QueryQrCodeUploadStatusWithChan(request *QueryQrCodeUploadStatusRequest) (<-chan *QueryQrCodeUploadStatusResponse, <-chan error) {
	responseChan := make(chan *QueryQrCodeUploadStatusResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.QueryQrCodeUploadStatus(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// QueryQrCodeUploadStatusWithCallback invokes the trademark.QueryQrCodeUploadStatus API asynchronously
// api document: https://help.aliyun.com/api/trademark/queryqrcodeuploadstatus.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) QueryQrCodeUploadStatusWithCallback(request *QueryQrCodeUploadStatusRequest, callback func(response *QueryQrCodeUploadStatusResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *QueryQrCodeUploadStatusResponse
		var err error
		defer close(result)
		response, err = client.QueryQrCodeUploadStatus(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// QueryQrCodeUploadStatusRequest is the request struct for api QueryQrCodeUploadStatus
type QueryQrCodeUploadStatusRequest struct {
	*requests.RpcRequest
	OssKey   string `position:"Query" name:"OssKey"`
	FieldKey string `position:"Query" name:"FieldKey"`
	Uuid     string `position:"Query" name:"Uuid"`
}

// QueryQrCodeUploadStatusResponse is the response struct for api QueryQrCodeUploadStatus
type QueryQrCodeUploadStatusResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	OssKey    string `json:"OssKey" xml:"OssKey"`
	OssUrl    string `json:"OssUrl" xml:"OssUrl"`
	Status    int    `json:"Status" xml:"Status"`
	Success   bool   `json:"Success" xml:"Success"`
}

// CreateQueryQrCodeUploadStatusRequest creates a request to invoke QueryQrCodeUploadStatus API
func CreateQueryQrCodeUploadStatusRequest() (request *QueryQrCodeUploadStatusRequest) {
	request = &QueryQrCodeUploadStatusRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Trademark", "2018-07-24", "QueryQrCodeUploadStatus", "trademark", "openAPI")
	return
}

// CreateQueryQrCodeUploadStatusResponse creates a response to parse from QueryQrCodeUploadStatus response
func CreateQueryQrCodeUploadStatusResponse() (response *QueryQrCodeUploadStatusResponse) {
	response = &QueryQrCodeUploadStatusResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_background_list"
    tools:context=".CreditsActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:fitsSystemWindows="true"
        >

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="@color/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp"
            >

            <ImageView
                android:id="@+id/iv_clint_avatar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@drawable/ic_person_grey"
                />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_height="?attr/actionBarSize"
                android:layout_width="match_parent"
                android:minHeight="?attr/actionBarSize"
                app:elevation="0dp"
                app:layout_collapseMode="pin"
                />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/content_area"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:paddingTop="24dp"
        android:paddingStart="16dp"
        android:paddingEnd="16dp"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="lalala"
            />
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:src="@drawable/ic_add_white_24dp"
        app:backgroundTint="@color/accent"
        app:fabSize="mini"
        android:layout_marginEnd="@dimen/fab_margin_right"
        android:layout_marginBottom="@dimen/fab_margin_bottom"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"

        />

</android.support.design.widget.CoordinatorLayout>


text:
This code is often convenient for simulating global-scale tsunami propagation.

It enables a variety of shallow water solvers to be used on a single grid in
spherical coordinates.

[Davies and Griffin (2018, p 178)](https://dx.doi.org/10.11636/Record.2018.041)
used this code to compare the linear shallow water solvers in SWALS with the
JAGURS model. That test case showed negligible differences in modelled wave
maxima and time-series between the two codes. That might be expected given
that the linear solvers in SWALS and JAGURS implement very similar staggered
grid numerical methods (albeit their implementations are completely different).

It you wish to create more complex models (e.g. with nesting, or different
boundary conditions) it is better to start from [../periodic_multidomain](../periodic_multidomain).

## The tests

The test-suite runs this code in the source-region of the 2011 Tohoku tsunami,
using a number of different solver options. The earthquake source was selected
from among randomly generated sources, so is not a precise representation of
the real forcing of Tohoku.

We perform a regression test by checking that the difference between the
modelled and observed wave is very close to previously computed values (which
are distinct for each solver). The idea is to detect any changes in the solver
predictions; the model is not supposed to give precise agreement to the data.

We also check that for models using a rise-time (i.e. applying the earthquake
forcing over a finite time), the solutions are equivalent to temporally
smoothed solutions from models using an instantaneous forcing.

* This is true analytically for the linear shallow water equations.

* In the specific situation tested, it is also a good approximation for the nonlinear shallow water equations.

## How to adapt the code to another case

* Copy one of the '\*.in' files to a new file (e.g. 'my_model.in'), and edit it
to ensure that the input_elevation_raster and input_stage_raster exist on your
filesystem, and that the model extents are as desired. The input rasters should
give the initial elevation and stage in lon-lat coordinates.

* The elevation raster should cover the desired model domain, but it can
have a larger north-east-south-west extent than the model. The
model will get the data it needs using bilinear interpolation. So for example,
you can run a small area model using a global DEM, without editing the DEM.
Furthermore it is not essential for the model resolution to match the data
resolution.  However the model does not correct for the periodicity of
longitude when extracting raster data. For instance, if the input raster has
east-west extent [-180, 180], then the tsunami model cannot have east-west
extent like [0, 360], but it could have [-180, 180], or [-180, 12], or [-50,
100], etc.

* The stage raster can be either smaller or larger than the desired model domain. The
model will extract stages from this raster where possible, using bilinear
interpolation. It will use a value of 0 elsewhere.

* If the model extent covers 360 degrees of longitude (e.g. [0, 360] or [-180, 180] or [-40, 320]),
then east-west periodic boundary conditions are used, with reflective
north-south boundaries. In this case, the EW model boundaries should agree
exactly with the EW boundaries of the input elevation data.

* If the model extent does not cover 360 degrees of longitudde, a transmissive
  boundary is used.

Then compile and run the model with (e.g.):

    make -B -f make_generic_model
    OMP_NUM_THREADS=6 ./generic_model my_model.in

The above code uses 6 openmp threads -- you can use any number relevant to your system.
It can also be advantageous to control the process affinity (e.g. include
"OMP_PROC_BIND=true" in the model run command), although this depends on your
hardware and what other jobs are being run.


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Button;

use Oro\Bundle\ActionBundle\Button\ButtonContext;
use Oro\Bundle\ActionBundle\Button\ButtonInterface;
use Oro\Bundle\WorkflowBundle\Button\TransitionButton;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Model\Transition;
use Oro\Bundle\WorkflowBundle\Model\Workflow;

class TransitionButtonTest extends \PHPUnit\Framework\TestCase
{
    /** @var Workflow|\PHPUnit\Framework\MockObject\MockObject */
    protected $workflow;

    /** @var WorkflowDefinition|\PHPUnit\Framework\MockObject\MockObject */
    protected $definition;

    /** @var Transition|\PHPUnit\Framework\MockObject\MockObject */
    protected $transition;

    /** @var ButtonContext|\PHPUnit\Framework\MockObject\MockObject */
    protected $buttonContext;

    /** @var TransitionButton */
    protected $button;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->transition = $this->getMockBuilder(Transition::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->definition = $this->getMockBuilder(WorkflowDefinition::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->workflow = $this->getMockBuilder(Workflow::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->workflow->expects($this->any())->method('getDefinition')->willReturn($this->definition);

        $this->buttonContext = $this->getMockBuilder(ButtonContext::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->button = new TransitionButton($this->transition, $this->workflow, $this->buttonContext);
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        unset($this->workflow, $this->definition, $this->button, $this->buttonContext, $this->transition);
    }

    public function testGetName()
    {
        $this->workflow->expects($this->once())->method('getName')->willReturn('test_workflow_name');
        $this->transition->expects($this->once())->method('getName')->willReturn('test_transition_name');

        $this->assertEquals('test_workflow_name_test_transition_name', $this->button->getName());
    }

    public function testGetLabel()
    {
        $label = 'test_label';
        $this->transition->expects($this->once())->method('getButtonLabel')->willReturn($label);

        $this->assertEquals($label, $this->button->getLabel());
    }

    public function testGetIcon()
    {
        $this->assertNull($this->button->getIcon());

        $icon = 'test-icon';
        $this->transition->expects($this->once())->method('getFrontendOptions')->willReturn(['icon' => $icon]);

        $this->assertEquals($icon, $this->button->getIcon());
    }

    public function testGetOrder()
    {
        $this->definition->expects($this->once())->method('getPriority')->willReturn(1);
        $this->assertEquals(1, $this->button->getOrder());
    }

    public function testGetTemplate()
    {
        $this->assertEquals(TransitionButton::DEFAULT_TEMPLATE, $this->button->getTemplate());
    }

    /**
     * @dataProvider getTemplateDataDataProvider
     *
     * @param array $customData
     */
    public function testGetTemplateData(array $customData = [])
    {
        $defaultData =             [
            'frontendOptions' => $this->transition->getFrontendOptions(),
            'hasForm' => $this->transition->hasForm(),
            'showDialog' => true,
            'routeParams' => [
                'workflowName' => $this->workflow->getName(),
                'transitionName' => $this->transition->getName(),
                'entityClass' => $this->buttonContext->getEntityClass(),
                'entityId' => $this->buttonContext->getEntityId(),
                'route' => $this->buttonContext->getRouteName(),
                'datagrid' => $this->buttonContext->getDatagridName(),
                'group' => $this->buttonContext->getGroup(),
                'originalUrl' => $this->buttonContext->getOriginalUrl(),
                'workflowItemId' => null
            ],
            'executionRoute' => $this->buttonContext->getExecutionRoute(),
            'requestMethod' => 'POST',
            'dialogRoute' => null,
            'additionalData' => [],
            'jsDialogWidget' => TransitionButton::TRANSITION_JS_DIALOG_WIDGET,
        ];

        $this->assertEquals(array_merge($defaultData, $customData), $this->button->getTemplateData($customData));
    }

    /**
     * @return array
     */
    public function getTemplateDataDataProvider()
    {
        return [
            'no custom data' => [],
            'with custom data' => ['customData' => ['workflowItem' => 'test_item', 'new index' => 'test value']],
        ];
    }

    public function testGetButtonContext()
    {
        $this->assertInstanceOf(ButtonContext::class, $this->button->getButtonContext());
    }

    public function testGetGroup()
    {
        $this->assertEquals(ButtonInterface::DEFAULT_GROUP, $this->button->getGroup());
    }

    public function testGetWorkflow()
    {
        $this->assertSame($this->workflow, $this->button->getWorkflow());
    }

    public function testGetTransition()
    {
        $this->assertEquals($this->transition, $this->button->getTransition());
    }

    public function testGetTranslationDomain()
    {
        $this->assertEquals('workflows', $this->button->getTranslationDomain());
    }

    public function testClone()
    {
        $newButton = clone $this->button;
        $this->assertEquals($newButton, $this->button);
        $this->assertEquals($newButton->getTransition(), $this->button->getTransition());

        $this->assertNotSame($newButton, $this->button);
        $this->assertNotSame($newButton->getTransition(), $this->button->getTransition());
    }
}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="shape_size">100dp</dimen>
    <dimen name="shape_border_width">2dp</dimen>

    <dimen name="drop_zone_box_width">152dp</dimen>
    <dimen name="drop_zone_box_height">152dp</dimen>
    <dimen name="drop_zone_padding">16dp</dimen>
    <dimen name="drop_zone_box_internal_shape_padding">2dp</dimen>
    <dimen name="drop_zone_box_internal_shape_width">60dp</dimen>
    <dimen name="drop_zone_box_internal_shape_height">60dp</dimen>
    <dimen name="drop_zone_box_internal_icon_margin_top">24dp</dimen>
    <dimen name="drop_zone_box_internal_shape_margin_top">0dp</dimen>

</resources>


text:
namespace media {

LineSegmentFrame::LineSegmentFrame(const FrameBase& aFrame)
    {
    Q_ASSERT(isCopyable(aFrame));
    setMaxVectors(aFrame.getDimensionT(VectorNo).mResolution);
    setVectorSizeT(VectorSize);
    int point[Dimensions] = {0, 0};
    for (point[VectorNo] = 0; point[VectorNo] < aFrame.getDimensionT(VectorNo).mResolution; ++point[VectorNo])
        for (point[ParamNo] = 0; point[ParamNo] < aFrame.getDimensionT(ParamNo).mResolution; ++point[ParamNo])
            setSampleT(point, aFrame.getSampleT(point));
    }

} // namespace media


text:
/*
 *  RegExp executor recursion limit
 */

/* Marked custom because limit is custom behavior. */
/*---
{
    "custom": true
}
---*/

/*===
success for: 1
success for: 10
success for: 100
success for: 1000
failure for: 10000 -> RangeError
===*/

function createRegexp(n) {
    var res = [];
    var i;

    // Each non-simple expression (where alternatives match different char
    // counts) cause executor recursion without causing compiler recursion.
    // The pattern and input must be such that the recursion actually
    // realizes.  Avoid making the input non-matching: this will cause a
    // long timeout due to execution *step limit* due to back tracking,
    // which we're not testing here.

    res = '';
    for (i = 0; i < n; i++) {
      res = '(?:y|y.)' + res;
    }

    return res;
}

function wrappedTest(n) {
    var src, reg;
    var input;

    try {
        src = createRegexp(n);
        reg = new RegExp(src);
        input = '';
        while (input.length < n) { input += 'y'; }
        reg.exec(input);
        print('success for:', n);
    } catch (e) {
        print('failure for:', n, '->', e.name);
    }
}

function test() {
    wrappedTest(1);
    wrappedTest(10);
    wrappedTest(100);
    wrappedTest(1000);
    wrappedTest(10000);
}

try {
    test();
} catch (e) {
    print(e.stack || e);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="zend.currency.position"><info><title>Où est le symbole monnétaire?</title></info>

    <para>
        Le signe symbolique de la monnaie est positionné par rapport à sa valeur en fonction de
        la locale utilisée. Cependant, vous pouvez forcer ce positionnement grâce à l'option
        <property>display</property> qui se configure au moyen de constantes:
    </para>

    <table xml:id="zend.currency.position.table-1"><info><title>Positions disponibles pour la monnaie</title></info>

        <tgroup cols="2" align="left">
            <thead>
                <row>
                    <entry>Constante</entry>
                    <entry>Description</entry>
                </row>
            </thead>

            <tbody>
                <row>
                    <entry><constant>STANDARD</constant></entry>
                    <entry>Affiche le symbole de la monnaie dans une position standard,
                    conforme à la locale</entry>
                </row>

                <row>
                    <entry><constant>RIGHT</constant></entry>

                    <entry>
                        Affiche le symbole de la monnaie à droite de sa valeur
                    </entry>
                </row>

                <row>
                    <entry><constant>LEFT</constant></entry>

                    <entry>
                        Affiche le symbole de la monnaie à gauche de sa valeur
                    </entry>
                </row>
            </tbody>
        </tgroup>
    </table>

    <example xml:id="zend.currency.position.example-1"><info><title>Paramétrer la position du symbole monnétaire</title></info>

        <para>
            Imaginons que le client utilise la locale "en_US". Sans option, la valeur retournée
            serait par exemple:
        </para>

        <programlisting language="php"><![CDATA[
$currency = new Zend_Currency(
    array(
        'value' => 100,
    )
);

print $currency; // Retournerait '$ 100'
]]></programlisting>

        <para>
            En utilisant la valeur par défaut, le symbole pourrait être retourné à gauche ou à droite
            de la valeur de monnaie. Voyons comment fixer cette position:
        </para>

        <programlisting language="php"><![CDATA[
$currency = new Zend_Currency(
    array(
        'value'    => 100,
        'position' => Zend_Currency::RIGHT,
    )
);

print $currency; // Retournerait '100 $';
]]></programlisting>

        <para>
            Notez que dans le deuxième exemple, la position de <acronym>USD</acronym> est fixée
            quelle que soit la locale ou la monnaie considérée.
        </para>
    </example>
</section>


text:
package kubernetes

import (
	"reflect"
	"testing"
	"time"

	proxyoptions "k8s.io/kubernetes/cmd/kube-proxy/app/options"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/apis/componentconfig"
	"k8s.io/kubernetes/pkg/kubelet/qos"
)

func TestProxyConfig(t *testing.T) {
	// This is a snapshot of the default config
	// If the default changes (new fields are added, or default values change), we want to know
	// Once we've reacted to the changes appropriately in buildKubeProxyConfig(), update this expected default to match the new upstream defaults
	oomScoreAdj := qos.KubeProxyOOMScoreAdj
	ipTablesMasqueratebit := 14
	expectedDefaultConfig := &proxyoptions.ProxyServerConfig{
		KubeProxyConfiguration: componentconfig.KubeProxyConfiguration{
			BindAddress:        "0.0.0.0",
			HealthzPort:        10249,
			HealthzBindAddress: "127.0.0.1",
			OOMScoreAdj:        &oomScoreAdj,
			ResourceContainer:  "/kube-proxy",
			IPTablesSyncPeriod: unversioned.Duration{Duration: 30 * time.Second},
			// from k8s.io/kubernetes/cmd/kube-proxy/app/options/options.go
			// defaults to 14.
			IPTablesMasqueradeBit:          &ipTablesMasqueratebit,
			UDPIdleTimeout:                 unversioned.Duration{Duration: 250 * time.Millisecond},
			ConntrackMax:                   256 * 1024,                                          // 4x default (64k)
			ConntrackTCPEstablishedTimeout: unversioned.Duration{Duration: 86400 * time.Second}, // 1 day (1/5 default)
		},
		ConfigSyncPeriod: 15 * time.Minute,
		KubeAPIQPS:       5.0,
		KubeAPIBurst:     10,
	}

	actualDefaultConfig := proxyoptions.NewProxyConfig()

	if !reflect.DeepEqual(expectedDefaultConfig, actualDefaultConfig) {
		t.Errorf("Default kube proxy config has changed. Adjust buildKubeProxyConfig() as needed to disable or make use of additions.")
		t.Logf("Expected default config:\n%#v\n\n", expectedDefaultConfig)
		t.Logf("Actual default config:\n%#v\n\n", actualDefaultConfig)
	}

}


text:
package core;

public class DomainObject {
    private String myS;

    public DomainObject(String s) {
        myS = s;
    }

    public String getS() {
        return myS;
    }
}


text:
/*
    @author         Okafor Anthony Ikenna
    @email          ikenna@getmp3video.com
    @description    The App object is the app's manager and performs all app specific functions

*/

function App(){
console.log("App");

Y = this;
Y.name = "App"; 	//This is the className returned by toString()
Y.serverURL = "http://www.getmp3video.com";
Y.fName = "App()";	//This is the full className returned by toFString()
Y.networkStatus		//The network's current status
Y.isOnline,			//App connectivity state, true if online else false
Y.db,      			//The local storage object
Y.DEVICE_NAME,  	//The device name
Y.PG_VER,           //Phonegap/Cordova version
Y.DEVICE_OS,        //Device's operating system name
Y.DEVICE_ID,        //The device's unique id
Y.OS_VERSION,       //The device's OS version

// Returns the name of the class
Y.toString = function(){
	console.log("Y.toString");
        return Y.name;
    },

// Returns the full name of the class
Y.toFString = function(){
	console.log("Y.toFString");
        return Y.fname;
    },

//This function runs the first time the app is run
Y.firstRun = function(){
	console.log("Y.firstRun");
        if(Y.db !== window.localStorage)
            Y.db = window.localStorage;
        Y.db.setItem('device_name',device.name); //replace all Ys in brackets with device
        Y.db.setItem('pg_version',device.cordova);
        Y.db.setItem('device_os',device.platform);
        Y.db.setItem('device_id',Y.uuid);
        Y.db.setItem('device_os_ver',Y.version);
		Y.db.setItem('setting_check_update', '1');
    },

//This function performs all data storage and retrievals
Y.dsQuery = function(){
	console.log("Y.dsQuery");
    },

//This function checks the device's connection status everytime it changes and upates the networkStatus and isOnline variables accordingly
Y.connectionUpdater = function(){
	console.log("Y.connectionUpdater");
		window.addEventListener('online', function(){
			Y.networkStatus = navigator.connection.type;
			Y.isOnline = true;
		});

		window.addEventListener('offline', function(){
			Y.networkStatus = navigator.connection.type;
			Y.isOnline = false;
		});
	},

/*
This function performs all server communication.
It accepts a single parameter, an object o which should have the following parameters and functions:
o.url: The url to be queied.
o.message: The message to be sent across the network. [String]
o.method: Either GET or POST. Method to be used in sending the message. [String]
o.success(optional): An optional callback function to be executed after the message has succeeded. [fn]
o.fail(optional): An optional callback function to be executed after the message has failed. [fn]
o.rHeader(optional): Request header parameters in a name=value pair. [String]

Returns
The function returns an object with the following values.
o.responseText: The responseText received from the server.
o.statusText: The response status text received from the server.
o.status: The status code receive from the server.
*/
Y.dataTransfer = function(o){
	console.log("Y.dataTransfer");
			if(!Y.isOnline){
				alert('Your device is offline',null,'Device offline!','Close');
				return null;
			} else {
				var ajax = new XMLHttpRequest();
				if(o.method == "GET"){
				ajax.open(o.method,o.url+o.message);
				ajax.send();
				} else {
					ajax.open(o.method, o.url);
					ajax.setRequestHeader(o.rHeader);
					ajax.send(o.message);
				}
				ajax.onreadystatechange = (function(e){
					if(o.callBackSuccess != null && ajax.status == 200 && ajax.readyState == 4){
						o.callBackSuccess.call(this,e);
					}
					if(o.callBackFail != null && ajax.status != 200 && ajax.readyState != 4){
						o.callBackFail.call(this,e);
					}
					return e;
				});
			}

		return;
    },

Y.youGetterApi = function(message, method, cbSuccess, cbFail){
	 //Sends video link to app's server
	console.log("Y.youGetterApi");
	},

Y.audioDownload = function(){
	console.log("Y.audioDownload");
},

Y.linkGetter = function(yid){
	console.log("Y.linkGetter");
	var sString = $(yid).value;

},
//state == 1: Show wait screen
//state == 0: Hide wait screen
Y.waitScreen = function(state){
	console.log("Y.waitScreen");
		if(state === 1) $("#wait-box").show();
	//document.getElementById("wait-box").addClass = "show";
		if(state === 0) $("#wait-box").hide();
},

Y.errorScreen = function(){
	console.log("Y.errorScreen");
	$("#error-box").show();
	//document.getElementById("Error-box").addClass = "show";
	setTimeout(2000);
	$("#error-box").hide();
	//document.getElementById("Error-box").addClass = "hide";
},

Y.youDownload = function(yid){
	console.log("Y.youDownload");
        /* your code goes here */
		linkGetter(yid);
		waitScreen(1);
		if(!responseOk) errorScreen();
		if(responseOk){

			}
	},

Y.alertDialog = function(msg){
	console.log("Y.alertDialog");
		//displays s custom alert box and an ok button to close
		//Temporarily use native alerts here till custom alert boxes are provide
		window.alert(msg);
	},

Y.confirmDialog = function(msg, callback){
		console.log("Y.confirmDialog");
		var args = arguments; //Holds the parameters passed to the function
		//Temporarily use native confirm dialog until custom dialog is available
		var response = window.confirm(msg);
		callback.call(response);
	},

Y.msgDialog = function(msg){
	console.log("Y.msgDialog");
	//Displays messages to the user and an ok button to close the dialog
	},

 Y.splashScreenShow = function(){
	console.log("Y.splashScreenShow");
	 	if( navigator.splashscreen && navigator.splashscreen.show ) {   // Cordova API detected
        navigator.splashscreen.show() ;
    }
    if( window.intel && intel.xdk && intel.xdk.device ) {           // Intel XDK device API detected, but...
        if( intel.xdk.device.showSplashScreen )                     // ...hideSplashScreen() is inside the base plugin
            intel.xdk.device.showSplashScreen() ;
    	}
 	},

 Y.splashScreenHide = function(){
	 console.log("Y.splashScreenHide");
	 	if( navigator.splashscreen && navigator.splashscreen.hide ) {   // Cordova API detected
        navigator.splashscreen.hide() ;
    }
    if( window.intel && intel.xdk && intel.xdk.device ) {           // Intel XDK device API detected, but...
        if( intel.xdk.device.hideSplashScreen )                     // ...hideSplashScreen() is inside the base plugin
            intel.xdk.device.hideSplashScreen() ;
    	}

 	},

Y.exit = function(){
	console.log("Y.exit");
	//Exits the application
	//Later perform app exit operations before exiting app here
	navigator.app.exitApp();

	},

//Performs all startup operations
Y.init = function(){
	console.log("Y.init");
    if(Y.db !== window.localStorage)
    Y.db = window.localStorage;
    Y.DEVICE_NAME  = Y.db.getItem('device_name');
    Y.PG_VER  = Y.db.getItem('pg_version');
    Y.DEVICE_OS  = Y.db.getItem('device_os');
    Y.DEVICE_ID  = Y.db.getItem('device_id');
    Y.OS_VERSION  = Y.db.getItem('device_os_ver');
	if(Y.DEVICE_ID == null) Y.firstRun();
	Y.connectionUpdater();
     //May be debugged here

}
//Y.init();
}
window.Y = App();


text:
<!doctype html>

<title>CodeMirror: Groovy mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">

<link rel="stylesheet" href="../../lib/codemirror.css">

CodeMirror

Home

Manual

Code

Language modes

Groovy

Groovy mode

<form><textarea id="code" name="code">
//Pattern for groovy script
def p = ~/.*\.groovy/
new File( 'd:\\scripts' ).eachFileMatch(p) {f ->
  // imports list
  def imports = []
  f.eachLine {
    // condition to detect an import instruction
    ln -> if ( ln =~ '^import .*' ) {
      imports << "${ln - 'import '}"
    }
  }
  // print thmen
  if ( ! imports.empty ) {
    println f
    imports.each{ println "   $it" }
  }
}

/* Coin changer demo code from http://groovy.codehaus.org */

enum UsCoin {
  quarter(25), dime(10), nickel(5), penny(1)
  UsCoin(v) { value = v }
  final value
}

enum OzzieCoin {
  fifty(50), twenty(20), ten(10), five(5)
  OzzieCoin(v) { value = v }
  final value
}

def plural(word, count) {
  if (count == 1) return word
  word[-1] == 'y' ? word[0..-2] + "ies" : word + "s"
}

def change(currency, amount) {
  currency.values().inject([]){ list, coin ->
     int count = amount / coin.value
     amount = amount % coin.value
     list += "$count ${plural(coin.toString(), count)}"
  }
}
</textarea></form>

MIME types defined: text/x-groovy


text:
package io.quarkus.opentelemetry.runtime.tracing.intrumentation.vertx;

import static io.opentelemetry.instrumentation.api.instrumenter.messaging.MessageOperation.RECEIVE;
import static io.opentelemetry.instrumentation.api.instrumenter.messaging.MessageOperation.SEND;
import static io.quarkus.opentelemetry.runtime.config.OpenTelemetryConfig.INSTRUMENTATION_NAME;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter;
import io.opentelemetry.instrumentation.api.instrumenter.InstrumenterBuilder;
import io.opentelemetry.instrumentation.api.instrumenter.messaging.MessagingAttributesExtractor;
import io.opentelemetry.instrumentation.api.instrumenter.messaging.MessagingAttributesGetter;
import io.opentelemetry.instrumentation.api.instrumenter.messaging.MessagingSpanNameExtractor;
import io.vertx.core.eventbus.Message;
import io.vertx.core.spi.tracing.TagExtractor;

@SuppressWarnings("rawtypes")
public class EventBusInstrumenterVertxTracer implements InstrumenterVertxTracer<Message, Message> {
    private final Instrumenter<Message, Message> consumerInstrumenter;
    private final Instrumenter<Message, Message> producerInstrumenter;

    public EventBusInstrumenterVertxTracer(final OpenTelemetry openTelemetry) {
        this.consumerInstrumenter = getConsumerInstrumenter(openTelemetry);
        this.producerInstrumenter = getProducerInstrumenter(openTelemetry);
    }

    @Override
    public <R> boolean canHandle(final R request, final TagExtractor<R> tagExtractor) {
        return request instanceof Message;
    }

    @Override
    public Instrumenter<Message, Message> getReceiveRequestInstrumenter() {
        return consumerInstrumenter;
    }

    @Override
    public Instrumenter<Message, Message> getSendResponseInstrumenter() {
        return consumerInstrumenter;
    }

    @Override
    public Instrumenter<Message, Message> getSendRequestInstrumenter() {
        return producerInstrumenter;
    }

    @Override
    public Instrumenter<Message, Message> getReceiveResponseInstrumenter() {
        return producerInstrumenter;
    }

    private static Instrumenter<Message, Message> getConsumerInstrumenter(final OpenTelemetry openTelemetry) {
        InstrumenterBuilder<Message, Message> serverBuilder = Instrumenter.builder(
                openTelemetry,
                INSTRUMENTATION_NAME, MessagingSpanNameExtractor.create(EventBusAttributesGetter.INSTANCE, RECEIVE));

        return serverBuilder
                .addAttributesExtractor(MessagingAttributesExtractor.create(EventBusAttributesGetter.INSTANCE, RECEIVE))
                .buildConsumerInstrumenter(new TextMapGetter<>() {
                    @Override
                    public Iterable<String> keys(final Message message) {
                        return message.headers().names();
                    }

                    @Override
                    public String get(final Message message, final String key) {
                        if (message == null) {
                            return null;
                        }
                        return message.headers().get(key);
                    }
                });
    }

    private static Instrumenter<Message, Message> getProducerInstrumenter(final OpenTelemetry openTelemetry) {
        InstrumenterBuilder<Message, Message> serverBuilder = Instrumenter.builder(
                openTelemetry,
                INSTRUMENTATION_NAME, MessagingSpanNameExtractor.create(EventBusAttributesGetter.INSTANCE, SEND));

        return serverBuilder
                .addAttributesExtractor(MessagingAttributesExtractor.create(EventBusAttributesGetter.INSTANCE, SEND))
                .buildProducerInstrumenter((message, key, value) -> {
                    if (message != null) {
                        message.headers().set(key, value);
                    }
                });
    }

    private enum EventBusAttributesGetter implements MessagingAttributesGetter<Message, Message> {
        INSTANCE;

        @Override
        public String system(final Message message) {
            return "vert.x";
        }

        @Override
        public String destinationKind(final Message message) {
            return message.isSend() ? "queue" : "topic";
        }

        @Override
        public String destination(final Message message) {
            return message.address();
        }

        @Override
        public boolean temporaryDestination(final Message message) {
            return false;
        }

        @Override
        public String protocol(final Message message) {
            return null;
        }

        @Override
        public String protocolVersion(final Message message) {
            return "4.0";
        }

        @Override
        public String url(final Message message) {
            return null;
        }

        @Override
        public String conversationId(final Message message) {
            return message.replyAddress();
        }

        @Override
        public Long messagePayloadSize(final Message message) {
            return null;
        }

        @Override
        public Long messagePayloadCompressedSize(final Message message) {
            return null;
        }

        @Override
        public String messageId(final Message message, final Message message2) {
            return null;
        }
    }
}


text:
class Data;
class ComponentCamera : public Component {
public:
	ComponentCamera();
	ComponentCamera(GameObject*);
	ComponentCamera(GameObject*, Frustum);
	~ComponentCamera();

	void UpdateComponent();
	void SaveComponentScene(Data* data);
	void ShowInspectorComponents();

public:
	Frustum cam_frustum;
	bool frustum_culling = true;

};

#endif


text:
@implementation NSManagedObjectContext (iOS10Additions)

#if NS_PERSISTENT_STORE_NOT_AVAILABLE_IN_SDK
- (BOOL)automaticallyMergesChangesFromParent {
    return self.ins_automaticallyMergesChangesFromParent;
}

- (void)setAutomaticallyMergesChangesFromParent:(BOOL)automaticallyMergesChangesFromParent {
    self.ins_automaticallyMergesChangesFromParent = automaticallyMergesChangesFromParent;
}
#endif

- (void)ins_dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextWillSaveNotification object:nil];
}

- (dispatch_queue_t)notificationQueue {
    dispatch_queue_t queue = objc_getAssociatedObject(self, @selector(notificationQueue));
    if (!queue) {
        queue = dispatch_queue_create("io.inspace.managedobjectcontext.notificationqueue", nil);
        objc_setAssociatedObject(self, @selector(notificationQueue), queue, OBJC_ASSOCIATION_RETAIN);
    }
    return queue;
}

- (BOOL)ins_automaticallyObtainPermanentIDsForInsertedObjects {
    __block BOOL value = NO;
    dispatch_sync(self.notificationQueue, ^{
        value = [self _ins_automaticallyObtainPermanentIDsForInsertedObjects];
    });
    return value;
}

- (BOOL)_ins_automaticallyObtainPermanentIDsForInsertedObjects {
    return [objc_getAssociatedObject(self, @selector(ins_automaticallyObtainPermanentIDsForInsertedObjects)) boolValue];
}

- (void)setIns_automaticallyObtainPermanentIDsForInsertedObjects:(BOOL)ins_automaticallyObtainPermanentIDsForInsertedObjects {
    dispatch_sync(self.notificationQueue, ^{
        if (ins_automaticallyObtainPermanentIDsForInsertedObjects != self._ins_automaticallyObtainPermanentIDsForInsertedObjects) {
            objc_setAssociatedObject(self, @selector(ins_automaticallyObtainPermanentIDsForInsertedObjects), @(ins_automaticallyObtainPermanentIDsForInsertedObjects), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            if (ins_automaticallyObtainPermanentIDsForInsertedObjects) {
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ins_automaticallyObtainPermanentIDsForInsertedObjectsFromWillSaveNotification:) name:NSManagedObjectContextWillSaveNotification object:self];
            } else {
                [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextWillSaveNotification object:nil];
            }
        }
    });
}

- (BOOL)ins_automaticallyMergesChangesFromParent {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
    if (self.concurrencyType == NSConfinementConcurrencyType) {
#pragma GCC diagnostic pop
        return NO;
    }
    __block BOOL value = NO;
    dispatch_sync(self.notificationQueue, ^{
        value = [self _ins_automaticallyMergesChangesFromParent];
    });
    return value;
}

- (BOOL)_ins_automaticallyMergesChangesFromParent {
    return [objc_getAssociatedObject(self, @selector(ins_automaticallyMergesChangesFromParent)) boolValue];
}

- (void)setIns_automaticallyMergesChangesFromParent:(BOOL)ins_automaticallyMergesChangesFromParent {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
    if (self.concurrencyType == NSConfinementConcurrencyType) {
#pragma GCC diagnostic pop
        [[NSException exceptionWithName:NSInvalidArgumentException reason:@"Automatic merging is not supported by contexts using NSConfinementConcurrencyType" userInfo:0x0] raise];
    }
    if (self.parentContext == nil && self.persistentStoreCoordinator == nil) {
        [[NSException exceptionWithName:NSInternalInconsistencyException reason:@"Cannot enable automatic merging for a context without a parent, set a parent context or persistent store coordinator first." userInfo:0x0] raise];
    }
    dispatch_sync(self.notificationQueue, ^{
        if (ins_automaticallyMergesChangesFromParent != [self _ins_automaticallyMergesChangesFromParent]) {
            objc_setAssociatedObject(self, @selector(ins_automaticallyMergesChangesFromParent), @(ins_automaticallyMergesChangesFromParent), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            if (ins_automaticallyMergesChangesFromParent) {
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ins_automaticallyMergeChangesFromContextDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:self.parentContext];
            } else {
                [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:nil];
            }
        }
    });
}

- (void)ins_automaticallyMergeChangesFromContextDidSaveNotification:(NSNotification *)notification {
    NSManagedObjectContext *context = (NSManagedObjectContext *)notification.object;
    if (context.persistentStoreCoordinator != self.persistentStoreCoordinator) {
        return;
    }
    BOOL isRootContext = context.parentContext == nil;
    BOOL isParentContext = self.parentContext == context;
    if (!(isRootContext || isParentContext) || context == self) {
        return;
    }

    [self performBlock:^{
        // WORKAROUND FOR: http://stackoverflow.com/questions/3923826/nsfetchedresultscontroller-with-predicate-ignores-changes-merged-from-different/3927811#3927811
        NSSet <NSManagedObject *> *updatedObjects = notification.userInfo[NSUpdatedObjectsKey];
        for (NSManagedObject *obj in updatedObjects) {
            [[self existingObjectWithID:obj.objectID error:nil] willAccessValueForKey:nil]; // ensures that a fault has been fired
        }

        [self mergeChangesFromContextDidSaveNotification:notification];
    }];
}

- (void)ins_automaticallyObtainPermanentIDsForInsertedObjectsFromWillSaveNotification:(NSNotification *)notification {
    NSManagedObjectContext *context = notification.object;
    if (context.insertedObjects.count <= 0) {
        return;
    }
    [context performBlock:^{
        [context obtainPermanentIDsForObjects:[context.insertedObjects allObjects] error:nil];
    }];
}

+ (void)load {

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_x_Max) {
        return;
    }

    Method automaticallyMergesChangesMethod = class_getInstanceMethod([self class], @selector(ins_automaticallyMergesChangesFromParent));
    class_addMethod([self class], @selector(automaticallyMergesChangesFromParent), method_getImplementation(automaticallyMergesChangesMethod), method_getTypeEncoding(automaticallyMergesChangesMethod));

    Method automaticallyMergesChangesSetMethod = class_getInstanceMethod([self class], @selector(setIns_automaticallyMergesChangesFromParent:));
    class_addMethod([self class], @selector(setAutomaticallyMergesChangesFromParent:), method_getImplementation(automaticallyMergesChangesSetMethod), method_getTypeEncoding(automaticallyMergesChangesSetMethod));
}

@end


text:
external help file: Microsoft.Azure.Commands.Sql.dll-Help.xml
Module Name: AzureRM.Sql
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.sql/get-azurermsqlserverkeyvaultkey
schema: 2.0.0
---

# Get-AzureRmSqlServerKeyVaultKey

## SYNOPSIS
Gets a SQL server's Key Vault keys.

## SYNTAX

```
Get-AzureRmSqlServerKeyVaultKey [[-KeyId] <String>] [-ServerName] <String> [-ResourceGroupName] <String>
 [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

## DESCRIPTION
The Get-AzureRmSqlServerKeyVaultKey cmdlet gets information about the Key Vault keys on a SQL server.
You can view all keys on a server or view a specific key by providing the KeyId.

## EXAMPLES

### Example 1: Get all Key Vault keys
```
PS C:\> Get-AzureRmSqlServerKeyVaultKey -ServerName 'ContosoServer' -ResourceGroupName 'ContosoResourceGroup'
```

This command gets all the Key Vault keys on a SQL server.
ResourceGroupName : ContosoResourceGroup
ServerName        : ContosoServer
ServerKeyName     : contoso_contosokey_01234567890123456789012345678901
Type              : AzureKeyVault
Uri               : https://contoso.vault.azure.net/keys/contosokey/01234567890123456789012345678901
Thumbprint        : 1122334455667788990011223344556677889900
CreationDate      : 1/1/2017 12:00:00 AM
ResourceGroupName : ContosoResourceGroup
ServerName        : ContosoServer
ServerKeyName     : contoso_contosokey2_01234567890123456789012345678901
Type              : AzureKeyVault
Uri               : https://contoso.vault.azure.net/keys/contosokey2/09876543210987654321098765432109
Thumbprint        : 0099887766554433221100998877665544332211
CreationDate      : 1/1/2017 12:00:00 AM

### Example 2: Get a specific Key Vault key
```
PS C:\> $MyServerKeyVaultKey = Get-AzureRmSqlServerKeyVaultKey -KeyId 'https://contoso.vault.azure.net/keys/contosokey/01234567890123456789012345678901' -ServerName 'ContosoServer' -ResourceGroupName 'ContosoResourceGroup'
```

This command gets the Key Vault key with Id 'https://contoso.vault.azure.net/keys/contosokey/01234567890123456789012345678901', and then stores it in the $MyServerKeyVaultKey variable.
You can inspect the properties of $MyServerKeyVaultKey to get details about the key vault.

## PARAMETERS

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with azure

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -KeyId
The Azure Key Vault KeyId.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: False
Position: 2
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ResourceGroupName
The name of the resource group

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ServerName
The Azure Sql Server name.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

## OUTPUTS

### Microsoft.Azure.Commands.Sql.ServerKeyVaultKey.Model.AzureSqlServerKeyVaultKeyModel

## NOTES

## RELATED LINKS

[SQL Database Documentation](https://docs.microsoft.com/azure/sql-database/)


text:
"""A command-line front-end for todone."""
import datetime
import os
import sys
from todone.core import ToDo, PROJECT_PREPEND_STRING

def usage():
    print """Usage: %(filename)s <command> [options]

Available Commands:
    add <todo item text>
        Adds a new todo item to the list.

    delete <todo number from list> [project name]
        Permanently deletes a todo item from the list. You probably want "done" instead.
        Prepend the "project name" with an '%(project_prepend)s'.

    done <todo number from list> [project name]
        Marks a todo item as complete and archives it.
        Prepend the "project name" with an '%(project_prepend)s'.

    edit <todo number from list> [project name] <todo item text>
        Edits a todo item within the list.
        Prepend the "project name" with an '%(project_prepend)s'.

    list [project name]
        Without the "project name" option, shows all todo items.
        With the "%(project_prepend)sproject name" option, shows only todo items within that project.
    """ % {'filename': os.path.basename(sys.argv[0]), 'project_prepend': PROJECT_PREPEND_STRING}
    sys.exit()

def add_item(todo, remaining_args):
    item = " ".join(remaining_args)
    todo.add(item)
    print "TODO: Added '%s'." % item
    print

def delete_item(todo, remaining_args):
    number = int(remaining_args.pop(0))
    correct_offset = number - 1
    project = None

    if remaining_args:
        project = remaining_args.pop(0)

        if project.startswith(PROJECT_PREPEND_STRING):
            project = project.replace(PROJECT_PREPEND_STRING, '')

    old_item = todo.get(correct_offset, project)
    todo.delete(correct_offset, project)
    print "TODO: Deleted #%s '%s'." % (number, old_item)
    print

def mark_item_as_done(todo, remaining_args):
    number = int(remaining_args.pop(0))
    correct_offset = number - 1
    project = None

    if remaining_args:
        project = remaining_args.pop(0)

        if project.startswith(PROJECT_PREPEND_STRING):
            project = project.replace(PROJECT_PREPEND_STRING, '')

    old_item = todo.get(correct_offset, project)
    todo.done(correct_offset, project)
    print "TODO: Marked #%s '%s' as done." % (number, old_item)
    print

def edit_item(todo, remaining_args):
    number = int(remaining_args.pop(0))
    correct_offset = number - 1
    item = " ".join(remaining_args)
    project = None

    if remaining_args:
        # Note that we're not popping, just checking it.
        project_filter = remaining_args[0]

        if project_filter.startswith(PROJECT_PREPEND_STRING):
            project = project_filter.replace(PROJECT_PREPEND_STRING, '')

    todo.edit(correct_offset, item, project)
    print "TODO: Edited #%s '%s'." % (number, item)
    print

def list_todos(todo, remaining_args):
    project_filter = None

    if remaining_args:
        project_filter = remaining_args.pop(0).replace(PROJECT_PREPEND_STRING, '')
        todos = todo.list(project=project_filter)
    else:
        todos = todo.list()

    if not todos:
        print "No todo items found."
        print
        return

    if project_filter:
        project_header = "Project: %s" % project_filter
        print project_header
        print "-" * len(project_header)

    for index, todo in enumerate(todos):
        if project_filter:
            todo = todo.replace("%s%s " % (PROJECT_PREPEND_STRING, project_filter), '')

        print "%s. %s" % (index + 1, todo)

    print

def process_command(todo, command, remaining_args):
    commands = {
        'add': add_item,
        'delete': delete_item,
        'done': mark_item_as_done,
        'edit': edit_item,
        'list': list_todos,
    }

    if not command in commands:
        print "Unrecognized command."
        usage()

    try:
        commands[command](todo, remaining_args)
    except (RuntimeError, AttributeError, IndexError), e:
        print "Command failed: %s" % e.args
        print

if __name__ == '__main__':
    if len(sys.argv) <= 1:
        usage()

    data_path = os.path.join('~', '.todone')
    todo = ToDo(data_path)

    command = sys.argv[1]
    remaining_args = sys.argv[2:]

    process_command(todo, command, remaining_args)


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="ca.ualberta.cs.cmput301f14t14.questionapp.SearchActivity" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

</menu>


text:
package com.intellij.lang.jsgraphql.types.analysis;

import com.intellij.lang.jsgraphql.types.PublicApi;

/**
 * The query complexity info.
 */
@PublicApi
public class QueryComplexityInfo {

    private final int complexity;

    private QueryComplexityInfo(int complexity) {
        this.complexity = complexity;
    }

    /**
     * This returns the query complexity.
     *
     * @return the query complexity
     */
    public int getComplexity() {
        return complexity;
    }

    @Override
    public String toString() {
        return "QueryComplexityInfo{" +
                "complexity=" + complexity +
                '}';
    }

    /**
     * @return a new {@link QueryComplexityInfo} builder
     */
    public static Builder newQueryComplexityInfo() {
        return new Builder();
    }

    @PublicApi
    public static class Builder {

        private int complexity;

        private Builder() {
        }

        /**
         * The query complexity.
         *
         * @param complexity the query complexity
         * @return this builder
         */
        public Builder complexity(int complexity) {
            this.complexity = complexity;
            return this;
        }

        /**
         * @return a built {@link QueryComplexityInfo} object
         */
        public QueryComplexityInfo build() {
            return new QueryComplexityInfo(complexity);
        }
    }
}


text:
#include <boost/assert.hpp>
#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <algorithm>

namespace boost
{
    namespace range
    {

        /// \brief template function transform
        ///
        /// range-based version of the transform std algorithm
        ///
        /// \pre SinglePassRange1 is a model of the SinglePassRangeConcept
        /// \pre SinglePassRange2 is a model of the SinglePassRangeConcept
        /// \pre OutputIterator is a model of the OutputIteratorConcept
        /// \pre UnaryOperation is a model of the UnaryFunctionConcept
        /// \pre BinaryOperation is a model of the BinaryFunctionConcept
        template< class SinglePassRange1,
                  class OutputIterator,
                  class UnaryOperation >
        inline OutputIterator
        transform(const SinglePassRange1& rng,
                  OutputIterator          out,
                  UnaryOperation          fun)
        {
            BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange1> ));
            return std::transform(boost::begin(rng),boost::end(rng),out,fun);
        }

    } // namespace range

    namespace range_detail
    {
        template< class SinglePassTraversalReadableIterator1,
                  class SinglePassTraversalReadableIterator2,
                  class OutputIterator,
                  class BinaryFunction >
        inline OutputIterator
        transform_impl(SinglePassTraversalReadableIterator1 first1,
                       SinglePassTraversalReadableIterator1 last1,
                       SinglePassTraversalReadableIterator2 first2,
                       SinglePassTraversalReadableIterator2 last2,
                       OutputIterator                       out,
                       BinaryFunction                       fn)
        {
            for (; first1 != last1 && first2 != last2; ++first1, ++first2)
            {
                *out = fn(*first1, *first2);
                ++out;
            }
            return out;
        }
    }

    namespace range
    {

        /// \overload
        template< class SinglePassRange1,
                  class SinglePassRange2,
                  class OutputIterator,
                  class BinaryOperation >
        inline OutputIterator
        transform(const SinglePassRange1& rng1,
                  const SinglePassRange2& rng2,
                  OutputIterator          out,
                  BinaryOperation         fun)
        {
            BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange1> ));
            BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange2> ));
            return boost::range_detail::transform_impl(
                        boost::begin(rng1), boost::end(rng1),
                        boost::begin(rng2), boost::end(rng2),
                        out, fun);
        }

    } // namespace range
    using range::transform;
} // namespace boost

#endif // include guard


text:
import { createAction } from 'redux-actions';
import { LOADER_SHOW, LOADER_HIDE, LOADER_CLEAR } from 'constants/actions/actionNames';
import type { ImmutableState } from 'store/StateTypes';

export const showLoader = createAction(LOADER_SHOW);
export const hideLoader = createAction(LOADER_HIDE);
export const clearLoader = createAction(LOADER_CLEAR);

export const mapStateToProps = (state: ImmutableState) => ({
  visible: state.toJS().loader.visible,
});


text:
package net.automatalib.automata.spa;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import net.automatalib.automata.concepts.FiniteRepresentation;
import net.automatalib.automata.concepts.InputAlphabetHolder;
import net.automatalib.automata.concepts.SuffixOutput;
import net.automatalib.automata.fsa.DFA;
import net.automatalib.automata.simple.SimpleAutomaton;
import net.automatalib.graphs.Graph;
import net.automatalib.graphs.concepts.GraphViewable;
import net.automatalib.ts.acceptors.DeterministicAcceptorTS;
import net.automatalib.ts.simple.SimpleTS;
import net.automatalib.words.SPAAlphabet;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A system of procedural automata. An {@link SPA} is a context-free system where each non-terminal (procedure) is
 * represented by a {@link DFA} that accepts the language of right-hand sides of its respective production rules.
 *

 * Take, for example, the following context-free palindrome system over {@code a,b,c} using two non-terminals {@code
 * S,T}:
 *

 *     S -> a | a S a | b | b S b | T | ε
 *     T -> c | c T c | S
 *

 * The corresponding {@link SPA} would consist of {@link DFA procedures} (for {@code S} and {@code T}), accepting the
 * regular languages {@code {a,aSa,b,bSb,T,ε}} and {@code {c,cTc,S}} respectively.
 *

 * In {@link SPA}s, calls to and returns from procedures are visible which make {@link SPA}s a special kind of visibly
 * push-down automata. For the above example, a possible word accepted by the respective {@link SPA} (when using {@code
 * S} as {@link #getInitialProcedure() initial procedure}) would be {@code SaSTcRRaR} (where {@code R} denotes the
 * designated {@link SPAAlphabet#getReturnSymbol() return symbol}.
 *

 * This interface makes no assumptions about how the semantics are implemented. One may use a stack-based approach,
 * graph expansion, or else. However, {@link SPA}s should be consistent with their alphabet definitions, i.e. an
 * {@link SPA} should be able to {@link #accepts(Iterable) parse} words over the {@link #getInputAlphabet() specified
 * alphabet} and each {@link #getProcedures() procedure} should be able to {@link DFA#accepts(Iterable) parse} words
 * over the {@link #getProceduralInputs() procedural inputs}.
 *
 * @param <S>
 *         state type
 * @param
 *         input symbol type
 *
 * @author frohme
 */
public interface SPA<S, I> extends DeterministicAcceptorTS<S, I>,
                                   SuffixOutput,
                                   InputAlphabetHolder,
                                   FiniteRepresentation,
                                   GraphViewable {

    /**
     * Refinement of {@link InputAlphabetHolder#getInputAlphabet()}' to add the constraint that an {@link SPA} operates
     * on {@link SPAAlphabet}s.
     *
     * @return the input alphabet
     */
    @Override
    SPAAlphabet getInputAlphabet();

    /**
     * Returns the initial procedure of this {@link SPA}, i.e. the call symbol with which each accepted word has to
     * start.
     *
     * @return the initial procedure
     */
    @Nullable I getInitialProcedure();

    /**
     * In a complete {@link SPA} every {@link #getInputAlphabet() call symbol} should be mapped to a corresponding
     * procedure.
     *
     * @return the procedures of this {@link SPA}
     */
    Map<I, DFA<?, I>> getProcedures();

    /**
     * Convenience method for {@link #getProceduralInputs(SPAAlphabet)} which uses the {@link #getInputAlphabet() input
     * alphabet} of {@code this} {@link SPA} as {@code constraints}.
     *
     * @return a collection of defined inputs for {@code this} {@link SPA}'s procedures.
     */
    default Collection getProceduralInputs() {
        return getProceduralInputs(this.getInputAlphabet());
    }

    /**
     * Returns a collection of input symbols which the procedural automata can process. The collection is computed by
     * the union of this {@link SPA}s {@link SPAAlphabet#getInternalAlphabet() internal symbols} and the {@link
     * #getProcedures() available procedure keys}.
     *

     * This collection can be further constrained via the {@code constraints} parameter which is used in a final
     * intersection operation with the previous collection.
     *
     * @param constraints
     *         an {@link SPAAlphabet} for additionally constraining the returned procedural inputs.
     *
     * @return the (constrained) procedural inputs
     */
    default Collection getProceduralInputs(SPAAlphabet constraints) {
        final List symbols = new ArrayList<>(constraints.size() - 1);

        for (I i : getInputAlphabet()) {
            if (constraints.isInternalSymbol(i)) {
                symbols.add(i);
            }
        }

        for (I procedure : getProcedures().keySet()) {
            if (constraints.isCallSymbol(procedure)) {
                symbols.add(procedure);
            }
        }

        return symbols;
    }

    /**
     * Return the size of this {@link SPA} which is given by the sum of the sizes of all {@link #getProcedures()
     * procedures}. Note that this value does not necessarily correspond to the classical notion of {@link
     * SimpleAutomaton#size()}, since semantically an {@link SPA}s may be infinite-sized {@link SimpleTS}.
     *
     * @return the size of this {@link SPA}
     */
    @Override
    default int size() {
        int size = 0;

        for (DFA<?, I> p : getProcedures().values()) {
            size += p.size();
        }

        return size;
    }

    @Override
    default Boolean computeOutput(Iterable<? extends I> input) {
        return this.accepts(input);
    }

    @Override
    default Graph<?, ?> graphView() {
        final SPAAlphabet alphabet = this.getInputAlphabet();
        // explicit type specification is required by checker-framework
        return new SPAGraphView<@Nullable Object, I>(alphabet.getCallAlphabet(),
                                                     this.getProceduralInputs(alphabet),
                                                     this.getProcedures());
    }

}


text:
redirect_to: /hub/kong-inc/key-auth
---


text:
package org.apereo.cas.pm.rest;

import org.apereo.cas.CipherExecutor;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.credential.UsernamePasswordCredential;
import org.apereo.cas.configuration.model.support.pm.PasswordManagementProperties;
import org.apereo.cas.pm.BasePasswordManagementService;
import org.apereo.cas.pm.PasswordChangeBean;
import org.apereo.cas.util.CollectionUtils;

import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.Map;

/**
 * This is {@link RestPasswordManagementService}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public class RestPasswordManagementService extends BasePasswordManagementService {

    private final transient RestTemplate restTemplate;

    public RestPasswordManagementService(final CipherExecutor<Serializable, String> cipherExecutor,
                                         final String issuer,
                                         final RestTemplate restTemplate,
                                         final PasswordManagementProperties passwordManagementProperties) {
        super(passwordManagementProperties, cipherExecutor, issuer);
        this.restTemplate = restTemplate;
    }

    @Override
    public boolean changeInternal(final Credential c, final PasswordChangeBean bean) {
        val rest = properties.getRest();
        if (StringUtils.isBlank(rest.getEndpointUrlChange())) {
            return false;
        }

        val upc = (UsernamePasswordCredential) c;

        val headers = new HttpHeaders();
        headers.setAccept(CollectionUtils.wrap(MediaType.APPLICATION_JSON));
        headers.put("username", CollectionUtils.wrap(upc.getUsername()));
        headers.put("password", CollectionUtils.wrap(bean.getPassword()));
        headers.put("oldPassword", CollectionUtils.wrap(upc.getPassword()));

        val entity = new HttpEntity<>(headers);
        val result = restTemplate.exchange(rest.getEndpointUrlChange(), HttpMethod.POST, entity, Boolean.class);
        if (result.getStatusCodeValue() == HttpStatus.OK.value()) {
            return result.getBody();
        }
        return false;
    }

    @Override
    public String findUsername(final String email) {
        val rest = properties.getRest();
        if (StringUtils.isBlank(rest.getEndpointUrlUser())) {
            return null;
        }

        val headers = new HttpHeaders();
        headers.setAccept(CollectionUtils.wrap(MediaType.APPLICATION_JSON));
        headers.put("email", CollectionUtils.wrap(email));
        val entity = new HttpEntity<>(headers);
        val result = restTemplate.exchange(rest.getEndpointUrlEmail(), HttpMethod.GET, entity, String.class);

        if (result.getStatusCodeValue() == HttpStatus.OK.value() && result.hasBody()) {
            return result.getBody();
        }
        return null;
    }

    @Override
    public String findEmail(final String username) {
        val rest = properties.getRest();
        if (StringUtils.isBlank(rest.getEndpointUrlEmail())) {
            return null;
        }

        val headers = new HttpHeaders();
        headers.setAccept(CollectionUtils.wrap(MediaType.APPLICATION_JSON));
        headers.put("username", CollectionUtils.wrap(username));
        val entity = new HttpEntity<>(headers);
        val result = restTemplate.exchange(rest.getEndpointUrlEmail(), HttpMethod.GET, entity, String.class);

        if (result.getStatusCodeValue() == HttpStatus.OK.value() && result.hasBody()) {
            return result.getBody();
        }
        return null;
    }

    @Override
    public Map<String, String> getSecurityQuestions(final String username) {
        val rest = properties.getRest();
        if (StringUtils.isBlank(rest.getEndpointUrlSecurityQuestions())) {
            return null;
        }
        val headers = new HttpHeaders();
        headers.setAccept(CollectionUtils.wrap(MediaType.APPLICATION_JSON));
        headers.put("username", CollectionUtils.wrap(username));
        val entity = new HttpEntity<>(headers);
        val result = restTemplate.exchange(rest.getEndpointUrlSecurityQuestions(),
            HttpMethod.GET, entity, Map.class);

        if (result.getStatusCodeValue() == HttpStatus.OK.value() && result.hasBody()) {
            return result.getBody();
        }
        return null;
    }
}


text:
import React from 'react';
import {
  header,
  tabs,
  tab,
  description,
  columns,
  playground,
  api,
  importExample,
  divider,
  testkit,
  example,
  title,
} from 'wix-storybook-utils/Sections';
import Text, { SIZES, SKINS, WEIGHTS } from '..';

import * as examples from './examples';

import { storySettings } from '../test/storySettings';
import { Layout, Cell } from '../../Layout';
import SectionHelper from '../../SectionHelper';
import { Category } from '../../../stories/storiesHierarchy';
import LinkTo from '@storybook/addon-links/react';

export default {
  category: storySettings.category,
  storyName: storySettings.storyName,
  component: Text,
  componentPath: '../Text.js',

  componentProps: {
    children: 'Some text',
    light: false,
    size: SIZES.medium,
    secondary: false,
    skin: SKINS.standard,
    weight: WEIGHTS.thin,
    tagName: 'span',
    ellipsis: false,
  },

  sections: [
    header({
      component: (
        <Layout>
          <Cell span={8}>
            <Text>
              The Life and Strange Surprizing Adventures of Robinson Crusoe, Of
              York, Mariner: Who lived Eight and Twenty Years, all alone in an
              un-inhabited Island on the Coast of America, near the Mouth of the
              Great River of Oroonoque; Having been cast on Shore by Shipwreck,
              wherein all the Men perished but himself. With An Account how he
              was at last as strangely deliver'd by Pyrates.
            </Text>
          </Cell>
        </Layout>
      ),
    }),

    tabs([
      tab({
        title: 'Description',
        sections: [
          columns([
            description({
              title: 'Description',
              text:
                'Text is a a component that makes general text appear in Wix Style. It supports three sizes, three weigths and has multiple skin colors. Use it to build any text content.',
            }),
          ]),

          importExample("import { Text } from 'wix-style-react';"),

          columns([
            description({
              title: 'Load Wix fonts from CDN:',
              text: (

                  <SectionHelper title="Helvetica Neue:">{`<link rel="stylesheet" href="//static.parastorage.com/services/third-party/fonts/Helvetica/fontFace.css"></link>`}</SectionHelper>

                    For Madefor font, plese see{' '}
                    <LinkTo kind={Category.GETTINGSTARTED} story="Madefor Font">
                      MadeforFont
                    </LinkTo>{' '}
                    section.

              ),
            }),
          ]),

          divider(),

          title('Examples'),

          example({
            title: 'Skins',
            text:
              'Text component supports four different styles of skins. Each skin is represents a specific use case. `Standard` skin can be placed on colored backrounds, while other skins should be used only on white or grey.',
            source: examples.skins,
          }),

          example({
            title: 'Light',
            text:
              'Text can appear on dark or light backgrounds. Use `light` prop to keep text in a high contrast.',
            source: examples.light,
          }),

          example({
            title: 'Secondary',
            text:
              'Text component supports secondary styling for `standard` and `light` skins.',
            source: examples.secondary,
          }),

          example({
            title: 'Weight',
            text:
              'Text component supports three weights – `thin`, `normal` and `bold`. Each weight represents a specific use case.',
            source: examples.weight,
          }),

          example({
            title: 'Size',
            text:
              'Text component supports three sizes – `medium`, `small` and `tiny`. Default size is `medium`.',
            source: examples.size,
          }),

          example({
            title: 'Inline Link',
            text:
              'Text component provides a style for html based links. Use them when text links are multiline or inline.',
            source: examples.link,
          }),

          example({
            title: 'Ellipsis',
            text:
              'Text component can wrap the text, show ellipsis or do both. Setting maxLines prop truncates the text at a specific number of lines (use this prop only when you need to show 2 lines or more).',
            source: examples.ellipsis,
          }),

          example({
            title: 'Ellipsis Show Tooltip',
            text:
              'Hidden text appears on hover in a tooltip. It can be turned off by setting `showTooltip` prop to `false`.',
            source: examples.ellipsisNoTooltip,
          }),

          example({
            title: `Tooltip Width`,
            text:
              'Maximum width of tooltip can be adjusted with `maxWidth` prop.',
            source: examples.maxwidth,
          }),

          example({
            title: `Tooltip size`,
            text:
              'Tooltip size can be adjusted with `size` prop that is passed through `tooltipProps`.',
            source: examples.smallTooltip,
          }),

          example({
            title: 'TagName',
            text: 'Control the rendered HTML tag.',
            source: examples.custom,
          }),

          example({
            title: 'Lists',
            text:
              'Text component provides a style for HTML based lists. Using the listStyle prop, an unordered list items can be styled as checkmark (default) or circle .',
            source: examples.list,
          }),
        ],
      }),

      ...[
        { title: 'API', sections: [api()] },
        { title: 'Testkit', sections: [testkit()] },
        { title: 'Playground', sections: [playground()] },
      ].map(tab),
    ]),
  ],
};


text:
namespace Lucene.Net.Analysis.Pt
{

    /// <summary>
    /// Minimal Stemmer for Portuguese
    /// <para>
    /// This follows the "RSLP-S" algorithm presented in:
    /// <c>A study on the Use of Stemming for Monolingual Ad-Hoc Portuguese
    /// Information Retrieval</c> (Orengo, et al)
    /// which is just the plural reduction step of the RSLP
    /// algorithm from <c>A Stemming Algorithm for the Portuguese Language</c>,
    /// Orengo et al.
    /// </para>
    /// </summary>
    /// <seealso cref="RSLPStemmerBase"/>
    public class PortugueseMinimalStemmer : RSLPStemmerBase
    {
        private static readonly Step pluralStep = Parse(typeof(PortugueseMinimalStemmer), "portuguese.rslp")["Plural"];

        public virtual int Stem(char[] s, int len)
        {
            return pluralStep.Apply(s, len);
        }
    }
}


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

<title>Utils</title>
<meta name="date" content="2014-01-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

ch.bfh.ti.ostes2.gossip

Class Utils

java.lang.Object

ch.bfh.ti.ostes2.gossip.Utils

public final class Utils
extends java.lang.Object

A class providing various
 helper functions for time stamps
 as well as definitions of tags
 used for communication of Messages.

Author:

sosterwalder

Field Summary

Fields

Modifier and Type
Field and Description

static int
GOSSIP_TAG

static int
QUERY_TAG

static int
UPDATE_TAG

Constructor Summary

Constructors

Constructor and Description

Utils()

Method Summary

Methods

Modifier and Type
Method and Description

static int[]
getMaximizedTimestamp(int[] timestampOne,
                     int[] timestampTwo)

Returns the (component-wise) maximum
 of two given time stamps,
 assuming that the time stamps have the
 same length.

static int[]
getMinimizedTimestamp(int[] timestampOne,
                     int[] timestampTwo)

Returns the (component-wise) minimum
 of two given time stamps, assuming that the time stamps have the
 same length.

static boolean
isSmallerOrEqualThan(int[] timestampOne,
                    int[] timestampTwo)

Checks if the first provided time stamp
 is smaller or equal as the second provided
 time stamp, assuming that the time stamps have the
 same length.

static int[]
mergeTimestamps(int[] timestampOne,
               int[] timestampTwo)

Merges two given time stamps to their
 maximal value, assuming that the time stamps have the
 same length.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

QUERY_TAG

public static final int QUERY_TAG

See Also:

Constant Field Values

UPDATE_TAG

public static final int UPDATE_TAG

See Also:

Constant Field Values

GOSSIP_TAG

public static final int GOSSIP_TAG

See Also:

Constant Field Values

Constructor Detail

Utils

public Utils()

Method Detail

isSmallerOrEqualThan

public static final boolean isSmallerOrEqualThan(int[] timestampOne,
                           int[] timestampTwo)

Checks if the first provided time stamp
 is smaller or equal as the second provided
 time stamp, assuming that the time stamps have the
 same length.

 E.g.:  ts1: [2, 3]
                        ts2: [5, 1]
                        => res: false (3 > 1)

Parameters:

timestampOne - the target time stamp

timestampTwo - the source time stamp

Returns:

true if timestampOne
                                                        is smaller or equal,
                                                        otherwise false

getMaximizedTimestamp

public static final int[] getMaximizedTimestamp(int[] timestampOne,
                          int[] timestampTwo)

Returns the (component-wise) maximum
 of two given time stamps,
 assuming that the time stamps have the
 same length.

 E.g.:  ts1: [2, 3]
                        ts2: [5, 1]
                        => res: [5, 3]

Parameters:

timestampOne -

timestampTwo -

Returns:

the maximum out of the
                                two time stamps

getMinimizedTimestamp

public static final int[] getMinimizedTimestamp(int[] timestampOne,
                          int[] timestampTwo)

Returns the (component-wise) minimum
 of two given time stamps, assuming that the time stamps have the
 same length.

 E.g.:  ts1: [2, 3]
                        ts2: [5, 1]
                        => res: [2, 1]

Parameters:

timestampOne -

timestampTwo -

Returns:

the minimum out of the
                                two time stamps

mergeTimestamps

public static final int[] mergeTimestamps(int[] timestampOne,
                    int[] timestampTwo)

Merges two given time stamps to their
 maximal value, assuming that the time stamps have the
 same length.

 E.g.:  ts1: [2, 3]
                        ts2: [5, 1]
                        => res: [5, 3]

Parameters:

timestampOne -

timestampTwo -

Returns:

the maximum out of the
                                two time stamps

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method