text:
ANT_URL="@{ant.url}"
ANT_SHA512="@{ant.sha512}"

# fetch tar
echo "Download $ANT_URL"
TAR=`basename $ANT_URL`
curl -v -L -o "$TAR" -z "$TAR" --retry 5 "$ANT_URL"

# verify archive via SHA512 checksum
ANT_SHA512_ACTUAL=`openssl dgst -sha512 -hex -r "$TAR" | cut -d' ' -f1`
echo "Expected SHA512 checksum: $ANT_SHA512"
echo "Actual SHA512 checksum: $ANT_SHA512_ACTUAL"

if [ "$ANT_SHA512" != "$ANT_SHA512_ACTUAL" ]; then
	echo "ERROR: SHA512 checksum mismatch"
	exit 1
fi

# unpack tar archive
echo "Extract $TAR"
tar -xvf "$TAR"

# find ant executable
export ANT_HOME="$PWD/apache-ant-@{version}"
export ANT_EXE="$ANT_HOME/bin/ant"

# fetch optional ant libs
export ANT_OPTS="-Duser.home=$PWD"
$ANT_EXE -f "$ANT_HOME/fetch.xml" -Ddest=system

# symlink only if explicitly requested
if [ "$1" != "install" ]; then
	echo "Download complete: $TAR"
	exit 0
fi

# link ant home to /usr/local/ant
ln -sf "$ANT_HOME" "/usr/local/ant"

# link executable into /usr/local/bin/ant
mkdir -p "/usr/local/bin"
ln -sf "$ANT_EXE" "/usr/local/bin/ant"

# run ant diagnostics
echo "Execute $ANT_EXE -diagnostics"
$ANT_EXE -diagnostics


text:
// jshint quotmark:false
define([ "dojo/dom", "dojo/on", "delite/register", "dcl/dcl", "dapp/View" ],
	function ( dom, on, register, dcl, View ) {
		return dcl([View], {
//	define([ /*"dojo/dom", "dojo/on", "delite/register", "dcl/dcl", "dapp/View"*/ ],
	//	function ( /*dom, on, register, dcl, View*/ ) {
		//return {
			name: "",
			_beforeActivateCallCount: 0,
			_beforeDeactivateCallCount: 0,
			_afterActivateCallCount: 0,
			_afterDeactivateCallCount: 0,
			init: function () {
				this.name = this.id;
			},
			//beforeActivate: function ( /*previousView, viewData*/ ) {
			//	//console.log("app-view:", "beforeActivate called for [" + this.viewName +
			//	//"] with previousView.id =[" + (previousView ? previousView.id : "") + "] with viewData=", viewData);
			//	this._beforeActivateCallCount++;
			//},
				beforeActivate: dcl.superCall(function (sup) {
					return function () {
						this._beforeActivateCallCount++;
						return sup.call(this);
					};
				}),

			beforeDeactivate: function ( /*nextView, viewData*/ ) {
				//console.log("app-view:", "beforeDeactivate called for [" + this.viewName +
				//	"] with previousView.id =[" + (nextView ? nextView.id : "") + "]");
				this._beforeDeactivateCallCount++;
			},
			afterActivate: function ( /*previousView, viewData*/ ) {
				//console.log("app-view:", "afterActivate called for [" + this.viewName + "] with previousView.id =[" +
				//	(previousView ? previousView.id : "") + "] with viewData=", viewData);
				this._afterActivateCallCount++;
			},
			afterDeactivate: function ( /*nextView, viewData*/ ) {
				//console.log("app-view:", "afterDeactivate called for [" + this.viewName +
				//	"] with previousView.id =[" + (nextView ? nextView.id : "") + "]");
				this._afterDeactivateCallCount++;
			},
			destroy: function () {
				//console.log("app-view:", " in [" + this.viewName + "] destroy called for [" + this.id + "]");
			}
		} //;
		); // for dcl view attempt...
	});

redpajama_set_name: RedPajamaGithub


text:
package com.esri.arcgisruntime.sample.performspatialoperations;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import androidx.appcompat.app.AppCompatActivity;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Part;
import com.esri.arcgisruntime.geometry.PartCollection;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.BasemapStyle;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;

public class MainActivity extends AppCompatActivity {

  final private GraphicsOverlay inputGeometryOverlay = new GraphicsOverlay();
  final private GraphicsOverlay resultGeometryOverlay = new GraphicsOverlay();
  // simple black (0xFF000000) line symbol for outlines
  final private SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFF000000, 1);
  final private SimpleFillSymbol resultFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, 0xFFE91F1F,
      lineSymbol);
  private Polygon inputPolygon1;
  private Polygon inputPolygon2;
  // The spatial operation switching menu items.
  private MenuItem noOperationMenuItem = null;
  private MenuItem intersectionMenuItem = null;
  private MenuItem unionMenuItem = null;
  private MenuItem differenceMenuItem = null;
  private MenuItem symmetricDifferenceMenuItem = null;
  private MapView mMapView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // authentication with an API key or named user is required to access basemaps and other
    // location services
    ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY);

    mMapView = findViewById(R.id.mapView);

    // create ArcGISMap with topographic basemap
    ArcGISMap map = new ArcGISMap(BasemapStyle.ARCGIS_LIGHT_GRAY);
    mMapView.setMap(map);

    // create graphics overlays to show the inputs and results of the spatial operation
    mMapView.getGraphicsOverlays().add(inputGeometryOverlay);
    mMapView.getGraphicsOverlays().add(resultGeometryOverlay);

    // create input polygons and add graphics to display these polygons in an overlay
    createPolygons();

    // center the map view on the input geometries
    Geometry viewpointGeom = GeometryEngine.union(inputPolygon1, inputPolygon2).getExtent();
    mMapView.setViewpointGeometryAsync(viewpointGeom, 20);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    // Get the menu items that perform spatial operations.
    noOperationMenuItem = menu.getItem(0);
    intersectionMenuItem = menu.getItem(1);
    unionMenuItem = menu.getItem(2);
    differenceMenuItem = menu.getItem(3);
    symmetricDifferenceMenuItem = menu.getItem(4);

    // set the 'no-op' menu item checked by default
    noOperationMenuItem.setChecked(true);

    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // handle menu item selection
    int itemId = item.getItemId();

    // clear previous operation result
    resultGeometryOverlay.getGraphics().clear();

    // perform spatial operations and add results as graphics, depending on the option selected
    // if-else is used because this sample is used elsewhere as a Library module
    if (itemId == R.id.action_no_operation) {
      // no spatial operation - graphics have been cleared previously
      noOperationMenuItem.setChecked(true);
      return true;
    } else if (itemId == R.id.action_intersection) {
      intersectionMenuItem.setChecked(true);
      showGeometry(GeometryEngine.intersection(inputPolygon1, inputPolygon2));
      return true;
    } else if (itemId == R.id.action_union) {
      unionMenuItem.setChecked(true);
      showGeometry(GeometryEngine.union(inputPolygon1, inputPolygon2));
      return true;
    } else if (itemId == R.id.action_difference) {
      differenceMenuItem.setChecked(true);
      // note that the difference method gives different results depending on the order of input geometries
      showGeometry(GeometryEngine.difference(inputPolygon1, inputPolygon2));
      return true;
    } else if (itemId == R.id.action_symmetric_difference) {
      symmetricDifferenceMenuItem.setChecked(true);
      showGeometry(GeometryEngine.symmetricDifference(inputPolygon1, inputPolygon2));
      return true;
    } else {
      return super.onOptionsItemSelected(item);
    }
  }

  private void showGeometry(Geometry resultGeometry) {
    // add a graphic from the result geometry, showing result in red (0xFFE91F1F)
    Graphic resultGraphic = new Graphic(resultGeometry, resultFillSymbol);
    resultGeometryOverlay.getGraphics().add(resultGraphic);

    // select the result to highlight it
    resultGraphic.setSelected(true);
  }

  private void createPolygons() {

    // create input polygon 1
    PointCollection pointsPoly = new PointCollection(SpatialReferences.getWebMercator());
    pointsPoly.add(new Point(-13160, 6710100));
    pointsPoly.add(new Point(-13300, 6710500));
    pointsPoly.add(new Point(-13760, 6710730));
    pointsPoly.add(new Point(-14660, 6710000));
    pointsPoly.add(new Point(-13960, 6709400));
    inputPolygon1 = new Polygon(pointsPoly);

    // create and add a blue graphic to show input polygon 1
    SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, 0x990000CC, lineSymbol);
    inputGeometryOverlay.getGraphics().add(new Graphic(inputPolygon1, fillSymbol));

    // create input polygon 2 with a green (0xFF009900) symbol
    // outer ring
    PointCollection outerRingSegmentCollection = new PointCollection(SpatialReferences.getWebMercator());
    outerRingSegmentCollection.add(new Point(-13060, 6711030));
    outerRingSegmentCollection.add(new Point(-12160, 6710730));
    outerRingSegmentCollection.add(new Point(-13160, 6709700));
    outerRingSegmentCollection.add(new Point(-14560, 6710730));
    outerRingSegmentCollection.add(new Point(-13060, 6711030));
    Part outerRing = new Part(outerRingSegmentCollection);

    // inner ring
    PointCollection innerRingSegmentCollection = new PointCollection(SpatialReferences.getWebMercator());
    innerRingSegmentCollection.add(new Point(-13060, 6710910));
    innerRingSegmentCollection.add(new Point(-12450, 6710660));
    innerRingSegmentCollection.add(new Point(-13160, 6709900));
    innerRingSegmentCollection.add(new Point(-14160, 6710630));
    innerRingSegmentCollection.add(new Point(-13060, 6710910));
    Part innerRing = new Part(innerRingSegmentCollection);

    // add both parts (rings) to a part collection and create a geometry from it
    PartCollection polygonParts = new PartCollection(outerRing);
    polygonParts.add(innerRing);
    inputPolygon2 = new Polygon(polygonParts);

    // create and add a green graphic to show input polygon 2
    fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, 0x99009900, lineSymbol);
    inputGeometryOverlay.getGraphics().add(new Graphic(inputPolygon2, fillSymbol));
  }

  @Override
  protected void onPause() {
    mMapView.pause();
    super.onPause();
  }

  @Override
  protected void onResume() {
    super.onResume();
    mMapView.resume();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    mMapView.dispose();
  }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title></title>
			<link rel="stylesheet" href="media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

[Tests_Amfphp_Plugins_CharsetConverter] element index

Package indexes

Amfphp_Core

Amfphp_Core_Amf

Amfphp_Core_Amf_Types

Amfphp_Core_Common

Amfphp

Amfphp_Plugins_Authentication

Amfphp_Plugins_CharsetConverter

Amfphp_Plugins_CustomClassConverter

Amfphp_Plugins_ErrorHandler

Amfphp_Plugins_FlexMessaging

Amfphp_Plugins_Json

Amfphp_Plugins_Logger

AmfphpLogger

