text:
package edmondScripts;

import org.testng.annotations.Test;

import spot.BaseSelenium;
import spot.components.MessageComponent.MessageType;
import spot.pages.CollectionEntryPage;
import spot.pages.DetailedItemViewPage;
import spot.pages.LoginPage;
import spot.pages.SingleUploadPage;
import spot.pages.StartPage;
import spot.pages.notAdmin.CreateNewCollectionPage;
import spot.pages.notAdmin.HomePage;
import spot.util.TimeStamp;

import org.testng.annotations.BeforeClass;

import java.awt.AWTException;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.TimeoutException;
import org.testng.Assert;
import org.testng.annotations.AfterClass;

public class DataUploadWithoutMetaDataProfileTest extends BaseSelenium/*extends BaseTest*/ {

	private static final Logger log4j = LogManager.getLogger(DataUploadWithoutMetaDataProfileTest.class.getName());

	private LoginPage loginPage;
	private HomePage homePage;
	private CollectionEntryPage collectionEntryPage;

	private HashMap<String, String> files;

	public final String collectionTitle = "Not published test collection without meta data profile: " + TimeStamp.getTimeStamp();

	@AfterClass
	public void afterClass() {
		homePage.logout();
	}

	@BeforeClass
	public void beforeClass() {
		navigateToStartPage();

		loginPage = new StartPage(driver).openLoginForm();

		files = new HashMap<String, String>();
		files.put("Chrysanthemum.jpg", "C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
//		files.put("SamplePNGFile.png", "C:\\Users\\Public\\Pictures\\Sample Pictures\\SamplePNGFile.png");
//		files.put("SampleWordFile.docx", "C:\\Users\\Public\\Pictures\\Sample Pictures\\SampleWordFile.docx");

//		new StartPage(driver).selectLanguage(englishSetup);
	}

	@Test (priority = 1)
	public void loginTest() {
		homePage = loginPage.loginAsAdmin(getPropertyAttribute(spotRUUserName), getPropertyAttribute(spotRUPassWord));

		String adminFullName = getPropertyAttribute(ruFamilyName) + ", " + getPropertyAttribute(ruGivenName);
		Assert.assertEquals(homePage.getLoggedInUserFullName(), adminFullName, "User name doesn't match");

	}

	@Test(priority = 2)
	public void createCollectionWithoutMetaDataProfileTest() {

		CreateNewCollectionPage createNewCollectionPage = homePage.goToCreateNewCollectionPage();

		String collectionDescription = "This collection has no meta data profile. It is not being published.";

		collectionEntryPage = createNewCollectionPage.createCollectionWithoutStandardMetaDataProfile(collectionTitle,
				collectionDescription, getPropertyAttribute(ruGivenName), getPropertyAttribute(ruFamilyName),
				getPropertyAttribute(ruOrganizationName));

		Assert.assertTrue(
				collectionEntryPage.getMessageComponent().getMessageTypeOfPageMessageArea() == MessageType.INFO,
				"Collection couldn't be created");

		String siteContentHeadline = collectionEntryPage.getSiteContentHeadline();
		Assert.assertTrue(siteContentHeadline.equals(collectionTitle), "Collection title not correct");
	}

	@Test (priority = 3)
	public void uploadFilesTest() throws AWTException {

		for (Map.Entry<String, String> file : files.entrySet()) {
			String fileTitle = file.getKey();
			String filePath = file.getValue();

			testFile(fileTitle, filePath);
		}
		navigateToStartPage();
	}

	private void testFile(String fileTitle, String filePath) throws AWTException {
		SingleUploadPage singleUploadPage = homePage.goToSingleUploadPage();

		DetailedItemViewPage detailedItemViewPage = null;

		try {
			detailedItemViewPage = singleUploadPage.upload(filePath, collectionTitle);

			Assert.assertTrue(detailedItemViewPage.isDetailedItemViewPageDisplayed(), "Detailed item view page not displayed");

			Assert.assertTrue(detailedItemViewPage.getCollectionTitle().equals(collectionTitle), "Something went wrong with uploading file; collection title not the one that was selected");

			Assert.assertTrue(detailedItemViewPage.getFileTitle().equals(fileTitle), "Something went wrong with uploading file; file title not the one that was selected");

		} catch (TimeoutException timeOutExc) {
			log4j.error(timeOutExc);
			Assert.assertTrue(false, "Time out error regarding single upload: Either collection couldn't be found or the button 'save' didn't appear. Summarized: The upload failed.");
		}

	}

}


text:
<?php
/**
 * Class WPML_Option_Settings
 *
 * @package  WPML
 * @category WordPress Plugins
 * @version  2.1.7
 * @author   Victor Villaverde Laan
 * @link     http://www.freelancephp.net/
 * @link     https://github.com/freelancephp/WP-Mailto-Links
 * @link     https://wordpress.org/plugins/wp-mailto-links/
 * @license  Dual licensed under the MIT and GPLv2+ licenses
 */
final class WPML_Option_Settings extends MyDevLib_OptionAbstract_0x5x0
{

    /**
     * @var string
     */
    protected $optionGroup = 'wp-mailto-links';

    /**
     * Recommended optionGroup and optionName have same name
     * @var string
     */
    protected $optionName = 'wp-mailto-links';

    /**
     * @var array
     */
    protected $defaultValues = array(
        'protect'           => 1,
        'convert_emails'    => 1,
        'filter_body'       => 1,
        'filter_posts'      => 1,
        'filter_comments'   => 1,
        'filter_widgets'    => 1,
        'filter_rss'        => 1,
        'filter_head'       => 1,
        'input_strong_protection' => 0,
        'protection_text'   => '*protected email*',
        'mail_icon'         => '',
        'image'              => 1,
        'dashicons'         => '',
        'fontawesome'       => '',
        'show_icon_before'  => 0,
        'image_no_icon'     => 0,
        'no_icon_class'     => 'no-mail-icon',
        'class_name'        => 'mail-link',
        'security_check'    => 0,
        'own_admin_menu'    => 1,
    );

}

/*?>*/

redpajama_set_name: RedPajamaGithub


text:
% Removes DC component from image patches
% Data given as a matrix where each patch is one column vectors
% That is, the patches are vectorized.

function [Y,meanX]=removeDC(X, dim);

% Subtract local mean gray-scale value from each patch in X to give output Y
if nargin == 1
    dim = 1;
end

meanX = mean(X,dim);

if dim==1
    Y = X-meanX(ones(size(X,1),1),:);
else
    Y = X-meanX(:,ones(size(X,2),1));
end

return;


text:
module Organizer
  module Filter
    module Selector
      def select_filters(_filters, _filter_methods)
        selected_filters = Organizer::Filter::Collection.new
        return selected_filters if _filters.blank? || _filter_methods.blank?

        _filter_methods.each do |filter_name, value|
          filter = _filters.find_by_name(filter_name)
          raise_error(:unknown_filter) unless filter

          if filter
            filter.value = value
            selected_filters << filter
          end
        end

        selected_filters
      end
    end
  end
end


text:
require 'thread'

module Discordrb
  # Gateway packet opcodes
  module Opcodes
    # **Received** when Discord dispatches an event to the gateway (like MESSAGE_CREATE, PRESENCE_UPDATE or whatever).
    # The vast majority of received packets will have this opcode.
    DISPATCH = 0

    # **Two-way**: The client has to send a packet with this opcode every ~40 seconds (actual interval specified in
    # READY or RESUMED) and the current sequence number, otherwise it will be disconnected from the gateway. In certain
    # cases Discord may also send one, specifically if two clients are connected at once.
    HEARTBEAT = 1

    # **Sent**: This is one of the two possible ways to initiate a session after connecting to the gateway. It
    # should contain the authentication token along with other stuff the server has to know right from the start, such
    # as large_threshold and, for older gateway versions, the desired version.
    IDENTIFY = 2

    # **Sent**: Packets with this opcode are used to change the user's status and played game. (Sending this is never
    # necessary for a gateway client to behave correctly)
    PRESENCE = 3

    # **Sent**: Packets with this opcode are used to change a user's voice state (mute/deaf/unmute/undeaf/etc.). It is
    # also used to connect to a voice server in the first place. (Sending this is never necessary for a gateway client
    # to behave correctly)
    VOICE_STATE = 4

    # **Sent**: This opcode is used to ping a voice server, whatever that means. The functionality of this opcode isn't
    # known well but non-user clients should never send it.
    VOICE_PING = 5

    # **Sent**: This is the other of two possible ways to initiate a gateway session (other than {IDENTIFY}). Rather
    # than starting an entirely new session, it resumes an existing session by replaying all events from a given
    # sequence number. It should be used to recover from a connection error or anything like that when the session is
    # still valid - sending this with an invalid session will cause an error to occur.
    RESUME = 6

    # **Received**: Discord sends this opcode to indicate that the client should reconnect to a different gateway
    # server because the old one is currently being decommissioned. Counterintuitively, this opcode also invalidates the
    # session - the client has to create an entirely new session with the new gateway instead of resuming the old one.
    RECONNECT = 7

    # **Sent**: This opcode identifies packets used to retrieve a list of members from a particular server. There is
    # also a REST endpoint available for this, but it is inconvenient to use because the client has to implement
    # pagination itself, whereas sending this opcode lets Discord handle the pagination and the client can just add
    # members when it receives them. (Sending this is never necessary for a gateway client to behave correctly)
    REQUEST_MEMBERS = 8

    # **Received**: The functionality of this opcode is less known than the others but it appears to specifically
    # tell the client to invalidate its local session and continue by {IDENTIFY}ing.
    INVALIDATE_SESSION = 9

    # **Received**: Sent immediately for any opened connection; tells the client to start heartbeating early on, so the
    # server can safely search for a session server to handle the connection without the connection being terminated.
    # As a side-effect, large bots are less likely to disconnect because of very large READY parse times.
    HELLO = 10

    # **Received**: Returned after a heartbeat was sent to the server. This allows clients to identify and deal with
    # zombie connections that don't dispatch any events anymore.
    HEARTBEAT_ACK = 11
  end

  # This class stores the data of an active gateway session. Note that this is different from a websocket connection -
  # there may be multiple sessions per connection or one session may persist over multiple connections.
  class Session
    attr_reader :session_id
    attr_accessor :sequence

    def initialize(session_id)
      @id = session_id
      @sequence = 0
      @suspended = false
      @invalid = false
    end

