text:
namespace webrtc {
class DataChannelInterface;
}  // namespace webrtc

namespace blink {
class LocalFrame;
class MediaConstraints;
class MockPeerConnectionTracker;
class PeerConnectionTrackerTest;
class RTCAnswerOptionsPlatform;
class RTCIceCandidatePlatform;
class RTCOfferOptionsPlatform;
class RTCPeerConnectionHandler;
class UserMediaRequest;
class WebLocalFrame;

// This class collects data about each peer connection,
// sends it to the browser process, and handles messages
// from the browser process.
class MODULES_EXPORT PeerConnectionTracker
    : public GarbageCollected<PeerConnectionTracker>,
      public Supplement<LocalDOMWindow>,
      public blink::mojom::blink::PeerConnectionManager {
 public:
  static const char kSupplementName[];

  static PeerConnectionTracker& From(LocalDOMWindow& window);
  static PeerConnectionTracker* From(LocalFrame& frame);
  static PeerConnectionTracker* From(WebLocalFrame& frame);
  PeerConnectionTracker(
      LocalDOMWindow& window,
      scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner,
      base::PassKey<PeerConnectionTracker>);

  PeerConnectionTracker(const PeerConnectionTracker&) = delete;
  PeerConnectionTracker& operator=(const PeerConnectionTracker&) = delete;

  ~PeerConnectionTracker() override;

  // Ctors for tests.
  PeerConnectionTracker(
      mojo::Remote<mojom::blink::PeerConnectionTrackerHost> host,
      scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner,
      base::PassKey<PeerConnectionTrackerTest> key)
      : PeerConnectionTracker(std::move(host), main_thread_task_runner) {}
  PeerConnectionTracker(
      mojo::Remote<mojom::blink::PeerConnectionTrackerHost> host,
      scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner,
      base::PassKey<MockPeerConnectionTracker> key)
      : PeerConnectionTracker(std::move(host), main_thread_task_runner) {}

  static void BindToFrame(
      LocalFrame* frame,
      mojo::PendingReceiver<mojom::blink::PeerConnectionManager> receiver);

  enum Source { kSourceLocal, kSourceRemote };

  enum Action {
    kActionSetLocalDescription,
    kActionSetLocalDescriptionImplicit,
    kActionSetRemoteDescription,
    kActionCreateOffer,
    kActionCreateAnswer
  };

  // In Plan B: "Transceiver" refers to RTCRtpSender or RTCRtpReceiver.
  // In Unified Plan: "Transceiver" refers to RTCRtpTransceiver.
  enum class TransceiverUpdatedReason {
    kAddTransceiver,
    kAddTrack,
    kRemoveTrack,
    kSetLocalDescription,
    kSetRemoteDescription,
  };

  // The following methods send an update to the browser process when a
  // PeerConnection update happens. The caller should call the Track* methods
  // after calling RegisterPeerConnection and before calling
  // UnregisterPeerConnection, otherwise the Track* call has no effect.

  // Sends an update when a PeerConnection has been created in Javascript. This
  // should be called once and only once for each PeerConnection. The
  // |pc_handler| is the handler object associated with the PeerConnection, the
  // |servers| are the server configurations used to establish the connection,
  // the |constraints| are the media constraints used to initialize the
  // PeerConnection, the |frame| is the WebLocalFrame object representing the
  // page in which the PeerConnection is created.
  void RegisterPeerConnection(
      RTCPeerConnectionHandler* pc_handler,
      const webrtc::PeerConnectionInterface::RTCConfiguration& config,
      const MediaConstraints& constraints,
      const blink::WebLocalFrame* frame);

  // Sends an update when a PeerConnection has been destroyed.
  virtual void UnregisterPeerConnection(RTCPeerConnectionHandler* pc_handler);

  // Sends an update when createOffer/createAnswer has been called.
  // The |pc_handler| is the handler object associated with the PeerConnection,
  // the |constraints| is the media constraints used to create the offer/answer.
  virtual void TrackCreateOffer(RTCPeerConnectionHandler* pc_handler,
                                RTCOfferOptionsPlatform* options);
  // TODO(hta): Get rid of the version below.
  virtual void TrackCreateOffer(RTCPeerConnectionHandler* pc_handler,
                                const MediaConstraints& options);
  virtual void TrackCreateAnswer(RTCPeerConnectionHandler* pc_handler,
                                 blink::RTCAnswerOptionsPlatform* options);
  virtual void TrackCreateAnswer(RTCPeerConnectionHandler* pc_handler,
                                 const MediaConstraints& constraints);

  // Sends an update when setLocalDescription or setRemoteDescription is called.
  virtual void TrackSetSessionDescription(RTCPeerConnectionHandler* pc_handler,
                                          const String& sdp,
                                          const String& type,
                                          Source source);
  virtual void TrackSetSessionDescriptionImplicit(
      RTCPeerConnectionHandler* pc_handler);

  // Sends an update when setConfiguration is called.
  virtual void TrackSetConfiguration(
      RTCPeerConnectionHandler* pc_handler,
      const webrtc::PeerConnectionInterface::RTCConfiguration& config);

  // Sends an update when an Ice candidate is added.
  virtual void TrackAddIceCandidate(RTCPeerConnectionHandler* pc_handler,
                                    RTCIceCandidatePlatform* candidate,
                                    Source source,
                                    bool succeeded);
  // Sends an update when an Ice candidate error is receiver.
  virtual void TrackIceCandidateError(RTCPeerConnectionHandler* pc_handler,
                                      const String& address,
                                      absl::optional<uint16_t> port,
                                      const String& host_candidate,
                                      const String& url,
                                      int error_code,
                                      const String& error_text);

  // Sends an update when a transceiver is added, modified or removed. This can
  // happen as a result of any of the methods indicated by |reason|.
  // In Plan B: |transceiver| refers to its Sender() or Receiver() depending on
  // ImplementationType(). Example events: "senderAdded", "receiverRemoved".
  // In Plan B: |transceiver| has a fully implemented ImplementationType().
  // Example events: "transceiverAdded", "transceiverModified".
  // See peer_connection_tracker_unittest.cc for expected resulting event
  // strings.
  virtual void TrackAddTransceiver(RTCPeerConnectionHandler* pc_handler,
                                   TransceiverUpdatedReason reason,
                                   const RTCRtpTransceiverPlatform& transceiver,
                                   size_t transceiver_index);
  virtual void TrackModifyTransceiver(
      RTCPeerConnectionHandler* pc_handler,
      TransceiverUpdatedReason reason,
      const RTCRtpTransceiverPlatform& transceiver,
      size_t transceiver_index);
  // TODO(hbos): When Plan B is removed this is no longer applicable.
  // https://crbug.com/857004
  virtual void TrackRemoveTransceiver(
      RTCPeerConnectionHandler* pc_handler,
      TransceiverUpdatedReason reason,
      const RTCRtpTransceiverPlatform& transceiver,
      size_t transceiver_index);

  // Sends an update when a DataChannel is created.
  virtual void TrackCreateDataChannel(
      RTCPeerConnectionHandler* pc_handler,
      const webrtc::DataChannelInterface* data_channel,
      Source source);

  // Sends an update when a PeerConnection has been closed.
  virtual void TrackClose(RTCPeerConnectionHandler* pc_handler);

  // Sends an update when the signaling state of a PeerConnection has changed.
  virtual void TrackSignalingStateChange(
      RTCPeerConnectionHandler* pc_handler,
      webrtc::PeerConnectionInterface::SignalingState state);

  // Sends an update when the ICE connection state of a PeerConnection has
  // changed. There's a legacy and non-legacy version. The non-legacy version
  // reflects the blink::RTCPeerConnection::iceConnectionState.
  //
  // "Legacy" usage: In Unifed Plan, TrackLegacyIceConnectionStateChange() is
  // used to report the webrtc::PeerConnection layer implementation of the
  // state, which might not always be the same as the
  // blink::RTCPeerConnection::iceConnectionState reported with
  // TrackIceConnectionStateChange(). In Plan B, the webrtc::PeerConnection
  // layer implementation is the only iceConnectionState version, and
  // TrackLegacyIceConnectionStateChange() is not applicable.
  virtual void TrackLegacyIceConnectionStateChange(
      RTCPeerConnectionHandler* pc_handler,
      webrtc::PeerConnectionInterface::IceConnectionState state);
  virtual void TrackIceConnectionStateChange(
      RTCPeerConnectionHandler* pc_handler,
      webrtc::PeerConnectionInterface::IceConnectionState state);

  // Sends an update when the connection state
  // of a PeerConnection has changed.
  virtual void TrackConnectionStateChange(
      RTCPeerConnectionHandler* pc_handler,
      webrtc::PeerConnectionInterface::PeerConnectionState state);

  // Sends an update when the Ice gathering state
  // of a PeerConnection has changed.
  virtual void TrackIceGatheringStateChange(
      RTCPeerConnectionHandler* pc_handler,
      webrtc::PeerConnectionInterface::IceGatheringState state);

  // Sends an update when the SetSessionDescription or CreateOffer or
  // CreateAnswer callbacks are called.
  virtual void TrackSessionDescriptionCallback(
      RTCPeerConnectionHandler* pc_handler,
      Action action,
      const String& type,
      const String& value);

  // Sends an update when the session description's ID is set.
  virtual void TrackSessionId(RTCPeerConnectionHandler* pc_handler,
                              const String& session_id);

  // Sends an update when onRenegotiationNeeded is called.
  virtual void TrackOnRenegotiationNeeded(RTCPeerConnectionHandler* pc_handler);

  // Sends an update when getUserMedia is called.
  virtual void TrackGetUserMedia(UserMediaRequest* user_media_request);
  // Sends an update when getUserMedia resolveѕ with a stream.
  virtual void TrackGetUserMediaSuccess(UserMediaRequest* user_media_request,
                                        MediaStream* stream);
  // Sends an update when getUserMedia fails with an error.
  virtual void TrackGetUserMediaFailure(UserMediaRequest* user_media_request,
                                        const String& error,
                                        const String& error_message);

  // Sends a new fragment on an RtcEventLog.
  virtual void TrackRtcEventLogWrite(RTCPeerConnectionHandler* pc_handler,
                                     const WTF::Vector<uint8_t>& output);

 private:
  FRIEND_TEST_ALL_PREFIXES(PeerConnectionTrackerTest, OnSuspend);
  FRIEND_TEST_ALL_PREFIXES(PeerConnectionTrackerTest, OnThermalStateChange);
  FRIEND_TEST_ALL_PREFIXES(PeerConnectionTrackerTest, OnSpeedLimitChange);
  FRIEND_TEST_ALL_PREFIXES(PeerConnectionTrackerTest,
                           ReportInitialThermalState);

  PeerConnectionTracker(
      mojo::Remote<mojom::blink::PeerConnectionTrackerHost> host,
      scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner);

  void Bind(mojo::PendingReceiver<blink::mojom::blink::PeerConnectionManager>
                receiver);

  // Assign a local ID to a peer connection so that the browser process can
  // uniquely identify a peer connection in the renderer process.
  // The return value will always be positive.
  int GetNextLocalID();

  // Looks up a handler in our map and if found, returns its ID. If the handler
  // is not registered, the return value will be -1.
  int GetLocalIDForHandler(RTCPeerConnectionHandler* handler) const;

  void TrackTransceiver(const char* callback_type_ending,
                        RTCPeerConnectionHandler* pc_handler,
                        PeerConnectionTracker::TransceiverUpdatedReason reason,
                        const RTCRtpTransceiverPlatform& transceiver,
                        size_t transceiver_index);

  // PeerConnectionTracker implementation.
  void OnSuspend() override;
  void OnThermalStateChange(
      mojom::blink::DeviceThermalState thermal_state) override;
  void OnSpeedLimitChange(int32_t speed_limit) override;
  void StartEventLog(int peer_connection_local_id,
                     int output_period_ms) override;
  void StopEventLog(int peer_connection_local_id) override;
  void GetStandardStats() override;
  void GetLegacyStats() override;

  // Called to deliver an update to the host (PeerConnectionTrackerHost).
  // |local_id| - The id of the registered RTCPeerConnectionHandler.
  //              Using an id instead of the hander pointer is done on purpose
  //              to force doing the lookup before building the callback data
  //              in case the handler isn't registered.
  // |callback_type| - A string, most often static, that represents the type
  //                   of operation that the data stored in |value| comes from.
  //                   E.g. "createOffer", "createAnswer",
  //                   "setRemoteDescription" etc.
  // |value| - A json serialized string containing all the information for the
  //           update event.
  void SendPeerConnectionUpdate(int local_id,
                                const String& callback_type,
                                const String& value);

  void AddStandardStats(int lid, base::Value::List value);
  void AddLegacyStats(int lid, base::Value::List value);

  // This map stores the local ID assigned to each RTCPeerConnectionHandler.
  typedef WTF::HashMap<RTCPeerConnectionHandler*, int> PeerConnectionLocalIdMap;
  PeerConnectionLocalIdMap peer_connection_local_id_map_;
  mojom::blink::DeviceThermalState current_thermal_state_ =
      mojom::blink::DeviceThermalState::kUnknown;
  int32_t current_speed_limit_ = mojom::blink::kSpeedLimitMax;

  THREAD_CHECKER(main_thread_);
  mojo::Remote<blink::mojom::blink::PeerConnectionTrackerHost>
      peer_connection_tracker_host_;
  mojo::Receiver<blink::mojom::blink::PeerConnectionManager> receiver_{this};

  scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_PEER_CONNECTION_TRACKER_H_


text:
//
// Copyright 2011-2012 Jeff Verkoeyen
//
// 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.
//

#import "NITableViewModel.h"

@class NIMutableTableViewModel;

/**
 * A protocol for NIMutableTableViewModel to handle editing states for objects.
 *
 *      @ingroup TableViewModels
 */
@protocol NIMutableTableViewModelDelegate <NSObject, NITableViewModelDelegate>

@optional

/**
 * Asks the receiver whether the object at the given index path should be editable.
 *
 * If this method is not implemented, the default response is assumed to be NO.
 */
- (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel
         canEditObject:(id)object
           atIndexPath:(NSIndexPath *)indexPath
           inTableView:(UITableView *)tableView;

/**
 * Asks the receiver whether the object at the given index path should be moveable.
 *
 * If this method is not implemented, the default response is assumed to be NO.
 */
- (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel
         canMoveObject:(id)object
           atIndexPath:(NSIndexPath *)indexPath
           inTableView:(UITableView *)tableView;

/**
 * Asks the receiver whether the given object should be moved.
 *
 * If this method is not implemented, the default response is assumed to be YES.
 *
 * Returning NO will stop the model from handling the move logic.
 */
- (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel
      shouldMoveObject:(id)object
           atIndexPath:(NSIndexPath *)indexPath
           toIndexPath:(NSIndexPath *)toIndexPath
           inTableView:(UITableView *)tableView;

/**
 * Asks the receiver what animation should be used when deleting the object at the given index path.
 *
 * If this method is not implemented, the default response is assumed to be
 * UITableViewRowAnimationAutomatic.
 */
- (UITableViewRowAnimation)tableViewModel:(NIMutableTableViewModel *)tableViewModel
              deleteRowAnimationForObject:(id)object
                              atIndexPath:(NSIndexPath *)indexPath
                              inTableView:(UITableView *)tableView;

/**
 * Asks the receiver whether the given object should be deleted.
 *
 * If this method is not implemented, the default response is assumed to be YES.
 *
 * Returning NO will stop the model from handling the deletion logic. This is a good opportunity for
 * you to show a UIAlertView or similar feedback prompt to the user before initiating the deletion
 * yourself.
 *
 * If you implement the deletion of the object yourself, your code may resemble the following:
@code
NSArray *indexPaths = [self removeObjectAtIndexPath:indexPath];
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
@endcode
 */
- (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel
    shouldDeleteObject:(id)object
           atIndexPath:(NSIndexPath *)indexPath
           inTableView:(UITableView *)tableView;

@end

/**
 * The NIMutableTableViewModel class is a mutable table view model.
 *
 * When modifications are made to the model there are two ways to reflect the changes in the table
 * view.
 *
 * - Call reloadData on the table view. This is the most destructive way to update the table view.
 * - Call insert/delete/reload methods on the table view with the retuned index path arrays.
 *
 * The latter option is the recommended approach to adding new cells to a table view. Each method in
 * the mutable table view model returns a data structure that can be used to inform the table view
 * of the exact modifications that have been made to the model.
 *
 * Example of adding a new section:
@code
// Appends a new section to the end of the model.
NSIndexSet* indexSet = [self.model addSectionWithTitle:@"New section"];

// Appends a cell to the last section in the model (in this case, the new section we just created).
[self.model addObject:[NITitleCellObject objectWithTitle:@"A cell"]];

// Inform the table view that we've modified the model.
[self.tableView insertSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
@endcode
 *
 *      @ingroup TableViewModels
 */
@interface NIMutableTableViewModel : NITableViewModel

- (NSArray *)addObject:(id)object;
- (NSArray *)addObject:(id)object toSection:(NSUInteger)section;
- (NSArray *)addObjectsFromArray:(NSArray *)array;
- (NSArray *)insertObject:(id)object atRow:(NSUInteger)row inSection:(NSUInteger)section;
- (NSArray *)insertObjects:(NSArray *)objects atRow:(NSUInteger)row inSection:(NSUInteger)section;
- (NSArray *)removeObjectAtIndexPath:(NSIndexPath *)indexPath;

- (NSIndexSet *)addSectionWithTitle:(NSString *)title;
- (NSIndexSet *)insertSectionWithTitle:(NSString *)title atIndex:(NSUInteger)index;
- (NSIndexSet *)removeSectionAtIndex:(NSUInteger)index;

- (void)updateSectionIndex;

@property (nonatomic, NI_WEAK) id<NIMutableTableViewModelDelegate> delegate;

@end

/** @name Modifying Objects */

/**
 * Appends an object to the last section.
 *
 * If no sections exist, a section will be created without a title and the object will be added to
 * this new section.
 *
 *      @param object The object to append to the last section.
 *      @returns An array with a single NSIndexPath representing the index path of the new object
 *               in the model.
 *      @fn NIMutableTableViewModel::addObject:
 */

/**
 * Appends an object to the end of the given section.
 *
 *      @param object The object to append to the section.
 *      @param section The index of the section to which this object should be appended.
 *      @returns An array with a single NSIndexPath representing the index path of the new object
 *               in the model.
 *      @fn NIMutableTableViewModel::addObject:toSection:
 */

/**
 * Appends an array of objects to the last section.
 *
 * If no section exists, a section will be created without a title and the objects will be added to
 * this new section.
 *
 *      @param array The array of objects to append to the last section.
 *      @returns An array of NSIndexPath objects representing the index paths of the objects in the
 *               model.
 *      @fn NIMutableTableViewModel::addObjectsFromArray:
 */

/**
 * Inserts an object into the given section at the given row.
 *
 *      @param object The object to append to the section.
 *      @param row The row within the section at which to insert the object.
 *      @param section The index of the section in which the object should be inserted.
 *      @returns An array with a single NSIndexPath representing the index path of the new object
 *               in the model.
 *      @fn NIMutableTableViewModel::insertObject:atRow:inSection:
 */

/**
 * Removes an object at the given index path.
 *
 * If the index path does not represent a valid object then a debug assertion will fire and the
 * method will return nil without removing any object.
 *
 *      @param indexPath The index path at which to remove a single object.
 *      @returns An array with a single NSIndexPath representing the index path of the object that
 *               was removed from the model, or nil if no object exists at the given index path.
 *      @fn NIMutableTableViewModel::removeObjectAtIndexPath:
 */

/** @name Modifying Sections */

/**
 * Appends a section with a given title to the model.
 *
 *      @param title The title of the new section.
 *      @returns An index set with a single index representing the index of the new section.
 *      @fn NIMutableTableViewModel::addSectionWithTitle:
 */

/**
 * Inserts a section with a given title to the model at the given index.
 *
 *      @param title The title of the new section.
 *      @param index The index in the model at which to add the new section.
 *      @returns An index set with a single index representing the index of the new section.
 *      @fn NIMutableTableViewModel::insertSectionWithTitle:atIndex:
 */

/**
 * Removes a section at the given index.
 *
 *      @param index The index in the model of the section to remove.
 *      @returns An index set with a single index representing the index of the removed section.
 *      @fn NIMutableTableViewModel::removeSectionAtIndex:
 */

/** @name Updating the Section Index */

/**
 * Updates the section index with the current section index settings.
 *
 * This method should be called after modifying the model if a section index is being used.
 *
 *      @fn NIMutableTableViewModel::updateSectionIndex
 */

redpajama_set_name: RedPajamaGithub


text:
import os

def new():
    project_name = ''
    while not project_name:
        project_name = input('Enter name for project: ')
    os.makedirs(project_name + '/adapters')
    os.mkdir(project_name + '/plugins')
    print('Created directories')

    start_file = open(project_name + '/start.py', 'w')
    start_file.write("""
import argparse
from sheldon import Sheldon

parser = argparse.ArgumentParser(description='Start bot')
parser.add_argument('--config-prefix', type=str, default='SHELDON_',
                    help='a str from which starting all config variables')
parser.add_argument('--adapter', type=str, default='console',
                    help='a str with name of adapter from adapters folder'
                         'or PyPi')
args = parser.parse_args()

bot = Sheldon({'config-prefix': args.config_prefix,
               'adapter': args.adapter})

bot.start()
    """)
    start_file.close()
    print('Created start.py')

    plugin_file = open(project_name + '/plugins/hello.py', 'w')
    plugin_file.write("""
\"\"\"
# Config (valid YAML document) must be at __doc__.
name: hello     # Name of plugin, lowercase, match with
                # file or package name.
description: "Example plugin for testing bot."
config:                          # Config variable that needed to set
  SHELDON_HELLO_REPLY: 'Hi'      # in environment.
                                 # You must set default values after colon.
\"\"\"

import sheldon
import sheldon.utils.logger
import schedule

@sheldon.hooks.message(['hello, bot', 'hey, bot'])
def hello_message(message, bot):
    answer = sheldon.OutgoingMessage(text=bot.config.get('SHELDON_HELLO_REPLY'),
                                     attachments=[])
    bot.send_message(answer)

@sheldon.hooks.command('hello')
def hello_command(message, bot):
    answer = sheldon.OutgoingMessage(text=bot.config.get('SHELDON_HELLO_REPLY'),
                                     attachments=[])
    bot.send_message(answer)

@sheldon.hooks.interval(schedule.every(5).minutes)
def hello_interval(bot):
    sheldon.utils.logger.info_message('Hello from hello module')

    """)
    plugin_file.close()
    print('Created plugin file')

    adapter_file = open(project_name + '/adapters/console.py', 'w')
    adapter_file.write("""
\"\"\"
# Config (valid YAML document) must be at __doc__.
name: console # Name of adapter, lowercase, match with
              # file or package name.
description: "Example adapter for testing bot."
config:                         # Config variable that needed to set
  SHELDON_CONSOLE_PROMPT: '>>>' # in environment.
                                # You can set default values after colon.
\"\"\"
from os import getlogin
from time import sleep
from random import randint
from sheldon.adapter import IncomingMessage, Attachment

# Code running on adapter loading may be here

def get_messages(bot):
    while True:
        # Let plugin thread end
        sleep(1)
        text = input('Enter message: ')

        attachments = []
        # For our example, attachment will be looking like:
        # '[type]_[path]'
        received_attachments = input(
            'Enter a comma-separated attachments'
            '(<type>_<path>):'
        ).split(',')

        # If user don't enter attachment,
        # message_attachments will be empty
        if received_attachments[0]:
            for attachment in received_attachments:
                # Parse incoming attachment:
                # attachment_data[0] will be attachment type
                # attachment_data[1] will be attachment path
                attachment_data = attachment.split('_')
                if len(attachment_data) < 2:
                    print('Incorrect attachment "{}"'.format(attachment))
                    continue
                attachments.append(Attachment(
                    attachment_type=attachment_data[0],
                    attachment_path=attachment_data[1:],
                    attachment_id=randint(1, 1000000000)  # Fake id
                ))

        yield IncomingMessage(sender=User(username=getlogin()), text=text,
                              attachments=attachments, variables={
                                  # Fake message id
                                  'console_id': randint(1, 1000000000)
                              })

def send_message(message, bot):
    print('BOT: ', message.text)
    print('Channel: ', message.channel)
    print('Attachments:')
    for attachment in message.attachments:
        print(attachment.id)
        print(attachment.type)
        print(attachment.path)
        print(attachment.text)

# Adapter must have implementation of User class.
class User:
    def __init__(self, username):
        \"\"\"
        Create new User for console adapter

        :param username: name in bash session
        :return:
        \"\"\"
        # Adapter object should have 'id' and 'username' params.
        self.id = hash(username)
        self.username = username

    """)
    adapter_file.close()
    print('Created adapter file')

    plugins_file = open(project_name + '/installed_plugins.txt', 'w')
    plugins_file.write("""plugins.hello\n""")
    plugins_file.close()
    print('Created installed plugins file')

    print('Project created')


text:
using System;
using UnityEngine;
using System.Collections;

public class PlayerShipController : MonoBehaviour
{
    /// <summary>
    /// Player's camera.
    /// </summary>
    private GameObject m_camera;

    /// <summary>
    /// Has the sail expansion been processed?
    /// </summary>
    private bool m_processedSailExpansion;

    /// <summary>
    /// Has the sail retration been processed?
    /// </summary>
    private bool m_processedSailRetraction;

    /// <summary>
    /// Called when the player ship controller has been awaken.
    /// </summary>
    private void Awake()
    {
        m_camera = GameObject.FindGameObjectWithTag("MainCamera");
    }

    /// <summary>
    /// Updates the logic of player ship movement.
    /// </summary>
    private void Update()
    {
        // Expanding or retracting sails.
        if (Input.GetKeyDown(KeyCode.W))
        {
            if (!m_processedSailExpansion)
            {
                m_processedSailExpansion = true;

                gameObject.SendMessage("ExpandSails");
                m_camera.SendMessage("ZoomOut");
            }
        }
        else
        {
            m_processedSailExpansion = false;

            if (Input.GetKeyDown(KeyCode.S))
            {
                if (!m_processedSailRetraction)
                {
                    m_processedSailRetraction = true;

                    gameObject.SendMessage("RetractSails");
                    m_camera.SendMessage("ZoomIn");
                }
            }
            else
            {
                m_processedSailRetraction = false;
            }
        }

        if (Input.GetKeyDown(KeyCode.LeftBracket))
        {
            gameObject.SendMessage("FireLeftCanons");
        }

        if (Input.GetKeyDown(KeyCode.RightBracket))
        {
            gameObject.SendMessage("FireRightCanons");
        }

        gameObject.SendMessage("SetHorizontalInput", Input.GetAxis("Horizontal"));
    }
}


text:
\hypertarget{_game_state_start_8h}{\section{jamms/\+Tower\+Defense/\+Tower\+Defense/include/game\+States/\+Game\+State\+Start.h File Reference}
\label{_game_state_start_8h}\index{jamms/\+Tower\+Defense/\+Tower\+Defense/include/game\+States/\+Game\+State\+Start.\+h@{jamms/\+Tower\+Defense/\+Tower\+Defense/include/game\+States/\+Game\+State\+Start.\+h}}
}

File containing the \hyperlink{class_game_state_start}{Game\+State\+Start} class.

{\ttfamily \#include $<$S\+F\+M\+L/\+Graphics.\+hpp$>$}\\*
{\ttfamily \#include $<$game\+States/\+Game\+State.\+h$>$}\\*
{\ttfamily \#include $<$game\+States/\+Game\+State\+Main\+Menu.\+h$>$}\\*
{\ttfamily \#include $<$managers/\+Texture\+Manager.\+h$>$}\\*
Include dependency graph for Game\+State\+Start.\+h\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=350pt]{_game_state_start_8h__incl}
\end{center}
\end{figure}
This graph shows which files directly or indirectly include this file\+:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=350pt]{_game_state_start_8h__dep__incl}
\end{center}
\end{figure}
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{class_game_state_start}{Game\+State\+Start}
\begin{DoxyCompactList}\small\item\em \hyperlink{class_game}{Game} state that represents the game start, including the main game menu. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
File containing the \hyperlink{class_game_state_start}{Game\+State\+Start} class.

The purpose of this file is to implement a class that is a concrete game state representing the \char`\"{}start\char`\"{} state.

\begin{DoxyAuthor}{Author}
Stephanie Li
\end{DoxyAuthor}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Heptadecagon</title>

定規

コンパス

undo

<canvas id="world" style="display:block;margin:auto;background-color:#eee"></canvas>


text:
BGP (Border Gateway Protocol) is used to dynamically program routes for pod traffic between nodes.

BGP is a standards-based routing protocol used to build the internet. It scales exceptionally well, and even the largest Kubernetes clusters represent a tiny amount of load compared to what BGP can cope with.

{{site.prodname}} can run BGP in three modes:
- **Full mesh** - where each node talks BGP to each other, easily scaling to 100 nodes, on top of an underlying L2 network or using IPIP overlay
- **With route reflectors** - where each node talks to one or more BGP route reflectors, scaling beyond 100 nodes, on top of an underlying L2 network or using IPIP overlay
- **Peered with TOR (Top of Rack) routers** - in a physical data center where each node talks to routers in the top of the corresponding rack, scaling to the limits of your physical data center.


text:
Email system with templates and email queuing.

## Features

- Emails can be sent directly, or saved into a spool to be sent later.
- Templates can be normal php files, or stored in the database and rendered with [MustachePHP](https://github.com/bobthecow/mustache.php) logic-less templates.
- Emails are send using [SwiftMailer](http://swiftmailer.org/), offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.
- Module uses [YiiStrap](http://getyiistrap.com/), the ultimate Twitter Bootstrap extension for Yii.

## Resources

- **[Documentation](http://cornernote.github.io/yii-email-module)**
- **[GitHub Project](https://github.com/cornernote/yii-email-module)**
- **[Yii Extension](http://www.yiiframework.com/extension/yii-email-module)**

## Support

- Does this README need improvement?  Go ahead and [suggest a change](https://github.com/cornernote/yii-email-module/edit/master/README.md).
- Found a bug, or need help using this project?  Check the [open issues](https://github.com/cornernote/yii-email-module/issues) or [create an issue](https://github.com/cornernote/yii-email-module/issues/new).

## License

[BSD-3-Clause](https://raw.github.com/cornernote/yii-email-module/master/LICENSE), Copyright © 2013-2014 [Mr PHP](mailto:info@mrphp.com.au)

[![Mr PHP](https://raw.github.com/cornernote/mrphp-assets/master/img/code-banner.png)](http://mrphp.com.au) [![Project Stats](https://www.ohloh.net/p/yii-email-module/widgets/project_thin_badge.gif)](https://www.ohloh.net/p/yii-email-module)

[![Latest Stable Version](https://poser.pugx.org/cornernote/yii-email-module/v/stable.png)](https://github.com/cornernote/yii-email-module/releases/latest) [![Total Downloads](https://poser.pugx.org/cornernote/yii-email-module/downloads.png)](https://packagist.org/packages/cornernote/yii-email-module) [![Monthly Downloads](https://poser.pugx.org/cornernote/yii-email-module/d/monthly.png)](https://packagist.org/packages/cornernote/yii-email-module) [![Latest Unstable Version](https://poser.pugx.org/cornernote/yii-email-module/v/unstable.png)](https://github.com/cornernote/yii-email-module) [![Build Status](https://travis-ci.org/cornernote/yii-email-module.png?branch=master)](https://travis-ci.org/cornernote/yii-email-module) [![License](https://poser.pugx.org/cornernote/yii-email-module/license.png)](https://raw.github.com/cornernote/yii-email-module/master/LICENSE)


text:
using System;
using EnvDTE;
using EnvDTE80;
using VSLangProj;
using System.Runtime.Serialization;
using Microsoft.Practices.RecipeFramework;
using System.Xml;

namespace SPALM.SPSF.Library.References
{

    [Serializable]
    public class MSTarget : UnboundRecipeReference
    {
        public MSTarget( string recipe ) : base( recipe )
        {
        }

        protected MSTarget(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        public override bool IsEnabledFor( object target )
        {
					try
					{
            if( target is ProjectItem)
            {
                if (((ProjectItem)target).Name.EndsWith(".msbuild"))
                {
                    return true;
                }
                if (((ProjectItem)target).Name.EndsWith(".targets"))
                {
                    return true;
                }
            }
					}
					catch (Exception)
					{
					}
            return false;
         }

        public override string AppliesTo
        {
             get
             {
                 return "*.msbuild or *.targets";
             }
        }
    }
}


text:
package dcdn

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

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

// EditRoutineConf invokes the dcdn.EditRoutineConf API synchronously
func (client *Client) EditRoutineConf(request *EditRoutineConfRequest) (response *EditRoutineConfResponse, err error) {
	response = CreateEditRoutineConfResponse()
	err = client.DoAction(request, response)
	return
}

// EditRoutineConfWithChan invokes the dcdn.EditRoutineConf API asynchronously
func (client *Client) EditRoutineConfWithChan(request *EditRoutineConfRequest) (<-chan *EditRoutineConfResponse, <-chan error) {
	responseChan := make(chan *EditRoutineConfResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.EditRoutineConf(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// EditRoutineConfWithCallback invokes the dcdn.EditRoutineConf API asynchronously
func (client *Client) EditRoutineConfWithCallback(request *EditRoutineConfRequest, callback func(response *EditRoutineConfResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *EditRoutineConfResponse
		var err error
		defer close(result)
		response, err = client.EditRoutineConf(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// EditRoutineConfRequest is the request struct for api EditRoutineConf
type EditRoutineConfRequest struct {
	*requests.RpcRequest
	Description string           `position:"Body" name:"Description"`
	EnvConf     string           `position:"Body" name:"EnvConf"`
	OwnerId     requests.Integer `position:"Query" name:"OwnerId"`
	Name        string           `position:"Body" name:"Name"`
}

// EditRoutineConfResponse is the response struct for api EditRoutineConf
type EditRoutineConfResponse struct {
	*responses.BaseResponse
	Content   map[string]interface{} `json:"Content" xml:"Content"`
	RequestId string                 `json:"RequestId" xml:"RequestId"`
}

// CreateEditRoutineConfRequest creates a request to invoke EditRoutineConf API
func CreateEditRoutineConfRequest() (request *EditRoutineConfRequest) {
	request = &EditRoutineConfRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("dcdn", "2018-01-15", "EditRoutineConf", "", "")
	request.Method = requests.POST
	return
}

// CreateEditRoutineConfResponse creates a response to parse from EditRoutineConf response
func CreateEditRoutineConfResponse() (response *EditRoutineConfResponse) {
	response = &EditRoutineConfResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
print("{{message}}")
print('{{prompt_message}}')


text:
<?php
namespace App\AdminBundle\Business\Server;

use App\AdminBundle\Business\Base\BaseEditHandler;
use App\ClientBundle\Entity;
use App\AdminBundle\Business;

class EditHandler extends BaseEditHandler
{
    public function loadEntity()
    {
        return $this->helperDoctrine->findOneByRequestId('AppClientBundle:Server');
    }

    public function getModelFromEntity($entity)
    {
        $model = new EditModel();

        $this->helperCommon->copyEntityToModel($this->entity, $model);

        $mcrypt               = $this->container->get('app_admin.helper.mcrypt');
        $model->encryptedIp   = $mcrypt->decrypt($model->encryptedIp);
        $model->encryptedUser = $mcrypt->decrypt($model->encryptedUser);
        $model->encryptedPass = $mcrypt->decrypt($model->encryptedPass);

        return $model;
    }

    public function buildForm($builder)
    {
        $builder->add('name', 'text', array(
            'attr'     => array(
                'placeholder' => 'NAME'
            ),
            'required' => true
        ));
        $builder->add('groupId', 'choice', array(
            'attr'     => array(
                'placeholder' => 'GROUP'
            ),
            'required' => false,
            'choices'  => $this->helperMapping->getMapping('server_group_list')
        ));
        $builder->add('encryptedIp', 'text', array(
            'attr'     => array(
                'placeholder' => 'IP'
            ),
            'required' => true
        ));
        $builder->add('encryptedUser', 'text', array(
            'attr'     => array(
                'placeholder' => 'USERNAME'
            ),
            'required' => true
        ));
        $builder->add('encryptedPass', 'text', array(
            'attr'     => array(
                'placeholder' => 'PASSWORD'
            ),
            'required' => true
        ));
        $builder->add('enabled', 'checkbox', array(
            'attr'     => array(
                'placeholder' => 'ENABLED',
            ),
            'required' => false
        ));
        return $builder;
    }

    public function onSuccess()
    {
        $model  = $this->getForm()->getData();
        $entity = $this->getEntity();

        $this->container->get('app_admin.helper.common')->copyModelToEntity($model, $entity);
        $mcrypt = $this->container->get('app_admin.helper.mcrypt');
        $entity->setEncryptedIp($mcrypt->encrypt($model->encryptedIp));
        $entity->setEncryptedUser($mcrypt->encrypt($model->encryptedUser));
        $entity->setEncryptedPass($mcrypt->encrypt($model->encryptedPass));

        parent::onSuccess();
    }
}


text:
VisualizeApp.directive('d3PieDirective', function($parse, $window){
   return {
       restrict: 'AEC',
       template: "<svg></svg>",
       link: function (scope, elem, attrs) {
            var exp = $parse(attrs.chartData);

            var PieChart=exp(scope);

            var d3 = $window.d3;
            var rawSvg=elem.find('svg');
            var svg = d3.select(rawSvg[0]);

            var parentHeight = svg.node().parentNode.getBoundingClientRect().height;
            if(parentHeight == 0)
              parentHeight = $('.boxAll').outerHeight()*0.3*0.95;
            var color;

            scope.$watchCollection(exp, function(newVal, oldVal){
                PieChart=newVal;

                var list = [];
                if(PieChart!=undefined){
                    for (var i = 0; i < newVal.LabeledInstance.length; i++) {
                        list.push(PieChart.LabeledInstance[i].label)
                    };
                    color = d3.scale.category20()
                        .domain(list);

                    change(color.domain().map(function(label){
                            return { label: label }
                        }).sort(function(a,b) {
                            return d3.ascending(a.label, b.label);
                        }));
                }
            });

            var width = (parentHeight)*2.13,
            height = parentHeight,
            radius = Math.min(width, height) / 2;

            svg
                .attr("width", width)
                .attr("height", height);

            var g = svg.append("g")
                .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
            g.append("g")
                .attr("class", "slices");
            g.append("g")
                .attr("class", "labels");
            g.append("g")
                .attr("class", "lines");
            g.append("g")
                .attr("class", "title");

            var pie = d3.layout.pie()
                .sort(null)
                .value(function(d) {

                    for (var i = 0; i < PieChart.LabeledInstance.length; i++) {
                            //alert(PieChart.LabeledInstance[i].measurement)
                        if(PieChart.LabeledInstance[i].label == d.label)
                            return Math.abs(PieChart.LabeledInstance[i].measurement.value);
                    };
                });

            var arc = d3.svg.arc()
                .outerRadius(radius * 0.8)
                .innerRadius(radius * 0.4);

            var outerArc = d3.svg.arc()
                .innerRadius(radius * 0.9)
                .outerRadius(radius * 0.9);

            var key = function(d){ return d.data.label; };

            function mergeWithFirstEqualZero(first, second){
                var secondSet = d3.set(); second.forEach(function(d) { secondSet.add(d.label); });

                var onlyFirst = first
                    .filter(function(d){ return !secondSet.has(d.label) })
                    .map(function(d) { return {label: d.label, value: 0}; });
                return d3.merge([ second, onlyFirst ])
                    .sort(function(a,b) {
                        return d3.ascending(a.label, b.label);
                    });
            }

            function change(data) {
                //var duration = +document.getElementById("duration").value;
                var data0 = svg.select(".slices").selectAll("path.slice")
                    .data().map(function(d) { return d.data });
                if (data0.length == 0) data0 = data;
                var was = mergeWithFirstEqualZero(data, data0);
                var is = mergeWithFirstEqualZero(data0, data);

                /* ------- SLICE ARCS -------*/

                var slice = svg.select(".slices").selectAll("path.slice")
                    .data(pie(was), key);

                slice.enter()
                    .insert("path")
                    .attr("class", "slice")
                    .style("fill", function(d) { return color(d.data.label); })
                    .each(function(d) {
                        this._current = d;
                    });

                slice = svg.select(".slices").selectAll("path.slice")
                    .data(pie(is), key);

                slice
                    .transition().duration(1000)
                    .attrTween("d", function(d) {
                        var interpolate = d3.interpolate(this._current, d);
                        var _this = this;
                        return function(t) {
                            _this._current = interpolate(t);
                            return arc(_this._current);
                        };
                    });

                slice = svg.select(".slices").selectAll("path.slice")
                    .data(pie(data), key);

                slice
                    .exit().transition().delay(1000).duration(0)
                    .remove();

                /* ------- TEXT LABELS -------*/

                var text = svg.select(".labels").selectAll("text")
                    .data(pie(was), key);

                text.enter()
                    .append("text")
                    .style("font-size", height/12 + "px")
                    .attr("dy", ".35em")
                    .style("opacity", 0)
                    .text(function(d) {
                        return d.data.label;
                    })
                    .each(function(d) {
                        this._current = d;
                    });

                function midAngle(d){
                    return d.startAngle + (d.endAngle - d.startAngle)/2;
                }

                text = svg.select(".labels").selectAll("text")
                    .data(pie(is), key);

                text.transition().duration(1000)
                    .style("opacity", function(d) {
                        return d.data.value == 0 ? 0 : 1;
                    })
                    .attrTween("transform", function(d) {
                        var interpolate = d3.interpolate(this._current, d);
                        var _this = this;
                        return function(t) {
                            var d2 = interpolate(t);
                            _this._current = d2;
                            var pos = outerArc.centroid(d2);
                            pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                            return "translate("+ pos +")";
                        };
                    })
                    .styleTween("text-anchor", function(d){
                        var interpolate = d3.interpolate(this._current, d);
                        return function(t) {
                            var d2 = interpolate(t);
                            return midAngle(d2) < Math.PI ? "start":"end";
                        };
                    });

                text = svg.select(".labels").selectAll("text")
                    .data(pie(data), key);

                text
                    .exit().transition().delay(1000)
                    .remove();

                /* ------- SLICE TO TEXT POLYLINES -------*/

                var polyline = svg.select(".lines").selectAll("polyline")
                    .data(pie(was), key);

                polyline.enter()
                    .append("polyline")
                    .style("opacity", 0)
                    .each(function(d) {
                        this._current = d;
                    });

                polyline = svg.select(".lines").selectAll("polyline")
                    .data(pie(is), key);

                polyline.transition().duration(1000)
                    .style("opacity", function(d) {
                        return d.data.value == 0 ? 0 : .5;
                    })
                    .attrTween("points", function(d){
                        this._current = this._current;
                        var interpolate = d3.interpolate(this._current, d);
                        var _this = this;
                        return function(t) {
                            var d2 = interpolate(t);
                            _this._current = d2;
                            var pos = outerArc.centroid(d2);
                            pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);
                            return [arc.centroid(d2), outerArc.centroid(d2), pos];
                        };
                    });

                polyline = svg.select(".lines").selectAll("polyline")
                    .data(pie(data), key);

                polyline
                    .exit().transition().delay(1000)
                    .remove();

                svg.select(".title").select("text")
                    .remove();
                svg.select(".title")
                   .attr("transform", "translate("+(width*0.4)+",-"+(height*0.4)+")")
                   .append("text")
                        .attr("y", 6)
                        .attr("dy", ".71em")
                        .style("text-anchor", "end")
                        .text(PieChart.config.label);
            };
        }
    }
});


text:
<!doctype html>
<meta charset="utf-8" />
<title>input type=password size</title>

	Below you should see an empty field that is 360 px in width.  Below the
	field, there should be a paragraph containing the word "PASS".

<form>

		<input id="test" name="test" type="password" size="50" />

</form>


text:
define(["streamhub-sdk/jquery", "inherits", "stream", "streamhub-sdk/view"],
function ($, inherits, Stream, View) {
    "use strict";

    var MultiView = function (opts, streams) {
        View.call(this, opts);

        opts = opts || {};
        streams = streams || [];

        this.startOn = opts.startOn;
        this._createView = opts.createView;
        this._active = {};
        this._streams = [];
        this._views = {};
        this._callback = opts.callback || function () {};
        this._init(streams);
    };
    inherits(MultiView, View);

    MultiView.prototype._init = function (streams) {
        for (var i = 0, len = streams.length; i < len; i++) {
            var stream = streams[i];
            var view = this._buildView(stream);
            if (typeof this.startOn == "undefined" && i == 0 ||
                this.startOn === stream.articleId) {
                this._startStream(stream, view);
            }
            else {
                this._queueStream(stream, view);
            }
        }

        this._callback.call(this);
        return this;
    };

    MultiView.prototype._startStream = function (stream, view, fakeStart) {
        var s;
        /*
         * TODO: This might be a bad assumption? Vet it
         * The assumption is if you pass a view, you want to pipe a
         * stream to it...so that means we've never seen you before.
         */
        if (view) {
            s = stream;
            s.pipe(view);
            this._streams.push(s);
            if (!fakeStart) {
                this._active.stream = s;
                this._active.view = view;
                this.el.appendChild(view.el);
            }
        }

        /*
         * I've seen you before... let's go find you.
         */
        else {
            this._active.stream.pause();
            s = this._streams[this._streams.indexOf(stream)];
            s.resume();
            this._active.stream = s;
            this._active.view = this._views[s.articleId];
        }

        /*
         * Kinda ghetto.. but force the view to fit the el width
         */
        $(window).trigger("resize");
        return s;
    };

    MultiView.prototype._queueStream = function (stream, view) {
        var s = this._startStream(stream, view, true);

        /*
         * Have to do start first THEN pause it... it should prevent it
         * from running since the pipe - which inherently calls read - is called
         * on the next tick while pause it "run" immediately
         */
        s.pause();
    };

    MultiView.prototype._createElement = function (parentEl, type, attributes) {
        var newEl = document.createElement(type);

        //TODO: Change this to just use a for-loop
        if (attributes.id) {
            newEl.setAttribute("id", attributes.id);
        }

        return parentEl.appendChild(newEl);
    };

    MultiView.prototype._buildView = function (stream) {
        var view = this._createView();
        this._views[stream.articleId] = view;
        return view;
    };

    MultiView.prototype.switchTo = function (stream) {
        //TODO: Handle the case that someone uses switch to before adding anything
        if (stream.id != this._active.stream.id) {
            this._active.view.$el.hide();
            if (this._views[stream.articleId]) {
                this._startStream(stream);
            }
            else {
                this._startStream(stream, this._buildView(stream));
            }

           this._active.view.$el.siblings().each(function(){
              $(this).css("opacity", 0);
           });
           this._active.view.$el.css("display", "block");
           var self = this;
           setTimeout(function() {self._active.view.$el.animate({opacity: 1.0}, 500);}, 1000);

           return this._active;
        }
    };

    MultiView.prototype.addStream = function (stream, start) {
        if (!this._views[stream.articleId]) {
            var view = this._buildView(stream);
            if (start) {
                this._startStream(stream, view);
            }
            else {
                this._queueStream(stream, view);
            }
            return this._active;
        }
    };

    return MultiView;
});


text:
define("d3/src/transition/subtransition", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){
import "transition";

d3_transitionPrototype.transition = function() {
  var id0 = this.id,
      id1 = ++d3_transitionId,
      ns = this.namespace,
      subgroups = [],
      subgroup,
      group,
      node,
      transition;

  for (var j = 0, m = this.length; j < m; j++) {
    subgroups.push(subgroup = []);
    for (var group = this[j], i = 0, n = group.length; i < n; i++) {
      if (node = group[i]) {
        transition = node[ns][id0];
        d3_transitionNode(node, i, ns, id1, {time: transition.time, ease: transition.ease, delay: transition.delay + transition.duration, duration: transition.duration});
      }
      subgroup.push(node);
    }
  }

  return d3_transition(subgroups, ns, id1);
};

});


text:
module.exports = defines

function defines(tokens) {
  var definitions = {}

  for (var i = 0; i < tokens.length; i++) {
    var token = tokens[i]
    if (token.type !== 'preprocessor') continue
    var datum = token.data.trim()
    if (datum.indexOf('#define')) continue
    var parts = datum.match(/#define\s+([^\s]+)(.+)?$/i)
    if (!parts) continue
    var name  = (parts[1] || '').trim()
    var value = (parts[2] || '').trim()

    definitions[name] = value
  }

  return definitions
}


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////

#include "Context.h"

#include "Basics/StringBuffer.h"
#include "Cluster/ClusterInfo.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "StorageEngine/StorageEngine.h"
#include "Transaction/Helpers.h"
#include "Transaction/Manager.h"
#include "Transaction/ManagerFeature.h"
#include "Transaction/Methods.h"
#include "Utils/CollectionNameResolver.h"
#include "VocBase/LogicalCollection.h"

#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Options.h>
#include <velocypack/velocypack-aliases.h>

using namespace arangodb;

namespace {
// custom type value handler, used for deciphering the _id attribute
struct CustomTypeHandler final : public VPackCustomTypeHandler {
  CustomTypeHandler(TRI_vocbase_t& vocbase, CollectionNameResolver const& resolver)
      : vocbase(vocbase), resolver(resolver) {}

  ~CustomTypeHandler() = default;

  void dump(VPackSlice const& value, VPackDumper* dumper, VPackSlice const& base) override final {
    dumper->appendString(toString(value, nullptr, base));
  }

  std::string toString(VPackSlice const& value, VPackOptions const* options,
                       VPackSlice const& base) override final {
    return transaction::helpers::extractIdString(&resolver, value, base);
  }

  TRI_vocbase_t& vocbase;
  CollectionNameResolver const& resolver;
};
}

/// @brief create the context
transaction::Context::Context(TRI_vocbase_t& vocbase)
    : _vocbase(vocbase),
      _customTypeHandler(),
      _builders{_arena},
      _stringBuffer(),
      _strings{_strArena},
      _options(arangodb::velocypack::Options::Defaults),
      _resolver(nullptr),
      _transaction{TransactionId::none(), false, false} {}

/// @brief destroy the context
transaction::Context::~Context() {
  // unregister the transaction from the logfile manager
  if (_transaction.id.isSet()) {
    transaction::ManagerFeature::manager()->unregisterTransaction(_transaction.id,
                                                                  _transaction.isReadOnlyTransaction,
                                                                  _transaction.isFollowerTransaction);
  }

  // call the actual cleanup routine which frees all
  // hogged resources
  cleanup();
}

/// @brief destroys objects owned by the context,
/// this can be called multiple times.
/// currently called by dtor and by unit test mocks.
/// we cannot move this into the dtor (where it was before) because
/// the mocked objects in unittests do not seem to call it and effectively leak.
void transaction::Context::cleanup() noexcept {
  // free all VPackBuilders we handed out
  for (auto& it : _builders) {
    delete it;
  }
  _builders.clear();

  // clear all strings handed out
  for (auto& it : _strings) {
    delete it;
  }
  _strings.clear();

  _stringBuffer.reset();

  _resolver.reset();
}

/// @brief factory to create a custom type handler, not managed
std::unique_ptr<VPackCustomTypeHandler> transaction::Context::createCustomTypeHandler(
    TRI_vocbase_t& vocbase, CollectionNameResolver const& resolver) {
  return std::make_unique<::CustomTypeHandler>(vocbase, resolver);
}

/// @brief temporarily lease a StringBuffer object
basics::StringBuffer* transaction::Context::leaseStringBuffer(size_t initialSize) {
  if (_stringBuffer == nullptr) {
    _stringBuffer.reset(new basics::StringBuffer(initialSize, false));
  } else {
    _stringBuffer->reset();
  }

  return _stringBuffer.release();
}

/// @brief return a temporary StringBuffer object
void transaction::Context::returnStringBuffer(basics::StringBuffer* stringBuffer) noexcept {
  _stringBuffer.reset(stringBuffer);
}

/// @brief temporarily lease a std::string
std::string* transaction::Context::leaseString() {
  if (_strings.empty()) {
    // create a new string and return it
    return new std::string();
  }

  // re-use an existing string
  std::string* s = _strings.back();
  s->clear();
  _strings.pop_back();
  return s;
}

/// @brief return a temporary std::string object
void transaction::Context::returnString(std::string* str) noexcept {
  try {  // put string back into our vector of strings
    _strings.push_back(str);
  } catch (...) {
    // no harm done. just wipe the string
    delete str;
  }
}

/// @brief temporarily lease a Builder object
VPackBuilder* transaction::Context::leaseBuilder() {
  if (_builders.empty()) {
    // create a new builder and return it
    return new VPackBuilder();
  }

  // re-use an existing builder
  VPackBuilder* b = _builders.back();
  b->clear();
  _builders.pop_back();

  return b;
}

/// @brief return a temporary Builder object
void transaction::Context::returnBuilder(VPackBuilder* builder) noexcept {
  try {
    // put builder back into our vector of builders
    _builders.push_back(builder);
  } catch (...) {
    // no harm done. just wipe the builder
    delete builder;
  }
}

/// @brief get velocypack options with a custom type handler
VPackOptions* transaction::Context::getVPackOptions() {
  if (_customTypeHandler == nullptr) {
    // this modifies options!
    orderCustomTypeHandler();
  }

  return &_options;
}

/// @brief create a resolver
CollectionNameResolver const& transaction::Context::resolver() {
  if (_resolver == nullptr) {
    _resolver = std::make_unique<CollectionNameResolver>(_vocbase);
  }
  return *_resolver;
}

std::shared_ptr<TransactionState> transaction::Context::createState(transaction::Options const& options) {
  // now start our own transaction
  TRI_ASSERT(vocbase().server().hasFeature<EngineSelectorFeature>());
  StorageEngine& engine = vocbase().server().getFeature<EngineSelectorFeature>().engine();
  return engine.createTransactionState(_vocbase, generateId(), options);
}

/// @brief unregister the transaction
/// this will save the transaction's id and status locally
void transaction::Context::storeTransactionResult(TransactionId id, bool wasRegistered,
                                                  bool isReadOnlyTransaction,
                                                  bool isFollowerTransaction) noexcept {
  TRI_ASSERT(_transaction.id.empty());

  if (wasRegistered) {
    _transaction.id = id;
    _transaction.isReadOnlyTransaction = isReadOnlyTransaction;
    _transaction.isFollowerTransaction = isFollowerTransaction;
  }
}

TransactionId transaction::Context::generateId() const {
  return Context::makeTransactionId();
}

std::shared_ptr<transaction::Context> transaction::Context::clone() const {
  TRI_ASSERT(false);
  THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_NOT_IMPLEMENTED,
                                 "transaction::Context::clone() is not implemented");
}

/*static*/ TransactionId transaction::Context::makeTransactionId() {
  auto role = ServerState::instance()->getRole();
  if (ServerState::isCoordinator(role)) {
    return TransactionId::createCoordinator();
  } else if (ServerState::isDBServer(role)) {
    return TransactionId::createLegacy();
  }
  return TransactionId::createSingleServer();
}


text:
export default class Cat {
  constructor() {
    this._name = 'Cat';
  }
  get name() {
    return this._name;
  }
}


text:
namespace BlogEngine.Core.Web.HttpHandlers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    using System.Xml;

    using BlogEngine.Core.Web.HttpModules;

    ///
    /// Implements a custom handler to synchronously process HTTP Web requests for a syndication feed.
    ///
    /// <remarks>
    /// This handler can generate syndication feeds in a variety of formats and filtering
    ///     options based on the query string parmaeters provided.
    /// </remarks>
    /// <seealso cref="IHttpHandler"/>
    /// <seealso cref="SyndicationGenerator"/>
    public class SyndicationHandler : IHttpHandler
    {
        #region Properties

        ///
        ///     Gets a value indicating whether another request can use the <see cref = "T:System.Web.IHttpHandler"></see> instance.
        ///
        /// <returns>true if the <see cref = "T:System.Web.IHttpHandler"></see> instance is reusable; otherwise, false.</returns>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region Implemented Interfaces

        #region IHttpHandler

        ///
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements
        ///     the <see cref="T:System.Web.IHttpHandler"></see> interface.
        ///
        /// <param name="context">
        /// An <see cref="T:System.Web.HttpContext"></see> object that provides references
        ///     to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.
        /// </param>
        public void ProcessRequest(HttpContext context)
        {
            if (!Security.IsAuthorizedTo(Rights.ViewPublicPosts))
            {
                context.Response.StatusCode = 401;
                return;
            }

            var title = RetrieveTitle(context);
            var format = RetrieveFormat(context);
            var list = GenerateItemList(context);
            list = CleanList(list);

            if (string.IsNullOrEmpty(context.Request.QueryString["post"]))
            {
                // Shorten the list to the number of posts stated in the settings, except for the comment feed.
                var max = Math.Min(BlogSettings.Instance.PostsPerFeed, list.Count);
                list = list.FindAll(item => item.IsVisible);

                list = list.GetRange(0, max);
            }

            SetHeaderInformation(context, list, format);

            if (BlogSettings.Instance.EnableHttpCompression)
            {
                CompressionModule.CompressResponse(context);
            }

            var generator = new SyndicationGenerator(BlogSettings.Instance, Category.Categories);
            generator.WriteFeed(format, context.Response.OutputStream, list, title);
        }

        #endregion

        #endregion

        #region Methods

        ///
        /// Cleans the list.
        ///
        /// <param name="list">The list of IPublishable.</param>
        /// <returns>The cleaned list of IPublishable.</returns>
        private static List<IPublishable> CleanList(List<IPublishable> list)
        {
            return list.FindAll(item => item.IsVisible);
        }

        ///
        /// A converter delegate used for converting Results to Posts.
        ///
        /// <param name="item">
        /// The publishable item.
        /// </param>
        /// <returns>
        /// Converts to publishable interface.
        /// </returns>
        private static IPublishable ConvertToIPublishable(IPublishable item)
        {
            return item;
        }

        ///
        /// Generates the list of feed items based on the URL.
        ///
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A list of IPublishable.
        /// </returns>
        private static List<IPublishable> GenerateItemList(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request.QueryString["category"]))
            {
                // All posts in the specified category
                var categoryId = new Guid(context.Request.QueryString["category"]);
                return Post.GetPostsByCategory(categoryId).ConvertAll(ConvertToIPublishable);
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["tag"]))
            {
                // All posts with the specified tag
                return Post.GetPostsByTag(context.Request.QueryString["tag"].Trim()).ConvertAll(ConvertToIPublishable);
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["author"]))
            {
                // All posts by the specified author
                var author = context.Request.QueryString["author"];
                return Post.GetPostsByAuthor(author).ConvertAll(ConvertToIPublishable);
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["post"]))
            {
                // All comments of the specified post
                var post = Post.GetPost(new Guid(context.Request.QueryString["post"]));
                return post.Comments.ConvertAll(ConvertToIPublishable);
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["comments"]))
            {
                // The recent comments added to any post.
                return RecentComments();
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["q"]))
            {
                // Searches posts and pages
                return Search.Hits(context.Request.QueryString["q"], false);
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["apml"]))
            {
                // Finds matches to  an APML file in both posts and pages
                try
                {
                    using (var client = new WebClient())
                    {
                        client.Credentials = CredentialCache.DefaultNetworkCredentials;
                        client.Encoding = Encoding.Default;
                        using (var stream = client.OpenRead(context.Request.QueryString["apml"]))
                        {
                            var doc = new XmlDocument();
                            if (stream != null)
                            {
                                doc.Load(stream);
                            }

                            var list = Search.ApmlMatches(doc, 30);
                            list.Sort((i1, i2) => i2.DateCreated.CompareTo(i1.DateCreated));
                            return list;
                        }
                    }
                }
                catch (Exception ex)
                {
                    context.Response.Clear();
                    context.Response.Write(ex.Message);
                    context.Response.ContentType = "text/plain";
                    context.Response.AppendHeader("Content-Disposition", "inline; filename=\"error.txt\"");
                    context.Response.End();
                }
            }

            // The latest posts
            return Post.ApplicablePosts.ConvertAll(ConvertToIPublishable);
        }

        ///
        /// Creates a list of the most recent comments
        ///
        /// <returns>
        /// A list of IPublishable.
        /// </returns>
        private static List<IPublishable> RecentComments()
        {
            var temp = Post.ApplicablePosts.SelectMany(post => post.ApprovedComments).ToList();

            temp.Sort();
            temp.Reverse();
            var list = temp.ToList();

            return list.ConvertAll(ConvertToIPublishable);
        }

        ///
        /// Retrieves the syndication format from the urL parameters.
        ///
        /// <param name="context">
        /// The HTTP context.
        /// </param>
        /// <returns>
        /// The syndication format.
        /// </returns>
        private static SyndicationFormat RetrieveFormat(HttpContext context)
        {
            var query = context.Request.QueryString["format"];
            var format = BlogSettings.Instance.SyndicationFormat;
            if (!string.IsNullOrEmpty(query))
            {
                format = context.Request.QueryString["format"];
            }

            try
            {
                return (SyndicationFormat)Enum.Parse(typeof(SyndicationFormat), format, true);
            }
            catch (ArgumentException)
            {
                return SyndicationFormat.None;
            }
        }

        ///
        /// Retrieves the title.
        ///
        /// <param name="context">The context.</param>
        /// <returns>The title string.</returns>
        private static string RetrieveTitle(HttpContext context)
        {
            var title = BlogSettings.Instance.Name;
            string subTitle = null;

            if (!string.IsNullOrEmpty(context.Request.QueryString["category"]))
            {
                if (context.Request.QueryString["category"].Length != 36)
                {
                    StopServing(context);
                }

                var categoryId = new Guid(context.Request.QueryString["category"]);
                var currentCategory = Category.GetCategory(categoryId);
                if (currentCategory == null)
                {
                    StopServing(context);
                }

                if (currentCategory != null)
                {
                    subTitle = currentCategory.Title;
                }
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["author"]))
            {
                subTitle = context.Request.QueryString["author"];
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["post"]))
            {
                if (context.Request.QueryString["post"].Length != 36)
                {
                    StopServing(context);
                }

                var post = Post.GetPost(new Guid(context.Request.QueryString["post"]));

                if (post == null)
                {
                    StopServing(context);
                }

                if (post != null)
                {
                    var arg = new ServingEventArgs(post.Content, ServingLocation.Feed);
                    post.OnServing(arg);
                    if (arg.Cancel)
                    {
                        StopServing(context);
                    }
                    else
                    {
                        subTitle = post.Title;
                    }
                }
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["comments"]))
            {
                subTitle = "Comments";
            }

            if (subTitle != null)
            {
                return string.Format("{0} - {1}", title, subTitle);
            }

            return title;
        }

        ///
        /// Sets the response header information.
        ///
        /// <param name="context">
        /// An <see cref="HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.
        /// </param>
        /// <param name="items">
        /// The collection of <see cref="IPublishable"/> instances used when setting the response header details.
        /// </param>
        /// <param name="format">
        /// The format of the syndication feed being generated.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="context"/> is a null reference (Nothing in Visual Basic) -or- the <paramref name="items"/> is a null reference (Nothing in Visual Basic).
        /// </exception>
        private static void SetHeaderInformation(
            HttpContext context, IEnumerable<IPublishable> items, SyndicationFormat format)
        {
            var lastModified = new DateTime(1900, 1, 3); // don't use DateTime.MinValue here, as Mono doesn't like it
            foreach (var item in items)
            {
                if (item.DateModified.AddHours(-BlogSettings.Instance.Timezone) > lastModified)
                {
                    lastModified = item.DateModified.AddHours(-BlogSettings.Instance.Timezone);
                }
            }

            switch (format)
            {
                case SyndicationFormat.Atom:
                    context.Response.ContentType = "application/atom+xml";
                    context.Response.AppendHeader("Content-Disposition", "inline; filename=atom.xml");
                    break;

                case SyndicationFormat.Rss:
                    context.Response.ContentType = "application/rss+xml";
                    context.Response.AppendHeader("Content-Disposition", "inline; filename=rss.xml");
                    break;
            }

            if (Utils.SetConditionalGetHeaders(lastModified))
            {
                context.Response.End();
            }
        }

        ///
        /// The stop serving.
        ///
        /// <param name="context">
        /// The context.
        /// </param>
        private static void StopServing(HttpContext context)
        {
            context.Response.Clear();
            context.Response.StatusCode = 404;
            context.Response.End();
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.example.yetti.toneplayer">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:name=".CoreApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme">
        <service
            android:name=".service.MediaService"
            android:exported="true"
            tools:ignore="ExportedService" >
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </service>
        <receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </receiver>
        <activity
            android:name=".ui.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden|orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
Ensure you have python 2.7 runtime

## Installation

Clone the repository

`git clone https://github.com/wenpengfei/python-crawl.git`

`cd python-crawl`

`pip install beautifulsoup4`

## Running

`python dytt.py`


text:
<?php

namespace AC\Transcoding\Event;

/**
 * Documents the events fired by the Transcoder
 *
 * @package Transcoding
 * @author Evan Villemez
 */
class TranscodeEvents
{
    /**
     * Fired when an adapter sends a message. An adapter can send 4 types of message (Debug, Info, Warn, Error)
     *
     * Listeners receive instance of MessageEvent
     */
    const MESSAGE = "adapter.message";

    /**
     * Fired before single transcode process begins
     *
     * Listeners receive instance of TranscodeEvent
     */
    const BEFORE = "transcode.before";

    /**
     * Fired after single transcode process ends
     *
     * Listeners receive instance of TranscodeEvent
     */
    const AFTER = "transcode.after";

    /**
     * Fired when an exception is thrown during a transcode process
     *
     * Listeners receive instance of TranscodeEvent
     */
    const ERROR = "transcode.error";

    /**
     * Fired when a new file has been created by the Transcoder
     *
     * Listeners receive instance of FileEvent
     */
    const FILE_CREATED = 'file.created';

    /**
     * Fired when a file has been modified by the transcoder, this is usually only when it changes permissions on a file for some reason
     *
     * Listeners receive instance of FileEvent
     */
    const FILE_MODIFIED = 'file.modified';

    /**
     * Fired when a file has been removed by the transcoder, this could happen because of a failed process, or because there was a file
     * with the given name that already exists, and is to be replaced with a new file
     *
     * Listeners receive instance of FileEvent
     */
    const FILE_REMOVED = 'file.removed';

    /**
     * Fired when the transcoder creates a new directory for containing files
     *
     * Listeners receive instance of FileEvent
     */
    const DIR_CREATED = 'dir.created';

    /**
     * Fired when a directory is modified, generally would only happen if the Transcoder changes file permissions on it directly
     *
     * Listeners receive instance of FileEvent
     */
    const DIR_MODIFIED = 'dir.modified';

    /**
     * Fired when a directory is removed
     *
     * Listeners receive instance of FileEvent
     */
    const DIR_REMOVED = 'dir.removed';
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.carobotics.networking;

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import org.carobotics.logic.RemoteProcessedCamera;
import org.carobotics.logic.ThreadManager;

/**
 *
 * @author CaRobotics
 */
public class Networking {

    public PacketSender sender;
    public PacketReceiver receiver;

    public Networking(ThreadManager manager, int period/*, InputManager inputs*/, RemoteProcessedCamera cam) {
        ServerSocketConnection ssc = null;
        try {
            ssc = (ServerSocketConnection) Connector.open("socket://:1735");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        sender = new PacketSender(ssc, period, manager);
        receiver = new PacketReceiver(period, manager, ssc/*, inputs*/, cam);
    }

    public void startThreads() {
        sender.start();
        receiver.start();
    }

    public void queue(byte[] data) {
        sender.queue(data);
    }
}


text:
package cmput301_17.includebucket;

import android.util.Log;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by michelletagarino on 16-11-26.
 */
public class OfflineRequestQueue {

    private static LinkedBlockingQueue<Command> requestQueue = null;

    public static LinkedBlockingQueue<Command> getRequestQueue() {
        if (requestQueue == null) {
            requestQueue = new LinkedBlockingQueue<>();
        }
        return requestQueue;
    }

    /**
     * Taken from: https://www.javacodegeeks.com/2015/09/command-design-pattern.html
     * Accessed: November 26, 2016
     * Author: Rohit Joshi
     * @param command
     */
    public static void addCommand(Command command) {
        try {
            getRequestQueue().put(command);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void execute() {
        while (!getRequestQueue().isEmpty()) {
            try {
                Command c = OfflineRequestQueue.getRequestQueue().take();
                c.execute();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


text:
package com.huanyu.doc.demo.pom.comm;

import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

/**
 * 购物篮条件
 *
 * @author yangtao
 */
public class BasketElement extends XmlElement {

  @XStreamAsAttribute
  private boolean overall;
  @XStreamImplicit(itemFieldName = "product")
  private List<ProductElement> products;
  @XStreamImplicit(itemFieldName = "element")
  private List<XmlElement> childrends;

  /**
   * 是否全场
   *
   * @return
   */
  public boolean isOverall() {
    return overall;
  }

  public void setOverall(boolean overall) {
    this.overall = overall;
  }

  public List<ProductElement> getProducts() {
    return products;
  }

  public void setProducts(List<ProductElement> products) {
    this.products = products;
  }

  @Override
  public List<XmlElement> getChildrends() {
    return childrends;
  }

  @Override
  public void setChildrends(List<XmlElement> childrends) {
    this.childrends = childrends;
  }

}


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.mute.events;

import io.github.nucleuspowered.nucleus.api.module.mute.event.NucleusMuteEvent;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;

import java.time.Duration;
import java.util.Optional;
import java.util.UUID;

public abstract class MuteEvent extends AbstractEvent implements NucleusMuteEvent {

    private final Cause cause;
    private final UUID mutedUser;

    public MuteEvent(final Cause cause, final UUID mutedUser) {
        this.cause = cause;
        this.mutedUser = mutedUser;
    }

    @Override
    public UUID getMutedUser() {
        return this.mutedUser;
    }

    @Override
    public Cause cause() {
        return this.cause;
    }

    public static class Muted extends MuteEvent implements NucleusMuteEvent.Muted {

        @Nullable public final Duration duration;
        public final Component reason;

        public Muted(final Cause cause, final UUID target, @Nullable final Duration duration, final Component reason) {
            super(cause, target);
            this.duration = duration;
            this.reason = reason;
        }

        @Override public Optional<Duration> getDuration() {
            return Optional.ofNullable(this.duration);
        }

        @Override public Component getReason() {
            return this.reason;
        }
    }

    public static class Unmuted extends MuteEvent implements NucleusMuteEvent.Unmuted {

        private final boolean expired;

        public Unmuted(final Cause cause, final UUID target, final boolean expired) {
            super(cause, target);
            this.expired = expired;
        }

        @Override public boolean expired() {
            return this.expired;
        }
    }
}


text:
@implementation JotDiskAssetManager {
    NSMutableDictionary* inProcessDiskWrites;
    NSOperationQueue* opQueue;
}

#pragma mark - Queues

static dispatch_queue_t diskAssetQueue;
static const void* const kDiskAssetQueueIdentifier = &kDiskAssetQueueIdentifier;

+ (dispatch_queue_t)diskAssetQueue {
    if (!diskAssetQueue) {
        diskAssetQueue = dispatch_queue_create("com.milestonemade.looseleaf.diskAssetQueue", DISPATCH_QUEUE_SERIAL);
        dispatch_queue_set_specific(diskAssetQueue, kDiskAssetQueueIdentifier, (void*)kDiskAssetQueueIdentifier, NULL);
    }
    return diskAssetQueue;
}

+ (BOOL)isDiskAssetQueue {
    return dispatch_get_specific(kDiskAssetQueueIdentifier) != NULL;
}

+ (UIImage*)imageWithContentsOfFile:(NSString*)path {
    return [[JotDiskAssetManager sharedManager] imageWithContentsOfFileHelper:path];
}

#pragma mark - Singleton

- (id)init {
    if (self = [super init]) {
        inProcessDiskWrites = [NSMutableDictionary dictionary];
        opQueue = [[NSOperationQueue alloc] init];
    }
    return self;
}

+ (JotDiskAssetManager*)sharedManager {
    static dispatch_once_t onceToken;
    static JotDiskAssetManager* manager;
    dispatch_once(&onceToken, ^{
        manager = [[[JotDiskAssetManager class] alloc] init];
    });
    return manager;
}

- (void)writeImage:(UIImage*)image toPath:(NSString*)path {
    JotImageWriteOperation* operation = nil;
    @synchronized(inProcessDiskWrites) {
        operation = [[JotImageWriteOperation alloc] initWithImage:image
                                                          andPath:path
                                                   andNotifyBlock:^(JotImageWriteOperation* operation) {
                                                       [self operationHasCompleted:operation];
                                                   }];

        JotImageWriteOperation* currOp = [self cancelAnyOperationFor:path];
        if (currOp) {
            [operation addDependency:currOp];
        }
        [inProcessDiskWrites setObject:operation forKey:path];
    }
    [opQueue addOperation:operation];
}

- (void)blockUntilCompletedForPath:(NSString*)path {
    if (path) {
        BOOL needsBlock = NO;
        @synchronized(inProcessDiskWrites) {
            needsBlock = [inProcessDiskWrites objectForKey:path] != nil;
        }
        if (needsBlock && opQueue.operationCount) {
            // blocking thread until we're done working
            [opQueue waitUntilAllOperationsAreFinished];
        }
    }
}

- (void)blockUntilCompletedForDirectory:(NSString*)dirPath {
    BOOL needsBlock = NO;
    if (dirPath) {
        @synchronized(inProcessDiskWrites) {
            needsBlock = [[[inProcessDiskWrites allKeys] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary* bindings) {
                return [evaluatedObject hasPrefix:dirPath];
            }]] count] > 0;
        }
        if (needsBlock && opQueue.operationCount) {
            // blocking thread until we're done working
            [opQueue waitUntilAllOperationsAreFinished];
        }
    }
}

- (void)blockUntilAllWritesHaveFinished {
    [opQueue waitUntilAllOperationsAreFinished];
}

#pragma mark - Notifications

- (void)operationHasCompleted:(JotImageWriteOperation*)operation {
    @synchronized(inProcessDiskWrites) {
        JotImageWriteOperation* currOpForPath = [inProcessDiskWrites objectForKey:operation.path];
        if (currOpForPath == operation) {
            [inProcessDiskWrites removeObjectForKey:operation.path];
        }
    }
}

- (JotImageWriteOperation*)cancelAnyOperationFor:(NSString*)path {
    JotImageWriteOperation* currentOperation = nil;
    @synchronized(inProcessDiskWrites) {
        if(path){
            currentOperation = [inProcessDiskWrites objectForKey:path];
            [inProcessDiskWrites removeObjectForKey:path];
        }
    }
    [currentOperation cancel];
    return currentOperation;
}

#pragma mark - Helper

- (UIImage*)imageWithContentsOfFileHelper:(NSString*)path {
    @synchronized(inProcessDiskWrites) {
        JotImageWriteOperation* operation = [inProcessDiskWrites objectForKey:path];
        if (operation) {
            return operation.image;
        }
    }
    return [UIImage imageWithContentsOfFile:path];
}

@end


text:
const snippetUrl = "https://snippet.babylonjs.com/";
const pgRoot = "https://playground.babylonjs.com";
export const loadPlayground = async (playgroundId: string) => {
    const data = await fetch(snippetUrl + playgroundId.replace(/#/g, "/"));
    const snippet = await data.json();
    let code = JSON.parse(snippet.jsonPayload).code.toString();
    code = code
        .replace(/\/textures\//g, pgRoot + "/textures/")
        .replace(/"textures\//g, '"' + pgRoot + "/textures/")
        .replace(/\/scenes\//g, pgRoot + "/scenes/")
        .replace(/"scenes\//g, '"' + pgRoot + "/scenes/")
        .replace(/"\.\.\/\.\.https/g, '"' + "https")
        .replace("http://", "https://");

    const createSceneFunction = code.indexOf("delayCreateScene") > -1 ? "delayCreateScene" : "createScene";

    const loadedScene = eval(`${code};${createSceneFunction}(engine);`);

    if (loadedScene.then) {
        // Handle if createScene returns a promise
        return await loadedScene;
    } else {
        return loadedScene;
    }
};

export const getPlaygroundId = () => {
    if (location.hash) {
        return location.hash.substring(1);
    } else {
        if (location.href.indexOf("pg=") > -1) {
            return location.href.split("pg=")[1];
        }
    }
    return "";
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>statsmodels.sandbox.stats.runs.cochrans_q — statsmodels 0.9.0 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.sandbox.stats.runs.Runs" href="statsmodels.sandbox.stats.runs.Runs.html" />
    <link rel="prev" title="statsmodels.sandbox.stats.runs.runstest_2samp" href="statsmodels.sandbox.stats.runs.runstest_2samp.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Statistics stats |

statsmodels.sandbox.stats.runs.cochrans_q¶

statsmodels.sandbox.stats.runs.cochrans_q(x)[source]¶

Cochran's Q test for identical effect of k treatments

Cochran's Q is a k-sample extension of the McNemar test. If there are only
two treatments, then Cochran's Q test and McNemar test are equivalent.

Test that the probability of success is the same for each treatment.
The alternative is that at least two treatments have a different
probability of success.

<col class="field-name" />
<col class="field-body" />

Parameters:	x (array_like, 2d (N,k)) – data with N cases and k variables

Returns:

q_stat (float) – test statistic

pvalue (float) – pvalue from the chisquare distribution

Notes

In Wikipedia terminology, rows are blocks and columns are treatments.
The number of rows N, should be large for the chisquare distribution to be
a good approximation.
The Null hypothesis of the test is that all treatments have the
same effect.

References

http://en.wikipedia.org/wiki/Cochran_test
SAS Manual for NPAR TESTS

Previous topic

statsmodels.sandbox.stats.runs.runstest_2samp

Next topic

statsmodels.sandbox.stats.runs.Runs

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

        © Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.7.4.


text:
function fileUploadInit() {
  this.hooks = [];
  this.uploadFileClicked = uploadFileClicked;
  this.submitClicked = submitClicked;
}

function dropdownClicked(name, width, height) {
  var wrapper = $('#' + name + '-wrapper');
  var panel = $('#' + name + '-panel');

  if (wrapper[0].expanded) {
    wrapper.animate({height:'0'});
    wrapper[0].expanded = false;
  } else {
    panel.css('height', height);
    panel.css('width', width);
    wrapper.css('width', width);
    wrapper.animate({height: height});
    wrapper[0].expanded = true;
  }
}

function uploadFileClicked () {
  dropdownClicked('fileUpload', '350px', '70px');
}

function submitClicked() {
  console.log("UPLAOD");
  $('#fileUploadForm').ajaxSubmit({
    complete: function (XMLHttpRequest, textStatus) {
      console.log([textStatus, XMLHttpRequest]);
    }

  });
}

/* used on the client side only */
fileUpload = new fileUploadInit();