Amfphp_Plugins_ServiceBrowser

Amfphp_Services

Amfphp_Examples_ExampleService

Amfphp_Examples

Tests_Amfphp_Core_Amf

Tests_Amfphp_Core_Common

Tests_Amfphp_Core

Tests_Amfphp_Plugins_Authentication

Tests_Amfphp_Plugins_CustomClassConverter

Tests_Amfphp_Plugins_FlexMessaging

Tests_Amfphp_Plugins_Logger

Tests

Tests_TestData

Tests_TestData_CustomClasses

Tests_TestData_Services

Tests_TestData_TestPlugins_DisabledPlugin

Tests_TestData_TestPlugins_DummyPlugin

All elements

	a
	o
	s
	t

a

top

						AmfphpCharsetConverterTest

AmfphpCharsetConverterTest in AmfphpCharsetConverterTest.php

Test class for CharsetConverter.

						AmfphpCharsetConverterTest.php

AmfphpCharsetConverterTest.php in AmfphpCharsetConverterTest.php

o

top

						$object

AmfphpCharsetConverterTest::$object in AmfphpCharsetConverterTest.php

s

top

						setUp

AmfphpCharsetConverterTest::setUp() in AmfphpCharsetConverterTest.php

Sets up the fixture, for example, opens a network connection.

t

top

						tearDown

AmfphpCharsetConverterTest::tearDown() in AmfphpCharsetConverterTest.php

Tears down the fixture, for example, closes a network connection.

						testRequestDeserializedFilter

AmfphpCharsetConverterTest::testRequestDeserializedFilter() in AmfphpCharsetConverterTest.php

						testResponseDeserializedFilter

AmfphpCharsetConverterTest::testResponseDeserializedFilter() in AmfphpCharsetConverterTest.php

	a
	o
	s
	t


text:
/*
             Licensed to the DARPA XDATA project.
       DARPA XDATA licenses this file to you 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.
*/
package smile.wide.data;

import java.net.URI;
import java.net.URISyntaxException;

/** Subclass of Dataset that wraps around the SMILE DataSet
 *
 * @author m.a.dejongh@gmail.com
 * @author tomas.singliar@boeing.com
 *
 */
public class SMILEData extends DataSet {
	/** SMILE DataSet class*/
	private smile.learning.DataSet data = null;
	private  String fileName_ = null;				// most recent location

	// =========================================================================
	public void Read(String filename) {
		if(data == null)
			data = new smile.learning.DataSet();
		data.readFile(filename);
		fileName_ = filename;
	}
	/** Write data from SMILE's data object into a text file*/
	public void Write(String filename) {
		if(data != null)
			data.writeFile(filename);
		fileName_ = filename;
	}
	/** Takes a SMILE data object and replaces the internal data object with the this one*/
	public smile.learning.DataSet getData() {
		return data;
	}

	public void setData(smile.learning.DataSet data) {
		this.data = data;
	}

	// =========================================================================
	@Override
	public URI location() {

		try {
			// TODO: convert to HDFS url if applicable
			return new URI("file://" + fileName_);
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		}

	}

	@Override
	public String getName() {
		return "A SMILE dataset";
	}

	@Override
	public String[] columns() {
		int varcount =  data.getVariableCount();
		String[] cols = new String[varcount];
		for (int i = 0; i < varcount; ++i)
		{
			cols[i] = data.getVariableId(i);
		}
		return cols;
	}

	@Override
	public int indexOfColumn(String s) {
		String[] cols = columns();

		if (s == null)
			return -1;

		for (int i = 0; i < cols.length; ++i)
		{
			if (s.equals(cols[i]))
				return i;
		}

		return -1;
	}

	@Override
	public int instanceIDColumnIndex() {
		return -1;
	}

}


text:
package org.jenkinsci.plugins.docker.commons.credentials;

import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.domains.DomainSpecification;
import hudson.security.ACL;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

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

import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author Stephen Connolly
 */
public class DockerServerCredentialsTest {
    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Test
    public void configRoundTripEmpty() throws Exception {
        CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next();
        assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
        Domain domain = new Domain("docker", "A domain for docker credentials",
                Collections.<DomainSpecification>singletonList(new DockerServerDomainSpecification()));
        DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", "", "", "");
        store.addDomain(domain, credentials);
        j.submit(j.createWebClient().goTo("credential-store/domain/" + domain.getName() + "/credential/"+credentials.getId()+"/update")
                .getFormByName("update"));

        j.assertEqualDataBoundBeans(credentials, CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(IdCredentials.class, j.getInstance(),
                ACL.SYSTEM, new DockerServerDomainRequirement()), CredentialsMatchers.withId(credentials.getId())));
    }

    @Test
    public void configRoundTripData() throws Exception {
        CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next();
        assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
        Domain domain = new Domain("docker", "A domain for docker credentials",
                Collections.<DomainSpecification>singletonList(new DockerServerDomainSpecification()));
        DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", "a", "b", "c");
        store.addDomain(domain, credentials);
        j.submit(j.createWebClient().goTo("credential-store/domain/" + domain.getName() + "/credential/"+credentials.getId()+"/update")
                .getFormByName("update"));

        j.assertEqualDataBoundBeans(credentials, CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(IdCredentials.class, j.getInstance(),
                ACL.SYSTEM, new DockerServerDomainRequirement()), CredentialsMatchers.withId(credentials.getId())));
    }

}


text:
<?php
use yii\helpers\Html;
?>

<?= $this->context->action->uniqueId ?>

        This is the view content for action "<?= $this->context->action->id ?>".
        The action belongs to the controller "<?= get_class($this->context) ?>"
        in the "<?= $this->context->module->id ?>" module.

        You may customize this page by editing the following file:

        <?= __FILE__ ?>

    <?= Html::a('Перейти в контроллер TEST', ['test/index', 'id' => $id], ['class' => 'profile-link']) ?>


text:
<?php

namespace Viagogo\Core;

/**
 *
 */
class OAuthToken extends ViagogoModel {
	protected $access_token;
	protected $token_type;
	protected $expires_in;
	protected $refresh_token;
	protected $scopes;

	public function getAccessToken() {
		return $this->access_token;
	}
}


text:
import json
import os
import sys
import time
import uuid

uuid_null = uuid.UUID(bytes='\x00'*16);
time_format = "%Y-%m-%d";

# class time_struct:
#     def __init__(self):
#         self.year = 0;
#         self.month = 0;
#         self.day = 0;
#     def to_time_string(self):
#         tstr = "";
#         return tstr;
#     def to_time_struct(self):
#         return time.;

# use some machine learing to automatically classify categories.
class categoryManager:
    def __init__(self, path):
        self.categories = ["None"] # Add default categories here.
        if os.path.exists(path):
            self.loadFromFile(path);
        else:
            pass

    def loadFromFile(self, path):
        pass

    def saveToFile(self, path):
        pass

#### end categoryManager ####

class transaction:
    def __init__(self, date = time.strftime(time_format, time.gmtime(0)), category = "None", amt = 0.0, desc = "", tid = uuid_null):
        self.__dict__ = {"date": time.strptime(date, time_format), "category":category, "amount": amt, "description": desc, "__transaction__":tid };

    def __str__(self):
        return json.dumps(self.toJSON()); # indent = 4 ?

    def __getitem__(self, name):
        return self.__dict__[name];

    def toJSON(self):
        temp = self.__dict__.copy();
        temp["date"] = time.strftime(time_format, temp["date"]);
        temp["__transaction__"] = str(temp["__transaction__"]);
        return temp;

    def fromJSON(self, temp):
        self.__dict__ = temp.copy();
        self.__dict__["date"] = time.strptime(temp["date"], time_format);
        self.__dict__["__transaction__"] = uuid.UUID(temp["__transaction__"]);

class TransactionEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, transaction):
            return obj.toJSON();
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

    @staticmethod
    def as_transaction(dct):
        if "__transaction__" in dct:
            t = transaction();
            t.fromJSON(dct)
            return t;
        return dct;

#### end transaction ####

class configuration:
    def __init__(self):
        self.path = "";
        self.bInit = False;
        self.__dict__ = {};

    def __setitem__(self, name, val):
        self.__dict__[name] = val;
    def __getitem__(self, name):
        return self.__dict__[name];

    def __str__(self):
        return json.dumps(self.__dict__);

    def loadFromFile(self):
        try:
            if not os.path.exists("config.json"):
                print "could not load configuration file"
                return False;
            else:
                cfile = open("config.json", "r");
                self.__dict__ = json.loads(cfile.read());
                cfile.close();
                self.bInit = True;
                return True;
        except:
            print "Error reading config file"
            return False;

    def saveToFile(self):
        try:
            cfile = open("config.json", "w");
            cfile.write(json.dumps(self.__dict__));
            cfile.close();
            return True;
        except:
            print "Error writing config file"
            return False;

#### end configuration ####


text:
let arr = [];
let each = arr.forEach;
let slice = arr.slice;

export function defaults(obj) {
  each.call(slice.call(arguments, 1), function(source) {
    if (source) {
      for (var prop in source) {
        if (obj[prop] === undefined) obj[prop] = source[prop];
      }
    }
  });
  return obj;
}

export function extend(obj) {
  each.call(slice.call(arguments, 1), function(source) {
    if (source) {
      for (var prop in source) {
        obj[prop] = source[prop];
      }
    }
  });
  return obj;
}


text:
//
// Pop3AuthenticationSecretDetectorTests.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2021 .NET Foundation and Contributors
//
// 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
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// 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.
//

using System.Text;
using System.Collections.Generic;

using NUnit.Framework;

using MailKit;
using MailKit.Net.Pop3;

namespace UnitTests.Net.Pop3 {
	[TestFixture]
	public class Pop3AuthenticationSecretDetectorTests
	{
		[Test]
		public void TestEmptyCommand ()
		{
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = new byte[0];

			detector.IsAuthenticating = true;

			var secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (0, secrets.Count, "# of secrets");
		}

		[Test]
		public void TestNonAuthCommand ()
		{
			const string command = "UIDL 1\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);

			detector.IsAuthenticating = true;

			var secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (0, secrets.Count, "# of secrets");
		}

		[Test]
		public void TestNotIsAuthenticating ()
		{
			const string command = "AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);

			var secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (0, secrets.Count, "# of secrets");
		}

		[Test]
		public void TestApopCommand ()
		{
			const string command = "APOP username AHVzZXJuYW1lAHBhc3N3b3Jk\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);

			detector.IsAuthenticating = true;

			var secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (2, secrets.Count, "# of secrets");
			Assert.AreEqual (5, secrets[0].StartIndex, "StartIndex");
			Assert.AreEqual (8, secrets[0].Length, "Length");
			Assert.AreEqual (14, secrets[1].StartIndex, "StartIndex");
			Assert.AreEqual (24, secrets[1].Length, "Length");
		}