    def suspend
      @suspended = true
    end

    def suspended?
      @suspended
    end

    def invalidate
      @invalid = true
    end

    def invalid?
      @invalid
    end

    def should_resume?
      suspended? && !invalid?
    end
  end

  # Client for the Discord gateway protocol
  class Gateway
    # How many members there need to be in a server for it to count as "large"
    LARGE_THRESHOLD = 100

    # The version of the gateway that's supposed to be used.
    GATEWAY_VERSION = 6

    def initialize(bot, token)
      @token = token
      @bot = bot

      @getc_mutex = Mutex.new

      # Whether the connection to the gateway has succeeded yet
      @ws_success = false
    end

    # Connect to the gateway server in a separate thread
    def run_async
      @ws_thread = Thread.new do
        Thread.current[:discordrb_name] = 'websocket'
        connect_loop
        LOGGER.warn('The WS loop exited! Not sure if this is a good thing')
      end

      LOGGER.debug('WS thread created! Now waiting for confirmation that everything worked')
      sleep(0.5) until @ws_success
      LOGGER.debug('Confirmation received! Exiting run.')
    end

    # Prevents all further execution until the websocket thread stops (e. g. through a closed connection).
    def sync
      @ws_thread.join
    end

    # Whether the WebSocket connection to the gateway is currently open
    def open?
      @handshake && @handshake.finished? && !@closed
    end

    # Stops the bot gracefully, disconnecting the websocket without immediately killing the thread. This means that
    # Discord is immediately aware of the closed connection and makes the bot appear offline instantly.
    #
    # If this method doesn't work or you're looking for something more drastic, use {#kill} instead.
    def stop(no_sync = false)
      @should_reconnect = false
      close(no_sync)
    end

    # Kills the websocket thread, stopping all connections to Discord.
    def kill
      @ws_thread.kill
    end

    # Notifies the {#run_async} method that everything is ready and the caller can now continue (i.e. with syncing,
    # or with doing processing and then syncing)
    def notify_ready
      @ws_success = true
    end

    # Injects a reconnect event (op 7) into the event processor, causing Discord to reconnect to the given gateway URL.
    # If the URL is set to nil, it will reconnect and get an entirely new gateway URL. This method has not much use
    # outside of testing and implementing highly custom reconnect logic.
    # @param url [String, nil] the URL to connect to or nil if one should be obtained from Discord.
    def inject_reconnect(url = nil)
      # When no URL is specified, the data should be nil, as is the case with Discord-sent packets.
      data = url ? { url: url } : nil

      handle_message({
        op: Opcodes::RECONNECT,
        d: data
      }.to_json)
    end

    # Injects a resume packet (op 6) into the gateway. If this is done with a running connection, it will cause an
    # error. It has no use outside of testing stuff that I know of, but if you want to use it anyway for some reason,
    # here it is.
    # @param seq [Integer, nil] The sequence ID to inject, or nil if the currently tracked one should be used.
    def inject_resume(seq)
      send_resume(raw_token, @session_id, seq || @sequence)
    end

    # Injects a terminal gateway error into the handler. Useful for testing the reconnect logic.
    # @param e [Exception] The exception object to inject.
    def inject_error(e)
      handle_internal_close(e)
    end

    # Sends a heartbeat with the last received packet's seq (to acknowledge that we have received it and all packets
    # before it), or if none have been received yet, with 0.
    # @see #send_heartbeat
    def heartbeat
      send_heartbeat(@session ? @session.sequence : 0)
    end

    # Sends a heartbeat packet (op 1). This tells Discord that the current connection is still active and that the last
    # packets until the given sequence have been processed (in case of a resume).
    # @param sequence [Integer] The sequence number for which to send a heartbeat.
    def send_heartbeat(sequence)
      send_packet(Opcodes::HEARTBEAT, sequence)
    end

    # Identifies to Discord with the default parameters.
    # @see #send_identify
    def identify
      send_identify(@token, {
                      :'$os' => RUBY_PLATFORM,
                      :'$browser' => 'discordrb',
                      :'$device' => 'discordrb',
                      :'$referrer' => '',
                      :'$referring_domain' => ''
                    }, true, 100)
    end

    # Sends an identify packet (op 2). This starts a new session on the current connection and tells Discord who we are.
    # This can only be done once a connection.
    # @param token [String] The token with which to authorise the session. If it belongs to a bot account, it must be
    #   prefixed with "Bot ".
    # @param properties [Hash<Symbol => String>] A list of properties for Discord to use in analytics. The following
    #   keys are recognised:
    #
    #    - "$os" (recommended value: the operating system the bot is running on)
    #    - "$browser" (recommended value: library name)
    #    - "$device" (recommended value: library name)
    #    - "$referrer" (recommended value: empty)
    #    - "$referring_domain" (recommended value: empty)
    #
    # @param compress [true, false] Whether certain large packets should be compressed using zlib.
    # @param large_threshold [Integer] The member threshold after which a server counts as large and will have to have
    #   its member list chunked.
    def send_identify(token, properties, compress, large_threshold)
      data = {
        # Don't send a v anymore as it's entirely determined by the URL now
        token: token,
        properties: properties,
        compress: compress,
        large_threshold: large_threshold
      }

      send_packet(Opcodes::IDENTIFY, data)
    end

    # Sends a status update packet (op 3). This sets the bot user's status (online/idle/...) and game playing/streaming.
    # @param status [String] The status that should be set (`online`, `idle`, `dnd`, `invisible`).
    # @param since [Integer] The unix timestamp in milliseconds when the status was set. Should only be provided when
    #   `afk` is true.
    # @param game [Hash<Symbol => Object>, nil] `nil` if no game should be played, or a hash of `:game => "name"` if a
    #   game should be played. The hash can also contain additional attributes for streaming statuses.
    # @param afk [true, false] Whether the status was set due to inactivity on the user's part.
    def send_status_update(status, since, game, afk)
      data = {
        status: status,
        since: since,
        game: game,
        afk: afk
      }

      send_packet(Opcodes::PRESENCE, data)
    end

    # Sends a voice state update packet (op 4). This packet can connect a user to a voice channel, update self mute/deaf
    # status in an existing voice connection, move the user to a new voice channel on the same server or disconnect an
    # existing voice connection.
    # @param server_id [Integer] The ID of the server on which this action should occur.
    # @param channel_id [Integer, nil] The channel ID to connect/move to, or `nil` to disconnect.
    # @param self_mute [true, false] Whether the user should itself be muted to everyone else.
    # @param self_deaf [true, false] Whether the user should be deaf towards other users.
    def send_voice_state_update(server_id, channel_id, self_mute, self_deaf)
      data = {
        guild_id: server_id,
        channel_id: channel_id,
        self_mute: self_mute,
        self_deaf: self_deaf
      }

      send_packet(Opcodes::VOICE_STATE, data)
    end

    # Resumes the session from the last recorded point.
    # @see #send_resume
    def resume
      send_resume(@token, @session.session_id, @session.sequence)
    end

    # Sends a resume packet (op 6). This replays all events from a previous point specified by its packet sequence. This
    # will not work if the packet to resume from has already been acknowledged using a heartbeat, or if the session ID
    # belongs to a now invalid session.
    #
    # If this packet is sent at the beginning of a connection, it will act similarly to an {#identify} in that it
    # creates a session on the current connection. Unlike identify however, this packet can also be sent in an existing
    # session and will just replay some of the events.
    # @param token [String] The token that was used to identify the session to resume.
    # @param session_id [String] The session ID of the session to resume.
    # @param seq [Integer] The packet sequence of the packet after which the events should be replayed.
    def send_resume(token, session_id, seq)
      data = {
        token: token,
        session_id: session_id,
        seq: seq
      }

      send_packet(Opcodes::RESUME, data)
    end

    # Sends a request members packet (op 8). This will order Discord to gradually sent all requested members as dispatch
    # events with type `GUILD_MEMBERS_CHUNK`. It is necessary to use this method in order to get all members of a large
    # server (see `large_threshold` in {#send_identify}), however it can also be used for other purposes.
    # @param server_id [Integer] The ID of the server whose members to query.
    # @param query [String] If this string is not empty, only members whose username starts with this string will be
    #   returned.
    # @param limit [Integer] How many members to send at maximum, or `0` to send all members.
    def send_request_members(server_id, query, limit)
      data = {
        guild_id: server_id,
        query: query,
        limit: limit
      }

      send_packet(Opcodes::REQUEST_MEMBERS, data)
    end

    private

    def setup_heartbeats(interval)
      # We don't want to have redundant heartbeat threads, so if one already exists, don't start a new one
      return if @heartbeat_thread

      @heartbeat_interval = interval
      @heartbeat_thread = Thread.new do
        Thread.current[:discordrb_name] = 'heartbeat'
        loop do
          begin
            # Send a heartbeat if heartbeats are active and either no session exists yet, or an existing session is
            # suspended (e.g. after op7)
            if (@session && !@session.suspended?) || !@session
              sleep @heartbeat_interval
              @bot.raise_heartbeat_event
              heartbeat
            else
              sleep 1
            end
          rescue => e
            LOGGER.error('An error occurred while heartbeating!')
            LOGGER.log_exception(e)
          end
        end
      end
    end

    def connect_loop
      # Initialize falloff so we wait for more time before reconnecting each time
      @falloff = 1.0

      @should_reconnect = true
      loop do
        connect

        break unless @should_reconnect

        if @instant_reconnect
          # We got an op 7! Don't wait before reconnecting
          LOGGER.info('Got an op 7, reconnecting right away')
          @instant_reconnect = false
        else
          wait_for_reconnect
        end

        # Restart the loop, i. e. reconnect
      end
    end

    # Separate method to wait an ever-increasing amount of time before reconnecting after being disconnected in an
    # unexpected way
    def wait_for_reconnect
      # We disconnected in an unexpected way! Wait before reconnecting so we don't spam Discord's servers.
      LOGGER.debug("Attempting to reconnect in #{@falloff} seconds.")
      sleep @falloff

      # Calculate new falloff
      @falloff *= 1.5
      @falloff = 115 + (rand * 10) if @falloff > 120 # Cap the falloff at 120 seconds and then add some random jitter
    end

    # Create and connect a socket using a URI
    def obtain_socket(uri)
      socket = TCPSocket.new(uri.host, uri.port || socket_port(uri))

