text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>CalendarContract.AttendeesColumns - Android SDK | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../assets/css/default.css" rel="stylesheet" type="text/css">

<link href="../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../')"
onkeyup="return search_changed(event, false, '../../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

          API level:

            <select id="apiLevelSelector">

            </select>

Android APIs

  android

  android.accessibilityservice

  android.accounts

  android.animation

  android.app

  android.app.admin

  android.app.backup

  android.appwidget

  android.bluetooth

  android.content

  android.content.pm

  android.content.res

  android.database

  android.database.sqlite

  android.drm

  android.gesture

  android.graphics

  android.graphics.drawable

  android.graphics.drawable.shapes

  android.graphics.pdf

  android.hardware

  android.hardware.display

  android.hardware.input

  android.hardware.location

  android.hardware.usb

  android.inputmethodservice

  android.location

  android.media

  android.media.audiofx

  android.media.effect

  android.mtp

  android.net

  android.net.http

  android.net.nsd

  android.net.rtp

  android.net.sip

  android.net.wifi

  android.net.wifi.p2p

  android.net.wifi.p2p.nsd

  android.nfc

  android.nfc.cardemulation

  android.nfc.tech

  android.opengl

  android.os

  android.os.storage

  android.preference

  android.print

  android.print.pdf

  android.printservice

  android.provider

  android.renderscript

  android.sax

  android.security

  android.service.dreams

  android.service.notification

  android.service.textservice

  android.service.wallpaper

  android.speech

  android.speech.tts

  android.support.v13.app

  android.support.v4.accessibilityservice

  android.support.v4.app

  android.support.v4.content

  android.support.v4.content.pm

  android.support.v4.database

  android.support.v4.graphics.drawable

  android.support.v4.hardware.display

  android.support.v4.media

  android.support.v4.net

  android.support.v4.os

  android.support.v4.print

  android.support.v4.text

  android.support.v4.util

  android.support.v4.view

  android.support.v4.view.accessibility

  android.support.v4.widget

  android.support.v7.app

  android.support.v7.appcompat

  android.support.v7.gridlayout

  android.support.v7.media

  android.support.v7.mediarouter

  android.support.v7.view

  android.support.v7.widget

  android.support.v8.renderscript

  android.telephony

  android.telephony.cdma

  android.telephony.gsm

  android.test

  android.test.mock

  android.test.suitebuilder

  android.text

  android.text.format

  android.text.method

  android.text.style

  android.text.util

  android.transition

  android.util

  android.view

  android.view.accessibility

  android.view.animation

  android.view.inputmethod

  android.view.textservice

  android.webkit

  android.widget

  dalvik.bytecode

  dalvik.system

  java.awt.font

  java.beans

  java.io

  java.lang

  java.lang.annotation

  java.lang.ref

  java.lang.reflect

  java.math

  java.net

  java.nio

  java.nio.channels

  java.nio.channels.spi

  java.nio.charset

  java.nio.charset.spi

  java.security

  java.security.acl

  java.security.cert

  java.security.interfaces

  java.security.spec

  java.sql

  java.text

  java.util

  java.util.concurrent

  java.util.concurrent.atomic

  java.util.concurrent.locks

  java.util.jar

  java.util.logging

  java.util.prefs

  java.util.regex

  java.util.zip

  javax.crypto

  javax.crypto.interfaces

  javax.crypto.spec

  javax.microedition.khronos.egl

  javax.microedition.khronos.opengles

  javax.net

  javax.net.ssl

  javax.security.auth

  javax.security.auth.callback

  javax.security.auth.login

  javax.security.auth.x500

  javax.security.cert

  javax.sql

  javax.xml

  javax.xml.datatype

  javax.xml.namespace

  javax.xml.parsers

  javax.xml.transform

  javax.xml.transform.dom

  javax.xml.transform.sax

  javax.xml.transform.stream

  javax.xml.validation

  javax.xml.xpath

  junit.framework

  junit.runner

  org.apache.http

  org.apache.http.auth

  org.apache.http.auth.params

  org.apache.http.client

  org.apache.http.client.entity

  org.apache.http.client.methods

  org.apache.http.client.params

  org.apache.http.client.protocol

  org.apache.http.client.utils

  org.apache.http.conn

  org.apache.http.conn.params

  org.apache.http.conn.routing

  org.apache.http.conn.scheme

  org.apache.http.conn.ssl

  org.apache.http.conn.util

  org.apache.http.cookie

  org.apache.http.cookie.params

  org.apache.http.entity

  org.apache.http.impl

  org.apache.http.impl.auth

  org.apache.http.impl.client

  org.apache.http.impl.conn

  org.apache.http.impl.conn.tsccm

  org.apache.http.impl.cookie

  org.apache.http.impl.entity

  org.apache.http.impl.io

  org.apache.http.io

  org.apache.http.message

  org.apache.http.params

  org.apache.http.protocol

  org.apache.http.util

  org.json

  org.w3c.dom

  org.w3c.dom.ls

  org.xml.sax

  org.xml.sax.ext

  org.xml.sax.helpers

  org.xmlpull.v1

  org.xmlpull.v1.sax2

Interfaces

BaseColumns

CalendarContract.AttendeesColumns

CalendarContract.CalendarAlertsColumns

CalendarContract.CalendarCacheColumns

CalendarContract.CalendarColumns

CalendarContract.CalendarSyncColumns

CalendarContract.ColorsColumns

CalendarContract.EventDaysColumns

CalendarContract.EventsColumns

CalendarContract.ExtendedPropertiesColumns

CalendarContract.RemindersColumns

CalendarContract.SyncColumns

Contacts.ContactMethodsColumns

Contacts.ExtensionsColumns

Contacts.GroupsColumns

Contacts.OrganizationColumns

Contacts.PeopleColumns

Contacts.PhonesColumns

Contacts.PhotosColumns

Contacts.PresenceColumns

Contacts.SettingsColumns

ContactsContract.BaseSyncColumns

ContactsContract.CommonDataKinds.BaseTypes

ContactsContract.CommonDataKinds.CommonColumns

ContactsContract.ContactNameColumns

ContactsContract.ContactOptionsColumns

ContactsContract.ContactsColumns

ContactsContract.ContactStatusColumns

ContactsContract.DataColumns

ContactsContract.DataColumnsWithJoins

ContactsContract.DataUsageStatColumns

ContactsContract.DeletedContactsColumns

ContactsContract.DisplayNameSources

ContactsContract.FullNameStyle

ContactsContract.GroupsColumns

ContactsContract.PhoneLookupColumns

ContactsContract.PhoneticNameStyle

ContactsContract.PresenceColumns

ContactsContract.RawContactsColumns

ContactsContract.SettingsColumns

ContactsContract.StatusColumns

ContactsContract.StreamItemPhotosColumns

ContactsContract.StreamItemsColumns

ContactsContract.SyncColumns

MediaStore.Audio.AlbumColumns

MediaStore.Audio.ArtistColumns

MediaStore.Audio.AudioColumns

MediaStore.Audio.GenresColumns

MediaStore.Audio.PlaylistsColumns

MediaStore.Files.FileColumns

MediaStore.Images.ImageColumns

MediaStore.MediaColumns

MediaStore.Video.VideoColumns

OpenableColumns

SyncStateContract.Columns

Telephony.BaseMmsColumns

Telephony.CanonicalAddressesColumns

Telephony.TextBasedSmsColumns

Telephony.ThreadsColumns

Classes

AlarmClock

Browser

Browser.BookmarkColumns

Browser.SearchColumns

CalendarContract

CalendarContract.Attendees

CalendarContract.CalendarAlerts

CalendarContract.CalendarCache

CalendarContract.CalendarEntity

CalendarContract.Calendars

CalendarContract.Colors

CalendarContract.EventDays

CalendarContract.Events

CalendarContract.EventsEntity

CalendarContract.ExtendedProperties

CalendarContract.Instances

CalendarContract.Reminders

CalendarContract.SyncState

CallLog

CallLog.Calls

Contacts

Contacts.ContactMethods

Contacts.Extensions

Contacts.GroupMembership

Contacts.Groups

Contacts.Intents

Contacts.Intents.Insert

Contacts.Intents.UI

Contacts.Organizations

Contacts.People

Contacts.People.ContactMethods

Contacts.People.Extensions

Contacts.People.Phones

Contacts.Phones

Contacts.Photos

Contacts.Settings

ContactsContract

ContactsContract.AggregationExceptions

ContactsContract.CommonDataKinds

ContactsContract.CommonDataKinds.Contactables

ContactsContract.CommonDataKinds.Email

ContactsContract.CommonDataKinds.Event

ContactsContract.CommonDataKinds.GroupMembership

ContactsContract.CommonDataKinds.Identity

ContactsContract.CommonDataKinds.Im

ContactsContract.CommonDataKinds.Nickname

ContactsContract.CommonDataKinds.Note

ContactsContract.CommonDataKinds.Organization

ContactsContract.CommonDataKinds.Phone

ContactsContract.CommonDataKinds.Photo

ContactsContract.CommonDataKinds.Relation

ContactsContract.CommonDataKinds.SipAddress

ContactsContract.CommonDataKinds.StructuredName

ContactsContract.CommonDataKinds.StructuredPostal

ContactsContract.CommonDataKinds.Website

ContactsContract.Contacts

ContactsContract.Contacts.AggregationSuggestions

ContactsContract.Contacts.Data

ContactsContract.Contacts.Entity

ContactsContract.Contacts.Photo

ContactsContract.Contacts.StreamItems

ContactsContract.Data

ContactsContract.DataUsageFeedback

ContactsContract.DeletedContacts

ContactsContract.Directory

ContactsContract.DisplayPhoto

ContactsContract.Groups

ContactsContract.Intents

ContactsContract.Intents.Insert

ContactsContract.PhoneLookup

ContactsContract.Presence

ContactsContract.Profile

ContactsContract.ProfileSyncState

ContactsContract.QuickContact

ContactsContract.RawContacts

ContactsContract.RawContacts.Data

ContactsContract.RawContacts.DisplayPhoto

ContactsContract.RawContacts.Entity

ContactsContract.RawContacts.StreamItems

ContactsContract.RawContactsEntity

ContactsContract.Settings

ContactsContract.StatusUpdates

ContactsContract.StreamItemPhotos

ContactsContract.StreamItems

ContactsContract.StreamItems.StreamItemPhotos

ContactsContract.SyncState

DocumentsContract

DocumentsContract.Document

DocumentsContract.Root

DocumentsProvider

LiveFolders

MediaStore

MediaStore.Audio

MediaStore.Audio.Albums

MediaStore.Audio.Artists

MediaStore.Audio.Artists.Albums

MediaStore.Audio.Genres

MediaStore.Audio.Genres.Members

MediaStore.Audio.Media

MediaStore.Audio.Playlists

MediaStore.Audio.Playlists.Members

MediaStore.Files

MediaStore.Images

MediaStore.Images.Media

MediaStore.Images.Thumbnails

MediaStore.Video

MediaStore.Video.Media

MediaStore.Video.Thumbnails

SearchRecentSuggestions

Settings

Settings.Global

Settings.NameValueTable

Settings.Secure

Settings.System

SyncStateContract

SyncStateContract.Constants

SyncStateContract.Helpers

Telephony