		[Test]
		public void TestApopCommandBitByBit ()
		{
			const string command = "APOP username AHVzZXJuYW1lAHBhc3N3b3Jk\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);
			IList<AuthenticationSecret> secrets;
			int index = 0;

			detector.IsAuthenticating = true;

			while (index < command.Length) {
				secrets = detector.DetectSecrets (buffer, index, 1);
				if (index >= 5 && index != 13 && index < command.Length - 2) {
					Assert.AreEqual (1, secrets.Count, "# of secrets @ index {0}", index);
					Assert.AreEqual (index, secrets[0].StartIndex, "StartIndex");
					Assert.AreEqual (1, secrets[0].Length, "Length");
				} else {
					Assert.AreEqual (0, secrets.Count, "# of secrets @ index {0}", index);
				}
				index++;
			}
		}

		[Test]
		public void TestUserPassCommand ()
		{
			var detector = new Pop3AuthenticationSecretDetector ();
			IList<AuthenticationSecret> secrets;
			byte[] buffer;

			detector.IsAuthenticating = true;

			buffer = Encoding.ASCII.GetBytes ("USER user\r\n");
			secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (1, secrets.Count, "USER # of secrets");
			Assert.AreEqual (5, secrets[0].StartIndex, "USER StartIndex");
			Assert.AreEqual (4, secrets[0].Length, "USER Length");

			buffer = Encoding.ASCII.GetBytes ("PASS p@$$w0rd\r\n");
			secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (1, secrets.Count, "PASS # of secrets");
			Assert.AreEqual (5, secrets[0].StartIndex, "PASS StartIndex");
			Assert.AreEqual (8, secrets[0].Length, "PASS Length");
		}

		[Test]
		public void TestUserPassCommandBitByBit ()
		{
			const string command = "USER user\r\nPASS p@$$w0rd\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);
			IList<AuthenticationSecret> secrets;
			int index = 0;

			detector.IsAuthenticating = true;

			while (index < command.Length) {
				secrets = detector.DetectSecrets (buffer, index, 1);
				if ((index >= 5 && index < 9) || (index >= 16 && index < 24)) {
					Assert.AreEqual (1, secrets.Count, "# of secrets @ index {0}", index);
					Assert.AreEqual (index, secrets[0].StartIndex, "StartIndex");
					Assert.AreEqual (1, secrets[0].Length, "Length");
				} else {
					Assert.AreEqual (0, secrets.Count, "# of secrets @ index {0}", index);
				}
				index++;
			}
		}

		[Test]
		public void TestSaslIRAuthCommand ()
		{
			const string command = "AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);

			detector.IsAuthenticating = true;

			var secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (1, secrets.Count, "# of secrets");
			Assert.AreEqual (11, secrets[0].StartIndex, "StartIndex");
			Assert.AreEqual (24, secrets[0].Length, "Length");
		}

		[Test]
		public void TestSaslIRAuthCommandBitByBit ()
		{
			const string command = "AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);
			int secretIndex = "AUTH PLAIN ".Length;
			IList<AuthenticationSecret> secrets;
			int index = 0;

			detector.IsAuthenticating = true;

			while (index < command.Length) {
				secrets = detector.DetectSecrets (buffer, index, 1);
				if (index >= secretIndex && command[index] != '\r' && command[index] != '\n') {
					Assert.AreEqual (1, secrets.Count, "# of secrets @ index {0}", index);
					Assert.AreEqual (index, secrets[0].StartIndex, "StartIndex");
					Assert.AreEqual (1, secrets[0].Length, "Length");
				} else {
					Assert.AreEqual (0, secrets.Count, "# of secrets @ index {0}", index);
				}
				index++;
			}
		}

		[Test]
		public void TestMultiLineSaslAuthCommand ()
		{
			var detector = new Pop3AuthenticationSecretDetector ();
			IList<AuthenticationSecret> secrets;
			byte[] buffer;

			detector.IsAuthenticating = true;

			buffer = Encoding.ASCII.GetBytes ("AUTH LOGIN\r\n");
			secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (0, secrets.Count, "initial # of secrets");

			buffer = Encoding.ASCII.GetBytes ("dXNlcm5hbWU=\r\n");
			secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (1, secrets.Count, "# of secrets");
			Assert.AreEqual (0, secrets[0].StartIndex, "StartIndex");
			Assert.AreEqual (12, secrets[0].Length, "Length");

			buffer = Encoding.ASCII.GetBytes ("cGFzc3dvcmQ=\r\n");
			secrets = detector.DetectSecrets (buffer, 0, buffer.Length);
			Assert.AreEqual (1, secrets.Count, "# of secrets");
			Assert.AreEqual (0, secrets[0].StartIndex, "StartIndex");
			Assert.AreEqual (12, secrets[0].Length, "Length");
		}

		[Test]
		public void TestMultiLineSaslAuthCommandBitByBit ()
		{
			const string command = "AUTH LOGIN\r\ndXNlcm5hbWU=\r\ncGFzc3dvcmQ=\r\n";
			var detector = new Pop3AuthenticationSecretDetector ();
			var buffer = Encoding.ASCII.GetBytes (command);
			int secretIndex = "AUTH LOGIN\r\n".Length;
			IList<AuthenticationSecret> secrets;
			int index = 0;

			detector.IsAuthenticating = true;

			while (index < command.Length) {
				secrets = detector.DetectSecrets (buffer, index, 1);
				if (index >= secretIndex && command[index] != '\r' && command[index] != '\n') {
					Assert.AreEqual (1, secrets.Count, "# of secrets @ index {0}", index);
					Assert.AreEqual (index, secrets[0].StartIndex, "StartIndex");
					Assert.AreEqual (1, secrets[0].Length, "Length");
				} else {
					Assert.AreEqual (0, secrets.Count, "# of secrets @ index {0}", index);
				}
				index++;
			}
		}
	}
}


text:
function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([hashtable])]
    param (
        [Parameter(Mandatory)]
        [ValidateSet('Public', 'Private', 'Domain')]
        [string] $Name
    )

    try
    {
        $profile = Get-NetFirewallProfile -Name $Name
    }
    catch
    {
        throw
    }

    return @{
        Name                            = $Name
        Enabled                         = $profile.Enabled
        DefaultInboundAction            = $profile.DefaultInboundAction
        DefaultOutboundAction           = $profile.DefaultOutboundAction
        AllowInboundRules               = $profile.AllowInboundRules
        AllowLocalFirewallRules         = $profile.AllowLocalFirewallRules
        AllowLocalIPsecRules            = $profile.AllowLocalIPsecRules
        AllowUserApps                   = $profile.AllowUserApps
        AllowUserPorts                  = $profile.AllowUserPorts
        AllowUnicastResponseToMulticast = $profile.AllowUnicastResponseToMulticast
        NotifyOnListen                  = $profile.NotifyOnListen
        EnableStealthModeForIPsec       = $profile.EnableStealthModeForIPsec
        LogFileName                     = $profile.LogFileName
        LogMaxSizeKilobytes             = $profile.LogMaxSizeKilobytes
        LogAllowed                      = $profile.LogAllowed
        LogBlocked                      = $profile.LogBlocked
        LogIgnored                      = $profile.LogIgnored
        DisabledInterfaceAliases        = $profile.DisabledInterfaceAliases
    }
}