      if secure_uri?(uri)
        ctx = OpenSSL::SSL::SSLContext.new
        ctx.ssl_version = 'SSLv23'
        ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # use VERIFY_PEER for verification

        cert_store = OpenSSL::X509::Store.new
        cert_store.set_default_paths
        ctx.cert_store = cert_store

        socket = ::OpenSSL::SSL::SSLSocket.new(socket, ctx)
        socket.connect
      end

      socket
    end

    # Whether the URI is secure (connection should be encrypted)
    def secure_uri?(uri)
      %w(https wss).include? uri.scheme
    end

    # The port we should connect to, if the URI doesn't have one set.
    def socket_port(uri)
      secure_uri?(uri) ? 443 : 80
    end

    def find_gateway
      response = API.gateway(@token)
      JSON.parse(response)['url']
    end

    def process_gateway
      raw_url = find_gateway

      # Append a slash in case it's not there (I'm not sure how well WSCS handles it otherwise)
      raw_url += '/' unless raw_url.end_with? '/'

      # Add the parameters we want
      raw_url + "?encoding=json&v=#{GATEWAY_VERSION}"
    end

    def connect
      LOGGER.debug('Connecting')

      # Get the URI we should connect to
      url = process_gateway
      LOGGER.debug("Gateway URL: #{url}")

      # Parse it
      gateway_uri = URI.parse(url)

      # Connect to the obtained URI with a socket
      @socket = obtain_socket(gateway_uri)
      LOGGER.debug('Obtained socket')

      # Initialise some properties
      @handshake = ::WebSocket::Handshake::Client.new(url: url) # Represents the handshake between us and the server
      @handshaked = false # Whether the handshake has finished yet
      @pipe_broken = false # Whether we've received an EPIPE at any time
      @closed = false # Whether the websocket is currently closed

      # We're done! Delegate to the websocket loop
      websocket_loop
    rescue => e
      LOGGER.error('An error occurred while connecting to the websocket!')
      LOGGER.log_exception(e)
    end

    def websocket_loop
      # Send the handshake data that we have so far
      @socket.write(@handshake.to_s)

      # Create a frame to handle received data
      frame = ::WebSocket::Frame::Incoming::Client.new

      until @closed
        begin
          recv_data = nil

          # Get some data from the socket, synchronised so the socket can't be closed during this
          @getc_mutex.synchronize { recv_data = @socket.getc }

          # Check if we actually got data
          unless recv_data
            # If we didn't, wait
            sleep 1
            next
          end

          # Check whether the handshake has finished yet
          if @handshaked
            # If it hasn't, add the received data to the current frame
            frame << recv_data

            # Try to parse a message from the frame
            msg = frame.next
            while msg
              # Check whether the message is a close frame, and if it is, handle accordingly
              if msg.respond_to?(:code) && msg.code
                handle_internal_close(msg)
                break
              end

              # If there is one, handle it and try again
              handle_message(msg.data)
              msg = frame.next
            end
          else
            # If the handshake hasn't finished, handle it
            handle_handshake_data(recv_data)
          end
        rescue => e
          handle_error(e)
        end
      end
    end

    def handle_handshake_data(recv_data)
      @handshake << recv_data
      return unless @handshake.finished?

      @handshaked = true
      handle_open
    end

    def handle_open
    end

    def handle_error(e)
      LOGGER.error('An error occurred in the main websocket loop!')
      LOGGER.log_exception(e)
    end

    def handle_message(msg)
      if msg.byteslice(0) == 'x'
        # The message is compressed, inflate it
        msg = Zlib::Inflate.inflate(msg)
      end

      # Parse packet
      packet = JSON.parse(msg)
      op = packet['op'].to_i

      LOGGER.in(packet)

      # If the packet has a sequence defined (all dispatch packets have one), make sure to update that in the
      # session so it will be acknowledged next heartbeat.
      # Only do this, of course, if a session has been created already; for a READY dispatch (which has s=0 set but is
      # the packet that starts the session in the first place) we need not do any handling since initialising the
      # session will set it to 0 by default.
      @session.sequence = packet['s'] if packet['s'] && @session

      case op
      when Opcodes::DISPATCH
        handle_dispatch(packet)
      when Opcodes::HELLO
        handle_hello(packet)
      when Opcodes::RECONNECT
        handle_reconnect
      when Opcodes::INVALIDATE_SESSION
        handle_invalidate_session
      when Opcodes::HEARTBEAT_ACK
        handle_heartbeat_ack(packet)
      else
        LOGGER.warn("Received invalid opcode #{op} - please report with this information: #{msg}")
      end
    end

    # Op 0
    def handle_dispatch(packet)
      data = packet['d']
      type = packet['t'].intern

      case type
      when :READY
        LOGGER.info("Discord using gateway protocol version: #{data['v']}, requested: #{GATEWAY_VERSION}")

        @session = Session.new(data['session_id'])
        @session.sequence = 0
      when :RESUMED
        # The RESUMED event is received after a successful op 6 (resume). It does nothing except tell the bot the
        # connection is initiated (like READY would). Starting with v5, it doesn't set a new heartbeat interval anymore
        # since that is handled by op 10 (HELLO).
        LOGGER.debug('Connection resumed')
        return
      end

      @bot.dispatch(type, data)
    end

    # Op 7
    def handle_reconnect
      @instant_reconnect = true
      close

      # Suspend session so we resume afterwards
      @session.suspend
    end

    # Op 9
    def handle_invalidate_session
      LOGGER.debug('Received op 9, invalidating session and re-identifying.')

      if @session
        @session.invalidate
      else
        LOGGER.warn('Received op 9 without a running session! Not invalidating, we *should* be fine though.')
      end

      identify
    end

    # Op 10
    def handle_hello(packet)
      LOGGER.debug('Hello!')

      # The heartbeat interval is given in ms, so divide it by 1000 to get seconds
      interval = packet['d']['heartbeat_interval'].to_f / 1000.0
      setup_heartbeats(interval)

      LOGGER.debug("Trace: #{packet['d']['_trace']}")

      if @session && @session.should_resume?
        resume
      else
        identify
      end
    end

    # Op 11
    def handle_heartbeat_ack(packet)
      LOGGER.debug("Received heartbeat ack for packet: #{packet.inspect}")
    end

    # Called when the websocket has been disconnected in some way - say due to a pipe error while sending
    def handle_internal_close(e)
      close
      handle_close(e)
    end

    def handle_close(e)
      if e.respond_to? :code
        # It is a proper close frame we're dealing with, print reason and message to console
        LOGGER.error('Websocket close frame received!')
        LOGGER.error("Code: #{e.code}")
        LOGGER.error("Message: #{e.data}")
      elsif e.is_a? Exception
        # Log the exception
        LOGGER.error('The websocket connection has closed due to an error!')
        LOGGER.log_exception(e)
      else
        LOGGER.error("The websocket connection has closed: #{e.inspect}")
      end
    end

    def send_packet(op, packet)
      data = {
        op: op,
        d: packet
      }

      send(data.to_json)
    end

    def send(data, type = :text)
      LOGGER.out(data)

      unless @handshaked && !@closed
        # If we're not handshaked or closed, it means there's no connection to send anything to
        raise 'Tried to send something to the websocket while not being connected!'
      end

      # Create the frame we're going to send
      frame = ::WebSocket::Frame::Outgoing::Client.new(data: data, type: type, version: @handshake.version)

      # Try to send it
      begin
        @socket.write frame.to_s
      rescue Errno::EPIPE => e
        # There has been an error!
        @pipe_broken = true
        handle_internal_close(e)
      end
    end

    def close(no_sync = false)
      # If we're already closed, there's no need to do anything - return
      return if @closed

      # Suspend the session so we don't send heartbeats
      @session.suspend if @session

      # Send a close frame (if we can)
      send nil, :close unless @pipe_broken

      # We're officially closed, notify the main loop.
      # This needs to be synchronised with the getc mutex, so the notification, and especially the actual
      # close afterwards, don't coincide with the main loop reading something from the SSL socket.
      # This would cause a segfault due to (I suspect) Ruby bug #12292: https://bugs.ruby-lang.org/issues/12292
      if no_sync
        @closed = true
      else
        @getc_mutex.synchronize { @closed = true }
      end

      # Close the socket if possible
      @socket.close if @socket
      @socket = nil

      # Make sure we do necessary things as soon as we're closed
      handle_close(nil)
    end
  end
end


text:
import fs from 'fs-extra';

export interface TableDef{
    name:string
}

export class BaseApp{
    tables:TableDef[]=[{name:'usuarios'}];
    constructor(){
    }
    getName():string{
        return "no esta"
    }
    getTables():TableDef[]{
        return this.tables;
    }
    async installPart(part:string, content:string){
        await fs.writeFile(`./out/${part}.txt`,content,{encoding:'utf8'});
        return;
    }
    async install():Promise<void>{
        console.log('INSTALLING',this.getName());
        await this.installPart('base-part','la base');
        await this.installPart('table-part',JSON.stringify(this.getTables(),null,'    '));
        return ;
    }
}


text:
/*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016-2017.
*/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;

namespace ShiftDrive {

    /// <summary>
    /// An INI-like settings file parser.
    /// </summary>
    internal sealed class SettingsFile {

        private readonly Dictionary<string, string> properties;
        private readonly string filename;

        /// <summary>
        /// Constructs a new SettingsFile by parsing a file from disk.
        /// </summary>
        /// <param name="filename">The path to the settings file to read.</param>
        public SettingsFile(string filename) {
            this.filename = filename;
            properties = new Dictionary<string, string>();

            if (!File.Exists(filename)) return;
            using (StreamReader reader = new StreamReader(filename, Encoding.UTF8)) {
                while (!reader.EndOfStream) {
                    // read a line, ignore comments, and split into key/value parts
                    string line = reader.ReadLine();
                    if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#")) continue;

                    string[] parts = line.Split(new[] {'='}, 2);
                    if (parts.Length != 2) continue;

                    // save key/value pair
                    string key = parts[0].Trim().ToUpperInvariant();
                    if (!properties.ContainsKey(key))
                        properties.Add(key, parts[1].Trim());
                }
            }
        }

        /// <summary>
        /// Saves this SettingsFile instance to disk, using the filename that was passed on creation.
        /// </summary>
        public void Save() {
            try {
                using (StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8)) {
                    foreach (var pair in properties) {
                        writer.WriteLine($"{pair.Key} = {pair.Value}");
                    }
                }
            } catch (IOException ex) {
                Logger.LogError($"Failed to write SettingsFile {filename}: {ex.Message}");
            }
        }