Telephony.Carriers

Telephony.Mms

Telephony.Mms.Addr

Telephony.Mms.Draft

Telephony.Mms.Inbox

Telephony.Mms.Intents

Telephony.Mms.Outbox

Telephony.Mms.Part

Telephony.Mms.Rate

Telephony.Mms.Sent

Telephony.MmsSms

Telephony.MmsSms.PendingMessages

Telephony.Sms

Telephony.Sms.Conversations

Telephony.Sms.Draft

Telephony.Sms.Inbox

Telephony.Sms.Intents

Telephony.Sms.Outbox

Telephony.Sms.Sent

Telephony.Threads

UserDictionary

UserDictionary.Words

VoicemailContract

VoicemailContract.Status

VoicemailContract.Voicemails

Exceptions

Settings.SettingNotFoundException

      fullscreen
      Use Tree NavigationUse Panel Navigation

Summary:

  Constants

| [Expand All]

  Added in API level 14

    protected
    static

    interface

CalendarContract.AttendeesColumns

        android.provider.CalendarContract.AttendeesColumns

  Known Indirect Subclasses

              CalendarContract.Attendees

              CalendarContract.Attendees
              Fields and helpers for interacting with Attendees.

Class Overview

Columns from the Attendees table that other tables join into themselves.

Summary

Constants

        String
        ATTENDEE_EMAIL
        The email address of the attendee.

        String
        ATTENDEE_IDENTITY
        The identity of the attendee as referenced in
 IDENTITY.

        String
        ATTENDEE_ID_NAMESPACE
        The identity name space of the attendee as referenced in
 NAMESPACE.

        String
        ATTENDEE_NAME
        The name of the attendee.

        String
        ATTENDEE_RELATIONSHIP
        The relationship of the attendee to the user.

        String
        ATTENDEE_STATUS
        The attendance status of the attendee.

        int
        ATTENDEE_STATUS_ACCEPTED

        int
        ATTENDEE_STATUS_DECLINED

        int
        ATTENDEE_STATUS_INVITED

        int
        ATTENDEE_STATUS_NONE

        int
        ATTENDEE_STATUS_TENTATIVE

        String
        ATTENDEE_TYPE
        The type of attendee.

        String
        EVENT_ID
        The id of the event.

        int
        RELATIONSHIP_ATTENDEE

        int
        RELATIONSHIP_NONE

        int
        RELATIONSHIP_ORGANIZER

        int
        RELATIONSHIP_PERFORMER

        int
        RELATIONSHIP_SPEAKER

        int
        TYPE_NONE

        int
        TYPE_OPTIONAL

        int
        TYPE_REQUIRED

        int
        TYPE_RESOURCE
        This specifies that an attendee is a resource, like a room, a
 cabbage, or something and not an actual person.

Constants

        public
        static
        final
        String

        ATTENDEE_EMAIL

  Added in API level 14

The email address of the attendee. Column name.

Type: STRING

        Constant Value:

                "attendeeEmail"

        public
        static
        final
        String

        ATTENDEE_IDENTITY

  Added in API level 16

The identity of the attendee as referenced in
 IDENTITY.
 This is required only if ATTENDEE_ID_NAMESPACE is present. Column name.

Type: STRING

        Constant Value:

                "attendeeIdentity"

        public
        static
        final
        String

        ATTENDEE_ID_NAMESPACE

  Added in API level 16

The identity name space of the attendee as referenced in
 NAMESPACE.
 This is required only if ATTENDEE_IDENTITY is present. Column name.

Type: STRING

        Constant Value:

                "attendeeIdNamespace"

        public
        static
        final
        String

        ATTENDEE_NAME

  Added in API level 14

The name of the attendee. Column name.

Type: STRING

        Constant Value:

                "attendeeName"

        public
        static
        final
        String

        ATTENDEE_RELATIONSHIP

  Added in API level 14

The relationship of the attendee to the user. Column name.

Type: INTEGER (one of RELATIONSHIP_ATTENDEE, ...}.

        Constant Value:

                "attendeeRelationship"

        public
        static
        final
        String

        ATTENDEE_STATUS

  Added in API level 14

The attendance status of the attendee. Column name.

Type: Integer (one of ATTENDEE_STATUS_ACCEPTED, ...).

        Constant Value:

                "attendeeStatus"

        public
        static
        final
        int

        ATTENDEE_STATUS_ACCEPTED

  Added in API level 14

        Constant Value:

                1
                (0x00000001)

        public
        static
        final
        int

        ATTENDEE_STATUS_DECLINED

  Added in API level 14

        Constant Value:

                2
                (0x00000002)

        public
        static
        final
        int

        ATTENDEE_STATUS_INVITED

  Added in API level 14

        Constant Value:

                3
                (0x00000003)

        public
        static
        final
        int

        ATTENDEE_STATUS_NONE

  Added in API level 14

        Constant Value:

                0
                (0x00000000)

        public
        static
        final
        int

        ATTENDEE_STATUS_TENTATIVE

  Added in API level 14

        Constant Value:

                4
                (0x00000004)

        public
        static
        final
        String

        ATTENDEE_TYPE

  Added in API level 14

The type of attendee. Column name.

 Type: Integer (one of TYPE_NONE, TYPE_REQUIRED,
 TYPE_OPTIONAL, TYPE_RESOURCE)

        Constant Value:

                "attendeeType"

        public
        static
        final
        String

        EVENT_ID

  Added in API level 14

The id of the event. Column name.

Type: INTEGER

        Constant Value:

                "event_id"

        public
        static
        final
        int

        RELATIONSHIP_ATTENDEE

  Added in API level 14

        Constant Value:

                1
                (0x00000001)

        public
        static
        final
        int

        RELATIONSHIP_NONE

  Added in API level 14

        Constant Value:

                0
                (0x00000000)

        public
        static
        final
        int

        RELATIONSHIP_ORGANIZER

  Added in API level 14

        Constant Value:

                2
                (0x00000002)

        public
        static
        final
        int

        RELATIONSHIP_PERFORMER

  Added in API level 14

        Constant Value:

                3
                (0x00000003)

        public
        static
        final
        int

        RELATIONSHIP_SPEAKER

  Added in API level 14

        Constant Value:

                4
                (0x00000004)

        public
        static
        final
        int

        TYPE_NONE

  Added in API level 14

        Constant Value:

                0
                (0x00000000)

        public
        static
        final
        int

        TYPE_OPTIONAL

  Added in API level 14

        Constant Value:

                2
                (0x00000002)

        public
        static
        final
        int

        TYPE_REQUIRED

  Added in API level 14

        Constant Value:

                1
                (0x00000001)

        public
        static
        final
        int

        TYPE_RESOURCE

  Added in API level 15

This specifies that an attendee is a resource, like a room, a
 cabbage, or something and not an actual person.

        Constant Value:

                3
                (0x00000003)

  Except as noted, this content is licensed under Apache 2.0.
  For details and restrictions, see the
  Content License.

    Android 4.4 r1 —

    About Android  |
    Legal  |
    Support


text:
require 'spec_helper'
require "rspec/em"
require 'websocket-eventmachine-client'
require 'faye/websocket'

describe Wamp::Client::Transport do
  describe Wamp::Client::Transport::EventMachineBase do
    it '#start/stop' do
      value = 0
      described_class.start_event_machine do
        EM.tick_loop do
          value += 1
          described_class.stop_event_machine if value == 10
        end
      end

      expect(value).to eq(10)
    end

    it '#add_tick_loop' do
      value = 0
      described_class.start_event_machine do
        described_class.add_tick_loop do
          value += 1
          described_class.stop_event_machine if value == 10
        end
      end

      expect(value).to eq(10)
    end

    context '#add_timer' do
      include RSpec::EM::FakeClock

      before { clock.stub }
      after { clock.reset }

      it 'adds a timer with the class method' do
        value = 0
        described_class.add_timer(3000) do
          value = 1
        end

        expect(value).to eq(0)
        clock.tick(1)
        expect(value).to eq(0)
        clock.tick(1)
        expect(value).to eq(0)
        clock.tick(1)
        expect(value).to eq(1)
      end

      it 'adds a timer with the instance method' do
        transport = described_class.new({})

        value = 0
        transport.add_timer(2000) do
          value = 1
        end

        expect(value).to eq(0)
        clock.tick(1)
        expect(value).to eq(0)
        clock.tick(1)
        expect(value).to eq(1)
      end
    end
  end

  context 'transports' do
    let(:test_uri) { 'wss://router.examples.com' }
    let(:test_proxy) { 'http://proxy.examples.com' }
    let(:options) {
      {
          uri: test_uri,
          headers: {}
      }
    }

    describe Wamp::Client::Transport::WebSocketEventMachine do
      include RSpec::EM::FakeClock
      before { clock.stub }
      after { clock.reset }

      let(:transport) { described_class.new(options) }
      let(:socket) { transport.socket }
      before(:each) {
        allow(WebSocket::EventMachine::Client).to receive(:connect) { |options|
          WebSocketEventMachineClientStub.new
        }

        transport.connect
        clock.tick(1)  # Simulate connecting
      }

      it 'initializes' do
        expect(transport.uri).to eq(test_uri)
      end

      it 'connects to the router' do
        expect(transport.connected?).to eq(true)
      end

      it 'disconnects from the router' do
        value = false
        transport.on(:close) do
          value = true
        end

        transport.disconnect

        expect(transport.connected?).to eq(false)
        expect(value).to eq(true)
      end

      it 'sends a message' do
        transport.send_message({test: 'value'})
        expect(socket.last_message).to eq('{"test":"value"}')
      end

      it 'receives a message' do
        message = nil
        transport.on(:message) do |msg, type|
          message = msg
        end

        socket.receive('{"test":"value"}')
        expect(message).to eq({test: 'value'})
      end

      it 'raises exception if sending message when closed' do
        transport.disconnect
        expect {
          transport.send_message({test: 'value'})
        }.to raise_error(RuntimeError)
      end

      it 'raises exception if proxy is included' do
        expect {
          options[:proxy] = { origin: 'something', headers: 'something' }
          described_class.new(options)
        }.to raise_error(RuntimeError)
      end
    end

    describe Wamp::Client::Transport::FayeWebSocket do
      include RSpec::EM::FakeClock
      before { clock.stub }
      after { clock.reset }

      let(:transport) { described_class.new(options) }
      let(:socket) { transport.socket }
      before(:each) {
        allow(Faye::WebSocket::Client).to receive(:new) { |uri, protocols, options|
          FayeWebSocketClientStub.new
        }

        transport.connect
        clock.tick(1)  # Simulate connecting
      }

      it 'initializes' do
        expect(transport.uri).to eq(test_uri)
      end

      it 'connects to the router' do
        expect(transport.connected?).to eq(true)
      end

      it 'disconnects from the router' do
        value = false
        transport.on(:close) do
          value = true
        end

        transport.disconnect

        expect(transport.connected?).to eq(false)
        expect(value).to eq(true)
      end

      it 'sends a message' do
        transport.send_message({test: 'value'})
        expect(socket.last_message).to eq('{"test":"value"}')
      end

      it 'receives a message' do
        message = nil
        transport.on(:message) do |msg, type|
          message = msg
        end

        socket.receive('{"test":"value"}')
        expect(message).to eq({test: 'value'})
      end

      it 'raises exception if sending message when closed' do
        transport.disconnect
        expect {
          transport.send_message({test: 'value'})
        }.to raise_error(RuntimeError)
      end

      it 'does not raise exception if proxy is included' do
        expect {
          options[:proxy] = { origin: 'something', headers: 'something' }
          described_class.new(options)
        }.not_to raise_error
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package edu.unm;