function Set-TargetResource
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateSet('Public', 'Private', 'Domain')]
        [string] $Name,

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $Enabled = 'True',

        [ValidateSet('Allow', 'Block', 'NotConfigured')]
        [string]
        $DefaultInboundAction = 'NotConfigured',

        [ValidateSet('Allow', 'Block', 'NotConfigured')]
        [string]
        $DefaultOutboundAction = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowInboundRules = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowLocalFirewallRules = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowLocalIPsecRules = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowUserApps = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowUserPorts = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowUnicastResponseToMulticast = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $NotifyOnListen = 'True',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $EnableStealthModeForIPsec = 'NotConfigured',

        [string]
        $LogFileName = '%systemroot%\system32\LogFiles\Firewall\pfirewall.log',

        [uint64]
        $LogMaxSizeKilobytes = 4096,

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $LogAllowed = 'False',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $LogBlocked = 'False',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $LogIgnored = 'NotConfigured',

        [string[]]
        $DisabledInterfaceAliases = @('NotConfigured')
    )

    Set-NetFirewallProfile -Name $Name `
                           -Enabled $Enabled `
                           -DefaultInboundAction $DefaultInboundAction `
                           -DefaultOutboundAction $DefaultOutboundAction `
                           -AllowInboundRules $AllowInboundRules `
                           -AllowLocalFirewallRules $AllowLocalFirewallRules `
                           -AllowLocalIPsecRules $AllowLocalIPsecRules `
                           -AllowUserApps $AllowUserApps `
                           -AllowUserPorts $AllowUserPorts `
                           -AllowUnicastResponseToMulticast $AllowUnicastResponseToMulticast `
                           -NotifyOnListen $NotifyOnListen `
                           -EnableStealthModeForIPsec $EnableStealthModeForIPsec `
                           -LogFileName $LogFileName `
                           -LogMaxSizeKilobytes $LogMaxSizeKilobytes `
                           -LogAllowed $LogAllowed `
                           -LogBlocked $LogBlocked `
                           -LogIgnored $LogIgnored `
                           -DisabledInterfaceAliases $DisabledInterfaceAliases
}

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([bool])]
    param (
        [Parameter(Mandatory)]
        [ValidateSet('Public', 'Private', 'Domain')]
        [string] $Name,

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $Enabled = 'True',

        [ValidateSet('Allow', 'Block', 'NotConfigured')]
        [string]
        $DefaultInboundAction = 'NotConfigured',

        [ValidateSet('Allow', 'Block', 'NotConfigured')]
        [string]
        $DefaultOutboundAction = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowInboundRules = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowLocalFirewallRules = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowLocalIPsecRules = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowUserApps = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowUserPorts = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $AllowUnicastResponseToMulticast = 'NotConfigured',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $NotifyOnListen = 'True',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $EnableStealthModeForIPsec = 'NotConfigured',

        [string]
        $LogFileName = '%systemroot%\system32\LogFiles\Firewall\pfirewall.log',

        [uint64]
        $LogMaxSizeKilobytes = 4096,

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $LogAllowed = 'False',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $LogBlocked = 'False',

        [ValidateSet('True', 'False', 'NotConfigured')]
        [string]
        $LogIgnored = 'NotConfigured',

        [string[]]
        $DisabledInterfaceAliases = @('NotConfigured')
    )

    try
    {
        $profile = Get-NetFirewallProfile -Name $Name
    }
    catch
    {
        throw
    }

    return ($profile.Enabled -eq $Enabled -and
            $profile.DefaultInboundAction -eq $DefaultInboundAction -and
            $profile.DefaultOutboundAction -eq $DefaultOutboundAction -and
            $profile.AllowInboundRules -eq $AllowInboundRules -and
            $profile.AllowLocalFirewallRules -eq $AllowLocalFirewallRules -and
            $profile.AllowLocalIPsecRules -eq $AllowLocalIPsecRules -and
            $profile.AllowUserApps -eq $AllowUserApps -and
            $profile.AllowUserPorts -eq $AllowUserPorts -and
            $profile.AllowUnicastResponseToMulticast -eq $AllowUnicastResponseToMulticast -and
            $profile.NotifyOnListen -eq $NotifyOnListen -and
            $profile.EnableStealthModeForIPsec -eq $EnableStealthModeForIPsec -and
            $profile.LogFileName -eq $LogFileName -and
            $profile.LogMaxSizeKilobytes -eq $LogMaxSizeKilobytes -and
            $profile.LogAllowed -eq $LogAllowed -and
            $profile.LogBlocked -eq $LogBlocked -and
            $profile.LogIgnored -eq $LogIgnored -and
            -not [bool](Compare-Object $profile.DisabledInterfaceAliases $DisabledInterfaceAliases))
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Writ. 6: 901 (1919)

#### Original name
Hypoxylon hibisci Henn., 1908

### Remarks
null


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**end** | **int** | End time of event, in epoch millis | [optional]
**hosts** | **list[str]** | Sources (hosts) to which the event pertains | [optional]
**is_ephemeral** | **bool** | Whether the event is an artificial event generated by a literal expression or alert backtesting, i.e. not stored in the Wavefront backend | [optional]
**name** | **str** | Event name | [optional]
**start** | **int** | Start time of event, in epoch millis | [optional]
**summarized** | **int** | In some event queries, multiple events that occur nearly simultaneously are summarized under a single event.  This value specifies the number of events summarized under this one | [optional]
**tags** | **dict(str, str)** | Tags (annotations) on the event | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
#ifndef PagePopupBlackBerry_h
#define PagePopupBlackBerry_h

#include "IntRect.h"
#include "PagePopup.h"
#include <wtf/RefCounted.h>
#include <wtf/RefPtr.h>

namespace BlackBerry {
namespace WebKit {
class WebPage;
class WebPagePrivate;
}
}

namespace WebCore {
class Frame;
class Page;
class PagePopupClient;
class PlatformMouseEvent;

class PagePopupBlackBerry : public PagePopup {
public:
    PagePopupBlackBerry(BlackBerry::WebKit::WebPagePrivate*, PagePopupClient*, const IntRect&);
    ~PagePopupBlackBerry();

    bool sendCreatePopupWebViewRequest();
    bool init(BlackBerry::WebKit::WebPage*);
    void closePopup();
    void setRect();

    class SharedClientPointer : public RefCounted<SharedClientPointer> {
    public:
        explicit SharedClientPointer(PagePopupClient* client) : m_client(client) { }
        void clear() { m_client = 0; }
        PagePopupClient* get() const { return m_client; }
    private:
        PagePopupClient* m_client;
    };

private:
    void generateHTML(BlackBerry::WebKit::WebPage*);
    void installDOMFunction(Frame*);

    BlackBerry::WebKit::WebPagePrivate* m_webPagePrivate;
    OwnPtr<PagePopupClient> m_client;
    RefPtr<SharedClientPointer> m_sharedClientPointer;
    IntRect m_rect;
};

}

#endif // PagePopupBlackBerry_h


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Kaisean.Tools.CollapseXml
{
	/// <summary>
	/// Determines what to do if a filter is expected but has not been defined
	/// </summary>
	public enum MissingFilterBehavior
	{
		/// <summary>
		/// CollapseXML will throw a FilterNotFoundException if a filter is not defined
		/// </summary>
		ThrowException,

		/// <summary>
		/// Item will be included if a filter is not defined
		/// </summary>
		IncludeItem,

		/// <summary>
		/// Item will be omitted if a filter is not defined
		/// </summary>
		OmitItem
	}
}


text:
<?xml version='1.0' encoding='utf-8'?>
<TEI xmlns="http://www.tei-c.org/ns/1.0" xml:id="PrL-1051">
   <teiHeader>
      <fileDesc>
         <titleStmt>
            <title>Private Letter: 1898 June 4: to Mrs de Lisle</title>
            <author>
               <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/9614/">William Colenso</name>
            </author>
         </titleStmt>
         <publicationStmt>

         </publicationStmt>
         <sourceDesc>

MTG HB m64/14, m67/37, 57844.

         </sourceDesc>
      </fileDesc>
      <profileDesc>
         <correspDesc>

               <correspAction type="received">
                  <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/75566/">Mrs de Lisle</name>
               </correspAction>
            </correspDesc>
         <creation xmlns:tei="http://www.tei-c.org/ns/1.0">
            <date when="1898-06-04">1898 June 4</date>
         </creation>
      </profileDesc>
   </teiHeader>
   <text>
      <front>

1898 June 4: to Mrs de Lisle<note xml:id="ftn3-903" place="foot" n="903"> MTG HB m64/14, m67/37, 57844.</note>

      </front>

Napier'<lb/>June 4<hi rend="sup ">th</hi>., 1898.

Dear Mrs. de Lisle

I have to thank you for your kind note—so full of good news <hi rend="italic">re </hi>your son:—I received it while inland, where I stayed much longer than I had intended, owing to kind-hearted folks & fine weather: I returned last week & have been <hi rend="italic">once </hi>in town since, but, having several little matters of business to attend, could not well call, [only look up in passing] but <hi rend="italic">fully intend </hi>to do so when I next go down, say some day of next week—if <hi rend="italic">fine</hi>. I trust <hi rend="italic">you </hi>(<hi rend="underline italic">all</hi>) are quite well & happy.–

I am Yours, faithy.,

W. Colenso.

   </text>
</TEI>


text:
  protected function addSortCriteria($criteria)
  {
    if (array(null, null) == ($sort = $this->getSort()))
    {
      return;
    }

    $column = <?php echo constant($this->getModelClass() . '::PEER') ?>::translateFieldName($sort[0], BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
    if ('asc' == $sort[1])
    {
      $criteria->addAscendingOrderByColumn($column);
    }
    else
    {
      $criteria->addDescendingOrderByColumn($column);
    }
  }

  protected function getSort()
  {
    if (null !== $sort = $this->getUser()->getAttribute('<?php echo $this->getModuleName() ?>.sort', null, 'admin_module'))
    {
      return $sort;
    }

    $this->setSort($this->configuration->getDefaultSort());

    return $this->getUser()->getAttribute('<?php echo $this->getModuleName() ?>.sort', null, 'admin_module');
  }

  protected function setSort(array $sort)
  {
    if (null !== $sort[0] && null === $sort[1])
    {
      $sort[1] = 'asc';
    }

    $this->getUser()->setAttribute('<?php echo $this->getModuleName() ?>.sort', $sort, 'admin_module');
  }

  protected function isValidSortColumn($column)
  {
    return in_array($column, BasePeer::getFieldnames('<?php echo $this->getModelClass() ?>', BasePeer::TYPE_FIELDNAME));
  }


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using NUnit.Framework;

using TSQL;
using TSQL.Clauses;
using TSQL.Clauses.Parsers;
using TSQL.Statements;
using TSQL.Tokens;

namespace Tests.Clauses
{
	[TestFixture(Category = "Clause Parsing")]
	public class OrderByClauseTests
	{
		[Test]
		public void OrderByClause_SanityCheck()
		{
			using (StringReader reader = new StringReader(
				@"bogus"))
			using (ITSQLTokenizer tokenizer = new TSQLTokenizer(reader))
			{
				Assert.IsTrue(tokenizer.MoveNext());
				Exception ex = Assert.Throws<InvalidOperationException>(
					delegate
					{
						TSQLOrderByClause orderBy = new TSQLOrderByClauseParser().Parse(tokenizer);
					});
			}
		}

		[Test]
		public void OrderByClause_OffsetFetch()
		{
			// regression test for https://github.com/bruce-dunwiddie/tsql-parser/issues/75

			List<TSQLStatement> statements = TSQLStatementReader.ParseStatements(
				@"
				SELECT *
				FROM Product.Product P
				ORDER BY P.ProductId
				OFFSET (@page -1) * @RowPerPage ROWS
				FETCH NEXT @RowPerPage ROWS ONLY",
				includeWhitespace: false);

			TSQLSelectStatement select = statements[0].AsSelect;

			Assert.AreEqual(1, statements.Count);
			Assert.AreEqual(26, select.Tokens.Count);
		}
	}
}


text:
package com.stehno.codeperks.lang;

import java.util.Date;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

/**
 *  An object for storing two Date objects representing a range of dates from start to
 *  finish.
 *
 *  This class assumes immutable Date treatment since they only mutators for Date objects
 *  are deprecated.
 *
 *  @author Christopher J. Stehno (chris@stehno.com)
 */
public final class DateRange {

	private Date start, end;

	/**
	 *  Creates an empty date range object. Both dates are null.
	 */
	public DateRange(){
		super();
	}

	/**
	 *  Creates a date range with the specified starting and ending dates.
	 *
	 *  @param start the starting date
	 *  @param end the ending date
	 */
	public DateRange(final Date start, final Date end){
		this();
		this.start = start;
		this.end = end;
	}

	/**
	 * Copy constructor. Simply creates a new DateRange with the same starting
	 * and ending Date objects.
	 *
	 * @param range the DateRange to be copied
	 */
	public DateRange(final DateRange range){
		this(range.getStart(),range.getEnd());
	}

	/**
	 * 	Used to determine if the given date within the date range. The endpoints of the range are also inclusive.
	 *
	 */
	public boolean isWithin(final Date date){
		return((start == null || date.equals(start) || date.after(start)) && (end == null || date.equals(end) || date.before(end)));
	}

	/**
	 *  This method is used to retrieve the starting date of the range.
	 *
	 *  @return the starting date of the range
	 */
	public Date getStart(){return(start);}

	/**
	 *  This method is used to specify the starting date for the date range.
	 *
	 *  @param start the starting date for the range
	 *  @throws IllegalArgumentException if the start date is null
	 */
	public void setStart(final Date start){
		this.start = start;
	}

	/**
	 *  This method is used to specify the ending date for the date range.
	 *
	 *  @param end the ending date for the range
	 *  @throws IllegalArgumentException if the end date is null
	 */
	public void setEnd(final Date end){
		this.end = end;
	}

	/**
	 *  This method is used to retrieve the ending date of the range.
	 *
	 *  @return the ending date of the range
	 */
	public Date getEnd(){return(end);}

	/**
	 *  This method is used to retrieve a two-element Date array containing the starting and ending dates
	 *  respectively.
	 *
	 *  @return an array of Dates containing both the starting and ending dates
	 */
	public Date[] getRange(){return(new Date[]{start,end});}

	/**
	 * Used to retrieve the number of milliseconds represented by the date range. This number will
	 * always be positive.
	 *
	 * @return the number of milliseconds represented by the date range.
	 */
	public long duration(){
		return(Math.abs(end.getTime() - start.getTime()));
	}

	@Override
	public int hashCode(){
		return(new HashCodeBuilder(7,13).append(start).append(end).toHashCode());
	}

	/**
	 *  This method is used to determine whether two date ranges are equivalent.
	 *
	 *  @param obj the object to be compared with this date range
	 *  @return a value of true if the two date ranges are equal
	 */
	@Override
	public boolean equals(final Object obj){
		return(
				obj instanceof DateRange &&
				new EqualsBuilder().append(((DateRange)obj).start,start).append(((DateRange)obj).end,end).isEquals()
		);
	}

	/**
	 *  This method is used to retrieve the date range as a string. No date formatting is performed.
	 *
	 *  @return the date range represented as a string
	 */
	@Override
	public String toString(){
		final StringBuilder str = new StringBuilder("[DateRange: ");
		str.append("start='").append(getStart().toString()).append("' end='").append(getEnd().toString()).append("']");
		return(str.toString());
	}
}


text:
using System.ComponentModel.Composition.Hosting;
using System.IO;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarLint.VisualStudio.Integration.UnitTests;

namespace SonarLint.VisualStudio.AdditionalFiles.UnitTests
{
    [TestClass]
    public class TypeScriptPathsProviderTests
    {
        [TestMethod]
        [DataRow("SonarLint.TypeScript.EsLintBridgeServerPath", @"\ts\bin\server")]
        [DataRow("SonarLint.TypeScript.RuleDefinitionsFilePath", @"\ts\sonarlint-metadata.json")]
        public void ExportPathByContractName_ReturnsExpectedValue(string contractName, string expectedEnding)
        {
            using var scope = new AssertIgnoreScope();

            var exportedValue = GetExportedString(contractName);

            exportedValue.Should().EndWith(expectedEnding);
            Path.IsPathRooted(exportedValue).Should().BeTrue();
        }

        private static string GetExportedString(string contractName)
        {
            var catalog = new TypeCatalog(typeof(TypeScriptPathsProvider));
            using var container = new CompositionContainer(catalog);
            return container.GetExportedValue<string>(contractName);
        }
    }
}


text:
Event Hubs is built to support unit testing with mocks, as described in the [Azure SDK Design Guidelines](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-mocking). This is an important feature of the library that allows developers to write tests that are completely focused on their own application logic, though they depend on the Event Hubs types.

The following examples focus on scenarios likely to occur in applications, and demonstrate how to mock the Event Hubs types typically used in each scenario. The code snippets utilize the mock object framework, Moq, in order to provide practical examples. However, many mocking frameworks exist and can be used with the same approach in mind.

## Table of contents

- **Publishing events**
  - [Using the EventHubProducerClient](#publishing-events-with-the-eventhubproducerclient)
  - [Using the EventHubBufferedProducerClient](#publishing-events-using-an-eventhubbufferedproducerclient)
- **Consuming events**
  - [Using the EventHubConsumerClient](#consuming-events-using-an-eventhubconsumerclient)
  - [Using the PartitionReceiver](#consuming-events-using-the-partitionreceiver)
- **Querying metadata**
  - [Using any client type](#querying-metadata-properties-using-the-eventhubproducerclient-eventhubbufferedproducerclient-or-eventhubconsumerclient)

## Publishing events with the `EventHubProducerClient`

When using batches to publish to Event Hubs, the key interactions with the `EventHubProducerClient` are calling `CreateBatchAsync` to create the batch and `SendAsync` to publish it.
 Mocked batches accept a `List<EventData>` that is used as a backing store and can be inspected to verify that the application is adding events to the batch as expected.  The custom `TryAdd` callback can be used to control the decision for whether an event is accepted into the batch or is rejected.

This snippet demonstrates mocking the `EventHubProducerClient`, and creating `EventDataBatch` instances using the `EventHubsModelFactory`.

```C# Snippet:EventHubs_Sample11_MockingEventDataBatch
Mock<EventHubProducerClient> mockProducer = new();