        /// <summary>
        /// Returns a string from the property table.
        /// </summary>
        /// <param name="key">The key to look up in the table. Not case-sensitive.</param>
        /// <param name="def">The default value to return if the key is missing.</param>
        public string GetString(string key, string def = null) {
            if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));

            key = key.ToUpperInvariant();
            return properties.ContainsKey(key) ? properties[key] : def;
        }

        /// <summary>
        /// Stores a value in the property table.
        /// </summary>
        /// <param name="key">The key to save the value under. Not case-sensitive.</param>
        /// <param name="value">The value to save.</param>
        public void SetString(string key, string value) {
            key = key.ToUpperInvariant();
            if (properties.ContainsKey(key))
                properties[key] = value;
            else
                properties.Add(key, value);
        }

        /// <summary>
        /// Parses and returns an entry from the property table as an integer.
        /// </summary>
        /// <param name="key">The key to look up in the table. Not case-sensitive.</param>
        /// <param name="def">The default value to return if the key is missing, or the value cannot be parsed.</param>
        public int GetInt32(string key, int def = 0) {
            string prop = GetString(key);
            if (prop == null) return def;

            int outval;
            return Int32.TryParse(prop, NumberStyles.Integer, CultureInfo.InvariantCulture, out outval)
                ? outval
                : def;
        }

        /// <summary>
        /// Saves an integer in the property table.
        /// </summary>
        /// <param name="key">The key to save the value under. Not case-sensitive.</param>
        /// <param name="value">The value to save.</param>
        public void SetInt32(string key, int value) {
            SetString(key, value.ToString(CultureInfo.InvariantCulture));
        }

        /// <summary>
        /// Parses and returns an entry from the property table as a boolean.
        /// </summary>
        /// <param name="key">The key to look up in the table. Not case-sensitive.</param>
        /// <param name="def">The default value to return if the key is missing, or the value cannot be parsed.</param>
        public bool GetBool(string key, bool def = false) {
            string prop = GetString(key);
            if (prop == null) return def;

            return !prop.Equals("0", StringComparison.InvariantCultureIgnoreCase);
        }

        /// <summary>
        /// Saves an integer in the property table.
        /// </summary>
        /// <param name="key">The key to save the value under. Not case-sensitive.</param>
        /// <param name="value">The value to save.</param>
        public void SetBool(string key, bool value) {
            SetString(key, value ? "1" : "0");
        }

    }

}


text:
package org.duracloud.chunk.manifest;

import java.util.List;

/**
 * This class is a simple bean for a ChunksManifest.
 *
 * @author Andrew Woods
 * Date: Feb 9, 2010
 */
public class ChunksManifestBean {

    private ManifestHeader header;
    private List<ManifestEntry> entries;

    public ManifestHeader getHeader() {
        return header;
    }

    public void setHeader(ManifestHeader header) {
        this.header = header;
    }

    public List<ManifestEntry> getEntries() {
        return entries;
    }

    public void setEntries(List<ManifestEntry> entries) {
        this.entries = entries;
    }

    /**
     * Manifest Header inner class.
     */
    public static class ManifestHeader {
        private String sourceContentId;
        private String sourceMimetype;
        private String sourceMD5;
        private long sourceByteSize;

        public ManifestHeader(String sourceContentId,
                              String sourceMimetype,
                              long sourceByteSize) {
            this.sourceContentId = sourceContentId;
            this.sourceMimetype = sourceMimetype;
            this.sourceByteSize = sourceByteSize;
        }

        public String getSourceContentId() {
            return sourceContentId;
        }

        public String getSourceMimetype() {
            return sourceMimetype;
        }

        public long getSourceByteSize() {
            return sourceByteSize;
        }

        public String getSourceMD5() {
            return sourceMD5;
        }

        public void setSourceMD5(String sourceMD5) {
            this.sourceMD5 = sourceMD5;
        }
    }

    /**
     * Manifest Entry inner class.
     */
    public static class ManifestEntry {
        private String chunkId;
        private String chunkMD5;
        private int index;
        private long byteSize;

        public ManifestEntry(String chunkId,
                             String chunkMD5,
                             int index,
                             long byteSize) {
            this.chunkId = chunkId;
            this.chunkMD5 = chunkMD5;
            this.index = index;
            this.byteSize = byteSize;
        }

        public String getChunkId() {
            return chunkId;
        }

        public String getChunkMD5() {
            return chunkMD5;
        }

        public int getIndex() {
            return index;
        }

        public long getByteSize() {
            return byteSize;
        }
    }
}


text:
using Foundation;
using System.CodeDom.Compiler;

namespace iOSTenThree
{
	[Register ("ViewController")]
	partial class ViewController
	{
		[Outlet]
		UIKit.UIButton AlternateIconButton { get; set; }

		[Outlet]
		UIKit.UIButton PrimaryIconButton { get; set; }

		[Outlet]
		UIKit.UIScrollView ScrollView { get; set; }

		[Outlet]
		UIKit.UIImageView XamarinImage { get; set; }

		[Action ("ToggleIndexDisplayMode:")]
		partial void ToggleIndexDisplayMode (Foundation.NSObject sender);

		[Action ("UseAlternateIcon:")]
		partial void UseAlternateIcon (Foundation.NSObject sender);

		[Action ("UsePrimaryIcon:")]
		partial void UsePrimaryIcon (Foundation.NSObject sender);

		void ReleaseDesignerOutlets ()
		{
			if (ScrollView != null) {
				ScrollView.Dispose ();
				ScrollView = null;
			}

			if (XamarinImage != null) {
				XamarinImage.Dispose ();
				XamarinImage = null;
			}

			if (PrimaryIconButton != null) {
				PrimaryIconButton.Dispose ();
				PrimaryIconButton = null;
			}

			if (AlternateIconButton != null) {
				AlternateIconButton.Dispose ();
				AlternateIconButton = null;
			}
		}
	}
}


text:
extern crate mudi;
use mudi::Array;

fn main() {
    let array = Array::from_element(0.0, (2, 6));
    array[(1, -1)];
    //~^ error: unary negation of unsigned integer
}


text:
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// Test of Vincent's reduction for the chuncker demo

using System;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;

namespace ChunkerTest
{
  class Chunker
  {
    string src;
    int ChunkSize;

    [ContractInvariantMethod]
    private void ObjectInvariant()
    {
      Contract.Invariant(src != null);
      Contract.Invariant(0 < ChunkSize);
      Contract.Invariant(0 <= n);
      Contract.Invariant(n <= src.Length);
    }
    int n;  // the number of characters returned so far

    /// <summary>
    /// Also tests OOB from mscorlib (on string class).
    /// </summary>
    [ClousotRegressionTest]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 112, MethodILOffset = 0)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 169, MethodILOffset = 0)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 192, MethodILOffset = 0)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 22, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 28, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 46, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 74, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 77)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 31, MethodILOffset = 77)]
    [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=54,MethodILOffset=77)]
    [RegressionOutcome(Outcome=ProofOutcome.True,Message="requires is valid",PrimaryILOffset=79,MethodILOffset=77)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 134)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 36, MethodILOffset = 134)]
    public string/*!*/ NextChunk()
    {
      Contract.Ensures(Contract.Result<string>().Length <= ChunkSize);

      string s;
      if (n + ChunkSize <= src.Length)
      {
        s = src.Substring(n, ChunkSize);

        Contract.Assert(n + s.Length <= src.Length);
      }
      else
      {
        s = src.Substring(n);

        Contract.Assert(n + s.Length <= src.Length);
        Contract.Assert(s.Length <= ChunkSize);
      }
      n += s.Length;

      return s;
    }

    // old version working for both cci1 and cci2
    [ClousotRegressionTest]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 134)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 15, MethodILOffset = 77)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 112, MethodILOffset = 0)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 169, MethodILOffset = 0)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 192, MethodILOffset = 0)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 22, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 28, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 46, MethodILOffset = 223)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 74, MethodILOffset = 223)]
    public string/*!*/ NextChunkOld()
    {
      Contract.Ensures(Contract.Result<string>().Length <= ChunkSize);

      string s;
      if (n + ChunkSize <= src.Length)
      {
        s = HelperMethods.SubstringHelper(src, n, ChunkSize);

        Contract.Assert(n + s.Length <= src.Length);
      }
      else
      {
        s = HelperMethods.SubstringHelper(src, n);

        Contract.Assert(n + s.Length <= src.Length);
        Contract.Assert(s.Length <= ChunkSize);
      }
      n += s.Length;

      return s;
    }

    // Ok: It proves all but the src != null (which is because we are doing the regression without the "-nonnull" analysis
    [ClousotRegressionTest]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = (int)13, MethodILOffset = (int)53)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = (int)28, MethodILOffset = (int)53)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = (int)46, MethodILOffset = (int)53)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = (int)74, MethodILOffset = (int)53)]
    public Chunker(string/*!*/ source, int chunkSize)
    {
      Contract.Requires(0 < chunkSize);
      Contract.Requires(source != null);

      src = source;
      ChunkSize = chunkSize;
      n = 0;
    }

    [ClousotRegressionTest]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 3)]
    [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "requires unproven: startIndex <= this.Length", PrimaryILOffset = 36, MethodILOffset = 3)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 12)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 28, MethodILOffset = 12)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 46, MethodILOffset = 12)]
    [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 74, MethodILOffset = 12)]
    public string NotSatisfyingOOB(string s)
    {
      return s.Substring(5);
    }
  }

  public static class HelperMethods // specific methods with contracts ; contracts are not supposed to be proven
  {
    // This is just to help the ChunckerDemo, so we do not test them
    public static string SubstringHelper(string source, int startIndex)
    {
      Contract.Requires(startIndex <= source.Length);

      // Contract.Ensures(Contract.Result<string>() != null);
      Contract.Ensures(Contract.Result<string>().Length == source.Length - startIndex);
      // Contract.Ensures(source == Contract.OldValue(source));

      return source;
    }

    // This is just to help the ChunckerDemo, so we do not test them
    public static string SubstringHelper(string source, int startIndex, int count)
    {
      Contract.Requires(startIndex + count <= source.Length);

      // Contract.Ensures(Contract.Result<string>() != null);
      Contract.Ensures(Contract.Result<string>().Length == count);
      // Contract.Ensures(source == Contract.OldValue(source));

      return source;
    }

    public static void PexHelper(string s, int i)
    {
      Chunker c = new Chunker(s, i);

      string chunk;
      while ((chunk = c.NextChunk()) != "")
      {
        Console.WriteLine(chunk);
      }
    }

  }

}