import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author John Ericksen
 */
public class IAntXMLBuilder {

    private final String iAntXml;

    public IAntXMLBuilder(String templateFile) throws IOException {
        iAntXml = IOUtils.toString(new FileInputStream(templateFile));
    }

    public String buildXML(String chromosome, int seed, ExperimentParameters parameters, int distribution) {
        return iAntXml
                .replace("${chromosome}", chromosome)
                .replace("${seed}", Integer.toString(seed))
                .replace("${distribution}", Integer.toString(distribution))
                .replace("${runtime}", Integer.toString(parameters.runtime()))
                .replace("${entitycount}", Integer.toString(parameters.entityCount()));
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0" processorArchitecture="*" name="CompanyName.ProductName.YourApp" type="win32" />
  <description>Your application description here.</description>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
    </dependentAssembly>
  </dependency>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>


text:
package com.complexible.common.base;

import com.google.common.math.DoubleMath;

/**
 *
 * @author Evren Sirin
 * @since 2.0
 * @version 2.0
 */
public final class Numbers {
	/**
	 * Constant field for thousand.
	 */
	public static final long THOUSAND = 1000;

	/**
	 * Short-name constant field for thousand (1000).
	 */
	public static final long K = THOUSAND;

	/**
	 * Constant field for million.
	 */
	public static final long MILLION = 1000000;

	/**
	 * Short-name constant field for million.
	 */
	public static final long M = MILLION;

	/**
	 * Constant field for billion.
	 */
	public static final long BILLION = 1000000000;

	private Numbers() {
	}

	/**
	 * Returns a human-readable representation of numbers. This function is similar to {@link Memory#readable(long)} in
	 * spirit but works with powers of 10 (not 2), supports only two suffixes ('K' for thousands and 'M' for millions),
	 * and always prints one fraction digit for numbers greater then 1M.
	 *
	 *

	 *  500 = 500
	 *  1000 = 1.0K
	 *  6700 = 6.7K
	 *  10000 = 10K
	 *  17500 = 18K
	 *  940000 = 940K
	 *  1120000 = 1.1M
	 *  4600000 = 4.6M
	 *  12000000 = 12.0M
	 *  130000000 = 130.0M
	 *  1240000000 = 1240.0M
	 *

	 */
	public static String readable(long number) {
		if (number < THOUSAND)
			return String.valueOf(number);
		else if (number < 10 * THOUSAND)
			return String.format("%1.1fK", number / 1E3);
		else if (number < MILLION)
			return String.format("%1.0fK", number / 1E3);
		else
			return String.format("%1.1fM", number / 1E6);
	}

	/**
	 * The opposite of {@link #readable(long)}: parses a readable string and returns the corresponding number.
	 *
	 * @param theStr input string
	 * @return number represented by the string
	 */
	public static Number fromReadable(final String theStr) {
		if (theStr == null || theStr.isEmpty()) {
			throw new IllegalArgumentException("Empty string");
		}

		char aSuffix = theStr.charAt(theStr.length()-1);
		int aEndIndex = theStr.length() - 1;

		if (Character.isDigit(aSuffix)) {
			aEndIndex += 1;
			aSuffix = ' ';
		}

		final double aBase = Double.parseDouble(theStr.substring(0, aEndIndex));

		switch (aSuffix) {
			case ' ':
				return valueOf(aBase);
			case 'K':
			case 'k':
				return valueOf(aBase * K);
			case 'm':
			case 'M':
				return valueOf(aBase * M);
			default:
				throw new IllegalArgumentException("Unknown suffix: " + aSuffix);
		}
	}

	public static String readable(double number) {
		return String.format("%1.3f", number);
	}

	/**
	 * Return an {@link Integer} if given value long is less than Integer.MAX_VALUE or a {@link Long}
	 * otherwise.
	 */
	public static Number valueOf(long value) {
		return (value < Integer.MAX_VALUE) ? (Number) Integer.valueOf((int) value) : (Number) Long.valueOf(value);
	}

	public static Number valueOf(double value) {
		return DoubleMath.isMathematicalInteger(value) ? valueOf((long) value) : value;
	}
}


text: #include <aws/common/clock.inl>


text:
package net.canadensys.harvester;

import java.util.Map;

import net.canadensys.harvester.occurrence.SharedParameterEnum;

/**
 * Item reading interface
 * @author canadensys
 *
 * @param <T> type of object to read
 */
public interface ItemReaderIF<T> {

	public void openReader(Map<SharedParameterEnum,Object> sharedParameters);
	public void closeReader();

	public void abort();

	/**
	 * Return the next object from the reader or null if the end is reached.
	 * null will also be returned if abort() is called.
	 * @return
	 */
	public T read();
}


text:
from __future__ import absolute_import

import time

from google.protobuf import timestamp_pb2

from apache_beam.metrics.cells import DistributionData
from apache_beam.metrics.cells import DistributionResult
from apache_beam.metrics.cells import GaugeData
from apache_beam.metrics.cells import GaugeResult
from apache_beam.portability import common_urns
from apache_beam.portability.api.beam_fn_api_pb2 import CounterData
from apache_beam.portability.api.beam_fn_api_pb2 import Metric
from apache_beam.portability.api.beam_fn_api_pb2 import MonitoringInfo

ELEMENT_COUNT_URN = common_urns.monitoring_infos.ELEMENT_COUNT.urn
START_BUNDLE_MSECS_URN = common_urns.monitoring_infos.START_BUNDLE_MSECS.urn
PROCESS_BUNDLE_MSECS_URN = common_urns.monitoring_infos.PROCESS_BUNDLE_MSECS.urn
FINISH_BUNDLE_MSECS_URN = common_urns.monitoring_infos.FINISH_BUNDLE_MSECS.urn
TOTAL_MSECS_URN = common_urns.monitoring_infos.TOTAL_MSECS.urn
USER_COUNTER_URN_PREFIX = (
    common_urns.monitoring_infos.USER_COUNTER_URN_PREFIX.urn)

# TODO(ajamato): Implement the remaining types, i.e. Double types
# Extrema types, etc. See:
# https://s.apache.org/beam-fn-api-metrics
SUM_INT64_TYPE = common_urns.monitoring_info_types.SUM_INT64_TYPE.urn
DISTRIBUTION_INT64_TYPE = (
    common_urns.monitoring_info_types.DISTRIBUTION_INT64_TYPE.urn)
LATEST_INT64_TYPE = common_urns.monitoring_info_types.LATEST_INT64_TYPE.urn

COUNTER_TYPES = set([SUM_INT64_TYPE])
DISTRIBUTION_TYPES = set([DISTRIBUTION_INT64_TYPE])
GAUGE_TYPES = set([LATEST_INT64_TYPE])

def to_timestamp_proto(timestamp_secs):
  """Converts seconds since epoch to a google.protobuf.Timestamp.

  Args:
    timestamp_secs: The timestamp in seconds since epoch.
  """
  seconds = int(timestamp_secs)
  nanos = int((timestamp_secs - seconds) * 10**9)
  return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)

def to_timestamp_secs(timestamp_proto):
  """Converts a google.protobuf.Timestamp to seconds since epoch.

  Args:
    timestamp_proto: The google.protobuf.Timestamp.
  """
  return timestamp_proto.seconds + timestamp_proto.nanos * 10**-9

def extract_counter_value(monitoring_info_proto):
  """Returns the int coutner value of the monitoring info."""
  if is_counter(monitoring_info_proto) or is_gauge(monitoring_info_proto):
    return monitoring_info_proto.metric.counter_data.int64_value
  return None

def extract_distribution(monitoring_info_proto):
  """Returns the relevant DistributionInt64 or DistributionDouble.

  Args:
    monitoring_info_proto: The monitoring infor for the distribution.
  """
  if is_distribution(monitoring_info_proto):
    return monitoring_info_proto.metric.distribution_data.int_distribution_data
  return None

def create_labels(ptransform='', tag=''):
  """Create the label dictionary based on the provided tags.

  Args:
    ptransform: The ptransform/step name.
    tag: he output tag name, used as a label.
  """
  labels = {}
  if tag:
    labels['TAG'] = tag
  if ptransform:
    labels['PTRANSFORM'] = ptransform
  return labels

def int64_counter(urn, metric, ptransform='', tag=''):
  """Return the counter monitoring info for the specifed URN, metric and labels.

  Args:
    urn: The URN of the monitoring info/metric.
    metric: The metric proto field to use in the monitoring info.
        Or an int value.
    ptransform: The ptransform/step name used as a label.
    tag: The output tag name, used as a label.
  """
  labels = create_labels(ptransform=ptransform, tag=tag)
  if isinstance(metric, int):
    metric = Metric(
        counter_data=CounterData(
            int64_value=metric
        )
    )
  return create_monitoring_info(urn, SUM_INT64_TYPE, metric, labels)

def int64_distribution(urn, metric, ptransform='', tag=''):
  """Return the distribution monitoring info for the URN, metric and labels.

  Args:
    urn: The URN of the monitoring info/metric.
    metric: The metric proto field to use in the monitoring info.
        Or an int value.
    ptransform: The ptransform/step name used as a label.
    tag: The output tag name, used as a label.
  """
  labels = create_labels(ptransform=ptransform, tag=tag)
  return create_monitoring_info(urn, DISTRIBUTION_INT64_TYPE, metric, labels)

def int64_gauge(urn, metric, ptransform='', tag=''):
  """Return the gauge monitoring info for the URN, metric and labels.

  Args:
    urn: The URN of the monitoring info/metric.
    metric: The metric proto field to use in the monitoring info.
        Or an int value.
    ptransform: The ptransform/step name used as a label.
    tag: The output tag name, used as a label.
  """
  labels = create_labels(ptransform=ptransform, tag=tag)
  return create_monitoring_info(urn, LATEST_INT64_TYPE, metric, labels)

def create_monitoring_info(urn, type_urn, metric_proto, labels=None):
  """Return the gauge monitoring info for the URN, type, metric and labels.

  Args:
    urn: The URN of the monitoring info/metric.
    type_urn: The URN of the type of the monitoring info/metric.
        i.e. beam:metrics:sum_int_64, beam:metrics:latest_int_64.
    metric_proto: The metric proto field to use in the monitoring info.
        Or an int value.
    labels: The label dictionary to use in the MonitoringInfo.
  """
  return MonitoringInfo(
      urn=urn,
      type=type_urn,
      labels=labels or dict(),
      metric=metric_proto,
      timestamp=to_timestamp_proto(time.time())
  )

def user_metric_urn(namespace, name):
  """Returns the metric URN for a user metric, with a proper URN prefix.

  Args:
    namespace: The namespace of the metric.
    name: The name of the metric.
  """
  return '%s%s:%s' % (USER_COUNTER_URN_PREFIX, namespace, name)

def is_counter(monitoring_info_proto):
  """Returns true if the monitoring info is a coutner metric."""
  return monitoring_info_proto.type in COUNTER_TYPES

def is_distribution(monitoring_info_proto):
  """Returns true if the monitoring info is a distrbution metric."""
  return monitoring_info_proto.type in DISTRIBUTION_TYPES

def is_gauge(monitoring_info_proto):
  """Returns true if the monitoring info is a gauge metric."""
  return monitoring_info_proto.type in GAUGE_TYPES

def is_user_monitoring_info(monitoring_info_proto):
  """Returns true if the monitoring info is a user metric."""
  return monitoring_info_proto.urn.startswith(USER_COUNTER_URN_PREFIX)

def extract_metric_result_map_value(monitoring_info_proto):
  """Returns the relevant GaugeResult, DistributionResult or int value.

  These are the proper format for use in the MetricResult.query() result.
  """
  # Returns a metric result (AKA the legacy format).
  # from the MonitoringInfo
  if is_counter(monitoring_info_proto):
    return extract_counter_value(monitoring_info_proto)
  if is_distribution(monitoring_info_proto):
    distribution_data = extract_distribution(monitoring_info_proto)
    return DistributionResult(
        DistributionData(distribution_data.sum, distribution_data.count,
                         distribution_data.min, distribution_data.max))
  if is_gauge(monitoring_info_proto):
    timestamp_secs = to_timestamp_secs(monitoring_info_proto.timestamp)
    return GaugeResult(GaugeData(
        extract_counter_value(monitoring_info_proto), timestamp_secs))

def parse_namespace_and_name(monitoring_info_proto):
  """Returns the (namespace, name) tuple of the URN in the monitoring info."""
  to_split = monitoring_info_proto.urn
  if is_user_monitoring_info(monitoring_info_proto):
    # Remove the URN prefix which indicates that it is a user counter.
    to_split = monitoring_info_proto.urn[len(USER_COUNTER_URN_PREFIX):]
  # If it is not a user counter, just use the first part fo the URN, i.e. 'beam'
  split = to_split.split(':')
  return split[0], ':'.join(split[1:])

def to_key(monitoring_info_proto):
  """Returns a key based on the URN and labels.

  This is useful in maps to prevent reporting the same MonitoringInfo twice.
  """
  key_items = [i for i in monitoring_info_proto.labels.items()]
  key_items.append(monitoring_info_proto.urn)
  return frozenset(key_items)


text:
"""
Сравнение
"""

# read string and convert to integer
number1 = raw_input( "Please enter first integer: " )
number1 = int( number1 )

number2 = raw_input( "Please enter second integer: " )
number2 = int( number2 )

if number1 == number2:
   print "%d is equal to %d" % ( number1, number2 )

if number1 != number2:
   print "%d is not equal to %d" % ( number1, number2 )

if number1 < number2:
   print "%d is less than %d" % ( number1, number2 )

if number1 > number2:
   print "%d is greater than %d" % ( number1, number2 )

if number1 <= number2:
   print "%d is less than or equal to %d" % ( number1, number2 )

if number1 >= number2:
   print "%d is greater than or equal to %d" % ( number1, number2 )


text:
import urllib2
import cStringIO
import tempfile
import random
import csv
import os
import numpy as np
import pytest
from contextlib import closing
import networkx as nx
import makeunitdb
from ndlib.ndtype import ANNOTATION, UINT32
from params import Params
from ramonmethods import H5AnnotationFile, setField, getField, queryField, makeAnno, createSpecificSynapse
from postmethods import putAnnotation, getAnnotation, getURL, postURL
from test_settings import *

p = Params()
p.token = 'unittest'
p.resolution = 0
p.channels = ['ANNO1']
p.channel_type = ANNOTATION
p.datatype = UINT32

@pytest.mark.skipif(True, reason='Test not necessary for dev mode')
class Test_GraphGen:

  def setup_class(self):
    """Create the unittest database"""
    makeunitdb.createTestDB(p.token, channel_list=p.channels, public=True, readonly=0, ximagesize=100, yimagesize=100, zimagesize=100)

    cutout1 = "0/2,5/1,3/1,3"
    cutout2 = "0/1,3/4,6/2,5"
    cutout3 = "0/4,6/2,5/5,7"
    cutout4 = "0/6,8/5,9/2,4"

    syn_segments1 = [7, 3]
    syn_segments2 = [7, 4]
    syn_segments3 = [3, 9]
    syn_segments4 = [5, 4]

    # syn_presegments1 = [7, 3, 5]
    # syn_presegments2 = [7, 4, 2, 8]
    # syn_presegments3 = [3, 9]
    # syn_presegments4 = [5]

    # syn_postsegments1 = [7, 3, 5]
    # syn_postsegments2 = [7, 4, 2, 8]
    # syn_postsegments3 = [3, 9]
    # syn_postsegments4 = [5]

    # RB COMMENT Old RAMON schema list of lists.
    # syn_segments1 = [[7, 3],]
    # syn_segments2 = [[7, 4],]
    # syn_segments3 = [[3, 9],]
    # syn_segments4 = [[5, 4],]

    f1 = createSpecificSynapse(1, syn_segments1, cutout1)
    putid = putAnnotation(p, f1)
    f2 = createSpecificSynapse(2, syn_segments2, cutout2)
    putid = putAnnotation(p, f2)
    f3 = createSpecificSynapse(3, syn_segments3, cutout3)
    putid = putAnnotation(p, f3)
    f4 = createSpecificSynapse(4, syn_segments4, cutout4)
    putid = putAnnotation(p, f4)

  def teardown_class(self):
    """Destroy the unittest database"""
    makeunitdb.deleteTestDB(p.token)

  def test_checkTotal(self):
    """Test the original/non-specific dataset"""
    syn_segments = [[7, 3], [7, 12], [3, 9], [5, 12]]
    truthGraph = nx.Graph()
    truthGraph.add_edges_from(syn_segments)

    url = 'https://{}/ndgraph/{}/{}/'.format(SITE_HOST, p.token, p.channels[0])
    graphFile = getURL(url)
    with open(("/tmp/{}_{}.graphml").format(p.token, p.channels[0]), "wb") as f:
        f.write(graphFile.content)
    outputGraph = nx.read_graphml(("/tmp/{}_{}.graphml").format(p.token, p.channels[0]))
    assert(nx.is_isomorphic(outputGraph, truthGraph))

  def test_checkType(self):
    """Test the export to different data types"""
    syn_segments = [[7, 3], [7, 12], [3, 9], [5, 12]]
    truthGraph = nx.Graph()
    truthGraph.add_edges_from(syn_segments)

    url = 'https://{}/ndgraph/{}/{}/{}/'.format(
        SITE_HOST, p.token, p.channels[0], 'adjlist')
    graphFile = getURL(url)
    with open(("/tmp/{}_{}.adjlist").format(p.token, p.channels[0]), "wb") as f:
        f.write(graphFile.content)
    outputGraph = nx.read_adjlist(("/tmp/{}_{}.adjlist").format(p.token, p.channels[0]))
    assert(nx.is_isomorphic(outputGraph, truthGraph))

  def test_checkCutout(self):
    """Test the cutout arguement of graphgen"""

    syn_segments = [[7, 3], [7, 4], [5, 4]]
    truthGraph = nx.Graph()
    truthGraph.add_edges_from(syn_segments)

    url = 'https://{}/ndgraph/{}/{}/{}/{},{}/{},{}/{},{}/'.format(
        SITE_HOST, p.token, p.channels[0], 'graphml', 0, 7, 0, 8, 1, 4)
    graphFile = getURL(url)
    with open(("/tmp/{}_{}.graphml").format(p.token, p.channels[0]), "wb") as f:
        f.write(graphFile.content)
    outputGraph = nx.read_graphml(("/tmp/{}_{}.graphml").format(p.token, p.channels[0]))
    assert(nx.is_isomorphic(outputGraph, truthGraph))

  def test_ErrorHandling(self):
    """Invalid graphtype and invalid token"""
    syn_segments = [[7, 3], [7, 12], [3, 9], [5, 12]]
    truthGraph = nx.Graph()
    truthGraph.add_edges_from(syn_segments)

    url = 'https://{}/ndgraph/{}/{}/{}/'.format(SITE_HOST, p.token, p.channels[0], 'foograph')
    graphFile = getURL(url)
    with open(("/tmp/{}_{}.graphml").format(p.token, p.channels[0]), "wb") as f:
        f.write(graphFile.content)
    outputGraph = nx.read_graphml(("/tmp/{}_{}.graphml").format(p.token, p.channels[0]))
    assert(nx.is_isomorphic(outputGraph, truthGraph))

    """Invalid token"""
    url = 'https://{}/ndgraph/{}/{}/{}/{},{}/{},{}/{},{}/'.format(SITE_HOST, 'foo', p.channels[0], 'graphml', 0, 7, 0, 7, 0, 7)
    assert (getURL(url).status_code >= 500)


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

<title>L-Index</title>
<meta name="date" content="2016-10-23">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D G H I L N O P R S T U V

L

level - Variable in class ParemeterBeans.UUIDBean

A B C D G H I L N O P R S T U V

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
import os
import sys
import subprocess
import shutil
import time
import json
import argparse
import traceback
import requests
from random import randint
from subprocess import PIPE
from bitcoin import rpc
from bitcoin import SelectParams
from shutil import copyfile

TEST_SWARM_PORT = randint(1024, 65535)
TEST_GATEWAY_PORT = randint(1024, 65535)

BOOTSTRAP_NODES = [
    "/ip4/127.0.0.1/tcp/" + str(TEST_SWARM_PORT + 0) + "/ipfs/Qmdo6RpKtSqk73gUwaiaPkq6gWk49y3NCPCQbVsM9XTma3",
    "/ip4/127.0.0.1/tcp/" + str(TEST_SWARM_PORT + 1) + "/ipfs/QmVQzkdi3Fq6LRFG9UNqDZfSry67weCZV6ZL26QVx64UFy",
    "/ip4/127.0.0.1/tcp/" + str(TEST_SWARM_PORT + 2) + "/ipfs/Qmd5qDpcYkHCmkj9pMXU9TKBqEDWgEmtoHD5xjdJgumaHg"
]

BOOTSTAP_MNEMONICS = [
    "today summer matter always angry crumble rib lucky park shoulder police puppy",
    "husband letter control display skin tennis this expand garbage boil pig exchange",
    "resist museum dizzy there pulp suspect dust useless drama grab visa trumpet"
]

class TestFailure(Exception):
    pass

class OpenBazaarTestFramework(object):

    def __init__(self):
        self.nodes = []
        self.bitcoin_api = None

    def setup_nodes(self):
        for i in range(self.num_nodes):
            self.configure_node(i)
            self.start_node(self.nodes[i])

    def setup_network(self):
        if self.bitcoind is not None:
            self.start_bitcoind()
        self.setup_nodes()

    def run_test(self):
        raise NotImplementedError

    def send_bitcoin_cmd(self, *args):
        try:
            return self.bitcoin_api.call(*args)
        except BrokenPipeError:
            self.bitcoin_api = rpc.Proxy(btc_conf_file=self.btc_config)
            return self.send_bitcoin_cmd(*args)