EventHubProducerClient producer = mockProducer.Object;

// This argument sets the value returned by the EventDataBatch when accessing the Size property, it does
// not impact TryAdd on the mocked batch.

long batchSizeInBytes = 500;

// As events are added to the batch they will be added to this list as well. Altering the events in this
// list will not change the events in the batch though, since they are stored inside the batch as well.

List<EventData> backingList = new();

// For illustrative purposes, this is the number of events that the batch will contain, returning false
// from TryAdd for any additional calls.

int batchCountThreshold = 3;

EventDataBatch dataBatchMock = EventHubsModelFactory.EventDataBatch(
        batchSizeBytes : batchSizeInBytes,
        batchEventStore : backingList,
        batchOptions : new CreateBatchOptions(),
        // The model factory allows a custom TryAdd callback, allowing control of what
        // events the batch accepts.
        eventData =>
        {
            int eventCount = backingList.Count;
            return eventCount < batchCountThreshold;
        });

// This sets up a mock of the CreateBatchAsync method, returning the batch that was previously mocked.

mockProducer
    .Setup(p => p.CreateBatchAsync(It.IsAny<CancellationToken>()))
    .ReturnsAsync(dataBatchMock);

// The next part of this snippet illustrates how to create and fill a mocked batch. This would be where
// application methods in which batches are created and filled can be called and tested.

EventDataBatch batch = await producer.CreateBatchAsync();

// This is creating a list of events to use in our test.

List<EventData> sourceEvents = new();

for (int index = 0; index < batchCountThreshold; index++)
{
    var eventData = new EventData($"Sample-Event-{index}");
    sourceEvents.Add(eventData);
}

// Here we are adding events to the batch. They should all be accepted.

foreach (var eventData in sourceEvents)
{
    Assert.True(batch.TryAdd(eventData));
}

// Since there area already batchCountThreshold number of events in the batch, this event will be rejected
// from the batch.

EventData eventData4 = new EventData("Sample-Event-4-will-fail");
Assert.IsFalse(batch.TryAdd(eventData4));

// Here we are mocking the SendAsync method so it will throw an exception if the batch passed into it is
// not the one we are expecting to send.

mockProducer
    .Setup(p => p.SendAsync(
        It.Is<EventDataBatch>(sendBatch => sendBatch != dataBatchMock),
        It.IsAny<CancellationToken>()))
    .Throws(new Exception("The batch published was not the expected batch."));

// For illustrative purposes we are calling SendAsync. This would again be where application methods could be called
// and tested.

await producer.SendAsync(batch);

// This is demonstrating how to verify SendAsync was called once within the mocked producer client.

mockProducer
    .Verify(bp => bp.SendAsync(
        It.IsAny<EventDataBatch>(),
        It.IsAny<CancellationToken>()),
    Times.Once);

// For illustrative purposes, check that the events in the batch match what the application expects to have
// added.

foreach (EventData eventData in backingList)
{
    Assert.IsTrue(sourceEvents.Contains(eventData));
}
Assert.AreEqual(backingList.Count, sourceEvents.Count);
```

## Publishing events using an `EventHubBufferedProducerClient`

The following snippet demonstrates how to mock the `EventHubBufferedProducerClient`. When using the buffered producer to publish events the  key interactions are calls to `EnqueueEventAsync` and/or `EnqueueEventsAsync`. Since the buffered producer implictly batches events passed in, mocking these calls is relatively straightforward.

This snippet also demonstrates testing a send event failed handler. It is guaranteed by the library that the event handlers will be called at the appropriate times while the processor is running; it is recommended that handers be tested by calling them directly, rather than attempting to simulate having the buffered producer invoke them.

```C# Snippet:EventHubs_Sample11_MockingBufferedProducer
Mock<EventHubBufferedProducerClient> bufferedProducerMock = new();

// For this scenario, set up EnqueueEventAsync to always pass and return 1.

bufferedProducerMock
    .Setup(bp => bp.EnqueueEventAsync(
        It.IsAny<EventData>(),
        It.IsAny<CancellationToken>()))
    .ReturnsAsync(1);

EventHubBufferedProducerClient bufferedProducer = bufferedProducerMock.Object;

// The following demonstrates how to use the mocked EnqueueEventAsync. This would be where application-defined
// methods can be called and tested.

// This is an illustrative fail handler that can be added to the mock buffered producer.

Func<SendEventBatchFailedEventArgs, Task> sendFailed = new(async args =>
{
    foreach (EventData eventData in args.EventBatch)
    {
        // Do more complex error handling here...

        Debug.WriteLine($"Publishing failed for the event: {eventData.MessageId}.  Error: '{args.Exception.Message}'");
        await Task.CompletedTask;
    }
});

bufferedProducer.SendEventBatchFailedAsync += sendFailed;

// For illustrative purposes, enqueue a set of events to be published.

int numOfEventsToEnqueue = 15;
using CancellationTokenSource cancellationTokenSource = new();

for (int index = 0; index < numOfEventsToEnqueue; index++)
{
    EventData eventToEnqueue = new($"Event-{index}")
    {
        MessageId = index.ToString()
    };
    await bufferedProducer.EnqueueEventAsync(eventToEnqueue, cancellationTokenSource.Token);
}

// This shows how to verify that EnqueueEventAsync was called the correct number of times,
// with the expected arguments.

for (int index = 0; index < numOfEventsToEnqueue; index++)
{
    bufferedProducerMock
        .Verify(bp => bp.EnqueueEventAsync(
            It.Is<EventData>(e => (e.MessageId == index.ToString())), // Check that enqueue was called on each expected event
            It.IsAny<CancellationToken>()));
}

// The following lines demonstrate how to test a fail handler by calling it directly. Testing fail and success handlers
// does not require mocking.

int numEventsInBatch = 12;
List<EventData> eventsInBatch = new();

for (int index = 0; index < numEventsInBatch; index++)
{
    EventData eventToEnqueue = new($"Event-{index}")
    {
        MessageId = index.ToString()
    };
    await bufferedProducer.EnqueueEventAsync(eventToEnqueue, cancellationTokenSource.Token);
}

SendEventBatchFailedEventArgs args = new SendEventBatchFailedEventArgs(eventsInBatch, new Exception(), "0", default);

// The expected outcome of any application-specific complex processing can be verified here.

Assert.DoesNotThrowAsync(async () => await sendFailed(args));
```

## Consuming events using an `EventHubConsumerClient`

When testing code that is dependent on the `EventHubConsumerClient`, a developer may want to create a known set of expected events to verify that their application consumes them correctly.  Tests can mock `EventData` instances coming from the broker using the `EventHubModelFactory`. These can be used within the consumer client mock to mock returns from `ReadEventsFromPartitionAsync`, which for most applications is the key interaction to test.

This snippet also demonstrates how to mock `LastEnqueuedEventProperties` using the `EventHubsModelFactory`.

```C# Snippet:EventHubs_Sample11_MockingConsumerClient
Mock<EventHubConsumerClient> mockConsumer = new();

// This creates a mock LastEnqueuedEventProperties using the model factory.