text:
function HTMLActuator() {
  this.tileContainer    = document.querySelector(".tile-container");
  this.whiteScoreContainer   = document.querySelector(".white-score-container");
  this.blackScoreContainer   = document.querySelector(".black-score-container");
  this.messageContainer = document.querySelector(".game-message");

  this.whiteScore = 0;
  this.blackScore = 0;
}

HTMLActuator.prototype.actuate = function (grid, metadata) {
  var self = this;

  window.requestAnimationFrame(function () {
    self.clearContainer(self.tileContainer);

    grid.cells.forEach(function (column) {
      column.forEach(function (cell) {
        if (cell) {
          self.addTile(cell);
        }
      });
    });

    self.updateScore("white", metadata.whiteScore);
    self.updateScore("black", metadata.blackScore);

    if (metadata.terminated) {
      if (metadata.whiteWon) {
        self.message(true); // White wins!
      } else if (metadata.blackWon) {
        self.message(false); // Black wins!
      }
    }

  });
};

// Continues the game
HTMLActuator.prototype.continueGame = function () {
  this.clearMessage();
};

HTMLActuator.prototype.clearContainer = function (container) {
  while (container.firstChild) {
    container.removeChild(container.firstChild);
  }
};

HTMLActuator.prototype.addTile = function (tile) {
  var self = this;

  var wrapper   = document.createElement("div");
  var inner     = document.createElement("div");
  var position  = tile.previousPosition || { x: tile.x, y: tile.y };
  var positionClass = this.positionClass(position);

  // We can't use classlist because it somehow glitches when replacing classes
  var classes = ["tile", "tile-" + tile.value, positionClass];

  if (tile.value > 2048) classes.push("tile-super");

  this.applyClasses(wrapper, classes);

  inner.classList.add("tile-inner");
  inner.textContent = tile.value;

  if (tile.previousPosition) {
    // Make sure that the tile gets rendered in the previous position first
    window.requestAnimationFrame(function () {
      classes[2] = self.positionClass({ x: tile.x, y: tile.y });
      self.applyClasses(wrapper, classes); // Update the position
    });
  } else if (tile.mergedFrom) {
    classes.push("tile-merged");
    this.applyClasses(wrapper, classes);

    // Render the tiles that merged
    tile.mergedFrom.forEach(function (merged) {
      self.addTile(merged);
    });
  } else {
    classes.push("tile-new");
    this.applyClasses(wrapper, classes);
  }

  // Add the inner part of the tile to the wrapper
  wrapper.appendChild(inner);

  // Put the tile on the board
  this.tileContainer.appendChild(wrapper);
};

HTMLActuator.prototype.applyClasses = function (element, classes) {
  element.setAttribute("class", classes.join(" "));
};

HTMLActuator.prototype.normalizePosition = function (position) {
  return { x: position.x + 1, y: position.y + 1 };
};

HTMLActuator.prototype.positionClass = function (position) {
  position = this.normalizePosition(position);
  return "tile-position-" + position.x + "-" + position.y;
};

HTMLActuator.prototype.updateScore = function (team, score) {
  if(team === "white"){
    this.clearContainer(this.whiteScoreContainer);
  } else {
    this.clearContainer(this.blackScoreContainer);
  }

  if(team === "white"){
    var difference = score - this.whiteScore;
    this.whiteScore = score;
  } else {
    var difference = score - this.blackScore;
    this.blackScore = score;
  }

  if(team === "white"){
    this.whiteScoreContainer.textContent = this.whiteScore;
  } else {
    this.blackScoreContainer.textContent = this.blackScore;
  }

  if (difference > 0) {
    var addition = document.createElement("div");
    addition.classList.add("score-addition");
    addition.textContent = "+" + difference;

    if(team === "white"){
      this.whiteScoreContainer.appendChild(addition);
    } else {
      this.blackScoreContainer.appendChild(addition);
    }
  }
};

HTMLActuator.prototype.message = function (won) {
  var type    = "game-won";
  var message = won ? "White wins!" : "Black wins!";

  this.messageContainer.classList.add(type);
  this.messageContainer.getElementsByTagName("p")[0].textContent = message;
};

HTMLActuator.prototype.clearMessage = function () {
  // IE only takes one value to remove at a time.
  this.messageContainer.classList.remove("game-won");
};


text:
package org.apache.shindig.gadgets.rewrite;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.config.BasicContainerConfig;
import org.apache.shindig.config.ContainerConfig;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.http.HttpRequest;
import org.apache.shindig.gadgets.http.HttpResponseBuilder;
import org.apache.shindig.gadgets.parse.caja.CajaCssParser;
import org.apache.shindig.gadgets.uri.DefaultProxyUriManager;
import org.apache.shindig.gadgets.uri.ProxyUriManager;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * Tests for CssResponseRewriter.
 */
public class CssResponseRewriterTest extends RewriterTestBase {
  private static final ImmutableMap<String, Object> DEFAULT_CONTAINER_CONFIG = ImmutableMap
      .<String, Object>builder()
      .put(ContainerConfig.CONTAINER_KEY, ImmutableList.of("default"))
      .put(DefaultProxyUriManager.PROXY_HOST_PARAM, "www.test.com")
      .put(DefaultProxyUriManager.PROXY_PATH_PARAM, "/dir/proxy")
      .build();
  private static final ImmutableMap<String, Object> MOCK_CONTAINER_CONFIG = ImmutableMap
      .<String, Object>builder()
      .put(ContainerConfig.CONTAINER_KEY, ImmutableList.of(MOCK_CONTAINER))
      .put(DefaultProxyUriManager.PROXY_HOST_PARAM, "www.mock.com")
      .build();

  private CssResponseRewriter rewriter;
  private CssResponseRewriter rewriterNoOverrideExpires;
  private Uri dummyUri;
  private GadgetContext gadgetContext;
  private ProxyUriManager proxyUriManager;
  private ContentRewriterFeature.Factory factory;

  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    final ContentRewriterFeature.Config overrideFeatureNoOverrideExpires =
        rewriterFeatureFactory.get(createSpecWithRewrite(".*", ".*exclude.*", null, tags));
    ContentRewriterFeature.Factory factoryNoOverrideExpires =
        new ContentRewriterFeature.Factory(null, null) {
          @Override
          public ContentRewriterFeature.Config get(HttpRequest req) {
            return overrideFeatureNoOverrideExpires;
          }
        };
    ContainerConfig config = new BasicContainerConfig();
    config
        .newTransaction()
        .addContainer(DEFAULT_CONTAINER_CONFIG)
        .addContainer(MOCK_CONTAINER_CONFIG)
        .commit();
    proxyUriManager = new DefaultProxyUriManager(config, null);
    rewriterNoOverrideExpires = new CssResponseRewriter(new CajaCssParser(),
        proxyUriManager, factoryNoOverrideExpires);
    final ContentRewriterFeature.Config overrideFeature =
        rewriterFeatureFactory.get(createSpecWithRewrite(".*", ".*exclude.*", "3600", tags));
    factory = new ContentRewriterFeature.Factory(null, null) {
      @Override
      public ContentRewriterFeature.Config get(HttpRequest req) {
        return overrideFeature;
      }
    };