    def configure_node(self, n):
        dir_path = os.path.join(self.temp_dir, "openbazaar-go", str(n))
        args = [self.binary, "init", "-d", dir_path, "--testnet"]
        if n < 3:
            args.extend(["-m", BOOTSTAP_MNEMONICS[n]])
        process = subprocess.Popen(args, stdout=PIPE)
        self.wait_for_init_success(process)
        with open(os.path.join(dir_path, "config")) as cfg:
            config = json.load(cfg)
        config["Addresses"]["Gateway"] = "/ip4/127.0.0.1/tcp/" + str(TEST_GATEWAY_PORT + n)
        config["Addresses"]["Swarm"] = ["/ip4/127.0.0.1/tcp/" + str(TEST_SWARM_PORT + n)]
        to_boostrap = []
        for node in BOOTSTRAP_NODES:
            if config["Addresses"]["Swarm"][0] not in node:
                to_boostrap.append(node)
        config["Bootstrap-testnet"] = to_boostrap
        config["Wallet"]["TrustedPeer"] = "127.0.0.1:18444"
        config["Wallet"]["FeeAPI"] = ""
        config["Crosspost-gateways"] = []
        config["Swarm"]["DisableNatPortMap"] = True

        if self.bitcoincash:
            config["Wallet"]["Type"] = "bitcoincash"

        with open(os.path.join(dir_path, "config"), 'w') as outfile:
            outfile.write(json.dumps(config, indent=4))
        node = {
            "data_dir": dir_path,
            "gateway_url": "http://localhost:" + str(TEST_GATEWAY_PORT + n) + "/",
            "swarm_port": str(TEST_SWARM_PORT + n)
        }
        self.nodes.append(node)

    @staticmethod
    def wait_for_init_success(process):
        while True:
            if process.poll() is not None:
                raise Exception("OpenBazaar node initialization failed")
            output = process.stdout
            for o in output:
                if "OpenBazaar repo initialized" in str(o):
                    return

    def start_node(self, node):
        args = [self.binary, "start", "-v", "-d", node["data_dir"], *self.options]
        process = subprocess.Popen(args, stdout=PIPE)
        peerId = self.wait_for_start_success(process, node)
        node["peerId"] = peerId

    @staticmethod
    def wait_for_start_success(process, node):
        peerId = ""
        while True:
            if process.poll() is not None:
                raise Exception("OpenBazaar node failed to start")
            output = process.stdout
            for o in output:
                if "Peer ID:" in str(o):
                    peerId = str(o)[str(o).index("Peer ID:") + 10:len(str(o)) - 3]
                if "Gateway/API server listening" in str(o):
                    return peerId

    def start_bitcoind(self):
        SelectParams('regtest')
        dir_path = os.path.join(self.temp_dir, "openbazaar-go", "bitcoin")
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        btc_conf_file = os.path.join(dir_path, "bitcoin.conf")
        copyfile(os.path.join(os.getcwd(), "testdata", "bitcoin.conf"), btc_conf_file)
        self.btc_config = btc_conf_file
        args = [self.bitcoind, "-regtest", "-datadir=" + dir_path, "-debug=net"]
        process = subprocess.Popen(args, stdout=PIPE)
        self.wait_for_bitcoind_start(process, btc_conf_file)
        self.init_blockchain()

    def init_blockchain(self):
        self.send_bitcoin_cmd("generate", 1)
        self.bitcoin_address = self.send_bitcoin_cmd("getnewaddress")
        self.send_bitcoin_cmd("generatetoaddress", 1, self.bitcoin_address)
        self.send_bitcoin_cmd("generate", 435)

    def wait_for_bitcoind_start(self, process, btc_conf_file):
        while True:
            if process.poll() is not None:
                raise Exception('bitcoind exited with status %i during initialization' % process.returncode)
            try:
                self.bitcoin_api = rpc.Proxy(btc_conf_file=btc_conf_file)
                blocks = self.bitcoin_api.getblockcount()
                break # break out of loop on success
            except Exception:
                time.sleep(0.25)
                continue

    def print_logs(self, node, log):
        f = open(os.path.join(node["data_dir"], "logs", log), 'r')
        file_contents = f.read()
        print()
        print("~~~~~~~~~~~~~~~~~~~~~~ " + log + " ~~~~~~~~~~~~~~~~~~~~~~")
        print (file_contents)
        print()
        f.close()

    def teardown(self):
        for n in self.nodes:
            requests.post(n["gateway_url"] + "ob/shutdown")
        time.sleep(2)
        if self.bitcoin_api is not None:
            try:
                self.send_bitcoin_cmd("stop")
            except BrokenPipeError:
                pass
        time.sleep(10)

    def main(self, options=["--disablewallet", "--testnet", "--disableexchangerates"]):
        parser = argparse.ArgumentParser(
                    description="OpenBazaar Test Framework",
                    usage="python3 test_framework.py [options]"
        )
        parser.add_argument('-b', '--binary', required=True, help="the openbazaar-go binary")
        parser.add_argument('-d', '--bitcoind', help="the bitcoind binary")
        parser.add_argument('-t', '--tempdir', action='store_true', help="temp directory to store the data folders", default="/tmp/")
        parser.add_argument('-c', '--bitcoincash', help="test with bitcoin cash", action='store_true', default=False)
        args = parser.parse_args(sys.argv[1:])
        self.binary = args.binary
        self.temp_dir = args.tempdir
        self.bitcoind = args.bitcoind
        self.bitcoincash = args.bitcoincash
        self.options = options

        try:
            shutil.rmtree(os.path.join(self.temp_dir, "openbazaar-go"))
        except:
            pass

        failure = False
        try:
            self.setup_network()
            self.run_test()
        except TestFailure as e:
            print(repr(e))
            failure = True
        except Exception as e:
            print("Unexpected exception caught during testing: " + repr(e))
            traceback.print_tb(sys.exc_info()[2])
            failure = True

        self.teardown()

        if failure:
            sys.exit(1)


text:
<?php

namespace App\Http\Controllers\System;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Models\Category;
use App\Models\Article;
class TrashController extends CommonController
{
    public function index(Request $request)
    {
        //多条件查找
        $where = function ($query) use ($request) {
            if ($request->has('name') and $request->name != '') {
                $search = "%" . $request->name . "%";
                $query->where('name', 'like', $search);
            }

            if ($request->has('created_at') and $request->created_at != '') {
                $time = explode(" ~ ", $request->input('created_at'));
                foreach ($time as $k => $v) {
                    $time["$k"] = $k == 0 ? $v . " 00:00:00" : $v . " 23:59:59";
                }
                $query->whereBetween('created_at', $time);
            }
        };

        $articles = Article::onlyTrashed()->with('category','user')->paginate(15);
        //return $articles;
        $count = count($articles);
        return view('admin.trash.index')->with('articles',$articles)
            ->with('count',$count);
    }

    //还原
    public function restore($id)
    {
        Article::onlyTrashed()->where('id', $id)->restore();
        return redirect('admin/trash')->with('msg', '还原成功!');
    }
    //强制删除
    public function forceDelete($id)
    {
        Article::onlyTrashed()->where('id', $id)->forceDelete();
        return redirect('admin/trash')->with('msg', '删除成功!');
    }

    //回收站全选删除

    public function select_del(Request $request)
    {
        $select_id = $request->select_id;
        foreach($select_id as $v){
            $article = Article::onlyTrashed()->find($v);
            $article->forceDelete();
        }
    }

    //回收站全选还原
    public function select_restore(Request $request)
    {
        $select_id = $request->select_id;
        foreach($select_id as $v){
            $article = Article::onlyTrashed()->find($v);
            $article->restore();
        }
    }

}


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

import java.io.Serializable;

/**
 *

 * Policy for customizing shrink operations. Allows configuration of
 * decommissioning timeout and targeted instance shrinking.
 *

 */
public class ShrinkPolicy implements Serializable, Cloneable {

    /**
     *

     * The desired timeout for decommissioning an instance. Overrides the
     * default YARN decommissioning timeout.
     *

     */
    private Integer decommissionTimeout;
    /**
     *

     * Custom policy for requesting termination protection or termination of
     * specific instances when shrinking an instance group.
     *

     */
    private InstanceResizePolicy instanceResizePolicy;

    /**
     *

     * The desired timeout for decommissioning an instance. Overrides the
     * default YARN decommissioning timeout.
     *

     *
     * @param decommissionTimeout
     *        The desired timeout for decommissioning an instance. Overrides the
     *        default YARN decommissioning timeout.
     */

    public void setDecommissionTimeout(Integer decommissionTimeout) {
        this.decommissionTimeout = decommissionTimeout;
    }

    /**
     *

     * The desired timeout for decommissioning an instance. Overrides the
     * default YARN decommissioning timeout.
     *

     *
     * @return The desired timeout for decommissioning an instance. Overrides
     *         the default YARN decommissioning timeout.
     */

    public Integer getDecommissionTimeout() {
        return this.decommissionTimeout;
    }

    /**
     *

     * The desired timeout for decommissioning an instance. Overrides the
     * default YARN decommissioning timeout.
     *

     *
     * @param decommissionTimeout
     *        The desired timeout for decommissioning an instance. Overrides the
     *        default YARN decommissioning timeout.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ShrinkPolicy withDecommissionTimeout(Integer decommissionTimeout) {
        setDecommissionTimeout(decommissionTimeout);
        return this;
    }

    /**
     *

     * Custom policy for requesting termination protection or termination of
     * specific instances when shrinking an instance group.
     *

     *
     * @param instanceResizePolicy
     *        Custom policy for requesting termination protection or termination
     *        of specific instances when shrinking an instance group.
     */

    public void setInstanceResizePolicy(
            InstanceResizePolicy instanceResizePolicy) {
        this.instanceResizePolicy = instanceResizePolicy;
    }

    /**
     *

     * Custom policy for requesting termination protection or termination of
     * specific instances when shrinking an instance group.
     *

     *
     * @return Custom policy for requesting termination protection or
     *         termination of specific instances when shrinking an instance
     *         group.
     */

    public InstanceResizePolicy getInstanceResizePolicy() {
        return this.instanceResizePolicy;
    }

