text:
<!DOCTYPE html>

    <title>Bluejay Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

 Docs (44% documented)

         Reference

        Bluejay Class Reference

            Classes

                Bluejay

                Peripheral

                SynchronizedPeripheral

            Enums

                BackgroundRestoreMode

                ConnectionResult

                DisconnectionResult

                DiscoveryResult

                ListenAction

                ReadResult

                RunResult

                ScanAction

                WriteResult

            Extensions

                CBManagerState

                CBPeripheral

                CBPeripheralState

                CBService

                Data

                Integer

                Notification

                String

            Protocols

                ConnectionObserver

                ListenRestorer

                RSSIObserver

                Receivable

                Sendable

            Structs

                CharacteristicIdentifier

                DataPadding

                PeripheralIdentifier

                ScanDiscovery

                ServiceIdentifier

Bluejay

public class Bluejay: NSObject

Bluejay is a simple wrapper around CoreBluetooth that focuses on making a common usage case as straight forward as possible: a single connected peripheral that the user is interacting with regularly (think most personal electronics devices that have an associated iOS app: fitness trackers, guitar amps, etc).

It also supports a few other niceties for simplifying usage, including automatic discovery of services and characteristics as they are used, as well as supporting a background task mode where the interaction with the device can be written as synchronous calls running on a background thread to avoid callback pyramids of death, or heavily chained promises.

Public Properties

                    uuid

Helps distinguish one Bluejay instance from another.

Declaration

Swift

public var uuid = UUID()

                    isBluetoothAvailable

Allows checking whether Bluetooth is powered on.

Declaration

Swift

public var isBluetoothAvailable: Bool

                    isConnecting

Allows checking whether Bluejay is currently connecting to a peripheral.

Declaration

Swift

public var isConnecting: Bool

                    isConnected

Allows checking whether Bluejay is currently connected to a peripheral.

Declaration

Swift

public var isConnected: Bool

                    isDisconnecting

Allows checking whether Bluejay is currently disconnecting from a peripheral.

Declaration

Swift

public var isDisconnecting: Bool = false

                    isScanning

Allows checking whether Bluejay is currently scanning.

Declaration

Swift

public var isScanning: Bool

Initialization

                    init()

Initializing a Bluejay instance will not yet initialize the CoreBluetooth stack. An explicit call to start running a Bluejay instance after it is intialized is required because in cases where a state resotration is trying to restore a listen on a characteristic, a listen restorer must be available before the CoreBluetooth stack is re-initialized. This two-step startup allows you to insert and gaurantee the setup of your listen restorer in between the initialization of Bluejay and the initialization of the CoreBluetooth stack triggered via this call.

Declaration

Swift

public override init()

                    start(connectionObserver:backgroundRestore:)

Starting Bluejay will initialize the CoreBluetooth stack. Initializing a Bluejay instance will not yet initialize the CoreBluetooth stack. An explicit call to start running a Bluejay instance after it is intialized is required because in cases where a state resotration is trying to restore a listen on a characteristic, a listen restorer must be available before the CoreBluetooth stack is re-initialized. This two-step startup allows you to insert and gaurantee the setup of your listen restorer in between the initialization of Bluejay and the initialization of the CoreBluetooth stack triggered via this call.

Declaration

Swift

public func start(
        connectionObserver observer: ConnectionObserver? = nil,
        backgroundRestore restoreMode: BackgroundRestoreMode = .disable
        )

Parameters

                                observer

An object interested in observing Bluetooth connection events and state changes. You can register more observers using the register function.

                                restoreMode

Determines whether Bluejay will opt-in to state restoration, and if so, can optionally provide a listen restorer as well for restoring listens.

                    cancelEverything(_:)

This will cancel the current and all pending operations in the Bluejay queue, as well as stop any ongoing scan, and disconnect any connected peripheral.

Declaration

Swift

public func cancelEverything(_ error: NSError? = nil)

Parameters

                                error

If nil, all tasks in the queue will be cancelled without any errors. If an error is provided, all tasks in the queue will be failed with the supplied error.

Events Registration

                    register(observer:)

Register for notifications on Bluetooth connection events and state changes. Unregistering is not required, Bluejay will unregister for you if the observer is no longer in memory.

Declaration

Swift

public func register(observer: ConnectionObserver)

Parameters

                                observer

                    unregister(observer:)

Unregister for notifications on Bluetooth connection events and state changes. Unregistering is not required, Bluejay will unregister for you if the observer is no longer in memory.

Declaration

Swift

public func unregister(observer: ConnectionObserver)

Parameters

                                observer

Scanning

                    scan(duration:allowDuplicates:serviceIdentifiers:discovery:expired:stopped:)

Scan for the peripheral(s) specified.

Declaration

Swift

public func scan(
        duration: TimeInterval = 0,
        allowDuplicates: Bool = false,
        serviceIdentifiers: [ServiceIdentifier]?,
        discovery: @escaping (ScanDiscovery, [ScanDiscovery]) -> ScanAction,
        expired: ((ScanDiscovery, [ScanDiscovery]) -> ScanAction)? = nil,
        stopped: @escaping ([ScanDiscovery], Swift.Error?) -> Void
        )

Parameters

                                duration

Stops the scan when the duration in seconds is reached. Defaults to zero (indefinite).

                                allowDuplicates

Determines whether a previously scanned peripheral is allowed to be discovered again.

                                serviceIdentifiers

Specifies what visible services the peripherals must have in order to be discovered.

                                discovery

Called whenever a specified peripheral has been discovered.

                                expired

Called whenever a previously discovered peripheral has not been seen again for a while, and Bluejay is predicting that it may no longer be in range. (Only for a scan with allowDuplicates enabled)

                                stopped

Called when the scan is finished and provides an error if there is any.

                    stopScanning()

Stops an ongoing scan if there is one, otherwise it does nothing.

Declaration

Swift

public func stopScanning()

Connection

                    connect(_:completion:)

Attempt to connect directly to a known peripheral. The call will fail if Bluetooth is not available, or if Bluejay is already connected. Making a connection request while Bluejay is scanning will also cause Bluejay to stop the current scan for you behind the scene prior to fulfilling your connection request.

Declaration

Swift

public func connect(_ peripheralIdentifier: PeripheralIdentifier, completion: @escaping (ConnectionResult) -> Void)

Parameters

                                peripheralIdentifier

The peripheral to connect to.

                                completion

Called when the connection request has fully finished and indicates whether it was successful, cancelled, or failed.

                    disconnect(completion:)

Disconnect the currently connected peripheral. Providing a completion block is not necessary, but useful in most cases.

Declaration

Swift

public func disconnect(completion: ((DisconnectionResult) -> Void)? = nil)

Parameters

                                completion

Called when the disconnection request has fully finished and indicates whether it was successful, cancelled, or failed.

Actions

                    read(from:completion:)

Read from the specified characteristic.

Declaration

Swift

public func read<R: Receivable>(from characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void)

Parameters

                                characteristicIdentifier

The characteristic to read from.

                                completion

Called with the result of the attempt to read from the specified characteristic.

                    write(to:value:completion:)

Write to the specified characteristic.

Declaration

Swift

public func write<S: Sendable>(to characteristicIdentifier: CharacteristicIdentifier, value: S, completion: @escaping (WriteResult) -> Void)

Parameters

                                characteristicIdentifier

The characteristic to write to.

                                completion