    rewriter = new CssResponseRewriter(new CajaCssParser(),
        proxyUriManager, factory);
    dummyUri = Uri.parse("http://www.w3c.org");
    gadgetContext = new GadgetContext() {
      @Override
      public Uri getUrl() {
        return dummyUri;
      }
    };
  }

  @Test
  public void testCssBasic() throws Exception {
    String content = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic.css"));
    String expected = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic-expected.css"));
    HttpRequest request = new HttpRequest(Uri.parse("http://www.example.org/path/rewritebasic.css"));
    request.setMethod("GET");
    request.setGadget(SPEC_URL);

    HttpResponseBuilder response = new HttpResponseBuilder().setHeader("Content-Type", "text/css")
        .setResponseString(content);
    rewriter.rewrite(request, response);

    assertEquals(StringUtils.deleteWhitespace(expected),
        StringUtils.deleteWhitespace(response.getContent()));
  }

  @Test
  public void testCssBasicNoOverrideExpires() throws Exception {
    String content = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic.css"));
    String expected = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic-expected.css"));
    expected = expected.replace("refresh=3600", "refresh=86400");
    HttpRequest request = new HttpRequest(Uri.parse("http://www.example.org/path/rewritebasic.css"));
    request.setMethod("GET");
    request.setGadget(SPEC_URL);

    HttpResponseBuilder response = new HttpResponseBuilder().setHeader("Content-Type", "text/css")
      .setResponseString(content);
    rewriterNoOverrideExpires.rewrite(request, response);

    assertEquals(StringUtils.deleteWhitespace(expected),
        StringUtils.deleteWhitespace(response.getContent()));
  }

  @Test
  public void testCssBasicNoCache() throws Exception {
    String content = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic.css"));
    String expected = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic-expected.css"));
    expected = expected.replace("nocache=0", "nocache=1");
    HttpRequest request = new HttpRequest(Uri.parse("http://www.example.org/path/rewritebasic.css"));
    request.setMethod("GET");
    request.setGadget(SPEC_URL);
    request.setIgnoreCache(true);

    HttpResponseBuilder response = new HttpResponseBuilder().setHeader("Content-Type", "text/css")
      .setResponseString(content);
    rewriter.rewrite(request, response);

    assertEquals(StringUtils.deleteWhitespace(expected),
        StringUtils.deleteWhitespace(response.getContent()));
  }

  @Test
  public void testCssWithContainerProxy() throws Exception {
    String content = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic.css"));
    String expected = IOUtils.toString(this.getClass().getClassLoader().
        getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic-expected.css"));
    expected = replaceDefaultWithMockServer(expected);
    expected = expected.replace("container=default", "container=" + MOCK_CONTAINER);
    rewriter = new CssResponseRewriter(new CajaCssParser(),
        proxyUriManager, factory);

    HttpRequest request = new HttpRequest(Uri.parse("http://www.example.org/path/rewritebasic.css"));
    request.setMethod("GET");
    request.setGadget(SPEC_URL);
    request.setContainer(MOCK_CONTAINER);

    HttpResponseBuilder response = new HttpResponseBuilder().setHeader("Content-Type", "text/css")
      .setResponseString(content);

    rewriter.rewrite(request, response);

    assertEquals(StringUtils.deleteWhitespace(expected),
        StringUtils.deleteWhitespace(response.getContent()));
  }

  @Test
  public void testNoRewriteUnknownMimeType() throws Exception {
    HttpRequest req = control.createMock(HttpRequest.class);
    EasyMock.expect(req.getRewriteMimeType()).andReturn("unknown");
    control.replay();
    int changesBefore = fakeResponse.getNumChanges();
    rewriter.rewrite(req, fakeResponse);
    assertEquals(changesBefore, fakeResponse.getNumChanges());
    control.verify();
  }

  private void validateRewritten(String content, Uri base, String expected) throws Exception {
    HttpResponseBuilder response = new HttpResponseBuilder().setHeader("Content-Type", "text/css");
    response.setContent(content);
    HttpRequest request = new HttpRequest(base);
    rewriter.rewrite(request, response);
    assertEquals(StringUtils.deleteWhitespace(expected),
        StringUtils.deleteWhitespace(response.getContent()));
  }

  private void validateRewritten(String content, String expected) throws Exception {
    validateRewritten(content, dummyUri, expected);
  }

  @Test
  public void testUrlDeclarationRewrite() throws Exception {
    String original =
        "div {list-style-image:url('http://a.b.com/bullet.gif');list-style-position:outside;margin:5px;padding:0}\n" +
         ".someid {background-image:url(http://a.b.com/bigimg.png);float:right;width:165px;height:23px;margin-top:4px;margin-left:5px}";
    String rewritten =
        "div {list-style-image:url('//www.test.com/dir/proxy?container=default"
            + "&gadget=http%3A%2F%2Fwww.w3c.org&debug=0&nocache=0"
            + "&url=http%3A%2F%2Fa.b.com%2Fbullet.gif');\n"
            + "list-style-position:outside;margin:5px;padding:0}\n"
            + ".someid {background-image:url('//www.test.com/dir/proxy?container=default"
            + "&gadget=http%3A%2F%2Fwww.w3c.org&debug=0&nocache=0"
            + "&url=http%3A%2F%2Fa.b.com%2Fbigimg.png');\n"
            + "float:right;width:165px;height:23px;margin-top:4px;margin-left:5px}";
    validateRewritten(original, rewritten);
  }

  @Test
  public void testExtractImports() throws Exception {
    String original = " @import url(www.example.org/some.css);\n" +
        "@import url('www.example.org/someother.css');\n" +
        "@import url(\"www.example.org/another.css\");\n" +
        " div { color: blue; }\n" +
        " p { color: black; }\n" +
        " span { color: red; }";
    String expected = " div { color: blue; }\n" +
        " p { color: black; }\n" +
        " span { color: red; }";
    StringWriter sw = new StringWriter();
    List<String> stringList = rewriter
        .rewrite(new StringReader(original), dummyUri,
            CssResponseRewriter.uriMaker(proxyUriManager, defaultRewriterFeature), sw,
            true, gadgetContext);
    assertEquals(StringUtils.deleteWhitespace(expected),
        StringUtils.deleteWhitespace(sw.toString()));
    assertEquals(Lists.newArrayList("www.example.org/some.css",
        "www.example.org/someother.css", "www.example.org/another.css"), stringList);
  }

  @Test
  public void testMalformedImport() throws Exception {
    String original = " @import \"www.example.org/some.css\";\n" +
        " span { color: red; }";
    String expected = " span { color: red; }";
    StringWriter sw = new StringWriter();
    List<String> stringList = rewriter
        .rewrite(new StringReader(original), dummyUri,
            CssResponseRewriter.uriMaker(proxyUriManager, defaultRewriterFeature), sw,
            true, gadgetContext);
    assertEquals(StringUtils.deleteWhitespace(expected),
        StringUtils.deleteWhitespace(sw.toString()));
    assertEquals(Lists.newArrayList("www.example.org/some.css"), stringList);
  }
}


text:
class GURL;

namespace base {
class FilePath;
}

namespace net {

class CookieOptions;
class HttpRequestHeaders;
class HttpResponseHeaders;
class ProxyInfo;
class URLRequest;

class NET_EXPORT NetworkDelegateImpl : public NetworkDelegate {
 public:
  ~NetworkDelegateImpl() override {}

 private:
  // This is the interface for subclasses of NetworkDelegate to implement. These
  // member functions will be called by the respective public notification
  // member function, which will perform basic sanity checking.

  // Called before a request is sent. Allows the delegate to rewrite the URL
  // being fetched by modifying |new_url|. If set, the URL must be valid. The
  // reference fragment from the original URL is not automatically appended to
  // |new_url|; callers are responsible for copying the reference fragment if
  // desired.
  // |callback| and |new_url| are valid only until OnURLRequestDestroyed is
  // called for this request. Returns a net status code, generally either OK to
  // continue with the request or ERR_IO_PENDING if the result is not ready yet.
  // A status code other than OK and ERR_IO_PENDING will cancel the request and
  // report the status code as the reason.
  //
  // The default implementation returns OK (continue with request).
  int OnBeforeURLRequest(URLRequest* request,
                         const CompletionCallback& callback,
                         GURL* new_url) override;

  // Called right before the HTTP headers are sent. Allows the delegate to
  // read/write |headers| before they get sent out. |callback| and |headers| are
  // valid only until OnCompleted or OnURLRequestDestroyed is called for this
  // request.
  // See OnBeforeURLRequest for return value description. Returns OK by default.
  int OnBeforeSendHeaders(URLRequest* request,
                          const CompletionCallback& callback,
                          HttpRequestHeaders* headers) override;

  // Called after a proxy connection. Allows the delegate to read/write
  // |headers| before they get sent out. |headers| is valid only until
  // OnCompleted or OnURLRequestDestroyed is called for this request.
  void OnBeforeSendProxyHeaders(URLRequest* request,
                                const ProxyInfo& proxy_info,
                                HttpRequestHeaders* headers) override;

  // Called right before the HTTP request(s) are being sent to the network.
  // |headers| is only valid until OnCompleted or OnURLRequestDestroyed is
  // called for this request.
  void OnSendHeaders(URLRequest* request,
                     const HttpRequestHeaders& headers) override;

  // Called for HTTP requests when the headers have been received.
  // |original_response_headers| contains the headers as received over the
  // network, these must not be modified. |override_response_headers| can be set
  // to new values, that should be considered as overriding
  // |original_response_headers|.
  // If the response is a redirect, and the Location response header value is
  // identical to |allowed_unsafe_redirect_url|, then the redirect is never
  // blocked and the reference fragment is not copied from the original URL
  // to the redirection target.
  //
  // |callback|, |original_response_headers|, and |override_response_headers|
  // are only valid until OnURLRequestDestroyed is called for this request.
  // See OnBeforeURLRequest for return value description. Returns OK by default.
  int OnHeadersReceived(
      URLRequest* request,
      const CompletionCallback& callback,
      const HttpResponseHeaders* original_response_headers,
      scoped_refptr<HttpResponseHeaders>* override_response_headers,
      GURL* allowed_unsafe_redirect_url) override;

  // Called right after a redirect response code was received.
  // |new_location| is only valid until OnURLRequestDestroyed is called for this
  // request.
  void OnBeforeRedirect(URLRequest* request, const GURL& new_location) override;

  // This corresponds to URLRequestDelegate::OnResponseStarted.
  void OnResponseStarted(URLRequest* request) override;

  // Called when bytes are received from the network, such as after receiving
  // headers or reading raw response bytes. This includes localhost requests.
  // |bytes_received| is the number of bytes measured at the application layer
  // that have been received over the network for this request since the last
  // time OnNetworkBytesReceived was called. |bytes_received| will always be
  // greater than 0.
  // Currently, this is only implemented for HTTP transactions, and
  // |bytes_received| does not include TLS overhead or TCP retransmits.
  void OnNetworkBytesReceived(URLRequest* request,
                              int64_t bytes_received) override;

  // Called when bytes are sent over the network, such as when sending request
  // headers or uploading request body bytes. This includes localhost requests.
  // |bytes_sent| is the number of bytes measured at the application layer that
  // have been sent over the network for this request since the last time
  // OnNetworkBytesSent was called. |bytes_sent| will always be greater than 0.
  // Currently, this is only implemented for HTTP transactions, and |bytes_sent|
  // does not include TLS overhead or TCP retransmits.
  void OnNetworkBytesSent(URLRequest* request, int64_t bytes_sent) override;

  // Indicates that the URL request has been completed or failed.
  // |started| indicates whether the request has been started. If false,
  // some information like the socket address is not available.
  void OnCompleted(URLRequest* request, bool started) override;

  // Called when an URLRequest is being destroyed. Note that the request is
  // being deleted, so it's not safe to call any methods that may result in
  // a virtual method call.
  void OnURLRequestDestroyed(URLRequest* request) override;

  // Corresponds to ProxyResolverJSBindings::OnError.
  void OnPACScriptError(int line_number, const base::string16& error) override;

  // Called when a request receives an authentication challenge
  // specified by |auth_info|, and is unable to respond using cached
  // credentials. |callback| and |credentials| must be non-NULL, and must
  // be valid until OnURLRequestDestroyed is called for |request|.
  //
  // The following return values are allowed:
  //  - AUTH_REQUIRED_RESPONSE_NO_ACTION: |auth_info| is observed, but
  //    no action is being taken on it.
  //  - AUTH_REQUIRED_RESPONSE_SET_AUTH: |credentials| is filled in with
  //    a username and password, which should be used in a response to
  //    |auth_info|.
  //  - AUTH_REQUIRED_RESPONSE_CANCEL_AUTH: The authentication challenge
  //    should not be attempted.
  //  - AUTH_REQUIRED_RESPONSE_IO_PENDING: The action will be decided
  //    asynchronously. |callback| will be invoked when the decision is made,
  //    and one of the other AuthRequiredResponse values will be passed in with
  //    the same semantics as described above.
  AuthRequiredResponse OnAuthRequired(URLRequest* request,
                                      const AuthChallengeInfo& auth_info,
                                      const AuthCallback& callback,
                                      AuthCredentials* credentials) override;