    /**
     *

     * Custom policy for requesting termination protection or termination of
     * specific instances when shrinking an instance group.
     *

     *
     * @param instanceResizePolicy
     *        Custom policy for requesting termination protection or termination
     *        of specific instances when shrinking an instance group.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public ShrinkPolicy withInstanceResizePolicy(
            InstanceResizePolicy instanceResizePolicy) {
        setInstanceResizePolicy(instanceResizePolicy);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDecommissionTimeout() != null)
            sb.append("DecommissionTimeout: " + getDecommissionTimeout() + ",");
        if (getInstanceResizePolicy() != null)
            sb.append("InstanceResizePolicy: " + getInstanceResizePolicy());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof ShrinkPolicy == false)
            return false;
        ShrinkPolicy other = (ShrinkPolicy) obj;
        if (other.getDecommissionTimeout() == null
                ^ this.getDecommissionTimeout() == null)
            return false;
        if (other.getDecommissionTimeout() != null
                && other.getDecommissionTimeout().equals(
                        this.getDecommissionTimeout()) == false)
            return false;
        if (other.getInstanceResizePolicy() == null
                ^ this.getInstanceResizePolicy() == null)
            return false;
        if (other.getInstanceResizePolicy() != null
                && other.getInstanceResizePolicy().equals(
                        this.getInstanceResizePolicy()) == false)
            return false;
        return true;
    }

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

        hashCode = prime
                * hashCode
                + ((getDecommissionTimeout() == null) ? 0
                        : getDecommissionTimeout().hashCode());
        hashCode = prime
                * hashCode
                + ((getInstanceResizePolicy() == null) ? 0
                        : getInstanceResizePolicy().hashCode());
        return hashCode;
    }

    @Override
    public ShrinkPolicy clone() {
        try {
            return (ShrinkPolicy) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
using WebsitePanel.WebDavPortal.Models.Account.Enums;

namespace WebsitePanel.WebDavPortal.Models.Account
{
    public class PasswordResetPincodeSendOptionsModel
    {
        public PincodeSendMethod Method { get; set; }
        public string MobileNumber { get; set; }
        public string Email { get; set; }
    }
}


text:
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.CodeAnalysis;

namespace Dapplo.Windows.App;

/// <summary>
///     A simple enum for the GetAppVisibilityOnMonitor method, this tells us if an App is visible on the supplied monitor.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
internal enum MonitorAppVisibility
{
    MAV_UNKNOWN = 0, // The mode for the monitor is unknown
    MAV_NO_APP_VISIBLE = 1,
    MAV_APP_VISIBLE = 2
}


text:
export class Ng2PokedexPage {
  navigateTo() {
    return browser.get('/');
  }

  getParagraphText() {
    return element(by.css('ng2-pokedex-app h1')).getText();
  }
}


text:
package org.apache.hadoop.hbase.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HStoreKey;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.ReflectionUtils;

/**
 * A Writable Map.
 * Like {@link org.apache.hadoop.io.MapWritable} but dumb. It will fail
 * if passed a Writable it has not already been told about. Its also been
 * primed with hbase Writables.
 */
public class HbaseMapWritable implements Map<Writable, Writable>, Writable,
    Configurable {
  private AtomicReference<Configuration> conf =
    new AtomicReference<Configuration>();

  // Static maps of code to class and vice versa.  Includes types used in hbase
  // only.
  static final Map<Byte, Class<? extends Writable>> CODE_TO_CLASS =
    new HashMap<Byte, Class<? extends Writable>>();
  static final Map<Class<? extends Writable>, Byte> CLASS_TO_CODE =
    new HashMap<Class<? extends Writable>, Byte>();

  static {
    byte code = 0;
    addToMap(HStoreKey.class, code++);
    addToMap(ImmutableBytesWritable.class, code++);
    addToMap(Text.class, code++);
  }

  @SuppressWarnings("boxing")
  private static void addToMap(final Class<? extends Writable> clazz,
      final byte code) {
    CLASS_TO_CODE.put(clazz, code);
    CODE_TO_CLASS.put(code, clazz);
  }

  private Map<Writable, Writable> instance;

  /** Default constructor. */
  public HbaseMapWritable() {
    super();
    this.instance = new HashMap<Writable, Writable>();
  }

  /** @return the conf */
  public Configuration getConf() {
    return conf.get();
  }

  /** @param conf the conf to set */
  public void setConf(Configuration conf) {
    this.conf.set(conf);
  }

  /** {@inheritDoc} */
  public void clear() {
    instance.clear();
  }

  /** {@inheritDoc} */
  public boolean containsKey(Object key) {
    return instance.containsKey(key);
  }

  /** {@inheritDoc} */
  public boolean containsValue(Object value) {
    return instance.containsValue(value);
  }

  /** {@inheritDoc} */
  public Set<Map.Entry<Writable, Writable>> entrySet() {
    return instance.entrySet();
  }

  /** {@inheritDoc} */
  public Writable get(Object key) {
    return instance.get(key);
  }

  /** {@inheritDoc} */
  public boolean isEmpty() {
    return instance.isEmpty();
  }

  /** {@inheritDoc} */
  public Set<Writable> keySet() {
    return instance.keySet();
  }

  /** {@inheritDoc} */
  @SuppressWarnings("unchecked")
  public Writable put(Writable key, Writable value) {
    return instance.put(key, value);
  }

  /** {@inheritDoc} */
  public void putAll(Map<? extends Writable, ? extends Writable> t) {
    for (Map.Entry<? extends Writable, ? extends Writable> e: t.entrySet()) {
      instance.put(e.getKey(), e.getValue());
    }
  }

  /** {@inheritDoc} */
  public Writable remove(Object key) {
    return instance.remove(key);
  }

  /** {@inheritDoc} */
  public int size() {
    return instance.size();
  }

  /** {@inheritDoc} */
  public Collection<Writable> values() {
    return instance.values();
  }

  // Writable

  /** @return the Class class for the specified id */
  @SuppressWarnings({ "unchecked", "boxing" })
  protected Class<?> getClass(byte id) {
    return CODE_TO_CLASS.get(id);
  }

  /** @return the id for the specified Class */
  @SuppressWarnings({ "unchecked", "boxing" })
  protected byte getId(Class<?> clazz) {
    Byte b = CLASS_TO_CODE.get(clazz);
    if (b == null) {
      throw new NullPointerException("Nothing for : " + clazz);
    }
    return b;
  }

  public void write(DataOutput out) throws IOException {
    // Write out the number of entries in the map
    out.writeInt(instance.size());

    // Then write out each key/value pair
    for (Map.Entry<Writable, Writable> e: instance.entrySet()) {
      out.writeByte(getId(e.getKey().getClass()));
      e.getKey().write(out);
      out.writeByte(getId(e.getValue().getClass()));
      e.getValue().write(out);
    }
  }

  public void readFields(DataInput in) throws IOException {
    // First clear the map.  Otherwise we will just accumulate
    // entries every time this method is called.
    this.instance.clear();

    // Read the number of entries in the map
    int entries = in.readInt();

    // Then read each key/value pair
    for (int i = 0; i < entries; i++) {
      Writable key = (Writable) ReflectionUtils.newInstance(getClass(
          in.readByte()), getConf());

      key.readFields(in);

      Writable value = (Writable) ReflectionUtils.newInstance(getClass(
          in.readByte()), getConf());

      value.readFields(in);
      instance.put(key, value);
    }
  }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>cloud.iO</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="description" content="A scalable open source IoT solution.">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="_css/vue.css">
  <link rel="icon" href="/_media/cloudio.png">
  <link rel="stylesheet" href="_css/darklight.min.css" type="text/css"/>


text:
package de.fhg.iais.asc.xslt.timeparser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 *

 * Reads facets from a file.
 *

 *

 *
The first line in the file is ignored and can be used as a header line.

 *
Each line must consist of seven columns, separated by a tab character (\t). The columns must correspond to the following, in the specified order:
 *

 *
ID

 *
Notation

 *
Earliest date in years

 *
Latest date in years

 *
German description

 *
English description

 *
A sorting value to sort facets

 *

 *

 *

 */
public class FacetReader {

    private boolean skipHashes = true;

    public List<Facet> read(String path, String charsetName) throws IOException, FacetReaderException {
        ArrayList<Facet> facets = new ArrayList<Facet>();

        BufferedReader reader = null;
        try {
            File file = new File(path);
            if ( !file.exists() ) {
                throw new FacetReaderException("Facet file does could not be found for the given path \"" + path + "\"");
            } else if ( !file.canRead() ) {
                throw new FacetReaderException("Facet file does could not be opened with read access for the given path \"" + path + "\"");
            }

            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName));
            int i = 0;
            String line = null;
            boolean skippedFirstLine = false;
            while ( (line = reader.readLine()) != null ) {
                if ( skippedFirstLine ) {
                    line = line.trim();
                    if ( line.length() > 0 ) {
                        String[] columns = line.split("\t");
                        if ( columns.length < 7 ) {
                            throw new FacetReaderException("Expected 7 columns instead of "
                                + columns.length
                                + " in facet file \""
                                + path
                                + "\", line "
                                + i
                                + ": \""
                                + line
                                + "\"");
                        }

                        try {
                            Facet facet =
                                new Facet(columns[0], columns[1], Long.parseLong(columns[2]), Long.parseLong(columns[3]), columns[4], columns[5], columns[6]);
                            facets.add(facet);
                        } catch ( Exception x ) {
                            if ( !this.skipHashes ) {
                                throw new FacetReaderException("Incorrect number format in facet file \"" + path + "\", line " + i + ": \"" + line + "\"");
                            }
                        }
                    }
                } else {
                    skippedFirstLine = true;
                }
                i++;
            }
        } finally {
            if ( reader != null ) {
                reader.close();
            }
        }

        return facets;
    }