Called with the result of the attempt to write to the specified characteristic.

                    listen(to:completion:)

Listen for notifications on the specified characteristic.

Declaration

Swift

public func listen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void)

Parameters

                                characteristicIdentifier

The characteristic to listen to.

                                completion

Called with the result of the attempt to listen for notifications on the specified characteristic.

                    endListen(to:completion:)

End listening on the specified characteristic.

Declaration

Swift

public func endListen(to characteristicIdentifier: CharacteristicIdentifier, completion: ((WriteResult) -> Void)? = nil)

Parameters

                                characteristicIdentifier

The characteristic to stop listening to.

                                completion

Called with the result of the attempt to stop listening to the specified characteristic.

                    restoreListen(to:completion:)

Restore a (believed to be) active listening session, so if we start up in response to a notification, we can receive it.

Declaration

Swift

public func restoreListen<R: Receivable>(to characteristicIdentifier: CharacteristicIdentifier, completion: @escaping (ReadResult<R>) -> Void)

Parameters

                                characteristicIdentifier

The characteristic that needs the restoration.

                                completion

Called with the result of the attempt to restore the listen on the specified characteristic.

Background Task

                    run(backgroundTask:completionOnMainThread:)

One of the three ways to run a background task using a synchronous interface to the Bluetooth peripheral. This is the simplest one as the background task will not return any typed values back to the completion block on finishing the background task, except for thrown errors, and it also doesn’t provide an input for an object that might need thread safe access.

Warning

Be careful not to access anything that is not thread safe inside background task.

Declaration

Swift

public func run(
        backgroundTask: @escaping (SynchronizedPeripheral) throws -> Void,
        completionOnMainThread: @escaping (RunResult<Void>) -> Void)

Parameters

                                backgroundTask

A closure with the jobs to be executed in the background.

                                completionOnMainThread

A closure called on the main thread when the background task has either completed or failed.

                    run(backgroundTask:completionOnMainThread:)

One of the three ways to run a background task using a synchronous interface to the Bluetooth peripheral. This one allows the background task to potentially return a typed value back to the completion block on finishing the background task successfully.

Warning

Be careful not to access anything that is not thread safe inside background task.

Declaration

Swift

public func run<Result>(
        backgroundTask: @escaping (SynchronizedPeripheral) throws -> Result,
        completionOnMainThread: @escaping (RunResult<Result>) -> Void)

Parameters

                                backgroundTask

A closure with the jobs to be executed in the background.

                                completionOnMainThread

A closure called on the main thread when the background task has either completed or failed.

                    run(userData:backgroundTask:completionOnMainThread:)

One of the three ways to run a background task using a synchronous interface to the Bluetooth peripheral. This one allows the background task to potentially return a typed value back to the completion block on finishing the background task successfully, as well as supplying an object for thread safe access inside the background task.

Warning

Be careful not to access anything that is not thread safe inside background task.

Declaration

Swift

public func run<UserData, Result>(
        userData: UserData,
        backgroundTask: @escaping (SynchronizedPeripheral, UserData) throws -> Result,
        completionOnMainThread: @escaping (RunResult<Result>) -> Void)

Parameters

                                userData

Any object you wish to have thread safe access inside background task.

                                backgroundTask

A closure with the jobs to be executed in the background.

                                completionOnMainThread

A closure called on the main thread when the background task has either completed or failed.

Helpers

                    combine(sendables:)

A helper function to take an array of Sendables and combine their data together.

Declaration

Swift

public static func combine(sendables: [Sendable]) -> Data

Parameters

                                sendables

An array of Sendables whose Data should be appended in the order of the given array.

Return Value

The resulting data of all the Sendables combined in the order of the passed in array.

                    centralManagerDidUpdateState(_:)

Undocumented

Declaration

Swift

public class Bluejay: NSObject

                    centralManager(_:willRestoreState:)

Undocumented

Declaration

Swift

public class Bluejay: NSObject

                    centralManager(_:didConnect:)

Undocumented

Declaration

Swift

public class Bluejay: NSObject

                    centralManager(_:didDisconnectPeripheral:error:)

Undocumented

Declaration

Swift

public class Bluejay: NSObject

                    centralManager(_:didFailToConnect:error:)

Undocumented

Declaration

Swift

public class Bluejay: NSObject

                    centralManager(_:didDiscover:advertisementData:rssi:)

Undocumented

Declaration

Swift

public class Bluejay: NSObject

© 2017 . All rights reserved. (Last updated: 2017-06-02)

Generated by jazzy ♪♫ v0.8.2, a Realm project.


text:
package net.runelite.client.plugins.music;

import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;

@ConfigGroup(MusicConfig.GROUP)
public interface MusicConfig extends Config
{
	String GROUP = "music";
	String GRANULAR_SLIDERS = "granularSliders";
	String MUTE_AMBIENT_SOUNDS = "muteAmbientSounds";

	@ConfigItem(
		keyName = "muteOwnAreaSounds",
		name = "Mute player area sounds",
		description = "Mute area sounds caused by yourself",
		position = 0
	)
	default boolean muteOwnAreaSounds()
	{
		return false;
	}

	@ConfigItem(
		keyName = "muteOtherAreaSounds",
		name = "Mute other players' area sounds",
		description = "Mute area sounds caused by other players",
		position = 1
	)
	default boolean muteOtherAreaSounds()
	{
		return false;
	}

	@ConfigItem(
		keyName = "muteOtherAreaNPCSounds",
		name = "Mute NPCs' area sounds",
		description = "Mute area sounds caused by NPCs",
		position = 2
	)
	default boolean muteNpcAreaSounds()
	{
		return false;
	}

	@ConfigItem(
		keyName = "muteOtherAreaEnvironmentSounds",
		name = "Mute environment area sounds",
		description = "Mute area sounds caused by neither NPCs nor players",
		position = 3
	)
	default boolean muteEnvironmentAreaSounds()
	{
		return false;
	}

	@ConfigItem(
		keyName = MUTE_AMBIENT_SOUNDS,
		name = "Mute ambient sounds",
		description = "Mute background noise such as magic trees and furnaces",
		position = 4
	)
	default boolean muteAmbientSounds()
	{
		return false;
	}

	@ConfigItem(
		keyName = "mutePrayerSounds",
		name = "Mute prayer sounds",
		description = "Mute prayer activation and deactivation sounds",
		position = 5
	)
	default boolean mutePrayerSounds()
	{
		return false;
	}

	@ConfigItem(
		keyName = GRANULAR_SLIDERS,
		name = "Granular volume sliders",
		description = "Make the volume sliders allow better control of volume",
		position = 6
	)
	default boolean granularSliders()
	{
		return true;
	}

	@ConfigItem(
		keyName = "musicVolume",
		name = "",
		description = "",
		hidden = true
	)
	default int getMusicVolume()
	{
		return 0;
	}

	@ConfigItem(
		keyName = "musicVolume",
		name = "",
		description = "",
		hidden = true
	)
	void setMusicVolume(int vol);

	@ConfigItem(
		keyName = "soundEffectVolume",
		name = "",
		description = "",
		hidden = true
	)
	default int getSoundEffectVolume()
	{
		return 0;
	}

	@ConfigItem(
		keyName = "soundEffectVolume",
		name = "",
		description = "",
		hidden = true
	)
	void setSoundEffectVolume(int val);