LastEnqueuedEventProperties lastEnqueueEventProperties = EventHubsModelFactory.LastEnqueuedEventProperties(
    lastSequenceNumber : 1234,
    lastOffset : 234,
    lastEnqueuedTime : DateTimeOffset.Parse("1:24 AM"),
    lastReceivedTime : DateTimeOffset.Parse("1:26 AM"));

// This creates a mock of PartitionContext using the model factory.

PartitionContext partitionContext = EventHubsModelFactory.PartitionContext(
    fullyQualifiedNamespace: "sample-hub.servicebus.windows.net",
    eventHubName: "sample-event-hub",
    consumerGroup: "$Default",
    partitionId : "0",
    lastEnqueuedEventProperties : lastEnqueueEventProperties);

// This is a simple local method that returns an IAsyncEnumerable to use as the return for
// ReadEventsAsync below, since IAsyncEnumerables cannot be created directly.

async IAsyncEnumerable<PartitionEvent> mockReturn()
{
    // This mocks an EventData instance using the model factory. Different arguments can mock different
    // potential outputs from the broker.

    EventData eventData1 = EventHubsModelFactory.EventData(
        eventBody: new BinaryData($"Sample-Event-1"),
        systemProperties: new Dictionary<string, object>(), //arbitrary value
        partitionKey: "sample-key",
        sequenceNumber: 1000,
        offset: 1500,
        enqueuedTime: DateTimeOffset.Parse("11:36 PM"));

    EventData eventData2 = EventHubsModelFactory.EventData(
        eventBody: new BinaryData($"Sample-Event-2"),
        systemProperties: new Dictionary<string, object>(), //arbitrary value
        partitionKey: "sample-key",
        sequenceNumber: 1000,
        offset: 1500,
        enqueuedTime: DateTimeOffset.Parse("11:36 PM"));

    // This creates a mock PartitionEvent to return from the consumer client.

    PartitionEvent samplePartitionEvent1 = new(partitionContext, eventData1);
    PartitionEvent samplePartitionEvent2 = new(partitionContext, eventData2);

    // IAsyncEnumerable types can only be returned by async functions, use this no-op await statement to
    // force the method to be async.

    await Task.Yield();

    // Yield statements allow methods to emit multiple outputs. In async methods this can be over time.

    yield return samplePartitionEvent1;
    yield return samplePartitionEvent2;
}

// Use the method to mock a return from the consumer. We are setting up the method to return partition events that
// include the last enqueued event properties if the tracking flag is set in the options.

mockConsumer
    .Setup(c => c.ReadEventsFromPartitionAsync(
        It.IsAny<string>(),
        It.IsAny<EventPosition>(),
        It.Is<ReadEventOptions>(opts => opts.TrackLastEnqueuedEventProperties),
        It.IsAny<CancellationToken>()))
    .Returns(mockReturn());

// This sets up the consumer client to return a mocked set of partition Ids. Since GetPartitionIdsAsync is often
// used in conjunction with ReadEventsFromPartitionAsync, it may be useful for applications to mock both.

string[] consumerPartitions = new string[] { "0", "1" };

mockConsumer
    .Setup(p => p.GetPartitionIdsAsync(It.IsAny<CancellationToken>()))
    .ReturnsAsync(consumerPartitions);

// The following demonstrates how to use the mocked methods. This would be where application methods
// can be called and tested.

EventHubConsumerClient consumer = mockConsumer.Object;

using CancellationTokenSource cancellationTokenSource = new();

// Here we are setting the TrackLastEnqueuedEventProperties flag so that the EventHubConsumerClient receives
// LastEnqueuedEventProperties when reading events.

ReadEventOptions options = new()
{
    TrackLastEnqueuedEventProperties = true
};

string firstPartition = (await consumer.GetPartitionIdsAsync(cancellationTokenSource.Token)).First();
EventPosition startingPosition = EventPosition.Earliest;

await foreach (PartitionEvent receivedEvent in consumer.ReadEventsFromPartitionAsync(firstPartition, startingPosition, options, cancellationTokenSource.Token))
{
    // This is where application logic has control of the partition events.
}

// This is where applications can verify that the partition events output by the consumer client were handled as expected.
```

## Consuming events using the `PartitionReceiver`

The sample below illustrates how to mock a `PartitionReceiver`, and set up its `ReceiveBatchAsync` method to return a simple data batch.

Given the purpose of the `PartitionReceiver`, it is anticipated that most applications will have complex code surrounding their receivers, so this snippet is intentionally simple, with the focus being on using the `EventHubsModelFactory` to mock events being returned from the broker.

```C# Snippet:EventHubs_Sample11_PartitionReceiverMock
Mock<PartitionReceiver> mockReceiver = new();

// ReceivedEvents is a list of events to use when mocking ReceiveBatchAsync within the PartitionReceiver.

List<EventData> receivedEvents = new();

for (int index = 0; index < 10; index++)
{
    // Mocking an EventData instance, different arguments can simulate different potential
    // outputs from the broker
    EventData eventData = EventHubsModelFactory.EventData(
        eventBody: new BinaryData($"Sample-Event-{index}"),
        systemProperties: new Dictionary<string, object>(), //arbitrary value
        partitionKey: $"sample-key-{index}",
        sequenceNumber: 1234,
        offset: 234,
        enqueuedTime: DateTimeOffset.Parse("9:25 AM"));

    receivedEvents.Add(eventData);
}

// This sets up the mock to receive the list of events defined above when ReceiveBatchAsync is called
// on a given partition.

mockReceiver
    .Setup(r => r.ReceiveBatchAsync(
        It.IsAny<int>(),
        It.IsAny<TimeSpan>(),
        It.IsAny<CancellationToken>()))
    .ReturnsAsync(receivedEvents);

// The following demonstrates how to use the mocked methods. This would be where application code utilizing
// the mocked methods could be called and verified.

PartitionReceiver receiver = mockReceiver.Object;

using CancellationTokenSource cancellationTokenSource = new();

IEnumerable<EventData> receivedBatch = await receiver.ReceiveBatchAsync(
    maximumEventCount: 10,
    TimeSpan.FromSeconds(1),
    cancellationTokenSource.Token);
```

## Querying metadata properties using the `EventHubProducerClient`, `EventHubBufferedProducerClient`, or `EventHubConsumerClient`

Many applications make decisions for publishing based on the properties of the Event Hub itself or the properties of its partitions. Both can be mocked using the `EventHubsModelFactory`. The following snippet demonstrates how to mock Event Hub properties for both the `EventHubBufferedProducerClient` and the `EventHubProducerClient`, and how to set up the mocked producer clients to return a cohesive set of values for each of the accompanying getter methods.

These mocked properties can be used to test expected application behavior given a specific set of Event Hub properties. These property types can be mocked in the same way for `EventHubProducerClient`, `EventHubBufferedProducerClient`, and `EventHubConsumerClient`.

```C# Snippet:EventHubs_Sample11_MockingProducerProperties
// The first part of this snippet demonstrates mocking EventHubProperties on an EventHubProducerClient. Properties on
// EventHubBufferedProducerClients and EventHubConsumerClients can be mocked in the same way.

Mock<EventHubProducerClient> mockProducer = new();

// Here we are defining the set of partition identifiers we want for our testing scenario.

List<string> producerPartitions = new() { "0", "1" };

// Using the model factory, this call creates a mock of the EventHubProperties.

EventHubProperties eventHubProperties =
    EventHubsModelFactory.EventHubProperties(
        name: "fakeEventHubName",
        createdOn: DateTimeOffset.UtcNow, // arbitrary value
        partitionIds: producerPartitions.ToArray());

// This sets up GetEventHubPropertiesAsync to return the mocked Event Hub properties above.

mockProducer
    .Setup(p => p.GetEventHubPropertiesAsync(It.IsAny<CancellationToken>()))
    .ReturnsAsync(eventHubProperties);

// This sets up GetPartitionIdsAsync to return the mocked partition Ids above.

mockProducer
    .Setup(p => p.GetPartitionIdsAsync(It.IsAny<CancellationToken>()))
    .ReturnsAsync(producerPartitions.ToArray());

EventHubProducerClient producer = mockProducer.Object;

// Here we are demonstrating how to access the mocked EventHubProperties for illustrative purposes.

EventHubProperties properties = await producer.GetEventHubPropertiesAsync();
string eventHubName = properties.Name;
Debug.WriteLine($"Sending Events to: {eventHubName}");

// The second part of this snippet demonstrates mocking PartitionProperties on an EventHubBufferedProducerClient, which
// again can be done in the same way for the EventHubProducerClient and EventHubConsumerClient types.

Mock<EventHubBufferedProducerClient> bufferedProducerMock = new();

// This creates the set of partitions to mock for this test, and mocks the PartitionProperty instances using the model
// factory.

Dictionary<string, PartitionProperties> partitionProperties = new()
{
    // Non-empty partition
    { "0", EventHubsModelFactory.PartitionProperties(
        eventHubName : "eventhub-name",
        partitionId : "0",
        isEmpty : true,
        beginningSequenceNumber: 1000,
        lastSequenceNumber : 1100,
        lastOffset : 500,
        lastEnqueuedTime : DateTime.UtcNow) },

    // Empty partition
    { "1", EventHubsModelFactory.PartitionProperties(
        eventHubName : "eventhub-name",
        partitionId : "1",
        isEmpty : false,
        beginningSequenceNumber : 2000,
        lastSequenceNumber : 2000,
        lastOffset : 760,
        lastEnqueuedTime : DateTime.UtcNow) }
};

// This sets up GetPartitionIdsAsync to return the set of partition Ids mocked above.

bufferedProducerMock
    .Setup(p => p.GetPartitionIdsAsync(It.IsAny<CancellationToken>()))
    .ReturnsAsync(partitionProperties.Keys.ToArray());

// This sets up GetPartitionPropertiesAsync to return the mocked PartitionProperties for each partition Id input.

foreach (KeyValuePair<string, PartitionProperties> partition in partitionProperties)
{
    bufferedProducerMock
        .Setup(p => p.GetPartitionPropertiesAsync(
            partition.Key,
            It.IsAny<CancellationToken>()))
        .ReturnsAsync(partition.Value);
}

// The next lines demonstrate how to use the mocked partition Ids and PartitionProperties. This would be
// where application code utilizing the mocked methods could be called and verified.

EventHubBufferedProducerClient bufferedProducer = bufferedProducerMock.Object;

using CancellationTokenSource cancellationTokenSource = new();

// This gets all the partition Ids and arbitrarily takes the first partition Id.

string[] partitionIds = await bufferedProducer.GetPartitionIdsAsync(cancellationTokenSource.Token);
string partitionId = partitionIds[0];

// This gets the partition properties for the first partition Id.

PartitionProperties firstPartitionProperties =
    await bufferedProducer.GetPartitionPropertiesAsync(partitionId, cancellationTokenSource.Token);

string isPartitionEmpty = firstPartitionProperties.IsEmpty.ToString();