    public List<Facet> readSkipHashFacets(String path, String charsetName) throws IOException, FacetReaderException {
        this.skipHashes = true;
        return read(path, charsetName);
    }
}


text:
package pair

import (
	"strings"

	"github.com/thrasher-/gocryptotrader/common"
)

// CurrencyItem is an exported string with methods to manipulate the data instead
// of using array/slice access modifiers
type CurrencyItem string

// Lower converts the CurrencyItem object c to lowercase
func (c CurrencyItem) Lower() CurrencyItem {
	return CurrencyItem(strings.ToLower(string(c)))
}

// Upper converts the CurrencyItem object c to uppercase
func (c CurrencyItem) Upper() CurrencyItem {
	return CurrencyItem(strings.ToUpper(string(c)))
}

// String converts the CurrencyItem object c to string
func (c CurrencyItem) String() string {
	return string(c)
}

// CurrencyPair holds currency pair information
type CurrencyPair struct {
	Delimiter      string       `json:"delimiter"`
	FirstCurrency  CurrencyItem `json:"first_currency"`
	SecondCurrency CurrencyItem `json:"second_currency"`
}

// GetFirstCurrency returns the first currency item
func (c CurrencyPair) GetFirstCurrency() CurrencyItem {
	return c.FirstCurrency
}

// GetSecondCurrency returns the second currency item
func (c CurrencyPair) GetSecondCurrency() CurrencyItem {
	return c.SecondCurrency
}

// Pair returns a currency pair string
func (c CurrencyPair) Pair() CurrencyItem {
	return c.FirstCurrency + CurrencyItem(c.Delimiter) + c.SecondCurrency
}

// Display formats and returns the currency based on user preferences,
// overriding the default Pair() display
func (c CurrencyPair) Display(delimiter string, uppercase bool) CurrencyItem {
	var pair CurrencyItem

	if delimiter != "" {
		pair = c.FirstCurrency + CurrencyItem(delimiter) + c.SecondCurrency
	} else {
		pair = c.FirstCurrency + c.SecondCurrency
	}

	if uppercase {
		return pair.Upper()
	}
	return pair.Lower()
}

// Equal compares two currency pairs and returns whether or not they are equal
func (c CurrencyPair) Equal(p CurrencyPair, exact bool) bool {
	if !exact {
		if c.FirstCurrency.Upper() == p.FirstCurrency.Upper() &&
			c.SecondCurrency.Upper() == p.SecondCurrency.Upper() ||
			c.FirstCurrency.Upper() == p.SecondCurrency.Upper() &&
				c.SecondCurrency.Upper() == p.FirstCurrency.Upper() {
			return true
		}
	} else {
		if c.FirstCurrency.Upper() == p.FirstCurrency.Upper() &&
			c.SecondCurrency.Upper() == p.SecondCurrency.Upper() {
			return true
		}
	}
	return false
}

// Swap swaps the pairs first and second currencies
func (c CurrencyPair) Swap() CurrencyPair {
	p := c
	p.FirstCurrency = c.SecondCurrency
	p.SecondCurrency = c.FirstCurrency
	return p
}

// NewCurrencyPairDelimiter splits the desired currency string at delimeter,
// the returns a CurrencyPair struct
func NewCurrencyPairDelimiter(currency, delimiter string) CurrencyPair {
	result := strings.Split(currency, delimiter)
	return CurrencyPair{
		Delimiter:      delimiter,
		FirstCurrency:  CurrencyItem(result[0]),
		SecondCurrency: CurrencyItem(result[1]),
	}
}

// NewCurrencyPair returns a CurrencyPair without a delimiter
func NewCurrencyPair(firstCurrency, secondCurrency string) CurrencyPair {
	return CurrencyPair{
		FirstCurrency:  CurrencyItem(firstCurrency),
		SecondCurrency: CurrencyItem(secondCurrency),
	}
}

// NewCurrencyPairFromIndex returns a CurrencyPair via a currency string and
// specific index
func NewCurrencyPairFromIndex(currency, index string) CurrencyPair {
	i := strings.Index(currency, index)
	if i == 0 {
		return NewCurrencyPair(currency[0:len(index)], currency[len(index):])
	}
	return NewCurrencyPair(currency[0:i], currency[i:])
}

// NewCurrencyPairFromString converts currency string into a new CurrencyPair
// with or without delimeter
func NewCurrencyPairFromString(currency string) CurrencyPair {
	delimiters := []string{"_", "-"}
	var delimiter string
	for _, x := range delimiters {
		if strings.Contains(currency, x) {
			delimiter = x
			return NewCurrencyPairDelimiter(currency, delimiter)
		}
	}
	return NewCurrencyPair(currency[0:3], currency[3:])
}

// Contains checks to see if a specified pair exists inside a currency pair
// array
func Contains(pairs []CurrencyPair, p CurrencyPair, exact bool) bool {
	for x := range pairs {
		if pairs[x].Equal(p, exact) {
			return true
		}
	}
	return false
}

// ContainsCurrency checks to see if a pair contains a specific currency
func ContainsCurrency(p CurrencyPair, c string) bool {
	return p.FirstCurrency.Upper().String() == common.StringToUpper(c) ||
		p.SecondCurrency.Upper().String() == common.StringToUpper(c)
}

// RemovePairsByFilter checks to see if a pair contains a specific currency
// and removes it from the list of pairs
func RemovePairsByFilter(p []CurrencyPair, filter string) []CurrencyPair {
	var pairs []CurrencyPair
	for x := range p {
		if ContainsCurrency(p[x], filter) {
			continue
		}
		pairs = append(pairs, p[x])
	}
	return pairs
}

// FormatPairs formats a string array to a list of currency pairs with the
// supplied currency pair format
func FormatPairs(pairs []string, delimiter, index string) []CurrencyPair {
	var result []CurrencyPair
	for x := range pairs {
		if pairs[x] == "" {
			continue
		}
		var p CurrencyPair
		if delimiter != "" {
			p = NewCurrencyPairDelimiter(pairs[x], delimiter)
		} else {
			if index != "" {
				p = NewCurrencyPairFromIndex(pairs[x], index)
			} else {
				p = NewCurrencyPair(pairs[x][0:3], pairs[x][3:])
			}
		}
		result = append(result, p)
	}
	return result
}

// CopyPairFormat copies the pair format from a list of pairs once matched
func CopyPairFormat(p CurrencyPair, pairs []CurrencyPair, exact bool) CurrencyPair {
	for x := range pairs {
		if p.Equal(pairs[x], exact) {
			return pairs[x]
		}
	}
	return CurrencyPair{}
}

// FindPairDifferences returns pairs which are new or have been removed
func FindPairDifferences(oldPairs, newPairs []string) ([]string, []string) {
	var newPs, removedPs []string
	for x := range newPairs {
		if newPairs[x] == "" {
			continue
		}
		if !common.StringDataCompareUpper(oldPairs, newPairs[x]) {
			newPs = append(newPs, newPairs[x])
		}
	}
	for x := range oldPairs {
		if oldPairs[x] == "" {
			continue
		}
		if !common.StringDataCompareUpper(newPairs, oldPairs[x]) {
			removedPs = append(removedPs, oldPairs[x])
		}
	}
	return newPs, removedPs
}


text:
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * WooThemes Updater - Single Updater Class
 *
 * The WooThemes Updater - updater class.
 *
 * @package WordPress
 * @subpackage WooThemes Updater
 * @category Core
 * @author WooThemes
 * @since 1.0.0
 *
 * TABLE OF CONTENTS
 *
 * private $file
 * private $api_url
 * private $product_key
 * private $license_hash
 *
 * - __construct()
 * - update_check()
 * - plugin_information()
 * - request()
 */
class WooThemes_Updater_Update_Checker {
	protected $file;
	protected $api_url;
	protected $product_id;
	protected $file_id;
	protected $license_hash;

	/**
	 * Constructor.
	 *
	 * @access public
	 * @since  1.0.0
	 * @return void
	 */
	public function __construct ( $file, $product_id, $file_id, $license_hash = '' ) {
		$this->api_url = 'http://www.woothemes.com/?wc-api=woothemes-installer-api&';
		$this->file = $file;
		$this->product_id = $product_id;
		$this->file_id = $file_id;
		$this->license_hash = $license_hash;
		$this->init();
	} // End __construct()

	/**
	 * Initialise the update check process.
	 * @access  public
	 * @since   1.2.0
	 * @return  void
	 */
	public function init () {
		// Check For Updates
		add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'update_check' ) );

		// Check For Plugin Information
		add_filter( 'plugins_api', array( $this, 'plugin_information' ), 10, 3 );
	} // End init()

	/**
	 * Check for updates against the remote server.
	 *
	 * @access public
	 * @since  1.0.0
	 * @param  object $transient
	 * @return object $transient
	 */
	public function update_check ( $transient ) {

	    // Check if the transient contains the 'checked' information
	    // If no, just return its value without hacking it
	    if( empty( $transient->checked ) )
	        return $transient;

	    // The transient contains the 'checked' information
	    // Now append to it information form your own API
	    $args = array(
	        'request' => 'pluginupdatecheck',
	        'plugin_name' => $this->file,
	        'version' => $transient->checked[$this->file],
	        'product_id' => $this->product_id,
	        'file_id' => $this->file_id,
	        'license_hash' => $this->license_hash,
	        'url' => esc_url( home_url( '/' ) )
	    );

	    // Send request checking for an update
	    $response = $this->request( $args );

	    // If response is false, don't alter the transient
	    if( false !== $response ) {

	    	if( isset( $response->errors ) && isset ( $response->errors->woo_updater_api_license_deactivated ) ){

	    		add_action('admin_notices', array( $this, 'error_notice_for_deactivated_plugin') );

	    	}else{

	        	$transient->response[$this->file] = $response;

	        }

	    }

	    return $transient;
	} // End update_check()

	/**
	 * Display an error notice
	 * @param  strin $message The message
	 * @return void
	 */
	public function error_notice_for_deactivated_plugin( $message ) {

		$plugins = get_plugins();

		$plugin_name = isset( $plugins[$this->file] ) ? $plugins[$this->file]['Name'] : $this->file;

		echo sprintf( '

The license for the plugin %s has been deactivated. You can reactivate the license on your dashboard.

', $plugin_name ) ;

	}
	/**
	 * Check for the plugin's data against the remote server.
	 *
	 * @access public
	 * @since  1.0.0
	 * @return object $response
	 */
	public function plugin_information ( $false, $action, $args ) {
		$transient = get_site_transient( 'update_plugins' );

		// Check if this plugins API is about this plugin
		if( ! isset( $args->slug ) || ( $args->slug != $this->file ) ) {
			return $false;
		}

		// POST data to send to your API
		$args = array(
			'request' => 'plugininformation',
			'plugin_name' => $this->file,
			'version' => $transient->checked[$this->file],
			'product_id' => $this->product_id,
			'file_id' => $this->file_id,
	        'license_hash' => $this->license_hash,
	        'url' => esc_url( home_url( '/' ) )
		);

		// Send request for detailed information
		$response = $this->request( $args );

		$response->sections = (array)$response->sections;
		$response->compatibility = (array)$response->compatibility;
		$response->tags = (array)$response->tags;
		$response->contributors = (array)$response->contributors;

		if ( count( $response->compatibility ) > 0 ) {
			foreach ( $response->compatibility as $k => $v ) {
				$response->compatibility[$k] = (array)$v;
			}
		}

		return $response;
	} // End plugin_information()

	/**
	 * Generic request helper.
	 *
	 * @access protected
	 * @since  1.0.0
	 * @param  array $args
	 * @return object $response or boolean false
	 */
	protected function request ( $args ) {
	    // Send request
	    $request = wp_remote_post( $this->api_url, array(
			'method' => 'POST',
			'timeout' => 45,
			'redirection' => 5,
			'httpversion' => '1.0',
			'blocking' => true,
			'headers' => array( 'user-agent' => 'WooThemesUpdater/1.2.2' ),
			'body' => $args,
			'cookies' => array(),
			'sslverify' => false
		    ) );
	    // Make sure the request was successful
	    if( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) {
	        // Request failed
	        return false;
	    }
	    // Read server response, which should be an object
	    if ( $request != '' ) {
	    	$response = json_decode( wp_remote_retrieve_body( $request ) );
	    } else {
	    	$response = false;
	    }

	    if( is_object( $response ) && isset( $response->payload ) ) {
	        return $response->payload;
	    } else {
	        // Unexpected response
	        return false;
	    }
	} // End request()
} // End Class
?>


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid href: host-u0000-percent-encoded-percent-encoded</title>
<link href="http://%ef%bc%85%ef%bc%90%ef%bc%90.com" rel=help>


text:
package server.world.tile;

public enum TileType {

	GRASS, STONE(true);

	private boolean solid;

	private TileType() {
		solid = false;
	}

	private TileType(boolean solid) {
		this.solid = solid;
	}

	public boolean isSolid() {
		return solid;
	}

}


text:
import { BorderBox, Box, Join, Spacer } from "@artsy/palette"
import { ArtistMarketInsights_artist$data } from "__generated__/ArtistMarketInsights_artist.graphql"
import { Component } from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { ArtworkDefinitionList } from "Apps/Artwork/Components/ArtworkDefinitionList"
import { groupBy } from "lodash"

export interface MarketInsightsProps {
  artist: ArtistMarketInsights_artist$data
  border?: boolean
  Container?: (props: { children: JSX.Element }) => JSX.Element
}

export const CATEGORIES = {
  "blue-chip": "Blue-chip",
  "top-established": "Established",
  "top-emerging": "Emerging",
}
const CATEGORY_LABEL_MAP = {
  "blue-chip": "Represented by internationally recognized galleries.",
  "top-established": "Represented by industry leading galleries.",
  "top-emerging": "Represented by up-and-coming galleries.",
}

export class MarketInsights extends Component<MarketInsightsProps> {
  static defaultProps = {
    border: true,
  }