	@ConfigItem(
		keyName = "areaSoundEffectVolume",
		name = "",
		description = "",
		hidden = true
	)
	default int getAreaSoundEffectVolume()
	{
		return 0;
	}

	@ConfigItem(
		keyName = "areaSoundEffectVolume",
		name = "",
		description = "",
		hidden = true
	)
	void setAreaSoundEffectVolume(int vol);
}

redpajama_set_name: RedPajamaGithub


text:
'''
Created by: Tyler Linne
Coded in part as a Treehouse Project
Date: 4-20-16
'''

import random

from combat import Combat

COLORS = ['yellow', 'red', 'blue', 'green']

class Monster(Combat):
  min_hit_points = 1
  max_hit_points = 1
  min_experience = 1
  max_experience = 1
  weapon = 'sword'
  sound = 'roar'

  def __init__(self, **kwargs):
    self.hit_points = random.randint(self.min_hit_points, self.max_hit_points)
    self.experience = random.randint(self.min_experience, self.max_experience)
    self.color = random.choice(COLORS)

    for key, value in kwargs.items():
      setattr(self, key, value)

  def __str__(self):
    return '{} {}, HP: {}, XP: {}'.format(self.color.title(),
                                          self.__class__.__name__,
                                          self.hit_points,
                                          self.experience)

  def battlecry(self):
    return self.sound.upper()

class Goblin(Monster):
  max_hit_points = 3
  max_experience = 2
  sound = 'squeak'

class Troll(Monster):
  min_hit_points = 3
  max_hit_points = 5
  min_experience = 2
  max_experience = 6
  sound = 'growl'

class Dragon(Monster):
  min_hit_points = 5
  max_hit_points = 10
  min_experience = 6
  max_experience = 10
  sound = 'raaaaaaaaaaar'


text:
//
//  APCalendarCondition.h
//  APOperations
//
//  Created by Alex Perez on 11/4/15.
//  Copyright © 2015 Alex Perez. All rights reserved.
//

@import Foundation;
@import EventKit;

#import "APOperationCondition.h"

/*!
 * @class APCalendarCondition
 * @abstract A condition for verifying access to the user's calendar
 */
@interface APCalendarCondition : NSObject <APOperationCondition>

@property (nonatomic, readonly) EKEntityType entityType;

- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithEntityType:(EKEntityType)entityType NS_DESIGNATED_INITIALIZER;

@end


text:
<configuration xmlns="http://logging.apache.org/log4php/">
    <appender name="custom" class="LoggerAppenderDailyFile">
        <param name="file" value="./logs/daily-%s.log"/>
        <param name="DatePattern" value="Y-m-d"/>
        <layout class="LoggerLayoutPattern">
            <parm name="conversionPattern" value="[%t] %d{HH:mm:ss,SSS} %-5p %l - %m%n"/>
        </layout>
    </appender>

    <appender name="db" class="LoggerAppenderPDO">
        <param name="dsn" value="mysql:host=localhost;dbname=logdb" />
        <param name="user" value="root" />
        <param name="password" value="athome233" />
        <param name="table" value="log4php_log" />
    </appender>

    <appender name="console" class="LoggerAppenderConsole">
        <layout class="LoggerLayoutSimple" />
    </appender>

    <logger name="custom">
        <level value="INFO"/>
        <appender_ref ref="custom"/>
    </logger>

    <logger name="db">
        <level value="INFO"/>
        <appender_ref ref="db"/>
    </logger>
    <logger name="console">
        <level value="INFO" />
        <appender_ref ref="console" />
    </logger>
    <root>
        <level value="WARN"/>
        <appender_ref ref="custom"/>
    </root>
</configuration>


text:
package itunessearch.request;

/**
 * Utility class containing keys and values for constructing {@link Request} instances. It uses a mixture of static classes
 * with String fields, and Enums. Generally speaking, Enums have been used when there is a small list of valid parameters.
 *
 *

 * The use of inner classes is to make the calling code easier to read. For example, to set the Entity to albums
 * you would use {@code String entity = RequestKeys.Entity.Music.ALBUM;}.
 */
public abstract class RequestKeys {

    /**
     * List of valid Search keys. This is package-private and is used internally by the {@code SearchBuilder} class.
     *

     * Note, "callback" and "version", although valid, are not here since this
     * library only supports version 2 and does not support callback at all.
     */
    static class SearchKeys {
        static final String TERM = "term";
        static final String COUNTRY = "country";
        static final String MEDIA = "media";
        static final String ENTITY = "entity";
        static final String ATTRIBUTE = "attribute";
        static final String LIMIT = "limit";
        static final String LANG = "lang";
        static final String EXPLICIT = "explicit";
        static final String OFFSET = "offset";
        static final String SORT = "sort";
    }

    /**
     * List of valid Lookup keys. This is public since it is used by the {@code LookupBuilder} constructor.
     */
    public static class LookupKeys {
        public static final String ITUNES_ID = "id";
        public static final String AMG_ARTIST_ID = "amgArtistId";
        public static final String UPC = "upc";
        public static final String AMG_ALBUM_ID = "amgAlbumId";
        public static final String AMG_VIDEO_ID = "amgVideoId";
        public static final String ISBN = "isbn";

        // package-private
        static final String LIMIT = "limit";
        static final String ENTITY = "entity";
        static final String SORT = "sort";
    }

    /**
     * List of values for the MEDIA key.
     */
    public static class Media {
        public static final String MOVIE = "movie";
        public static final String MUSIC = "music";
        public static final String PODCAST = "podcast";
        public static final String MUSIC_VIDEO = "musicVideo";
        public static final String AUDIOBOOK = "audiobook";
        public static final String SHORT_FILM = "shortFilm";
        public static final String TV_SHOW = "tvShow";
        public static final String SOFTWARE = "software";
        public static final String EBOOK = "ebook";
        public static final String ALL = "all";
    }

    /**
     * List of Entity values for each MEDIA type.
     */
    public static class Entity {

        public static class Music {
            public static final String MUSIC_TRACK = "musicTrack"; // includes both songs and music videos
            public static final String ARTIST = "musicArtist";
            public static final String ALBUM = "album";
            public static final String MUSIC_VIDEO = "musicVideo";
            public static final String MIX = "mix";
            public static final String SONG = "song";
        }

        public static class Podcast {
            public static final String AUTHOR = "podcastAuthor";
            public static final String PODCAST = "podcast";
        }

        public static class MOVIE {
            public static final String ARTIST = "movieArtist";
            public static final String MOVIE = "movie";
        }

        public static class MusicVideo {
            public static final String ARTIST = "musicArtist";
            public static final String MUSIC_VIDEO = "musicVideo";
        }

        public static class Audiobook {
            public static final String AUTHOR = "audiobookAuthor";
            public static final String AUDIOBOOK = "audiobook";
        }

        public static class ShortFilm {
            public static final String ARTIST = "shortFilmArtist";
            public static final String SHORT_FILM = "shortFilm";
        }

        public static class TvShow {
            public static final String EPISODE = "tvEpisode";
            public static final String SEASON = "tvSeason";
        }

        public static class Software {
            public static final String SOFTWARE = "software";
            public static final String IPAD = "iPadSoftware";
            public static final String MAC = "macSoftware";
        }

        public static class Ebook {
            public static final String EBOOK = "ebook";
        }