// The last part of this snippet briefly demonstrates mocking Partition Ids with an EventHubConsumerClient. This
// illustrates how each client can mock properties in the same way.

// This sets up the consumer client to return a mocked set of partition Ids.

Mock<EventHubConsumerClient> mockConsumer = new();

string[] consumerPartitions = new string[] { "0", "1", "2" };

mockConsumer
    .Setup(p => p.GetPartitionIdsAsync(It.IsAny<CancellationToken>()))
    .ReturnsAsync(consumerPartitions);
```


text:
/*	$NetBSD: exec.h,v 1.134.2.1 2012/04/12 17:05:38 riz Exp $	*/

/*-
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)exec.h	8.4 (Berkeley) 2/19/95
 */

/*-
 * Copyright (c) 1993 Theo de Raadt.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*-
 * Copyright (c) 1994 Christopher G. Demetriou
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)exec.h	8.4 (Berkeley) 2/19/95
 */

#ifndef _SYS_EXEC_H_
#define _SYS_EXEC_H_

struct pathbuf; /* from namei.h */

/*
 * The following structure is found at the top of the user stack of each
 * user process. The ps program uses it to locate argv and environment
 * strings. Programs that wish ps to display other information may modify
 * it; normally ps_argvstr points to argv[0], and ps_nargvstr is the same
 * as the program's argc. The fields ps_envstr and ps_nenvstr are the
 * equivalent for the environment.
 */
struct ps_strings {
	char	**ps_argvstr;	/* first of 0 or more argument strings */
	int	ps_nargvstr;	/* the number of argument strings */
	char	**ps_envstr;	/* first of 0 or more environment strings */
	int	ps_nenvstr;	/* the number of environment strings */
};

#ifdef _KERNEL
struct ps_strings32 {
	uint32_t	ps_argvstr;	/* first of 0 or more argument strings */
	int32_t		ps_nargvstr;	/* the number of argument strings */
	uint32_t	ps_envstr;	/* first of 0 or more environment strings */
	int32_t		ps_nenvstr;	/* the number of environment strings */
};
#endif

/*
 * the following structures allow execve() to put together processes
 * in a more extensible and cleaner way.
 *
 * the exec_package struct defines an executable being execve()'d.
 * it contains the header, the vmspace-building commands, the vnode
 * information, and the arguments associated with the newly-execve'd
 * process.
 *
 * the exec_vmcmd struct defines a command description to be used
 * in creating the new process's vmspace.
 */

#include <special_includes/sys/uio.h>

struct lwp;
struct proc;
struct exec_package;
struct vnode;

typedef int (*exec_makecmds_fcn)(struct lwp *, struct exec_package *);

struct execsw {
	u_int	es_hdrsz;		/* size of header for this format */
	exec_makecmds_fcn es_makecmds;	/* function to setup vmcmds */
	union {				/* probe function */
		int (*elf_probe_func)(struct lwp *,
			struct exec_package *, void *, char *, vaddr_t *);
		int (*ecoff_probe_func)(struct lwp *, struct exec_package *);
		int (*mach_probe_func)(const char **);
	} u;
	struct  emul *es_emul;		/* os emulation */
	int	es_prio;		/* entry priority */
	int	es_arglen;		/* Extra argument size in words */
					/* Copy arguments on the new stack */
	int	(*es_copyargs)(struct lwp *, struct exec_package *,
			struct ps_strings *, char **, void *);
					/* Set registers before execution */
	void	(*es_setregs)(struct lwp *, struct exec_package *, vaddr_t);
					/* Dump core */
	int	(*es_coredump)(struct lwp *, void *);
	int	(*es_setup_stack)(struct lwp *, struct exec_package *);
};

#define EXECSW_PRIO_ANY		0x000	/* default, no preference */
#define EXECSW_PRIO_FIRST	0x001	/* this should be among first */
#define EXECSW_PRIO_LAST	0x002	/* this should be among last */

/* exec vmspace-creation command set; see below */
struct exec_vmcmd_set {
	u_int	evs_cnt;
	u_int	evs_used;
	struct	exec_vmcmd *evs_cmds;
};

#define	EXEC_DEFAULT_VMCMD_SETSIZE	9	/* # of cmds in set to start */

struct exec_package {
	const char *ep_name;		/* file's name */
	const char *ep_kname;		/* kernel-side copy of file's name */
	char *ep_resolvedname;		/* fully resolved path from namei */
	void	*ep_hdr;		/* file's exec header */
	u_int	ep_hdrlen;		/* length of ep_hdr */
	u_int	ep_hdrvalid;		/* bytes of ep_hdr that are valid */
	struct	exec_vmcmd_set ep_vmcmds;  /* vmcmds used to build vmspace */
	struct	vnode *ep_vp;		/* executable's vnode */
	struct	vattr *ep_vap;		/* executable's attributes */
	vaddr_t	ep_taddr;		/* process's text address */
	vsize_t	ep_tsize;		/* size of process's text */
	vaddr_t	ep_daddr;		/* process's data(+bss) address */
	vsize_t	ep_dsize;		/* size of process's data(+bss) */
	vaddr_t	ep_maxsaddr;		/* proc's max stack addr ("top") */
	vaddr_t	ep_minsaddr;		/* proc's min stack addr ("bottom") */
	vsize_t	ep_ssize;		/* size of process's stack */
	vaddr_t	ep_entry;		/* process's entry point */
	vaddr_t	ep_vm_minaddr;		/* bottom of process address space */
	vaddr_t	ep_vm_maxaddr;		/* top of process address space */
	u_int	ep_flags;		/* flags; see below. */
	size_t	ep_fa_len;		/* byte size of ep_fa */
	struct exec_fakearg {
		char *fa_arg;
		size_t fa_len;
	} *ep_fa;			/* a fake args vector for scripts */
	int	ep_fd;			/* a file descriptor we're holding */
	void	*ep_emul_arg;		/* emulation argument */
	const struct	execsw *ep_esch;/* execsw entry */
	struct vnode *ep_emul_root;     /* base of emulation filesystem */
	struct vnode *ep_interp;        /* vnode of (elf) interpeter */
	uint32_t ep_pax_flags;		/* pax flags */
	char	*ep_path;		/* absolute path of executable */
	void	(*ep_emul_arg_free)(void *);
					/* free ep_emul_arg */
};
#define	EXEC_INDIR	0x0001		/* script handling already done */
#define	EXEC_HASFD	0x0002		/* holding a shell script */
#define	EXEC_HASARGL	0x0004		/* has fake args vector */
#define	EXEC_SKIPARG	0x0008		/* don't copy user-supplied argv[0] */
#define	EXEC_DESTR	0x0010		/* destructive ops performed */
#define	EXEC_32		0x0020		/* 32-bit binary emulation */
#define	EXEC_FORCEAUX	0x0040		/* always use ELF AUX vector */

struct exec_vmcmd {
	int	(*ev_proc)(struct lwp *, struct exec_vmcmd *);
				/* procedure to run for region of vmspace */
	vsize_t	ev_len;		/* length of the segment to map */
	vaddr_t	ev_addr;	/* address in the vmspace to place it at */
	struct	vnode *ev_vp;	/* vnode pointer for the file w/the data */
	vsize_t	ev_offset;	/* offset in the file for the data */
	u_int	ev_prot;	/* protections for segment */
	int	ev_flags;
#define	VMCMD_RELATIVE	0x0001	/* ev_addr is relative to base entry */
#define	VMCMD_BASE	0x0002	/* marks a base entry */
#define	VMCMD_FIXED	0x0004	/* entry must be mapped at ev_addr */
#define	VMCMD_STACK	0x0008	/* entry is for a stack */
};

#ifdef _KERNEL
/*
 * funtions used either by execve() or the various CPU-dependent execve()
 * hooks.
 */
void	kill_vmcmd		(struct exec_vmcmd **);
int	exec_makecmds		(struct lwp *, struct exec_package *);
int	exec_runcmds		(struct lwp *, struct exec_package *);
void	vmcmdset_extend		(struct exec_vmcmd_set *);
void	kill_vmcmds		(struct exec_vmcmd_set *);
int	vmcmd_map_pagedvn	(struct lwp *, struct exec_vmcmd *);
int	vmcmd_map_readvn	(struct lwp *, struct exec_vmcmd *);
int	vmcmd_readvn		(struct lwp *, struct exec_vmcmd *);
int	vmcmd_map_zero		(struct lwp *, struct exec_vmcmd *);
int	copyargs		(struct lwp *, struct exec_package *,
				    struct ps_strings *, char **, void *);
int	copyin_psstrings	(struct proc *, struct ps_strings *);
int	copy_procargs		(struct proc *, int, size_t *,
    int (*)(void *, const void *, size_t, size_t), void *);
void	setregs			(struct lwp *, struct exec_package *, vaddr_t);
int	check_veriexec		(struct lwp *, struct vnode *,
				     struct exec_package *, int);
int	check_exec		(struct lwp *, struct exec_package *,
				     struct pathbuf *);
int	exec_init		(int);
int	exec_read_from		(struct lwp *, struct vnode *, u_long off,
				    void *, size_t);
int	exec_setup_stack	(struct lwp *, struct exec_package *);

int	coredump_write		(void *, enum uio_seg, const void *, size_t);

void	exec_free_emul_arg	(struct exec_package *);

/*
 * Machine dependent functions
 */
struct core;
struct core32;
int	cpu_coredump(struct lwp *, void *, struct core *);
int	cpu_coredump32(struct lwp *, void *, struct core32 *);

int	exec_add(struct execsw *, int);
int	exec_remove(struct execsw *, int);

void	new_vmcmd(struct exec_vmcmd_set *,
		    int (*)(struct lwp *, struct exec_vmcmd *),
		    vsize_t, vaddr_t, struct vnode *, u_long, u_int, int);
#define	NEW_VMCMD(evsp,lwp,len,addr,vp,offset,prot) \
	new_vmcmd(evsp,lwp,len,addr,vp,offset,prot,0)
#define	NEW_VMCMD2(evsp,lwp,len,addr,vp,offset,prot,flags) \
	new_vmcmd(evsp,lwp,len,addr,vp,offset,prot,flags)

typedef	int (*execve_fetch_element_t)(char * const *, size_t, char **);
int	execve1(struct lwp *, const char *, char * const *, char * const *,
    execve_fetch_element_t);

struct posix_spawn_file_actions;
struct posix_spawnattr;
int	check_posix_spawn	(struct lwp *);
void	posix_spawn_fa_free(struct posix_spawn_file_actions *, size_t);
int	do_posix_spawn(struct lwp *, pid_t *, bool*, const char *,
    struct posix_spawn_file_actions *, struct posix_spawnattr *,
    char *const *argv, char *const *, execve_fetch_element_t);

extern int	maxexec;

#endif /* _KERNEL */

#endif /* !_SYS_EXEC_H_ */


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

<title>org.opencv.features2d</title>
<meta name="date" content="2014-10-01">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.opencv.features2d

Classes

DescriptorExtractor

DescriptorMatcher

DMatch

FeatureDetector

Features2d

GenericDescriptorMatcher

KeyPoint


text:
package thappstudios.android.miniapps.apps;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.widget.Toast;
import thappstudios.android.miniapps.service.WindowService;
import thappstudios.android.miniapps.util.ErrorLog;
import thappstudios.android.miniapps.util.Keeper;
import thappstudios.android.miniapps.util.Sizes;

public class Flashlight extends App implements Runnable {

	public static final int ITEM_ID = 4;

	public static final String IS_FLASH_ON = "is_flash_on";
	public static final String CRASH_COUNTER = "crash_counter";
	public static final String SUPPORT_FLASH = "support_flash";

	private boolean hasFlash;
	private boolean isFlashOn;
	private Camera camera;
	private Camera.Parameters params;
	private Thread thread;

	@Override
	public void onCreate(Context context, Intent intent) {
		// TODO Auto-generated method stub
		super.onCreate(context, intent);
		thread = new Thread(this);
		hasFlash = context.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA_FLASH);
		if (hasFlash == false) {
			Toast.makeText(context, ErrorLog.FLASHLIGHT_ERROR,
					Toast.LENGTH_LONG).show();
			onDestroy(ErrorLog.FLASHLIGHT_ERROR);
			return;

		}

		if (mSharedPrefs.loadBoolean(IS_FLASH_ON) == false) {
			camera = openCamera();
			if (camera != null) {
				mSharedPrefs.saveBoolean(IS_FLASH_ON, true);
				thread.start();
				Keeper.saveCamera(camera);
				WindowService.getWindowService().updateMenuItem(ITEM_ID - 1,
						"Flashlight_ON");
			} else {
				mSharedPrefs.saveInt(CRASH_COUNTER,
						mSharedPrefs.loadInt(CRASH_COUNTER) + 1);
				if (mSharedPrefs.loadInt(CRASH_COUNTER) >= 5) {
					mSharedPrefs.saveBoolean(SUPPORT_FLASH, false);
				}
				Toast.makeText(context, ErrorLog.FLASHLIGHT_ERROR,
						Toast.LENGTH_LONG).show();
				onDestroy(ErrorLog.FLASHLIGHT_ERROR);

			}
		} else if (mSharedPrefs.loadBoolean(IS_FLASH_ON)) {
			mSharedPrefs.saveBoolean(IS_FLASH_ON, false);
			try {
				thread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (Keeper.getCamera() != null) {
				camera = Keeper.getCamera();
				params = camera.getParameters();
			}
			turnOffFlash();
			if (camera != null)
				camera.release();

			WindowService.getWindowService().updateMenuItem(ITEM_ID-1,
					"Flashlight");
		}

	}

	@Override
	public String[] getUsesLists() {
		// TODO Auto-generated method stub
		return null;

	}

	@Override
	public int getTouchCorrection() {
		// TODO Auto-generated method stub
		return 0;
	}

	public Camera openCamera() {
		Camera.Parameters oldParams = null;
		if (camera == null) {
			try {
				camera = Camera.open();
				params = camera.getParameters();
				oldParams = camera.getParameters();
				params.setFlashMode(Parameters.FLASH_MODE_TORCH);
				camera.setParameters(params);
			} catch (RuntimeException e) {
				e.printStackTrace();
				return null;

			} finally {
				if (oldParams != null)
					camera.setParameters(oldParams);
			}
		}
		return camera;

	}

	public void turnOnFlash() {
		if (!isFlashOn) {
			if (camera == null || params == null) {
				return;
			}

			try {
				params = camera.getParameters();
				params.setFlashMode(Parameters.FLASH_MODE_TORCH);
				camera.setParameters(params);
				camera.startPreview();
				isFlashOn = true;

			} catch (Exception e) {
				e.printStackTrace();

			}

		}

	}

	public void turnOffFlash() {
		if (isFlashOn) {
			if (camera == null || params == null) {
				return;
			}

			params = camera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.setParameters(params);
			camera.stopPreview();
			isFlashOn = false;

		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(mSharedPrefs.loadBoolean(IS_FLASH_ON)) {
			turnOnFlash();
		}
	}

	@Override
	public int getLayoutParamsID() {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	public Sizes getSizes() {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
package com.fireflysource.common.object;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class TestTypeUtils {
    @Test
    void convertHexDigitTest() {
        assertEquals((byte) 0, TypeUtils.convertHexDigit((byte) '0'));
        assertEquals((byte) 9, TypeUtils.convertHexDigit((byte) '9'));
        assertEquals((byte) 10, TypeUtils.convertHexDigit((byte) 'a'));
        assertEquals((byte) 10, TypeUtils.convertHexDigit((byte) 'A'));
        assertEquals((byte) 15, TypeUtils.convertHexDigit((byte) 'f'));
        assertEquals((byte) 15, TypeUtils.convertHexDigit((byte) 'F'));

        assertEquals(0, TypeUtils.convertHexDigit((int) '0'));
        assertEquals(9, TypeUtils.convertHexDigit((int) '9'));
        assertEquals(10, TypeUtils.convertHexDigit((int) 'a'));
        assertEquals(10, TypeUtils.convertHexDigit((int) 'A'));
        assertEquals(15, TypeUtils.convertHexDigit((int) 'f'));
        assertEquals(15, TypeUtils.convertHexDigit((int) 'F'));
    }

    @Test
    void testToHexInt() throws Exception {
        StringBuilder b = new StringBuilder();

        b.setLength(0);
        TypeUtils.toHex(0, b);
        assertEquals("00000000", b.toString());

        b.setLength(0);
        TypeUtils.toHex(Integer.MAX_VALUE, b);
        assertEquals("7FFFFFFF", b.toString());

        b.setLength(0);
        TypeUtils.toHex(Integer.MIN_VALUE, b);
        assertEquals("80000000", b.toString());

        b.setLength(0);
        TypeUtils.toHex(0x12345678, b);
        assertEquals("12345678", b.toString());

        b.setLength(0);
        TypeUtils.toHex(0x9abcdef0, b);
        assertEquals("9ABCDEF0", b.toString());
    }

    @Test
    void testToHexLong() throws Exception {
        StringBuilder b = new StringBuilder();

        b.setLength(0);
        TypeUtils.toHex((long) 0, b);
        assertEquals("0000000000000000", b.toString());

        b.setLength(0);
        TypeUtils.toHex(Long.MAX_VALUE, b);
        assertEquals("7FFFFFFFFFFFFFFF", b.toString());

        b.setLength(0);
        TypeUtils.toHex(Long.MIN_VALUE, b);
        assertEquals("8000000000000000", b.toString());

        b.setLength(0);
        TypeUtils.toHex(0x123456789abcdef0L, b);
        assertEquals("123456789ABCDEF0", b.toString());
    }

    @Test
    void testIsTrue() {
        assertTrue(TypeUtils.isTrue(Boolean.TRUE));
        assertTrue(TypeUtils.isTrue(true));
        assertTrue(TypeUtils.isTrue("true"));
        assertTrue(TypeUtils.isTrue(new Object() {
            @Override
            public String toString() {
                return "true";
            }
        }));

        assertFalse(TypeUtils.isTrue(Boolean.FALSE));
        assertFalse(TypeUtils.isTrue(false));
        assertFalse(TypeUtils.isTrue("false"));
        assertFalse(TypeUtils.isTrue("blargle"));
        assertFalse(TypeUtils.isTrue(new Object() {
            @Override
            public String toString() {
                return "false";
            }
        }));
    }

    @Test
    void testIsFalse() {
        assertTrue(TypeUtils.isFalse(Boolean.FALSE));
        assertTrue(TypeUtils.isFalse(false));
        assertTrue(TypeUtils.isFalse("false"));
        assertTrue(TypeUtils.isFalse(new Object() {
            @Override
            public String toString() {
                return "false";
            }
        }));

        assertFalse(TypeUtils.isFalse(Boolean.TRUE));
        assertFalse(TypeUtils.isFalse(true));
        assertFalse(TypeUtils.isFalse("true"));
        assertFalse(TypeUtils.isFalse("blargle"));
        assertFalse(TypeUtils.isFalse(new Object() {
            @Override
            public String toString() {
                return "true";
            }
        }));
    }
}


text:
package bt.bencoding.types;

import bt.bencoding.BEType;
import bt.bencoding.model.BEObject;
import bt.bencoding.serializers.BEEncoder;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;

/**
 * BEncoded dictionary.
 *
 * @since 1.0
 */
public class BEMap implements BEObject<Map<String, BEObject<?>>> {
    private static final BEEncoder ENCODER = BEEncoder.encoder();
    private final byte[] content;
    private final Map<String, BEObject<?>> value;

    public BEMap(Map<String, BEObject<?>> value) {
        this(null, value);
    }

    /**
     * @param content Binary representation of this dictionary, as read from source.
     * @param value   Parsed value
     * @since 1.0
     */
    public BEMap(byte[] content, Map<String, BEObject<?>> value) {
        this.content = content;
        this.value = Collections.unmodifiableMap(Objects.requireNonNull(value));
    }

    @Override
    public BEType getType() {
        return BEType.MAP;
    }

    @Override
    public byte[] getContent() {
        return content;
    }

    @Override
    public Map<String, BEObject<?>> getValue() {
        return value;
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        ENCODER.encode(this, out);
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    @Override
    public boolean equals(Object obj) {

        if (!(obj instanceof BEMap)) {
            return false;
        }

        if (obj == this) {
            return true;
        }

        return value.equals(((BEMap) obj).getValue());
    }

    @Override
    public String toString() {
        return value.toString();
    }
}


text:
import { StoreFrontPage } from './app.po';

describe('store-front App', () => {
  let page: StoreFrontPage;

  beforeEach(() => {
    page = new StoreFrontPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('app works!');
  });
});


text:
const chalk = require('chalk');
const jhiCore = require('jhipster-core');
const BaseGenerator = require('../generator-base');
const statistics = require('../statistics');

module.exports = class extends BaseGenerator {
    constructor(args, opts) {
        super(args, opts);
        this.baseName = this.config.get('baseName');
        this.argument('jdlFile', { type: String, required: false, defaults: `${this.baseName}.jdl` });
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false
        });
    }

    get default() {
        return {
            validateFromCli() {
                this.checkInvocationFromCLI();
            },

            insight() {
                statistics.sendSubGenEvent('generator', 'export-jdl');
            },

            convertToJDL() {
                try {
                    jhiCore.jdl.conversion.JSONToJDLConverter.convertToJDL('.', this.options.jdlFile);
                } catch (error) {
                    this.error(`An error occurred while exporting to JDL: ${error.message}\n${error}`);
                }
            }
        };
    }

    end() {
        this.log(chalk.green.bold('\nThe JDL export is complete!\n'));
    }
};