  // Called when reading cookies to allow the network delegate to block access
  // to the cookie. This method will never be invoked when
  // LOAD_DO_NOT_SEND_COOKIES is specified.
  bool OnCanGetCookies(const URLRequest& request,
                       const CookieList& cookie_list) override;

  // Called when a cookie is set to allow the network delegate to block access
  // to the cookie. This method will never be invoked when
  // LOAD_DO_NOT_SAVE_COOKIES is specified.
  bool OnCanSetCookie(const URLRequest& request,
                      const std::string& cookie_line,
                      CookieOptions* options) override;

  // Called when a file access is attempted to allow the network delegate to
  // allow or block access to the given file path.  Returns true if access is
  // allowed.
  bool OnCanAccessFile(const URLRequest& request,
                       const base::FilePath& path) const override;

  // Returns true if the given |url| has to be requested over connection that
  // is not tracked by the server. Usually is false, unless user privacy
  // settings block cookies from being get or set.
  bool OnCanEnablePrivacyMode(
      const GURL& url,
      const GURL& first_party_for_cookies) const override;

  // Returns true if the embedder has enabled the "first-party" cookie
  // experiment, and false otherwise.
  //
  // TODO(mkwst): Remove this once we decide whether or not we wish to ship
  // first-party cookies and cookie prefixes. https://crbug.com/459154,
  // https://crbug.com/541511
  bool OnAreExperimentalCookieFeaturesEnabled() const override;
  bool OnAreStrictSecureCookiesEnabled() const override;

  // Called when the |referrer_url| for requesting |target_url| during handling
  // of the |request| is does not comply with the referrer policy (e.g. a
  // secure referrer for an insecure initial target).
  // Returns true if the request should be cancelled. Otherwise, the referrer
  // header is stripped from the request.
  bool OnCancelURLRequestWithPolicyViolatingReferrerHeader(
      const URLRequest& request,
      const GURL& target_url,
      const GURL& referrer_url) const override;
};

}  // namespace net

#endif  // NET_BASE_NETWORK_DELEGATE_IMPL_H_


text:
//$Id: TCPMessageSender.java,v 1.2 2005/11/22 20:05:18 chien-liang Exp $

package edu.wustl.mobilab.nativebenchmark;

import java.io.*;
import java.net.*;

public class TCPMessageSender implements java.io.Serializable {
	private static final long serialVersionUID = 4512630202802842237L;
	InetAddress addr;
	int port;

	/**
     * Creates a TCPMessageSender.
     */
    public TCPMessageSender(InetAddress addr, int port) {
    	this.addr = addr;
    	this.port = port;
    }

    /**
     * Forces the TCPMessageSender to close all sockets and stop
     * functioning.
     */
    public void kill() {
    }