        public static class All {
            public static final String MOVIE = "movie";
            public static final String ALBUM = "album";
            public static final String ALL_ARTIST = "allArtist";
            public static final String PODCAST = "podcast";
            public static final String MUSIC_VIDEO = "musicVideo";
            public static final String MIX = "mix";
            public static final String AUDIOBOOK = "audiobook";
            public static final String TV_SHOW = "tvShow";
            public static final String ALL_TRACK = "allTrack";
        }

    } // end of Entity class

    /**
     * List of values for the {@code sort} option.
     */
    public enum Sort {
        POPULAR, RECENT;

        private String key;

        static {
            POPULAR.key = "popular";
            RECENT.key = "recent";
        }

        /**
         * Package-private method used to convert to a String key to be stored in the {@code []Builder.paramMap}.
         */
        String getKeyName(){
            return key;
        }
    }
}


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

using DodoNet.Overlay;

namespace DodoNet.Session
{
    [Serializable]
    public class SessionFinalizeReply : OverlayReply, ISessionRequestFinalizeReply
    {
        public string RequestId { get { return RequestId; } set { RequestId = value; } }

        private NodeId joinedNode;
        public NodeId JoinedNode { get { return joinedNode; } set { joinedNode = value; } }

        public SessionFinalizeReply(SessionFinalize request)
            : base((OverlayRequest)request)
        {
        }
    }
}


text:
import SiriWave, { IClassicCurveDefinition, ICurve } from "./index";
export class ClassicCurve implements ICurve {
  ctrl: SiriWave;
  definition: IClassicCurveDefinition;
  ATT_FACTOR = 4;
  GRAPH_X = 2;
  AMPLITUDE_FACTOR = 0.6;

  constructor(ctrl: SiriWave, definition: IClassicCurveDefinition) {
    this.ctrl = ctrl;
    this.definition = definition;
  }

  globalAttFn(x: number): number {
    return Math.pow(this.ATT_FACTOR / (this.ATT_FACTOR + Math.pow(x, this.ATT_FACTOR)), this.ATT_FACTOR);
  }

  _xpos(i: number): number {
    return this.ctrl.width * ((i + this.GRAPH_X) / (this.GRAPH_X * 2));
  }

  _ypos(i: number): number {
    return (
      this.AMPLITUDE_FACTOR *
      (this.globalAttFn(i) *
        (this.ctrl.heightMax * this.ctrl.amplitude) *
        (1 / this.definition.attenuation) *
        Math.sin(this.ctrl.opt.frequency! * i - this.ctrl.phase))
    );
  }

  draw(): void {
    const { ctx } = this.ctrl;

    ctx.moveTo(0, 0);
    ctx.beginPath();

    const color = this.ctrl.color.replace(/rgb\(/g, "").replace(/\)/g, "");
    ctx.strokeStyle = `rgba(${color},${this.definition.opacity})`;
    ctx.lineWidth = this.definition.lineWidth;

    // Cycle the graph from -X to +X every PX_DEPTH and draw the line
    for (let i = -this.GRAPH_X; i <= this.GRAPH_X; i += this.ctrl.opt.pixelDepth!) {
      ctx.lineTo(this._xpos(i), this.ctrl.heightMax + this._ypos(i));
    }

    ctx.stroke();
  }