  renderAuctionHighlight() {
    if (
      !this.props.artist.auctionResultsConnection ||
      (this.props.artist.auctionResultsConnection.edges?.length ?? 0) < 1
    ) {
      return null
    }

    const topAuctionResult =
      this.props.artist.auctionResultsConnection?.edges !== null
        ? this.props.artist.auctionResultsConnection.edges[0]?.node
        : null

    const display = [
      topAuctionResult?.price_realized?.display,
      topAuctionResult?.organization,
      topAuctionResult?.sale_date,
    ]
      .filter(Boolean)
      .join(", ")

    return (
      <ArtworkDefinitionList term="High auction record">
        {display}
      </ArtworkDefinitionList>
    )
  }
  renderGalleryRepresentation() {
    const { highlights } = this.props.artist
    const partnersConnection = highlights?.partnersConnection

    if (partnersConnection && (partnersConnection?.edges?.length ?? 0) > 0) {
      const highCategory = highestCategory(partnersConnection.edges)

      return (
        <ArtworkDefinitionList term={CATEGORIES[highCategory]}>
          {CATEGORY_LABEL_MAP[highCategory]}
        </ArtworkDefinitionList>
      )
    }
  }
  renderPermanentCollection() {
    const { collections } = this.props.artist

    if (!collections || collections.length === 0) {
      return null
    }

    const label =
      collections.length === 1
        ? "Collected by a major museum"
        : "Collected by major museums"

    return (
      <ArtworkDefinitionList term={label}>
        {collections.join(", ")}
      </ArtworkDefinitionList>
    )
  }

  render() {
    // @ts-expect-error PLEASE_FIX_ME_STRICT_NULL_CHECK_MIGRATION
    if (!hasSections(this.props.artist)) {
      return null
    }

    let Container

    if (this.props.Container) {
      Container = this.props.Container
    } else if (this.props.border) {
      Container = BorderBox
    } else {
      Container = Box
    }

    return (
      <>
        <Container flexDirection="column">
          <div>
            <Join separator={<Spacer mt={1} />}>
              {this.renderAuctionHighlight()}
              {this.renderGalleryRepresentation()}
              {this.renderPermanentCollection()}
            </Join>
          </div>
        </Container>

        {this.props.children}
      </>
    )
  }
}

export const ArtistMarketInsightsFragmentContainer = createFragmentContainer(
  MarketInsights,
  {
    artist: graphql`
      fragment ArtistMarketInsights_artist on Artist
        @argumentDefinitions(
          partnerCategory: {
            type: "[String]"
            defaultValue: ["blue-chip", "top-established", "top-emerging"]
          }
        ) {
        collections
        highlights {
          partnersConnection(
            first: 10
            displayOnPartnerProfile: true
            representedBy: true
            partnerCategory: $partnerCategory
          ) {
            edges {
              node {
                categories {
                  slug
                }
              }
            }
          }
        }
        auctionResultsConnection(
          recordsTrusted: true
          first: 1
          sort: PRICE_AND_DATE_DESC
        ) {
          edges {
            node {
              price_realized: priceRealized {
                display(format: "0.0a")
              }
              organization
              sale_date: saleDate(format: "YYYY")
            }
          }
        }
      }
    `,
  }
)

export const hasSections = ({
  highlights,
  auctionResults,
  collections,
}: {
  highlights: { partnersConnection?: { edges: ReadonlyArray<any> } }
  auctionResults?: { edges: ReadonlyArray<any> }
  collections?: ReadonlyArray<any>
}) => {
  const { partnersConnection } = highlights

  // Is there a gallery representation section?
  if (
    partnersConnection &&
    partnersConnection.edges &&
    partnersConnection.edges.length > 0
  ) {
    return true
  }

  // Is there an auction highlights section?
  if (
    auctionResults &&
    auctionResults.edges &&
    auctionResults.edges.length > 0
  ) {
    return true
  }

  // Is there a permanent collections section?
  if (collections && collections.length > 0) {
    return true
  }

  return false
}

const orderedCategories = ["blue-chip", "top-established", "top-emerging"]

export const highestCategory = edges => {
  const groups = groupedByCategories(edges)
  return orderedCategories.filter(
    category => groups[category] && groups[category].length > 0
  )[0]
}

const groupedByCategories = edges => {
  return groupBy(edges, ({ node: partner }) => {
    let category
    Object.keys(CATEGORIES).forEach(key => {
      partner.categories.forEach(partnerCategory => {
        if (partnerCategory.slug === key) {
          category = key
        }
      })
    })
    return category
  })
}


text:
package com.intellij.openapi.externalSystem.action.task;

import com.intellij.execution.RunManager;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.externalSystem.action.ExternalSystemActionUtil;
import com.intellij.openapi.externalSystem.action.ExternalSystemNodeAction;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo;
import com.intellij.openapi.externalSystem.model.task.TaskData;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

/**
 * @author Vladislav.Soroka
 */
public class RunExternalSystemTaskAction extends ExternalSystemNodeAction<TaskData> {

  public RunExternalSystemTaskAction() {
    super(TaskData.class);
  }

  @Override
  protected void perform(@NotNull Project project,
                         @NotNull ProjectSystemId projectSystemId,
                         @NotNull TaskData taskData,
                         @NotNull AnActionEvent e) {
    final ExternalTaskExecutionInfo taskExecutionInfo = ExternalSystemActionUtil.buildTaskInfo(taskData);
    ExternalSystemUtil.runTask(taskExecutionInfo.getSettings(), taskExecutionInfo.getExecutorId(), project, projectSystemId);

    final DataContext dataContext = e.getDataContext();
    final ConfigurationContext context = ConfigurationContext.getFromContext(dataContext);
    RunnerAndConfigurationSettings configuration = context.findExisting();
    RunManager runManager = context.getRunManager();
    if (configuration == null) {
      configuration = context.getConfiguration();
      if (configuration == null) {
        return;
      }
      runManager.setTemporaryConfiguration(configuration);
    }
    runManager.setSelectedConfiguration(configuration);
  }
}


text:
bool _state_config = false;
uint8_t _sleep_period = DEFAULT_SLEEP_MINS;

#define DEBUG true

// we use this to determine the minimum period between publish messages.
// This is so that if we're "always on" then we won't keep spamming the MQTT
// server with messages
#define MIN_PUBLISH_PERIOD (5 * 60 * 1000) // 5mins default

unsigned long _lastpublish = 0;
unsigned long _nextpublish = 0;

Peripheral * _vcc_sensor;
Peripheral * _device_peripheral;

MODES _mode = NONE;

void setup_node_peripherals(ESP_MQTTLogger& l) {
    // here we take the mode and we set up the sensors we're going to be using.

#ifdef DEBUG
    Serial.println("Setting up node peripherals");
    Serial.print("Defined MODE is: ");
    Serial.println(_mode);
#endif

    _vcc_sensor = new NoPeripheral();
    _vcc_sensor->begin(l);

    // choose which mode we're in and set up peripheral appropriately.
    switch (_mode) {

        case NONE:
            break;

        case TEMP_1WIRE:
            _device_peripheral = new TempPeripheral();
            break;

        case BARO:
            _device_peripheral = new BaroPeripheral();
            break;

        case DHT:
            _device_peripheral = new DHTPeripheral();
            break;

        case SERVO:
            _device_peripheral = new ServoPeripheral();
            break;

		case PIXEL:
            _device_peripheral = new PixelPeripheral();
            break;

        case LED:
            _device_peripheral = new LedPeripheral();
            break;
    }

    if (_mode > NONE) {
        _device_peripheral->begin(l);
    }

    // As this is only called from the .ino initialiser we set this true
    // here as it is possible that a set mode message has not arrived in time
    // and we land in a race condition with the network. As such in setting this
    // we explicitly state that our config is complete and if a mode change
    // occurs after this point then we'll handle it as though it were a "live"
    // mode change against the node
    _state_config = true;
}

void publish_peripheral_data() {
    // publish whatever the peripherals are.

    // do a check on timing for publish
    // we do a zero val check here to get a publish on wakeup.
    if (millis() > _nextpublish) {
#ifdef DEBUG
        Serial.println("Publishing peripheral data");
#endif

        _vcc_sensor->publish_data();

        if (_mode > NONE) {
            _device_peripheral->publish_data();
        }
        _lastpublish = millis();
        _nextpublish = _lastpublish + MIN_PUBLISH_PERIOD;
    } else {
        ;
    }
}

void update_peripheral() {
    // we use this to update the peripherals state if we are able to.

    if (_mode > NONE) {
        if (_device_peripheral->updatable() ) {
            _device_peripheral->update();
        }
    }
}

void subscription_handler(char* topic, byte* payload, unsigned int length) {

    // handles the things around any subscription messages
    //
    String t = (String)topic;

    // grab the data from the payload and get it in a form we can use it.
    char buf[length + 1];
    for (int i = 0; i < length; i++) {
        buf[i] = (char)payload[i];
    }
    buf[length] = '\0';
    String p = String(buf);

#ifdef DEBUG
    Serial.print("Topic: ");
    Serial.print(t);
    Serial.print(" Payload: ");
    Serial.println(p);
#endif

    // handle the message
    if (t.endsWith("sleep")) {
        set_sleep_time(p.toInt());
    } else if (t.endsWith("mode")) {
        set_mode(p);
    } else {
        // it's not a config message so pass it out to the peripheral
        if (_mode > NONE) {
            _device_peripheral->sub_handler(t, p);
        }
    }
}

bool state_configured() {
    return _state_config;
}

uint8_t get_sleep_time() {

    return _sleep_period;
}

void set_sleep_time(uint8_t sleep) {
    // here we set how long the system should hibernate for

    _sleep_period = sleep;
    // TODO Write to the file system.
}

MODES get_mode() {
    return _mode;
}

void set_mode(String modename) {

    MODES oldmode = _mode;

    if (modename == "1wiretemp") {
        _mode = TEMP_1WIRE;
    } else if (modename == "baro") {
        _mode = BARO;
    } else if (modename == "dht") {
        _mode = DHT;
    } else if (modename == "servo") {
        _mode = SERVO;
    } else if (modename == "pixel") {
        _mode = PIXEL;
    } else if (modename == "led") {
        _mode = LED;
    } else {
        _mode = NONE;
    }

    if (oldmode == _mode) {
        return; // nothing to see here
    }

    if (! _state_config) {
        _state_config = true;
    } else {
        // DEAL WITH A MODE CHANGE
        // The best thing to do here is actually trigger a
        // deep sleep reset as it will come back up in the different
        // mode with all the appropriate objects set up etc.
        #ifdef LIGHT_SLEEP
        Serial.println(F("Mode reconfigure"));
        #else
        Serial.println(F("Mode reconfigure. Reset 1 sec"));
        ESP.deepSleep(1 * 1000l * 1000l);
        #endif
    }

}
bool save_config(String filename, String value) {
    // takes a filename and a string and writes it down.
    File configFile = SPIFFS.open(filename, "w");

    if (!configFile) {
        Serial.println("Error saving to file system");
        return false;
    }

    configFile.print(value);
    return true;
}

String load_config(String filename) {
    // loads a file and returns its contents

    File configFile = SPIFFS.open(filename, "r");

    if (configFile) {
        return configFile.readString();
    }

    Serial.println("Error reading from file");
    return "";
}