    public void sendMessage(Object o) {

            // open a TCP socket to the destination host
            try {
            	ByteArrayOutputStream baos = new ByteArrayOutputStream();
            	ObjectOutputStream oos = new ObjectOutputStream(baos);
            	oos.writeObject(o);
            	oos.flush();

				log("Opening TCP socket to destination host \naddress:"
						+ addr + "\n port: " + port);
                //Socket socket = new Socket(dest.getAddress(), dest.getPort());
				Socket socket = new Socket(addr, port);
                socket.setTcpNoDelay(true);

                OutputStream os = socket.getOutputStream();
                InputStream is = socket.getInputStream();

                DataOutputStream dos = new DataOutputStream(os);
                //ObjectOutputStream oos = new ObjectOutputStream(os);
                //ObjectInputStream ois = ObjectInputStreamFactory.createStream(is);

				log("Sending the object to the destination.");
//                oos.writeObject(msg);
//                oos.flush();
				dos.write(baos.toByteArray());
				dos.flush();
                os.flush();

				log("Closing the socket to the destination host.");
                socket.close();

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

	void log(String msg) {
		//System.out.println("TCPMessageSender: " + msg);
	}
}


text:
#include <algorithm>
#include <cctype>
#include <functional>

#include <elg_defs.h>

#include "Error.h"
#include "Region.h"

using namespace std;
using namespace pearl;

//--- Utility functions -----------------------------------------------------

namespace
{

struct fo_tolower : public std::unary_function<int,int> {
  int operator()(int x) const {
    return std::tolower(x);
  }
};

string lowercase(const string& str)
{
  string result(str);

  transform(str.begin(), str.end(), result.begin(), fo_tolower());

  return result;
}

uint32_t classify_mpi(const string& name)
{
  // MPI setup
  if (name == "init" || name == "init_thread")
    return Region::CLASS_MPI | Region::CAT_MPI_SETUP | Region::TYPE_MPI_INIT;
  if (name == "finalize")
    return Region::CLASS_MPI | Region::CAT_MPI_SETUP | Region::TYPE_MPI_FINALIZE;

  // MPI collective
  if (name == "barrier")
    return Region::CLASS_MPI | Region::CAT_MPI_COLLECTIVE | Region::TYPE_MPI_BARRIER;
  if (name == "bcast" || name == "scatter" || name == "scatterv")
    return Region::CLASS_MPI | Region::CAT_MPI_COLLECTIVE | Region::TYPE_MPI_ONE_TO_N;
  if (name == "reduce" || name == "gather" || name == "gatherv")
    return Region::CLASS_MPI | Region::CAT_MPI_COLLECTIVE | Region::TYPE_MPI_N_TO_ONE;
  if (name == "allgather" || name == "allgatherv" || name == "allreduce" ||
      name == "alltoall" || name == "alltoallv" || name == "alltoallw" ||
      name == "reduce_scatter" || name == "reduce_scatter_block")
    return Region::CLASS_MPI | Region::CAT_MPI_COLLECTIVE | Region::TYPE_MPI_N_TO_N;
  if (name == "scan" || name == "exscan")
    return Region::CLASS_MPI | Region::CAT_MPI_COLLECTIVE | Region::TYPE_MPI_PARTIAL;

  // MPI point-to-point
  if (name.compare(0, 8, "sendrecv") == 0)
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_SENDRECV | Region::MODE_MPI_NONBLOCKING;

  if (name.find("send") != string::npos) {
    uint32_t result = Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_SEND;

    if (name[0] == 'i')
      result |= Region::MODE_MPI_NONBLOCKING;
    else if (name.find("init") != string::npos)
      result |= Region::MODE_MPI_PERSISTENT;

    if (name.find("ssend") != string::npos)
      result |= Region::MODE_MPI_SYNCHRONOUS;
    else if (name.find("bsend") != string::npos)
      result |= Region::MODE_MPI_BUFFERED;
    else if (name.find("rsend") != string::npos)
      result |= Region::MODE_MPI_READY;
    else
      result |= Region::MODE_MPI_STANDARD;

    return result;
  }

  if (name == "recv")
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_RECV;
  if (name == "irecv")
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_RECV | Region::MODE_MPI_NONBLOCKING;
  if (name == "recv_init")
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_RECV | Region::MODE_MPI_PERSISTENT;

  if (name == "test" || name == "testany")
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_TEST | Region::MODE_MPI_SINGLE;
  if (name == "testall" || name == "testsome")
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_TEST | Region::MODE_MPI_MANY;

  if (name == "wait" || name == "waitany")
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_WAIT | Region::MODE_MPI_SINGLE;
  if (name == "waitall" || name == "waitsome")
    return Region::CLASS_MPI | Region::CAT_MPI_P2P | Region::TYPE_MPI_WAIT | Region::MODE_MPI_MANY;

  if (name.compare(0, 6, "buffer") == 0 ||
      name == "cancel" ||
      name == "get_count" ||
      name.find("probe") != string::npos ||
      name.compare(0, 7, "request") == 0 ||
      name.compare(0, 5, "start") == 0)
    return Region::CLASS_MPI | Region::CAT_MPI_P2P;

  // MPI I/O
  if (name.compare(0, 4, "file") == 0)
    return Region::CLASS_MPI | Region::CAT_MPI_IO;

  // MPI RMA
  if (name == "accumulate" || name == "put")
    return Region::CLASS_MPI | Region::CAT_MPI_RMA | Region::TYPE_MPI_RMA_COMM | Region::MODE_RMA_PUT;
  if (name == "get")
    return Region::CLASS_MPI | Region::CAT_MPI_RMA | Region::TYPE_MPI_RMA_COMM | Region::MODE_RMA_GET;
  if (name.compare(0, 3, "win") == 0)
  {
    uint32_t result = Region::CLASS_MPI | Region::CAT_MPI_RMA;
    string   mode   = name.substr(4);

    if (mode == "fence")
      return result | Region::TYPE_MPI_RMA_COLL | Region::MODE_RMA_FENCE;
    if (mode == "create")
      return result | Region::TYPE_MPI_RMA_COLL | Region::MODE_RMA_WIN_CREATE;
    if (mode == "free")
      return result | Region::TYPE_MPI_RMA_COLL | Region::MODE_RMA_WIN_FREE;

    if (mode == "start")
      return result | Region::TYPE_MPI_RMA_GATS | Region::MODE_RMA_START;
    if (mode == "complete")
      return result | Region::TYPE_MPI_RMA_GATS | Region::MODE_RMA_COMPLETE;
    if (mode == "post")
      return result | Region::TYPE_MPI_RMA_GATS | Region::MODE_RMA_POST;
    if (mode == "wait")
      return result | Region::TYPE_MPI_RMA_GATS | Region::MODE_RMA_WAIT;
    if (mode == "test")
      return result | Region::TYPE_MPI_RMA_GATS | Region::MODE_RMA_TEST;

    if (mode == "lock")
      return result | Region::TYPE_MPI_RMA_PASSIVE | Region::MODE_RMA_LOCK;
    if (mode == "unlock")
      return result | Region::TYPE_MPI_RMA_PASSIVE | Region::MODE_RMA_UNLOCK;
  }

  return Region::CLASS_MPI;
}

uint32_t classify_omp(const string& name)
{
  if (name.compare(0, 14, "!$omp parallel") == 0)
    return Region::CLASS_OMP | Region::CAT_OMP_PARALLEL;

  if (name.compare(0, 13, "!$omp barrier") == 0)
    return Region::CLASS_OMP | Region::CAT_OMP_SYNC
           | Region::TYPE_OMP_BARRIER | Region::MODE_OMP_EXPLICIT;

  if (name.compare(0, 14, "!$omp ibarrier") == 0)
    return Region::CLASS_OMP | Region::CAT_OMP_SYNC
           | Region::TYPE_OMP_BARRIER | Region::MODE_OMP_IMPLICIT;

  return Region::CLASS_OMP;
}

uint32_t classify(const string& name, const string& file)
{
  // Measurement related regions
  if (file == "EPIK")
    return Region::CLASS_INTERNAL;

  // MPI regions
  if (file == "MPI")
    return classify_mpi(lowercase(name.substr(4)));

  // OpenMP regions
  if (name.compare(0, 5, "!$omp") == 0 || file == "OMP")
    return classify_omp(lowercase(name));

  // User regions
  return Region::CLASS_USER;
}

}   /* unnamed namespace */

/*
 *---------------------------------------------------------------------------
 *
 * class Region
 *
 *---------------------------------------------------------------------------
 */

//--- Constructors & destructor ---------------------------------------------

/**
 * Creates a new instance and sets its data fields to the given values.
 *
 * @param id          %Region identifier
 * @param name        %Region name
 * @param file        Name of file in which the region is defined
 * @param begin       Begin line number
 * @param end         End line number
 * @param description %Region description
 * @param type        %Region type
 */
Region::Region(ident_t            id,
               const std::string& name,
               const std::string& file,
               line_t             begin,
               line_t             end,
               const std::string& description,
               uint8_t            type)
  : NamedObject(id, name),
    m_file(file),
    m_begin(begin),
    m_end(end),
    m_description(description),
    m_type(type)
{
  m_class = classify(name, file);
}

//--- Get region information ------------------------------------------------

/**
 * Returns the name of the file in which the region is defined. If this
 * information is not available, an empty string is returned.
 *
 * @return File name
 */
string Region::get_file() const
{
  return m_file;
}

/**
 * Returns the begin line number of the source-code region. If this
 * information is not available, PEARL_NO_LINE is returned.
 *
 * @return Begin line number
 */
line_t Region::get_begin() const
{
  return m_begin;
}

/**
 * Returns the end line number of the source-code region. If this
 * information is not available, PEARL_NO_LINE is returned.
 *
 * @return End line number
 */
line_t Region::get_end() const
{
  return m_end;
}

/**
 * Returns the region description text associated with the source-code
 * region. If this information is not available, an empty string is
 * returned.
 *
 * @return %Region description.
 */
string Region::get_description() const
{
  return m_description;
}

/**
 * Returns the region type, which can be one of the following strings:
 *   - "FUNCTION"
 *   - "LOOP"
 *   - "USER_REGION" (user-defined region)
 *   - "FUNCTION_COLL_BARRIER"
 *   - "FUNCTION_COLL_ONE2ALL"
 *   - "FUNCTION_COLL_ALL2ONE"
 *   - "FUNCTION_COLL_ALL2ALL"
 *   - "FUNCTION_COLL_OTHER"
 *   - "OMP_PARALLEL"
 *   - "OMP_LOOP" (for/do construct)
 *   - "OMP_SECTIONS" (sections construct)
 *   - "OMP_SECTION" (individual section inside a sections construct)
 *   - "OMP_WORKSHARE"
 *   - "OMP_SINGLE"
 *   - "OMP_MASTER"
 *   - "OMP_CRITICAL"
 *   - "OMP_ATOMIC"
 *   - "OMP_BARRIER"
 *   - "OMP_IBARRIER" (implicit barrier)
 *   - "OMP_FLUSH"
 *   - "OMP_CRITICAL_SBLOCK" (body of critical construct)
 *   - "OMP_SINGLE_SBLOCK" (body of single construct)
 *   - "UNKNOWN"
 *
 * @return %Region type
 */
string Region::get_type() const
{
  string type;

  switch(m_type) {
    case ELG_UNKNOWN:
      type = "UNKNOWN";
      break;

    case ELG_FUNCTION:
      type = "FUNCTION";
      break;

    case ELG_FUNCTION_COLL_BARRIER:
      type = "FUNCTION_COLL_BARRIER";
      break;

    case ELG_FUNCTION_COLL_ONE2ALL:
      type = "FUNCTION_COLL_ONE2ALL";
      break;

    case ELG_FUNCTION_COLL_ALL2ONE:
      type = "FUNCTION_COLL_ALL2ONE";
      break;

    case ELG_FUNCTION_COLL_ALL2ALL:
      type = "FUNCTION_COLL_ALL2ALL";
      break;

    case ELG_FUNCTION_COLL_OTHER:
      type = "FUNCTION_COLL_OTHER";
      break;

    case ELG_LOOP:
      type = "LOOP";
      break;

    case ELG_USER_REGION:
      type = "USER_REGION";
      break;

    case ELG_OMP_PARALLEL:
      type = "OMP_PARALLEL";
      break;

    case ELG_OMP_LOOP:
      type = "OMP_LOOP";
      break;

    case ELG_OMP_SECTIONS:
      type = "OMP_SECTIONS";
      break;

    case ELG_OMP_SECTION:
      type = "OMP_SECTION";
      break;

    case ELG_OMP_WORKSHARE:
      type = "OMP_WORKSHARE";
      break;

    case ELG_OMP_SINGLE:
      type = "OMP_SINGLE";
      break;

    case ELG_OMP_MASTER:
      type = "OMP_MASTER";
      break;

    case ELG_OMP_CRITICAL:
      type = "OMP_CRITICAL";
      break;

    case ELG_OMP_ATOMIC:
      type = "OMP_ATOMIC";
      break;

    case ELG_OMP_BARRIER:
      type = "OMP_BARRIER";
      break;

    case ELG_OMP_IBARRIER:
      type = "OMP_IBARRIER";
      break;

    case ELG_OMP_FLUSH:
      type = "OMP_FLUSH";
      break;

    case ELG_OMP_CRITICAL_SBLOCK:
      type = "OMP_CRITICAL_SBLOCK";
      break;

    case ELG_OMP_SINGLE_SBLOCK:
      type = "OMP_SINGLE_SBLOCK";
      break;

    default:
      throw FatalError("Unknown region type.");
  }

  return type;
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StatisticsViewerMenuItem.xaml.cs" company="None">
//   None
// </copyright>
// <summary>
//   Interaction logic for StatisticsMenuItem.xaml
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace TfsWorkbench.StatisticsViewer
{
    /// <summary>
    /// Interaction logic for StatisticsMenuItem.xaml
    /// </summary>
    public partial class StatisticsViewerMenuItem
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="StatisticsViewerMenuItem"/> class.
        /// </summary>
        public StatisticsViewerMenuItem()
        {
            InitializeComponent();
        }
    }
}


text:
class CreateClusterGroups < ActiveRecord::Migration[4.2]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  def change
    create_table :cluster_groups do |t|
      t.references :cluster, null: false, foreign_key: { on_delete: :cascade }
      t.references :group, null: false, index: true

      t.index [:cluster_id, :group_id], unique: true
      t.foreign_key :namespaces, column: :group_id, on_delete: :cascade
    end
  end
end


text:
import * as core from "@actions/core";

/**
 * Get Secrets from the current environment using patterns to match keys.
 * @param patterns
 * @param env
 */
export function getSecrets(
  patterns: string[],
  env: NodeJS.ProcessEnv = process.env
): { [key: string]: string } {
  const regexPatterns = patterns.map((s) => new RegExp(s));
  const keys = Object.keys(env);

  core.info(`Available env keys: ${JSON.stringify(keys)}`);

  return keys
    .filter((k: string) => {
      return env[k] && regexPatterns.filter((r) => r.test(k)).length;
    })
    .reduce((o: { [key: string]: string }, k: string) => {
      // tell Github to mask this from logs
      if (!k.match(/GITHUB_.*/)) {
        core.setSecret(env[k] as string);
      }

      o[k] = env[k] as string;

      return o;
    }, {});
}


text:
<!--
BUGS: Please use this template.

SUPPORT REQUESTS/QUESTIONS: If you have a support request or question please
submit them to StackOverflow using the tags aurelia and aurelia-framework
http://stackoverflow.com/questions/tagged/aurelia
or the Aurelia Gitter https://gitter.im/aurelia/discuss

Blue Spire offers paid support agreements. Further information regarding paid support
may be obtained by emailing support@bluespire.com

Future support requests submitted here will be closed.

The HTML comments below are for your reference, and are not displayed
when your issue is submitted, feel free to leave them.

Choose one of the two headings, delete the other.
-->
**I'm submitting a bug report**
**I'm submitting a feature request**

* **Library Version:**
major.minor.patch-pre

**Please tell us about your environment:**
* **Operating System:**
OSX 10.x|Linux (distro)|Windows [7|8|8.1|10]

* **Node Version:**
6.2.0
<!--
Minimum supported Node version is latest Node 4.x LTS
run `node -v`
-->

* **NPM Version:**
3.8.9
<!--
Minimum supported NPM version is 3.x
run `npm -v`
-->

* **JSPM OR Webpack AND Version**
JSPM 0.16.32 | webpack 2.1.0-beta.17
<!--
If using JSPM
run `jspm -v`
If using Webpack
run `webpack --help | grep webpack`
-->

* **Browser:**
all | Chrome XX | Firefox XX | Edge XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView

* **Language:**
all | TypeScript X.X | ESNext

**Current behavior:**

**Expected/desired behavior:**
<!--
If the current behavior is a bug, please provide the steps to reproduce and, if possible, a minimal demo of the
problem using a runnable Gist.
To create a runnable gist, go to https://gist.run/?id=381fdb1a4b0865a4c25026187db865ce
Then click "Fork to Public Gist".
Create your gist, then finally click "Update Gist." Include a link to the gist.run below.
-->

* **What is the expected behavior?**

* **What is the motivation / use case for changing the behavior?**


text:
{% if page.headerimage %}
{% assign headerimage = page.headerimage %}
{% else %}
{% assign headerimage = include.headerimage %}
{% endif %}

            {% include html/navigation.html %}
            {% if page.headline %}

 {{page.headline}}

            {% else %}

                {% if include.title %}
                    {% assign title = include.title %}
                {% elsif page.category %}
                    {% assign title = page.category | capitalize %}
                {% elsif page.categories %}
                    {% assign title = page.categories | first | capitalize %}
                {% else %}
                    {% assign title = page.title %}
                {% endif %}

{{title}}

                {% include html/search_box.html %}

            {% endif %}

{% if site.facebook_comments %}

{% endif %}