  static getDefinition(): IClassicCurveDefinition[] {
    return [
      {
        attenuation: -2,
        lineWidth: 1,
        opacity: 0.1,
      },
      {
        attenuation: -6,
        lineWidth: 1,
        opacity: 0.2,
      },
      {
        attenuation: 4,
        lineWidth: 1,
        opacity: 0.4,
      },
      {
        attenuation: 2,
        lineWidth: 1,
        opacity: 0.6,
      },
      {
        attenuation: 1,
        lineWidth: 1.5,
        opacity: 1,
      },
    ];
  }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('common', '0002_settings'),
    ]

    operations = [
        migrations.CreateModel(
            name='Stage',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=128)),
                ('text', models.TextField(default=b'', blank=True)),
                ('link', models.URLField(default=None, null=True, blank=True)),
                ('state', models.CharField(default=b'info', max_length=24, blank=True)),
                ('weight', models.IntegerField(default=0)),
                ('updated', models.DateTimeField(default=datetime.datetime(2015, 6, 11, 16, 34, 32, 887390))),
                ('project', models.ForeignKey(to='common.Project')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--

   Copyright 2010 OpenEngSB Division, Vienna University of Technology

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

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

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

-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:my="http://openengsb.org/edb/1.0" xmlns:sm="http://servicemix.apache.org/config/1.0"
  xmlns:edb="urn:openengsb:edb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:drools="http://www.openengsb.org/domain/drools/1.0"
  xmlns:drl="urn:openengsb:drools" xmlns:context="http://www.openengsb.org/domain/context/1.0" xmlns:ctx="urn:openengsb:context"
  xmlns:email="http://www.openengsb.org/connector/email/1.0" xmlns:eml="urn:openengsb:email"
  xmlns:notification="http://www.openengsb.org/domain/notification/1.0" xmlns:ntf="urn:openengsb:notification"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <import resource="classpath:/edbBeans.xml" />
  <import resource="classpath:/testBeans.xml" />
  <sm:container createMBeanServer="false" embedded="true" id="jbi">
    <sm:activationSpecs>

      <sm:activationSpec>
        <sm:component>
          <my:edbComponent>
            <my:endpoints>
              <my:edb fullConfig="#fullConfig" endpoint="edb" service="edb:edb" />
              <my:edbEvent endpoint="edbEvent" service="edb:edbEvent" />
            </my:endpoints>
          </my:edbComponent>
        </sm:component>
      </sm:activationSpec>

      <sm:activationSpec>
        <sm:component>
          <drools:droolsComponent>
            <drools:endpoints>
              <drools:droolsEndpoint ruleSource="#ruleSource" noRemoteLogging="true" endpoint="droolsEndpoint" service="drl:droolsService" />
            </drools:endpoints>
          </drools:droolsComponent>
        </sm:component>
      </sm:activationSpec>

      <sm:activationSpec>
        <sm:component>
          <context:contextComponent>
            <context:endpoints>
              <context:contextEndpoint endpoint="contextEndpoint" service="ctx:contextService" />
            </context:endpoints>
          </context:contextComponent>
        </sm:component>
      </sm:activationSpec>

      <sm:activationSpec>
        <sm:component>
          <email:emailComponent>
            <email:endpoints>
              <email:emailEndpoint endpoint="emailEndpoint" service="eml:emailService" />
            </email:endpoints>
          </email:emailComponent>
        </sm:component>
      </sm:activationSpec>

    </sm:activationSpecs>
  </sm:container>

</beans>


text:
.supsystic-plugin .settings-list {
    line-height: 0;
}

.supsystic-plugin .settings {
	border-bottom: 1px solid gray;
    line-height: 0;
    padding: 2.2em 0;
}

.supsystic-plugin .supsystic-tooltip {
	clear: both;
	margin-left: 0.5em;
}

.supsystic-plugin .settings .setting-description a {
	display: block;
	margin-top: 1em;
}

.supsystic-plugin .settings .setting-description {
	width: 30%;
	display: inline-block;
}

.supsystic-plugin .settings .setting-description label {
	font-size: 16px;
	font-weight: bold;
}

.supsystic-plugin .settings .setting-control {
	display: inline-block;
	vertical-align: top;
}

.supsystic-plugin .chosen-select {
	min-width: 300px;
}


text:
/**
 *
 */
package com.athena.meerkat.controller.web.provisioning.xml;

import java.io.File;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

import com.athena.meerkat.controller.MeerkatConstants;

/**
 * xml utils
 *
 * @author BongJin Kwon
 *
 */
public abstract class XMLUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(XMLUtil.class);
	private static final String UTF8_BOM = "\uFEFF";

	/**
	 * return attribute value
	 *
	 * @param node
	 * @param attrName
	 * @return
	 */
	public static String getAttribute(Node node, String attrName) {
		NamedNodeMap nodeMap = node.getAttributes();

		if (nodeMap != null) {

			Node attrNode = nodeMap.getNamedItem(attrName);

			if (attrNode == null) {
				throw new XMLUtilException(attrName + " attribute is not found in "+ nodeToString(node));
			}

			return attrNode.getNodeValue();
		}

		throw new XMLUtilException("attribute map is not found in "+ nodeToString(node));
	}

	/**
	 * return attribute values
	 *
	 * @param node
	 * @param attrNames
	 * @return
	 */
	public static String[] getAttributes(Node node, String... attrNames) {

		String[] attrs = new String[attrNames.length];

		NamedNodeMap nodeMap = node.getAttributes();

		if (nodeMap != null) {

			for (int i = 0; i < attrNames.length; i++) {

				Node attrNode = nodeMap.getNamedItem(attrNames[i]);

				if (attrNode == null) {
					throw new XMLUtilException(attrNames[i] + " attribute is not found in " + nodeToString(node));
				}

				attrs[i] = attrNode.getNodeValue();
			}

			return attrs;
		}

		throw new XMLUtilException("attributes map is not found in " + nodeToString(node));
	}

	/**
	 * return Node by xpath expression
	 *
	 * @param item
	 *            The starting context (a node, for example).
	 * @param expression
	 *            The XPath expression.
	 * @return
	 */
	public static Node getNode(Object item, String expression) {

		Node node = null;
		XPath xPath = XPathFactory.newInstance().newXPath();

		try {
			node = (Node) xPath.compile(expression).evaluate(item, XPathConstants.NODE);

			if (node == null) {
				throw new XMLUtilException("node not found. xpath : " + expression);
			}

			return node;
		} catch (XPathExpressionException e) {
			throw new XMLUtilException(e);
		}
	}

	/**
	 * return NodeList by xpath expression
	 * @param item
	 *            The starting context (a node, for example).
	 * @param expression
	 *            The XPath expression.
	 * @return
	 */
	public static NodeList getNodeList(Object item, String expression) {

		NodeList nodeList = null;
		XPath xPath = XPathFactory.newInstance().newXPath();

		try {
			nodeList = (NodeList) xPath.compile(expression).evaluate(item, XPathConstants.NODESET);

			if (nodeList == null) {
				throw new XMLUtilException("node list not found. xpath : " + expression);
			}

			return nodeList;
		} catch (XPathExpressionException e) {
			throw new XMLUtilException(e);
		}
	}

	/**
	 * return string value by xpath expression.
	 *
	 * @param item
	 *            The starting context (a node, for example).
	 * @param expression
	 *            The XPath expression.
	 * @return
	 */
	public static String getStringValue(Object item, String expression) {

		XPath xPath = XPathFactory.newInstance().newXPath();

		try {
			String value = xPath.compile(expression).evaluate(item);

			if (value == null) {
				throw new XMLUtilException("string value not found. xpath : " + expression);
			}

			return value;
		} catch (XPathExpressionException e) {
			throw new XMLUtilException(e);
		}
	}

	/**
	 * convert node to string.
	 * @param node
	 * @return
	 */
	public static String nodeToString(Node node) {
		StringWriter sw = new StringWriter();
		try {
			Transformer t = TransformerFactory.newInstance().newTransformer();
			t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			//t.setOutputProperty(OutputKeys.INDENT, "yes");
			t.transform(new DOMSource(node), new StreamResult(sw));
		} catch (TransformerException e) {
			throw new XMLUtilException(e);
		}
		return sw.toString();
	}

	public static void writeToFile(Document doc, File file) {
		try {

			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");

			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(file);
			transformer.transform(source, result);

			/*
			DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
            LSSerializer writer = impl.createLSSerializer();

            writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
            writer.getDomConfig().setParameter("xml-declaration", Boolean.TRUE); // Set this to true if the declaration is needed to be outputted.

            FileUtils.writeStringToFile(file, writer.writeToString(doc), MeerkatConstants.UTF8);
            */
		} catch (Exception e) {
			throw new XMLUtilException(e);
		}
	}

	/**
	 * check UTF BOM byte of string
	 * @param s
	 * @return
	 */
	public static boolean hasUTF8BOM(String s){
		return s.startsWith(UTF8_BOM);
	}

	/**
	 * remove UTF BOM byte.
	 * @param s
	 * @return
	 */
	public static String removeUTF8BOM(String s) {

        if (hasUTF8BOM(s)) {
            s = s.substring(1);
            System.out.println("bommmmmm");
        }
        return s;
    }

}
// end of XMLUtil.java


text:
package ipc

import "encoding/json"

type IpcClient struct {
	conn chan string
}

func NewIpcClient(server *IpcServer) *IpcClient {
	c := server.Connect()

	return &IpcClient{c}
}

func (client *IpcClient) Call(method, params string) (resp *Response, err error) {
	req := &Request{method, params}

	var b []byte
	b, err = json.Marshal(req)
	if err != nil {
		return
	}

	client.conn <- string(b)
	str := <-client.conn

	var resp1 Response
	err = json.Unmarshal([]byte(str), &resp1)
	resp = &resp1
	return
}

func (client *IpcClient) Close() {
	client.conn <- "CLOSE"
}


text:
layout: post
title: "Example Content"
author: "Chester"
tags: Example
excerpt_separator:
---

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tincidunt ornare nibh, non elementum augue tempus eget. Pellentesque tempus scelerisque iaculis. Nullam interdum ultricies nibh quis sollicitudin. Donec ornare fermentum facilisis. Ut at sem ac sem imperdiet varius a eget tortor. Nam eu augue eget orci semper maximus in eget augue. Mauris ornare, nisl ut suscipit consectetur, mi quam interdum tellus, at rutrum quam eros ultrices mi.

# Headers
{% highlight markdown %}
# H1
## H2
### H3
#### H4
##### H5
###### H6
{% endhighlight %}

# H1
## H2
### H3
#### H4
##### H5
###### H6

# Text formatting
{% highlight markdown %}
- **Bold**
- _Italics_
- ~~Strikethrough~~
- Underline
- Superscript
- Subscript
- Abbreviation: HTML
- Citation: — Chester How
{% endhighlight %}

- **Bold**
- _Italics_
- ~~Strikethrough~~
- Underline
- Superscript
- Subscript
- Abbreviation: HTML
- Citation: — Chester How

# Lists
{% highlight markdown %}
1. Ordered list item 1
2. Ordered list item 2
3. Ordered list item 3

* Unordered list item 1
* Unordered list item 2
* Unordered list item 3
{% endhighlight %}

1. Ordered list item 1
2. Ordered list item 2
3. Ordered list item 3

* Unordered list item 1
* Unordered list item 2
* Unordered list item 3

# Links
{% highlight markdown %}
Check out tale on [GitHub](https://github.com/chesterhow/tale).
{% endhighlight %}

Check out tale on [GitHub](https://github.com/chesterhow/tale).

# Images
{% highlight markdown %}
![Placeholder image](https://placehold.it/800x400 "Placeholder image")

![Image with caption](https://placehold.it/700x400 "Image with caption")
_This is an image with a caption_
{% endhighlight %}

![Placeholder image](https://placehold.it/800x400 "Placeholder image")

![Image with caption](https://placehold.it/700x400 "Image with caption")
_This is an image with a caption_

# Code and Syntax Highlighting
Use back-ticks for `inline code`. Multi-line code snippets are supported too through Pygments.

{% highlight js %}
// Sample javascript code
var s = "JavaScript syntax highlighting";
alert(s);
{% endhighlight %}

{% highlight python %}
# Sample python code
s = "Python syntax highlighting"
print s
{% endhighlight %}

Adding `linenos` to the highlight tag enables line numbers.

{% highlight js  linenos %}
// Sample javascript code
var s = "JavaScript syntax highlighting";
alert(s);
{% endhighlight %}

# Blockquotes
{% highlight markdown %}
> Curabitur blandit tempus porttitor. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam id dolor id nibh ultricies vehicula ut id elit.

{% endhighlight %}

> Curabitur blandit tempus porttitor. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam id dolor id nibh ultricies vehicula ut id elit.

# Horizontal Rule & Line Break
{% highlight markdown %}
Use `<hr>` for horizontal rules

and `<br>` for line breaks.

{% endhighlight %}

Use `<hr>` for horizontal rules

and `<br>` for line breaks.

_The end_


text:
SELECT
  c1.concept_id   AS drug_concept_id,
  c2.concept_id   AS concept_id,
  c2.concept_name AS concept_name,
  ar1.count_value AS count_value
FROM @results_database_schema.achilles_results ar1
INNER JOIN
@vocab_database_schema.concept c1
ON ar1.stratum_1 = CAST(c1.concept_id AS VARCHAR(255))
INNER JOIN
@vocab_database_schema.concept c2
ON ar1.stratum_2 = CAST(c2.concept_id AS VARCHAR(255))
WHERE ar1.analysis_id = 705
AND ar1.stratum_1 = CAST('@conceptId' AS VARCHAR(255))


text:
using System.Collections.Generic;

namespace ShpToSql.SqlConnectionControl
{
    public interface ISmoTasks
    {
        IEnumerable<string> SqlServers {get;}
        List<string> GetDatabases(SqlConnectionString connectionString);
        List<DatabaseTable> GetTables(SqlConnectionString connectionString);
    }
}


text:
"""Mixture model for collaborative filtering"""
from typing import NamedTuple, Tuple
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Circle, Arc

class GaussianMixture(NamedTuple):
    """Tuple holding a gaussian mixture"""
    mu: np.ndarray  # (K, d) array - each row corresponds to a gaussian component mean
    var: np.ndarray  # (K, ) array - each row corresponds to the variance of a component
    p: np.ndarray  # (K, ) array = each row corresponds to the weight of a component

def init(X: np.ndarray, K: int,
         seed: int = 0) -> Tuple[GaussianMixture, np.ndarray]:
    """Initializes the mixture model with random points as initial
    means and uniform assingments

    Args:
        X: (n, d) array holding the data
        K: number of components
        seed: random seed

    Returns:
        mixture: the initialized gaussian mixture
        post: (n, K) array holding the soft counts
            for all components for all examples

    """
    np.random.seed(seed)
    n, _ = X.shape
    p = np.ones(K) / K

    # select K random points as initial means
    mu = X[np.random.choice(n, K, replace=False)]
    var = np.zeros(K)
    # Compute variance
    for j in range(K):
        var[j] = ((X - mu[j])**2).mean()

    mixture = GaussianMixture(mu, var, p)
    post = np.ones((n, K)) / K

    return mixture, post

ploti = 0
def plot(X: np.ndarray, mixture: GaussianMixture, post: np.ndarray,
         title: str):
    """Plots the mixture model for 2D data"""
    _, K = post.shape

    percent = post / post.sum(axis=1).reshape(-1, 1)
    fig, ax = plt.subplots()
    ax.title.set_text(title)
    ax.set_xlim((-20, 20))
    ax.set_ylim((-20, 20))
    r = 0.25
    color = ["r", "b", "k", "y", "m", "c"]
    for i, point in enumerate(X):
        theta = 0
        for j in range(K):
            offset = percent[i, j] * 360
            arc = Arc(point,
                      r,
                      r,
                      0,
                      theta,
                      theta + offset,
                      edgecolor=color[j])
            ax.add_patch(arc)
            theta += offset
    for j in range(K):
        mu = mixture.mu[j]
        sigma = np.sqrt(mixture.var[j])
        circle = Circle(mu, sigma, color=color[j], fill=False)
        ax.add_patch(circle)
        legend = "mu = ({:0.2f}, {:0.2f})\n stdv = {:0.2f}".format(
            mu[0], mu[1], sigma)
        ax.text(mu[0], mu[1], legend)
    plt.axis('equal')
    global ploti
    plt.savefig('%s.png' % title)
    ploti += 1

def rmse(X, Y):
    return np.sqrt(np.mean((X - Y)**2))

def bic(X: np.ndarray, mixture: GaussianMixture,
        log_likelihood: float) -> float:
    """Computes the Bayesian Information Criterion for a
    mixture of gaussians

    Args:
        X: (n, d) array holding the data
        mixture: a mixture of spherical gaussian
        log_likelihood: the log-likelihood of the data

    Returns:
        float: the BIC for this mixture
    """
    p = 0
    p += mixture.mu.shape[0] * mixture.mu.shape[1]
    p += mixture.var.shape[0]
    p += mixture.p.shape[0] - 1
    return log_likelihood - 1/2*p*np.log(X.shape[0])


text:
using System.Collections.Generic;
using ConsoleExamples.Examples;
using Encog.Engine.Network.Activation;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Neural.Freeform;
using Encog.Neural.Freeform.Basic;
using Encog.Neural.Freeform.Training;
using Encog.Util.Simple;

namespace Encog.Examples.Freeform
{
    public class FreeformOnlineXOR : IExample
    {
        /// <summary>
        ///     Input for the XOR function.
        /// </summary>
        public static double[][] XORInput =
        {
            new[] {0.0, 0.0},
            new[] {1.0, 0.0},
            new[] {0.0, 1.0},
            new[] {1.0, 1.0}
        };

        /// <summary>
        ///     Ideal output for the XOR function.
        /// </summary>
        public static double[][] XORIdeal =
        {
            new[] {0.0},
            new[] {1.0},
            new[] {1.0},
            new[] {0.0}
        };

        public static ExampleInfo Info
        {
            get
            {
                var info = new ExampleInfo(
                    typeof(FreeformOnlineXOR),
                    "freeform-online-xor",
                    "Freeform Network: Online XOR",
                    "Use a freeform neural network to fit the XOR operator with online training.");
                return info;
            }
        }

        public void Execute(IExampleInterface app)
        {
            // create a neural network, without using a factory
            var network = new FreeformNetwork();
            IFreeformLayer inputLayer = network.CreateInputLayer(2);
            IFreeformLayer hiddenLayer1 = network.CreateLayer(3);
            IFreeformLayer outputLayer = network.CreateOutputLayer(1);

            network.ConnectLayers(inputLayer, hiddenLayer1, new ActivationSigmoid(), 1.0, false);
            network.ConnectLayers(hiddenLayer1, outputLayer, new ActivationSigmoid(), 1.0, false);

            network.Reset();

            // create training data
            var trainingSet = new BasicMLDataSet(XORInput, XORIdeal);
            var train = new FreeformBackPropagation(network, trainingSet, 0.7, 0.2);
            train.BatchSize = 1;

            EncogUtility.TrainToError(train, 0.01);
            EncogUtility.Evaluate(network, trainingSet);

            EncogFramework.Instance.Shutdown();
        }
    }
}


text:
/**
 * @module @react-md/tree
 */
export * from "./defaultTreeItemRenderer";
export * from "./getChildItems";
export * from "./getItemsFrom";
export * from "./Tree";
export * from "./TreeGroup";
export * from "./TreeItem";
export * from "./types";
export * from "./useTreeItemExpansion";
export * from "./useTreeItemSelection";


text:
@class NSView;

@interface IDEDebugNavigatorStackFrameRowView : DVTTableRowView
{
    BOOL _showsPointerAnnotationView;
    NSView *_pointerAnnotationView;
}

+ (void)registerNibWithOutlineView:(id)arg1 forIdentifier:(id)arg2;
- (void).cxx_destruct;
@property(nonatomic) BOOL showsPointerAnnotationView; // @synthesize showsPointerAnnotationView=_showsPointerAnnotationView;
@property(retain) NSView *pointerAnnotationView; // @synthesize pointerAnnotationView=_pointerAnnotationView;
- (void)_updatePointerAnnotationViewFrame;
- (void)_updateInstructionPointerAnnotation;
- (void)setFrameSize:(struct CGSize)arg1;

@end


text:
<?php

namespace App\Events;

use App\Models\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\InteractsWithSockets;

class UserDeleted
{
    use InteractsWithSockets, SerializesModels;

    /**
     * @var User
     */
    public $user;

    /**
     * @param $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('user');
    }
}


text:
namespace ygo.application.Dto
{
    public class ArchetypeCardDto
    {
        public long ArchetypeId { get; set; }
        public long CardId { get; set; }
    }
}


text:
import json
import os
import unittest

import sas

class DeregistrationTestcase(unittest.TestCase):

  def setUp(self):
    self._sas, self._sas_admin = sas.GetTestingSas()
    self._sas_admin.Reset()

  def tearDown(self):
    pass

  def test_10_15_4_1_1(self):
    """Successful CBSD deregistration request.

    CBSD sends deregistration request to SAS with its correct and valid CBSD
    ID, the response should be SUCCESS.
    """

    # Register the device
    device_a = json.load(
        open(os.path.join('testcases', 'testdata', 'device_a.json')))
    self._sas_admin.InjectFccId({'fccId': device_a['fccId']})
    request = {'registrationRequest': [device_a]}
    response = self._sas.Registration(request)['registrationResponse'][0]
    # Check registration response
    self.assertEqual(response['response']['responseCode'], 0)
    cbsd_id = response['cbsdId']
    del request, response

    # Deregister the device
    request = {'deregistrationRequest': [{'cbsdId': cbsd_id}]}
    response = self._sas.Deregistration(request)['deregistrationResponse'][0]
    # Check the deregistration response
    self.assertEqual(response['cbsdId'], cbsd_id)
    self.assertEqual(response['response']['responseCode'], 0)


text:
static void * const LCCKSendImageViewShouldShowIndicatorViewContext = (void*)&LCCKSendImageViewShouldShowIndicatorViewContext;

@interface LCCKMessageSendStateView ()

@property (nonatomic, weak) UIActivityIndicatorView *indicatorView;
@property (nonatomic, assign, getter=shouldShowIndicatorView) BOOL showIndicatorView;

@end

@implementation LCCKMessageSendStateView

- (instancetype)init {
    if (self = [super init]) {
        UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        indicatorView.hidden = YES;
        [self addSubview:self.indicatorView = indicatorView];
        // KVO注册监听
        [self addObserver:self forKeyPath:@"showIndicatorView" options:NSKeyValueObservingOptionNew context:LCCKSendImageViewShouldShowIndicatorViewContext];
        __unsafe_unretained __typeof(self) weakSelf = self;
        [self cyl_executeAtDealloc:^{
            [weakSelf removeObserver:weakSelf forKeyPath:@"showIndicatorView"];
        }];
        [self addTarget:self action:@selector(failImageViewTap:) forControlEvents:UIControlEventTouchUpInside];

    }
    return self;
}

- (void)showErrorIcon:(BOOL)showErrorIcon {
    if (showErrorIcon) {
        NSString *imageName = @"MessageSendFail";
        UIImage *image = [UIImage lcck_imageNamed:imageName bundleName:@"MessageBubble" bundleForClass:[self class]];
        [self setImage:image forState:UIControlStateNormal];
    } else {
        [self setImage:nil forState:UIControlStateNormal];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.indicatorView.frame = self.bounds;
}

#pragma mark - Setters
- (void)setMessageSendState:(LCCKMessageSendState)messageSendState {
    _messageSendState = messageSendState;
    if (_messageSendState == LCCKMessageSendStateSending) {
        dispatch_async(dispatch_get_main_queue(),^{
            [self.indicatorView startAnimating];
        });
        self.showIndicatorView = YES;
    } else {
        dispatch_async(dispatch_get_main_queue(),^{
            [self.indicatorView stopAnimating];
        });
        self.showIndicatorView = NO;
    }

    switch (_messageSendState) {
        case LCCKMessageSendStateSending:
            self.showIndicatorView = YES;
            break;

        case LCCKMessageSendStateFailed:
            self.showIndicatorView = NO;
            break;
        default:
            self.hidden = YES;
            break;
    }
}

//- (void)setMessageSendState:(LCCKMessageSendState)messageSendState {
//    _messageSendState = messageSendState;
//    if (_messageSendState == LCCKMessageSendStateSending) {
//        dispatch_async(dispatch_get_main_queue(),^{
//            if (!self.indicatorView.isAnimating) {
//                [self.indicatorView startAnimating];
//            }
//        });
//        self.indicatorView.hidden = NO;
//    } else {
//        dispatch_async(dispatch_get_main_queue(),^{
//            if (self.indicatorView.isAnimating) {
//                [self.indicatorView stopAnimating];
//            }
//        });
//        self.indicatorView.hidden = YES;
//    }
//
//    switch (_messageSendState) {
//        case LCCKMessageSendStateSending:
//        case LCCKMessageSendStateFailed:
//            self.hidden = NO;
//            break;
//        default:
//            self.hidden = YES;
//            break;
//    }
//}

// KVO监听执行
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if(context != LCCKSendImageViewShouldShowIndicatorViewContext) {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        return;
    }
    if(context == LCCKSendImageViewShouldShowIndicatorViewContext) {
        if ([keyPath isEqualToString:@"showIndicatorView"]) {
            id newKey = change[NSKeyValueChangeNewKey];
            BOOL showIndicatorView = [newKey boolValue];
            if (showIndicatorView) {
                self.hidden = NO;
                self.indicatorView.hidden = NO;
                [self showErrorIcon:NO];
            } else {
                self.hidden = NO;
                self.indicatorView.hidden = YES;
                [self showErrorIcon:YES];
            }
        }
    }
}

- (void)failImageViewTap:(id)sender {
    if (self.shouldShowIndicatorView) {
        return;
    }
    if ([self.delegate respondsToSelector:@selector(resendMessage:)]) {
        [self.delegate resendMessage:self];
    }
}

@end


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import json
import os
import sys

def red(msg):
    return "\033[41m\033[1;30m %s \033[0m" % str(msg)

def yellow(msg):
    return "\033[43m\033[1;30m %s \033[0m" % str(msg)

def green(msg):
    return "\033[42m\033[1;30m %s \033[0m" % str(msg)

def blue(msg):
    return "\033[46m\033[1;30m %s \033[0m" % str(msg)

def read_config(path):
    with open(path, "r") as fh:
        return json.loads(fh.read())

def write_config(data={}):
    with open(data["options"]["config_path"], "w") as fh:
        fh.write(json.dumps(data))

def queries_from_config(config_path):
    config = {}
    try:
        with open(config_path, "r") as fh:
            config = json.loads(fh.read())
    except Exception as e:
        print ("Cannot open/parse config: %s" % str(e))
        exit(1)
    queries = {}
    if "scheduledQueries" in config:
        for query in config["scheduledQueries"]:
            queries[query["name"]] = query["query"]
    if "schedule" in config:
        for name, details in config["schedule"].iteritems():
            queries[name] = details["query"]
    if len(queries) == 0:
        print ("Could not find a schedule/queries in config: %s" % config_path)
        exit(0)
    return queries

def queries_from_tables(path, restrict):
    """Construct select all queries from all tables."""
    # Let the caller limit the tables
    restrict_tables = [t.strip() for t in restrict.split(",")]
    platform = sys.platform if sys.platform is not "linux2" else "linux"
    tables = []
    for base, _, files in os.walk(path):
        for spec in files:
            spec_platform = os.path.basename(base)
            table_name = spec.split(".table", 1)[0]
            if spec_platform not in ["x", platform]:
                continue
            # Generate all tables to select from, with abandon.
            tables.append("%s.%s" % (spec_platform, table_name))

    if len(restrict) > 0:
        tables = [t for t in tables if t.split(".")[1] in restrict_tables]
    queries = {}
    for table in tables:
        queries[table] = "SELECT * FROM %s;" % table.split(".", 1)[1]
    return queries


text:
<?php

defined('JPATH_BASE') or die;

JHtml::_('behavior.core');

$title = $displayData['title'];

?>
<button data-toggle="modal" onclick="{jQuery( '#collapseModal' ).modal('show'); return true;}" class="btn btn-small">
	<span class="icon-checkbox-partial" title="<?php echo $title; ?>">
	<?php echo $title; ?>
</button>


text:
<emu-clause id="async-function-objects">

Async Function Objects

  <emu-clause id="async-function-constructor">

The Async Function Constructor

The `AsyncFunction` Constructor is the %AsyncFunction% intrinsic object and is a subclass of `Function`. When `AsyncFunction` is called as a function rather than as a constructor, it creates and initializes a new AsyncFunction object. Thus the function call `AsyncFunction(…)` is equivalent to the object creation expression `new AsyncFunction(…)` with the same arguments.

The `AsyncFunction` constructor is designed to be subclassable. It may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the specified AsyncFunction behaviour must include a super call to the AsyncFunction constructor to create and initialize a subclass instances with the internal slots necessary for built-in async function behaviour.

    <emu-clause id="async-function-constructor-arguments">

AsyncFunction(_p1_, _p2_, ..., _pn_, _body_)

The last argument specifies the body (executable code) of an async function. Any preceding arguments specify formal parameters.

When the `AsyncFunction` function is called with some arguments _p1_, _p2_, ..., _pn_, _body_ (where _n_ might be 0, that is, there are no _p_ arguments, and where _body_ might also not be provided), the following steps are taken:

      <emu-alg>
          1. Let _C_ be the active function object.
          2. Let _args_ be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
          3. Return CreateDynamicFunction(_C_, NewTarget, "async", _args_).
      </emu-alg>

      <emu-note>See note for 19.2.1.1</emu-note>
    </emu-clause>
  </emu-clause>
  <emu-clause id="async-function-constructor-properties">

Properties of the AsyncFunction constructor

The AsyncFunction constructor is a standard built-in function object that inherits from the `Function` constructor. The value of the [[Prototype]] internal slot of the AsyncFunction constructor is the intrinsic object %Function%.

The value of the [[Extensible]] internal slot of the AsyncFunction constructor is *true*.

The value of the *name* property of the AsyncFunction is "AsyncFunction".

The AsyncFunction constructor has the following properties:

    <emu-clause id="async-function-constructor-length">

AsyncFunction.length

This is a data property with a value of 1. This property has the attributes { [[Writable]]: *false*, [[Enumerable]]: *false*, [[Configurable]]: *true* }.

    </emu-clause>

    <emu-clause id="async-function-constructor-prototype">

AsyncFunction.prototype

The intitial value of `AsyncFunction.prototype` is the intrinsic object %AsyncFunctionPrototype%.

This property has the attributes { [[Writable]]: *false*, [[Enumerable]]: *false*, [[Configurable]]: *false* }.

    </emu-clause>
  </emu-clause>
  <emu-clause id="async-function-prototype-properties">

Properties of the AsyncFunction Prototype Object

The AsyncFunction prototype object is an ordinary object. In addition to being the value of the prototpe property of the %AsyncFunction% instrinsic, it is the %AsyncFunctionPrototype% intrinsic.

The value of the [[Prototype]] internal slot of the AsyncFunction prototype object is the %FunctionPrototype% intrinsic object. The initial value of the [[Extensible]] internal slot of the AsyncFunction prototype object is *true*.

The AsyncFunction prototype object does not have a prototype property.

    <emu-note>Presumably this could be Promise.prototype but I'm not sure this has any value?</emu-note>

    <emu-clause id="async-function-prototype-properties-constructor">

AsyncFunction.prototype.constructor

The initial value of `AsyncFunction.prototype.constructor` is the intrinsic object %AsyncFunction%

This property has the attributes { [[Writable]]: *false*, [[Enumerable]]: *false*, [[Configurable]]: *true* }.

    </emu-clause>

    <emu-clause id="async-function-prototype-properties-toStringTag">

AsyncFunction.prototype[@@toStringTag]

The initial value of the @@toStringTag property is the string value "AsyncFunction".

This property has the attributes { [[Writable]]: *false*, [[Enumerable]]: *false*, [[Configurable]]: *true* }.

    </emu-clause>
  </emu-clause>

  <emu-clause id="async-function-instances">

AsyncFunction Instances

Every AsyncFunction instance is an ECMAScript function object and has the internal slots listed in Table 27. The value of the [[FunctionKind]] internal slot for all such instances is `"normal"`.

Each AsyncFunction instance has the following own properties:

AsyncFunction instances do not have a prototype property as they are not constructable.

    <emu-clause id="async-function-instances-length">

length

The value of the *length* property is an integer that indicates the typical number of arguments expected by the AsyncFunction. However, the language permits the function to be invoked with some other number of arguments. The behaviour of an AsyncFunction when invoked on a number of arguments other than the number specified by its length property depends on the function.

This property has the attributes { [[Writable]]: *false*, [[Enumerable]]: *false*, [[Configurable]]: *true* }.

    </emu-clause>
    <emu-clause id="async-function-instances-name">

name

The specification for the `name` property of Function instances given in 19.2.4.2 also applies to AsyncFunction instances.

    </emu-clause>
  </emu-clause>
</emu-clause>