text:
#ifndef CPPWEBCONTROLLER_H
#define CPPWEBCONTROLLER_H

#include "controller.h"
#include "request.h"
#include "response.h"
#include "cppwebframework_global.h"

CWF_BEGIN_NAMESPACE
/**
* @brief This class is responsible for displaying the standard pages of C++ Web Framework: index, examples, documentation, ssl and authors.
*/
class CPPWEBFRAMEWORKSHARED_EXPORT CppWebController : public Controller
{
public:
    /**
     * @brief Method overload to answer the requests the system default pages.
     * @param Request  &request  : Parameter generated by HttpReadRequest.
     * @param Response &response : Parameter generated by HttpReadRequest.
     */
    void doGet(Request &request, Response &response) const override;
};

CWF_END_NAMESPACE

#endif // CPPWEBCONTROLLER_H


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

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" href="demo.css" type="text/css" />

	<title>Mif.Menu Demo</title>

Add item to menu

redpajama_set_name: RedPajamaGithub


text:
package org.zstack.test.core.thread;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.thread.Task;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.test.BeanConstructor;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class TestThreadFacadeReturnValueException {
    private static final CLogger logger = Utils.getLogger(TestThreadFacadeReturnValueException.class);
    ComponentLoader loader;
    ThreadFacade thdf;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    class Tester implements Task<Integer> {
        int index;

        Tester(int index) {
            this.index = index;
        }

        @Override
        public Integer call() throws Exception {
            throw new CloudRuntimeException("This is on purpose");
        }

        @Override
        public String getName() {
            return "Tester";
        }
    }

    @Before
    public void setUp() throws Exception {
        BeanConstructor con = new BeanConstructor();
        loader = con.build();
        thdf = loader.getComponent(ThreadFacade.class);
    }

    @Test
    public void test() throws InterruptedException, ExecutionException {
        thrown.expect(ExecutionException.class);
        Tester worker = new Tester(100);
        Future<Integer> f = thdf.submit(worker);
        Integer ret = f.get();
    }
}


text:
    <button id="myClick">click here to fire my event</button>

    <% _.each(children,function(value,index){ %>
    <li data-aura-component="child" data-aura-my-name="<%= value %> " >

    <% }) %>


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

<TITLE>
ProficiencyLevelType
</TITLE>

<META NAME="date" CONTENT="2011-06-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

com.google.code.linkedinapi.schema

Enum ProficiencyLevelType

java.lang.Object
  java.lang.Enum<ProficiencyLevelType>
      com.google.code.linkedinapi.schema.ProficiencyLevelType

All Implemented Interfaces:
java.io.Serializable, java.lang.Comparable<ProficiencyLevelType>

public enum ProficiencyLevelType
extends java.lang.Enum<ProficiencyLevelType>

Java class for null.

The following schema fragment specifies the expected content contained within this class.

 <simpleType>
   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
     <enumeration value="elementary"/>
     <enumeration value="limited_working"/>
     <enumeration value="professional_working"/>
     <enumeration value="full_professional"/>
     <enumeration value="native_or_bilingual"/>
     <enumeration value="beginner"/>
     <enumeration value="intermediate"/>
     <enumeration value="advanced"/>
     <enumeration value="expert"/>
   </restriction>
 </simpleType>

Enum Constant Summary

ADVANCED

BEGINNER

ELEMENTARY

EXPERT

FULL_PROFESSIONAL

INTERMEDIATE

LIMITED_WORKING

NATIVE_BILINGUAL

PROFESSIONAL_WORKING

Method Summary

static ProficiencyLevelType
fromValue(java.lang.String v)

 java.lang.String
value()

static ProficiencyLevelType
valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static ProficiencyLevelType[]
values()

          Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

ELEMENTARY

public static final ProficiencyLevelType ELEMENTARY

LIMITED_WORKING

public static final ProficiencyLevelType LIMITED_WORKING

PROFESSIONAL_WORKING

public static final ProficiencyLevelType PROFESSIONAL_WORKING

FULL_PROFESSIONAL

public static final ProficiencyLevelType FULL_PROFESSIONAL

NATIVE_BILINGUAL

public static final ProficiencyLevelType NATIVE_BILINGUAL

BEGINNER

public static final ProficiencyLevelType BEGINNER

INTERMEDIATE

public static final ProficiencyLevelType INTERMEDIATE

ADVANCED

public static final ProficiencyLevelType ADVANCED

EXPERT

public static final ProficiencyLevelType EXPERT

Method Detail

values

public static ProficiencyLevelType[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (ProficiencyLevelType c : ProficiencyLevelType.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in
the order they are declared

valueOf

public static ProficiencyLevelType valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:
name - the name of the enum constant to be returned.

Returns:
the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

value

public java.lang.String value()

fromValue

public static ProficiencyLevelType fromValue(java.lang.String v)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD


text:
describe LiftedDeploy::Config do
  describe '#git_path' do
    subject { described_class.new.git_path }

    describe 'defaults to' do
      it { should eq(`which git`) }
    end

    describe 'can be overridden by .deploy.yml' do
      before { create_deploy_yml(git: { path: '/path/to/git' }) }
      after { delete_deploy_yml }

      it { should eq('/path/to/git') }
    end
  end
end


text:
require 'spec_helper'

RSpec.describe "some other group" do
  it "is not very interesting" do
    expect(true).to be_truthy
  end
end

RSpec.describe "a second group in a file" do
  it "does not expect the Spanish Inquisition" do
    expect(ENV.fetch("GLOBAL_MUTABLE_STATE", 3)).to eq 3
  end
end


text:
<? include(ADMIN_VIEW_PATH."/editors.php"); ?>

	<?php echo form_open_multipart(HOST_URL."/".$folder_name."/edit/".$data_record->id."/".$parent_id."/".$parent_name,'name="frmRegister" id="frmRegister"'); ?>

<img src="<?=ADMIN_IMG_PATH?>/icon_<?php echo $folder_name; ?>.png" alt="<?=$module_name?>" />

<a href="<?=HOST_URL?>/<?=$folder_name?>" class="module_nameBig"><?php echo $module_name; ?> : Edit Record

<input type="submit" name="btnsubmit" id="btnsubmit" value="Save & Close" class="btn_save_close" >

				<a href="<?=HOST_URL?>/<?=$folder_name?>/pages/<?=$parent_id?>/<?=$parent_name?>">

Back

	<? if (isset($MSG)){ ?>
	<div class="<? if (isset($Error) && $Error=="Y"){ echo "alert"; }else{ echo "success"; }  ?>"><?php echo $MSG; ?>

	<? } ?>

Edit Details

Heading (English) :

<?php echo form_input('heading_en',$heading_en, 'id="heading_en" class="textBox required"'); ?>

Website Title :

<?php echo form_textarea('website_title', $website_title, 'id="website_title" class="textArea required"'); ?>

Meta Keywords :

<?php echo form_textarea('meta_keywords', $meta_keywords, 'id="meta_keywords" class="textArea required"'); ?>

Meta Description :

<?php echo form_textarea('meta_description', $meta_description, 'id="meta_description" class="textArea required"'); ?>

Description Small :

<?php echo form_textarea('description_sm_en', $description_sm_en, 'id="description_sm" style="height:60px; width:80%;" class="textArea required"'); ?>

                                        <?php if($parent_name != 'home'):?>

Description :

<?php echo form_textarea('description_en', $description_en, 'id="description_en" class="editor"'); ?>

 				  <?php endif;?>

Options

Status

						<? if ($is_active=="Y"){ $p=TRUE; $up=FALSE; }else{ $p=FALSE; $up=TRUE; }  ?>

<? echo form_radio('is_active', 'Y', $p); ?> Publish  <? echo form_radio('is_active', 'N', $up); ?> Unpublish

Images

Jpeg, Gif & PNG only

Width = 94 pixels , Height = 92 pixels

Image

<? echo form_upload('image1','', 'id="image1" class="fileBox"'); ?>

						<? if (!empty($data_record->image1)){ ?>

<img src="<?=$this->thumb_show_path?><?=$data_record->image1?>" class="thumb" /> <img src="<?=ADMIN_IMG_PATH?>/cross.png" alt="Delete" hspace="2" border="0" onclick="javascript:if(delConfirmation()==true){DeleteFile('<?=$data_record->image1?>', 'image1')}" style="cursor:pointer;" />

						<? } ?>

<?php echo $comments; ?>

	<?php echo form_hidden('delete_file',''); ?>
	<?php echo form_hidden('file_name',''); ?>
	<?php echo form_hidden('field_name',''); ?>
	<?php echo form_close(); ?>


text:
<!DOCTYPE HTML>

<html>
    <head>
        <title>
            Rizy Corner
        </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    </head>
    <body>
        <div id="app">

        </div>
    </body>
    <script type="text/javascript" src="js/index.js"></script>
</html>


text:
class AddIsReadonlyToClusterParameter < ActiveRecord::Migration
  def self.up
    add_column :cluster_parameters, :is_readonly, :boolean, :default => 0
  end

  def self.down
    remove_column :cluster_parameters, :is_readonly
  end
end


text:
'''
Created on 2015/7/8

:author: hubo
'''
from vlcp.protocol import Protocol
from vlcp.config import defaultconfig
from .defs import common, openflow10
from .defs.definations import definations
from vlcp.event.core import Event, withIndices, QuitException
from vlcp.event.runnable import RoutineContainer, RoutineException
from vlcp.event.connection import ConnectionWriteEvent, ConnectionControlEvent
import logging
import os
from namedstruct import dump
from contextlib import closing
from vlcp.event.ratelimiter import RateLimiter
from vlcp.event.event import M_

@withIndices('datapathid', 'auxiliaryid', 'state', 'connection', 'connmark', 'createby')
class OpenflowConnectionStateEvent(Event):
    """
    Event when connection state changes
    """
    # Connection Setup
    CONNECTION_SETUP = 'setup'
    # Connection Down
    CONNECTION_DOWN = 'down'

@withIndices('datapathid', 'auxiliaryid', 'connection', 'connmark', 'xid', 'iserror', 'createby')
class OpenflowResponseEvent(Event):
    """
    Event for an OpenFlow response is received
    """
    pass

@withIndices('type', 'datapathid', 'auxiliaryid', 'tableid', 'cookie', 'connection', 'connmark', 'createby')
class OpenflowAsyncMessageEvent(Event):
    """
    Event for an async message is received
    """
    pass

@withIndices('connection', 'type', 'connmark', 'createby')
class OpenflowPresetupMessageEvent(Event):
    """
    Event for messages before connection setup
    """
    pass

@withIndices('experimenter', 'exptype', 'datapathid', 'auxiliaryid', 'connection', 'connmark', 'createby')
class OpenflowExperimenterMessageEvent(Event):
    """
    Event for experimenter messages
    """
    pass

class OpenflowProtocolException(Exception):
    """
    Critical protocol break exception
    """
    pass

class OpenflowErrorResultException(Exception):
    """
    OpenFlow returns error
    """
    def __init__(self, errormsg, prompt = 'An error message is returned: ', result = None):
        if result is None:
            result = errormsg
        Exception.__init__(self, prompt + repr(dump(errormsg)))
        self.result = result

@defaultconfig
class Openflow(Protocol):
    '''
    Openflow control protocol
    '''
    _default_persist = True
    # Default OpenFlow port
    _default_defaultport = common.OFP_TCP_PORT
    # Allowed versions for OpenFlow handshake; should be one or both of OFP10_VERSION and OFP13_VERSION
    _default_allowedversions = (common.OFP10_VERSION, common.OFP13_VERSION)
    # Disconnect when OFPT_HELLO message is not received for a long time
    _default_hellotimeout = 10
    # Disconnect when OFPT_FEATURES_REQUEST message does not get response
    _default_featurerequesttimeout = 30
    # Send OFPT_ECHO packet when connection is idle
    _default_keepalivetime = 10
    # When OFPT_ECHO packet does not get response in the specified time, disconnect
    _default_keepalivetimeout = 3
    _default_createqueue = True
    _default_writequeuesize = 200
    _default_buffersize = 65536
    # Show debugging messages in log
    _default_debugging = False
    # Disable nicira extension; when you are not using VLCP with OpenvSwitch (e.g. using with
    # physical switches) you should set this to True
    _default_disablenxext = False
    # Disable using ofp_action_group in another group: this is only supported in OpenvSwitch 2.5+,
    # so it is disabled by default
    _default_disablechaining = True
    _logger = logging.getLogger(__name__ + '.Openflow')
    _default_tcp_nodelay = True
    def __init__(self, allowedVersions = None):
        '''
        Constructor

        :param allowedVersions: if specified, should be a tuple of allowed OpenFlow versions.
        '''
        Protocol.__init__(self)
        if allowedVersions is not None:
            self.allowedversions = allowedVersions
    async def handler(self, connection):
        try:
            # Create a hello message
            connmark = connection.connmark
            hello = common.ofp_hello.new()
            allowedversions = tuple(v for v in self.allowedversions if v in definations)
            if not allowedversions:
                raise OpenflowProtocolException('No valid OpenFlow versions are specified')
            hello.header.version = max(allowedversions)
            versionbitmap = common.ofp_hello_elem_versionbitmap.new()
            versionStart = 0
            thisBitmap = 0
            for v in sorted(allowedversions):
                while v > versionStart + 32:
                    versionbitmap.bitmaps.append(thisBitmap)
                    thisBitmap = 0
                    versionStart += 32
                thisBitmap = thisBitmap | (1<<(v - versionStart))
            versionbitmap.bitmaps.append(thisBitmap)
            hello.elements.append(versionbitmap)
            write = self.formatrequest(hello, connection)
            await connection.write(write, False)
            # Wait for a hello
            hellomatcher = OpenflowPresetupMessageEvent.createMatcher(connection = connection)
            timeout, ev, _ = await connection.wait_with_timeout(self.hellotimeout, hellomatcher)
            if timeout:
                # Drop the connection
                raise OpenflowProtocolException('Did not receive hello message before timeout')
            else:
                msg = ev.message
                if msg.header.type != common.OFPT_HELLO:
                    raise OpenflowProtocolException('The first packet on this connection is not OFPT_HELLO')
                else:
                    helloversion = None
                    usebitmap = False
                    for e in msg.elements:
                        if e.type == common.OFPHET_VERSIONBITMAP:
                            # There is a bitmap
                            for v in reversed(sorted(allowedversions)):
                                bitmapIndex = v // 32
                                bitmapPos = (v & 31)
                                if len(e.bitmaps) < bitmapIndex:
                                    continue
                                if e.bitmaps[bitmapIndex] & (1 << bitmapPos):
                                    helloversion = v
                                    break
                            usebitmap = True
                            break
                    if not usebitmap:
                        helloversion = min(max(allowedversions), msg.header.version)
                    if helloversion is None or helloversion not in allowedversions:
                        self._logger.warning('Remote switch openflow protocol version is not compatible. Their hello message: %r, we expect version: %r. Connection = %r', common.dump(msg), allowedversions, connection)
                        # Hello fail
                        hellofail = common.ofp_error_msg.new()
                        hellofail.header.version = max(allowedversions)
                        hellofail.type = common.OFPET_HELLO_FAILED
                        hellofail.code = common.OFPHFC_INCOMPATIBLE
                        if helloversion is None:
                            hellofail.data = b'A common version is not found from the bitmap\x00'
                        else:
                            hellofail.data = ('Openflow version is not supported\x00' % (common.ofp_version.getName(helloversion, str(helloversion)),)).encode()
                        write = self.formatreply(hellofail, msg, connection)
                        await connection.write(write)
                        await connection.reset(False, connmark)
                        return
                    else:
                        # Still we may receive a hello fail from the other side, we should expect that.
                        # The error message may come before feature request is sent.
                        err_matcher = OpenflowPresetupMessageEvent.createMatcher(connection = connection, type = common.OFPT_ERROR)
                        # Send a feature request message
                        connection.openflowversion = helloversion
                        currdef = definations[helloversion]
                        connection.openflowdef = currdef
                        # Feature request message has no body
                        featurereq = currdef.ofp_msg.new()
                        featurereq.header.type = currdef.OFPT_FEATURES_REQUEST
                        write = self.formatrequest(featurereq, connection)
                        try:
                            await connection.with_exception(connection.write(write, False), err_matcher)
                            featurereply_matcher = OpenflowPresetupMessageEvent.createMatcher(connection = connection, type = currdef.OFPT_FEATURES_REPLY)
                            timeout, ev, m = await connection.wait_with_timeout(self.featurerequesttimeout, featurereply_matcher, err_matcher)
                            if timeout:
                                raise OpenflowProtocolException('Remote switch did not response to feature request.')
                            elif m is err_matcher:
                                self._logger.warning('Error while request feature: %r Connection = %r', ev.message, connection)
                                raise OpenflowProtocolException('Error while request feature: %r' % (ev.message,))
                            else:
                                msg = ev.message
                                connection.openflow_featuresreply = msg
                                connection.openflow_datapathid = msg.datapath_id
                                connection.openflow_auxiliaryid = getattr(msg, 'auxiliary_id', 0)
                                connection.openflow_capabilities = msg.capabilities
                                connection.openflow_n_buffers = msg.n_buffers
                                connection.openflow_n_tables = msg.n_tables
                                statechange = OpenflowConnectionStateEvent(connection.openflow_datapathid, connection.openflow_auxiliaryid, OpenflowConnectionStateEvent.CONNECTION_SETUP, connection, connection.connmark, self)
                                await connection.wait_for_send(statechange)
                                for msg in connection.openflow_msgbuffer:
                                    e = self._createevent(connection, msg)
                                    if e is not None:
                                        await connection.wait_for_send(e)
                        except RoutineException as exc:
                            self._logger.warning('Remote report hello fail: %r Connection = %r', common.dump(exc.arguments[1].message), connection)
                            await connection.reset(True, connmark)
                            return
        except QuitException:
            pass
        except:
            self._logger.exception('Unexpected exception on processing openflow protocols, Connection = %r', connection)
            async def _cleanup():
                await connection.reset(True, connmark)
            connection.subroutine(_cleanup(), False)
            raise
    def formatrequest(self, request, connection, assignxid = True):
        if assignxid:
            self.assignxid(request, connection)
        c = ConnectionWriteEvent(connection = connection, connmark = connection.connmark, data = request._tobytes())
        if self.debugging:
            self._logger.debug('message formatted: %r', common.dump(request))
        return c
    def assignxid(self, request, connection):
        request.header.xid = connection.xid
        connection.xid += 1
        if connection.xid > 0xffffffff:
            # Skip xid = 0 for special response
            connection.xid = 1
    def formatreply(self, reply, request, connection):
        reply.header.xid = request.header.xid
        c = ConnectionWriteEvent(connection = connection, connmark = connection.connmark, data = reply._tobytes())
        if self.debugging:
            self._logger.debug('message formatted: %r', common.dump(request))
        return c
    def replymatcher(self, request, connection, iserror = None):
        """
        Create an event matcher to match a reply to this request
        """
        matcherparam = {'datapathid': connection.openflow_datapathid, 'auxiliaryid': connection.openflow_auxiliaryid, 'connection' : connection, 'connmark': connection.connmark,
                        'xid': request.header.xid}
        if iserror is not None:
            matcherparam['iserror'] = iserror
        return OpenflowResponseEvent.createMatcher(**matcherparam)
    def statematcher(self, connection, state = OpenflowConnectionStateEvent.CONNECTION_DOWN, currentconn = True):
        """
        Create an event matcher to match the connection state of this connection
        """
        if currentconn:
            return OpenflowConnectionStateEvent.createMatcher(connection.openflow_datapathid, connection.openflow_auxiliaryid, state, connection, connection.connmark)
        else:
            return OpenflowConnectionStateEvent.createMatcher(connection.openflow_datapathid, connection.openflow_auxiliaryid, state)
    async def querywithreply(self, request, connection, container = None, raiseonerror = True):
        """
        Send an OpenFlow normal request, wait for the response of this request. The request must have
        exactly one response.
        """
        await connection.write(self.formatrequest(request, connection), False)
        reply = self.replymatcher(request, connection)
        conndown = self.statematcher(connection)
        ev, m = await M_(reply, conndown)
        if m is conndown:
            raise OpenflowProtocolException('Connection is down before reply received')
        if ev.iserror:
            raise OpenflowErrorResultException(ev.message)
        else:
            return ev.message

    async def querymultipart(self, request, connection, container = None, raiseonerror = True):
        """
        Send a multipart request, wait for all the responses. Return a list of reply messages
        """
        await connection.write(self.formatrequest(request, connection), False)
        reply = self.replymatcher(request, connection)
        conndown = self.statematcher(connection)
        messages = []
        while True:
            ev, m = await M_(reply, conndown)
            if m is conndown:
                raise OpenflowProtocolException('Connection is down before reply received')
            msg = ev.message
            messages.append(msg)
            if msg.header.type == common.OFPT_ERROR or not (msg.flags & common.OFPSF_REPLY_MORE):
                if msg.header.type == common.OFPT_ERROR and raiseonerror:
                    raise OpenflowErrorResultException(msg, result=messages)
                break
        return messages

    async def batch(self, requests, connection, container, raiseonerror = True):
        """
        Send multiple requests, return when all the requests are done. Requests can have no responses.
        The attributes are set even if an OpenflowErrorResultException is raised.

        :return: (openflow_reply, openflow_replydict) in which `openflow_reply` is the list of messages in receiving order.
                `openflow_replydict` is the dictionary `{request:reply}`.

        :raise OpenflowErrorResultException: when some replies are errors. `exc.result` returns
                                             (openflow_reply, openflow_replydict)
        """
        for r in requests:
            self.assignxid(r, connection)
        replymatchers = dict((self.replymatcher(r, connection), r) for r in requests)
        replydict = {}
        replymessages = []
        conndown = self.statematcher(connection)
        firsterror = [None]
        def callback(event, matcher):
            if matcher is conndown:
                raise OpenflowProtocolException('Connection is down before reply received')
            msg = event.message
            if event.iserror and not firsterror[0]:
                firsterror[0] = msg
            replydict.setdefault(matcher, []).append(msg)
            replymessages.append(msg)
        async def batchprocess():
            for r in requests:
                await connection._rate_limiter.limit()
                await connection.write(self.formatrequest(r, connection, False), False)
            barrier = connection.openflowdef.ofp_msg.new()
            barrier.header.type = connection.openflowdef.OFPT_BARRIER_REQUEST
            await container.wait_for_send(self.formatrequest(barrier, connection))
            barrierreply = self.replymatcher(barrier, connection)
            await barrierreply
        await container.with_callback(batchprocess(), callback, conndown, *replymatchers.keys())
        openflow_reply = replymessages
        openflow_replydict = dict((replymatchers[k],v) for k,v in replydict.items())
        if firsterror[0] and raiseonerror:
            raise OpenflowErrorResultException(firsterror[0], 'One or more error message is returned from a batch process, the first is: ',
                                               result=(openflow_reply, openflow_replydict))
        else:
            return (openflow_reply, openflow_replydict)

    async def init(self, connection):
        await Protocol.init(self, connection)
        connection.createdqueues.append(connection.scheduler.queue.addSubQueue(\
                self.messagepriority, OpenflowPresetupMessageEvent.createMatcher(connection = connection), ('presetup', connection)))
        connection.createdqueues.append(connection.scheduler.queue.addSubQueue(\
                self.messagepriority, OpenflowConnectionStateEvent.createMatcher(connection = connection), ('connstate', connection)))
        connection.createdqueues.append(connection.scheduler.queue.addSubQueue(\
                self.messagepriority + 1, OpenflowResponseEvent.createMatcher(connection = connection), ('response', connection), self.messagequeuesize))
        connection.createdqueues.append(connection.scheduler.queue.addSubQueue(\
                self.messagepriority, OpenflowAsyncMessageEvent.createMatcher(connection = connection), ('async', connection), self.messagequeuesize))
        connection.createdqueues.append(connection.scheduler.queue.addSubQueue(\
                self.messagepriority, OpenflowExperimenterMessageEvent.createMatcher(connection = connection), ('experimenter', connection), self.messagequeuesize))
        # Add priority to echo reply, or the whole connection is down
        connection.createdqueues.append(connection.scheduler.queue.addSubQueue(\
                self.writepriority + 10, ConnectionWriteEvent.createMatcher(connection = connection, _ismatch = lambda x: hasattr(x, 'echoreply') and x.echoreply), ('echoreply', connection)))
        connection._rate_limiter = RateLimiter(200, connection)
        await self.reconnect_init(connection)
    async def reconnect_init(self, connection):
        connection.xid = ord(os.urandom(1)) + 1
        connection.openflowversion = 0
        connection.openflow_datapathid = None
        connection.openflow_msgbuffer = []
        connection.subroutine(self.handler(connection), asyncStart = False, name = 'handler')
    async def closed(self, connection):
        await Protocol.closed(self, connection)
        connection.handler.close()
        self._logger.info('Openflow connection is closed on %r', connection)
        if connection.openflow_datapathid is not None:
            await connection.wait_for_send(OpenflowConnectionStateEvent(connection.openflow_datapathid, connection.openflow_auxiliaryid, OpenflowConnectionStateEvent.CONNECTION_DOWN, connection, connection.connmark, self))
    async def error(self, connection):
        await Protocol.error(self, connection)
        connection.handler.close()
        self._logger.warning('Openflow connection is reset on %r', connection)
        if connection.openflow_datapathid is not None:
            await connection.wait_for_send(OpenflowConnectionStateEvent(connection.openflow_datapathid, connection.openflow_auxiliaryid, OpenflowConnectionStateEvent.CONNECTION_DOWN, connection, connection.connmark, self))
    def _createevent(self, connection, msg):
        if msg.header.type == common.OFPT_ECHO_REQUEST:
            # Direct reply without enqueue
            msg.header.type = common.OFPT_ECHO_REPLY
            echoreply = self.formatreply(msg, msg, connection)
            echoreply.echoreply = True
            return echoreply
        elif connection.openflow_datapathid is None:
            # Connection is pre-setup
            if msg.header.type == common.OFPT_HELLO or msg.header.type == common.OFPT_ERROR:
                return OpenflowPresetupMessageEvent(connection, msg.header.type, connection.connmark, self, message = msg)
            else:
                # Other messages must be parsed in specified version
                ofdef = definations.get(msg.header.version)
                if ofdef is None:
                    # Version is not supported
                    self._logger.warning('Illegal message received from connection %r, message = %r', connection, common.dump(msg))
                    err = common.ofp_error_msg.new()
                    err.header.version = msg.header.version
                    err.type = common.OFPET_BAD_REQUEST
                    err.code = common.OFPBRC_BAD_VERSION
                    err.data = (msg._tobytes())[0:64]
                    write = self.formatreply(err, msg, connection)
                    return write
                elif msg.header.type == ofdef.OFPT_FEATURES_REPLY:
                    return OpenflowPresetupMessageEvent(connection, msg.header.type, connection.connmark, self, message = msg)
                else:
                    # Store other messages
                    connection.openflow_msgbuffer.append(msg)
                    return None
        else:
            if msg.header.version != connection.openflowversion:
                self._logger.warning('Illegal message (version not match) received from connection %r, message = %r', connection, common.dump(msg))
                err = common.ofp_error_msg.new()
                err.header.version = connection.openflowversion
                err.type = common.OFPET_BAD_REQUEST
                err.code = common.OFPBRC_BAD_VERSION
                err.data = (msg._tobytes())[0:64]
                write = self.formatreply(err, msg, connection)
                return write
            elif msg.header.type == openflow10.OFPT_VENDOR:
                if connection.openflowversion > common.OFP10_VERSION:
                    experimenter = msg.experimenter
                    exptype = msg.exp_type
                else:
                    experimenter = msg.vendor
                    exptype = getattr(msg, 'subtype', 0)
                return OpenflowExperimenterMessageEvent(experimenter, exptype, connection.openflow_datapathid, connection.openflow_auxiliaryid,
                                                        connection, connection.connmark, self, message = msg)
            elif msg.header.type == common.OFPT_ERROR or msg.header.type in connection.openflowdef.ofp_type_reply_set:
                iserror = (msg.header.type == common.OFPT_ERROR)
                return OpenflowResponseEvent(connection.openflow_datapathid, connection.openflow_auxiliaryid, connection, connection.connmark, msg.header.xid, iserror, self, message = msg)
            elif msg.header.type in connection.openflowdef.ofp_type_asyncmessage_set:
                return OpenflowAsyncMessageEvent(msg.header.type, connection.openflow_datapathid, connection.openflow_auxiliaryid,
                                                 getattr(msg, 'table_id', 0), getattr(msg, 'cookie', 0), connection, connection.connmark, self, message = msg)
            else:
                # These messages are requests, send a BADREQUEST error
                self._logger.warning('Illegal message (type error) received from connection %r, message = %r', connection, common.dump(msg))
                err = common.ofp_error_msg.new()
                err.header.version = connection.openflowversion
                err.type = common.OFPET_BAD_REQUEST
                err.code = common.OFPBRC_BAD_TYPE
                err.data = (msg._tobytes())[0:64]
                return self.formatreply(err, msg, connection)
    def parse(self, connection, data, laststart):
        start = 0
        events = []
        while True:
            result = common.ofp_msg.parse(data[start:])
            if result is None:
                break
            msg, size = result
            if self.debugging:
                self._logger.debug('message received: %r', common.dump(msg))
            start += size
            e = self._createevent(connection, msg)
            if e is not None:
                events.append(e)
        if laststart == len(data):
            # Remote write close
            events.append(ConnectionWriteEvent(connection, connection.connmark, data = b'', EOF = True))
        return (events, len(data) - start)
    async def keepalive(self, connection):
        echo = common.ofp_echo()
        echo.header.version = connection.openflowversion
        try:
            timeout, _ = await connection.execute_with_timeout(self.keepalivetimeout, self.querywithreply(echo, connection, connection))
            if timeout:
                self._logger.warning("Keepalive timeout on connection %r with exception, reset the connection", connection)
                await connection.reset(True)
        except Exception:
            self._logger.warning("Keepalive failed on connection %r with exception, reset the connection", connection, exc_info=True)
            await connection.reset(True)


text:
package blade.indexerpostprocessor;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.BooleanQuery;
import com.liferay.portal.kernel.search.Document;
import com.liferay.portal.kernel.search.IndexerPostProcessor;
import com.liferay.portal.kernel.search.SearchContext;
import com.liferay.portal.kernel.search.Summary;
import com.liferay.portal.kernel.search.filter.BooleanFilter;

import java.util.Locale;

import org.osgi.service.component.annotations.Component;

@Component(
	immediate = true,
	property = {
		"indexer.class.name=com.liferay.portlet.messageboards.util.MBMessageIndexer",
		"indexer.class.name=com.liferay.portlet.usersadmin.util.ContactIndexer"
	},
	service = IndexerPostProcessor.class
)
public class MultipleIndexerPostProcessor implements IndexerPostProcessor {

	@Override
	public void postProcessContextBooleanFilter(
			BooleanFilter booleanFilter, SearchContext searchContext)
		throws Exception {

		_log.info("postProcessContextBooleanFilter");
	}

	@Override
	public void postProcessContextQuery(BooleanQuery contextQuery,
			SearchContext searchContext) throws Exception {

		_log.info("postProcessContextQuery");
	}

	@Override
	public void postProcessDocument(Document document, Object obj)
		throws Exception {

		_log.info("postProcessDocument");
	}

	@Override
	public void postProcessFullQuery(BooleanQuery fullQuery,
			SearchContext searchContext) throws Exception {

		_log.info("postProcessFullQuery");
	}

	@Override
	public void postProcessSearchQuery(
		BooleanQuery searchQuery, BooleanFilter booleanFilter,
		SearchContext searchContext) throws Exception {

		_log.info("postProcessSearchQuery");
	}

	@Override
	public void postProcessSearchQuery(BooleanQuery searchQuery,
			SearchContext searchContext) throws Exception {

		_log.info("postProcessSearchQuery");
	}

	@Override
	public void postProcessSummary(Summary summary, Document document,
			Locale locale, String snippet) {

		_log.info("postProcessSummary");
	}

	private static final Log _log = LogFactoryUtil.getLog(
		MultipleIndexerPostProcessor.class);

}


text:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace MediaBrowser.Theater.Interfaces.Presentation
{
    /// <summary>
    /// Interface IHiddenWindow
    /// </summary>
    public interface IHiddenWindow
    {
        event EventHandler SizeChanged;
        event KeyEventHandler KeyDown;
        event MouseEventHandler MouseClick;
        event MouseEventHandler MouseMove;
        /// <summary>
        /// Gets the windows forms host.
        /// </summary>
        /// <value>The windows forms host.</value>
        Form Form { get; }

        Size ContentPixelSize { get; }

        Action OnWMGRAPHNOTIFY { get; set; }
        Action OnDVDEVENT { get; set; }
    }
}


text:
package org.apache.kafka.streams.kstream;

import org.junit.Test;

import static java.time.Duration.ofMillis;
import static org.apache.kafka.streams.EqualityCheck.verifyEquality;
import static org.apache.kafka.streams.EqualityCheck.verifyInEquality;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

public class SlidingWindowsTest {

    private static final long ANY_SIZE = 123L;

    @Test
    public void shouldSetTimeDifference() {
        assertEquals(ANY_SIZE, SlidingWindows.withTimeDifferenceAndGrace(ofMillis(ANY_SIZE), ofMillis(3)).timeDifferenceMs());
    }

    @Test
    public void timeDifferenceMustNotBeNegative() {
        assertThrows(IllegalArgumentException.class, () ->  SlidingWindows.withTimeDifferenceAndGrace(ofMillis(-1), ofMillis(5)));
    }

    @Test
    public void shouldSetGracePeriod() {
        assertEquals(ANY_SIZE, SlidingWindows.withTimeDifferenceAndGrace(ofMillis(10), ofMillis(ANY_SIZE)).gracePeriodMs());
    }

    @Test
    public void gracePeriodMustNotBeNegative() {
        assertThrows(IllegalArgumentException.class, () ->  SlidingWindows.withTimeDifferenceAndGrace(ofMillis(10), ofMillis(-1)));
    }

    @Test
    public void equalsAndHashcodeShouldBeValidForPositiveCases() {
        final long grace = 1L + (long) (Math.random() * (20L - 1L));
        final long timeDifference = 1L + (long) (Math.random() * (20L - 1L));
        verifyEquality(
                SlidingWindows.withTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(grace)),
                SlidingWindows.withTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(grace))
        );
    }

    @Test
    public void equalsAndHashcodeShouldNotBeEqualForDifferentTimeDifference() {
        final long grace = 1L + (long) (Math.random() * (10L - 1L));
        final long timeDifferenceOne = 1L + (long) (Math.random() * (10L - 1L));
        final long timeDifferenceTwo = 21L + (long) (Math.random() * (41L - 21L));
        verifyInEquality(
                SlidingWindows.withTimeDifferenceAndGrace(ofMillis(timeDifferenceOne), ofMillis(grace)),
                SlidingWindows.withTimeDifferenceAndGrace(ofMillis(timeDifferenceTwo), ofMillis(grace))
        );
    }

    @Test
    public void equalsAndHashcodeShouldNotBeEqualForDifferentGracePeriod() {
        final long timeDifference = 1L + (long) (Math.random() * (10L - 1L));
        final long graceOne = 1L + (long) (Math.random() * (10L - 1L));
        final long graceTwo = 21L + (long) (Math.random() * (41L - 21L));
        verifyInEquality(
                SlidingWindows.withTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(graceOne)),
                SlidingWindows.withTimeDifferenceAndGrace(ofMillis(timeDifference), ofMillis(graceTwo))
        );
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>V8 API Reference Guide for node.js v9.6.0 - v9.7.1: v8::ScriptOriginOptions Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

V8 API Reference Guide for node.js v9.6.0 - v9.7.1

Main Page

Related Pages

Namespaces

Classes

Files

Examples

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

v8

ScriptOriginOptions

Public Member Functions |
List of all members

v8::ScriptOriginOptions Class Reference

#include <v8.h>

Public Member Functions

V8_INLINE 	ScriptOriginOptions (bool is_shared_cross_origin=false, bool is_opaque=false, bool is_wasm=false, bool is_module=false)

V8_INLINE 	ScriptOriginOptions (int flags)

bool 	IsSharedCrossOrigin () const

bool 	IsOpaque () const

bool 	IsWasm () const

bool 	IsModule () const

int 	Flags () const

Detailed Description

The optional attributes of ScriptOrigin.

The documentation for this class was generated from the following file:

deps/v8/include/v8.h

<address class="footer">
Generated by

 1.8.11
</address>


text:
package org.pentaho.di.trans.steps.socketreader;

import java.util.List;
import java.util.Map;

import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.w3c.dom.Node;

/*
 * Created on 02-jun-2003
 *
 */

public class SocketReaderMeta extends BaseStepMeta implements StepMetaInterface
{
	private static Class<?> PKG = SocketReaderMeta.class; // for i18n purposes, needed by Translator2!!   $NON-NLS-1$

    private String hostname;
    private String port;
    private String bufferSize;
    private boolean compressed;

	public SocketReaderMeta()
	{
		super(); // allocate BaseStepMeta
	}

	public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters)
		throws KettleXMLException
	{
		readData(stepnode);
	}

	public Object clone()
	{
		Object retval = super.clone();
		return retval;
	}

    public String getXML()
    {
        StringBuffer xml = new StringBuffer();

        xml.append("     "+XMLHandler.addTagValue("hostname", hostname));
        xml.append("     "+XMLHandler.addTagValue("port", port));
        xml.append("     "+XMLHandler.addTagValue("buffer_size", bufferSize));
        xml.append("     "+XMLHandler.addTagValue("compressed", compressed));

        return xml.toString();
    }

	private void readData(Node stepnode)
	{
        hostname      = XMLHandler.getTagValue(stepnode, "hostname");
        port          = XMLHandler.getTagValue(stepnode, "port");
        bufferSize    = XMLHandler.getTagValue(stepnode, "buffer_size");
        compressed    = "Y".equalsIgnoreCase( XMLHandler.getTagValue(stepnode, "compressed") );
	}

	public void setDefault()
	{
        bufferSize = "3000";
        compressed = true;
	}

	public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException
	{
        hostname      = rep.getStepAttributeString(id_step, "hostname");
        port          = rep.getStepAttributeString(id_step, "port");
        bufferSize    = rep.getStepAttributeString(id_step, "buffer_size");
        compressed    = rep.getStepAttributeBoolean(id_step, "compressed");
	}

	public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step) throws KettleException
	{
        rep.saveStepAttribute(id_transformation, id_step, "hostname", hostname);
        rep.saveStepAttribute(id_transformation, id_step, "port", port);
        rep.saveStepAttribute(id_transformation, id_step, "buffer_size", bufferSize);
        rep.saveStepAttribute(id_transformation, id_step, "compressed", compressed);
	}

	public void getFields(RowMetaInterface rowMeta, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException
	{
		// Default: nothing changes to rowMeta
	}

	public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepinfo, RowMetaInterface prev, String input[], String output[], RowMetaInterface info)
	{
		CheckResult cr;
		if (prev==null || prev.size()==0)
		{
			cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, BaseMessages.getString(PKG, "SocketReaderMeta.CheckResult.NotReceivingFields"), stepinfo); //$NON-NLS-1$
			remarks.add(cr);
		}
		else
		{
			cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "SocketReaderMeta.CheckResult.StepRecevingData",prev.size()+""), stepinfo); //$NON-NLS-1$ //$NON-NLS-2$
			remarks.add(cr);
		}

		// See if we have input streams leading to this step!
		if (input.length>0)
		{
			cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "SocketReaderMeta.CheckResult.StepRecevingData2"), stepinfo); //$NON-NLS-1$
			remarks.add(cr);
		}
		else
		{
			cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(PKG, "SocketReaderMeta.CheckResult.NoInputReceivedFromOtherSteps"), stepinfo); //$NON-NLS-1$
			remarks.add(cr);
		}
	}

	public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr, Trans trans)
	{
		return new SocketReader(stepMeta, stepDataInterface, cnr, tr, trans);
	}

	public StepDataInterface getStepData()
	{
		return new SocketReaderData();
	}

    /**
     * @return the hostname
     */
    public String getHostname()
    {
        return hostname;
    }

    /**
     * @param hostname the hostname to set
     */
    public void setHostname(String hostname)
    {
        this.hostname = hostname;
    }

    /**
     * @return the port
     */
    public String getPort()
    {
        return port;
    }

    /**
     * @param port the port to set
     */
    public void setPort(String port)
    {
        this.port = port;
    }

    public String getBufferSize()
    {
        return bufferSize;
    }

    public void setBufferSize(String bufferSize)
    {
        this.bufferSize = bufferSize;
    }

    /**
     * @return the compressed
     */
    public boolean isCompressed()
    {
        return compressed;
    }

    /**
     * @param compressed the compressed to set
     */
    public void setCompressed(boolean compressed)
    {
        this.compressed = compressed;
    }
}


text:
// Copyright 2015 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using Serilog.Settings.KeyValuePairs;

namespace Serilog.Configuration
{
    /// <summary>
    /// Allows additional setting sources to drive the logger configuration.
    /// </summary>
    public class LoggerSettingsConfiguration
    {
        readonly LoggerConfiguration _loggerConfiguration;

        internal LoggerSettingsConfiguration(LoggerConfiguration loggerConfiguration)
        {
            if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
            _loggerConfiguration = loggerConfiguration;
        }

        /// <summary>
        /// Apply external settings to the logger configuration.
        /// </summary>
        /// <returns>Configuration object allowing method chaining.</returns>
        public LoggerConfiguration Settings(ILoggerSettings settings)
        {
            if (settings == null) throw new ArgumentNullException(nameof(settings));

            settings.Configure(_loggerConfiguration);

            return _loggerConfiguration;
        }

        /// <summary>
        /// Apply settings specified in the Serilog key-value setting format to the logger configuration.
        /// </summary>
        /// <param name="settings">A list of key-value pairs describing logger settings.</param>
        /// <returns>Configuration object allowing method chaining.</returns>
        public LoggerConfiguration KeyValuePairs(IEnumerable<KeyValuePair<string, string>> settings)
        {
            if (settings == null) throw new ArgumentNullException(nameof(settings));
            return Settings(new KeyValuePairSettings(settings));
        }
    }
}


text:
package com.nolanlawson.logcat.helper;

import android.os.Build;
import com.nolanlawson.logcat.util.UtilLogger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class LogcatHelper {

	public static final String BUFFER_MAIN = "main";
	public static final String BUFFER_EVENTS = "events";
	public static final String BUFFER_RADIO = "radio";

	private static UtilLogger log = new UtilLogger(LogcatHelper.class);

	public static Process getLogcatProcess(String buffer) throws IOException {

		List<String> args = getLogcatArgs(buffer);
		Process process = RuntimeHelper.exec(args);

		return process;
	}

	private static List<String> getLogcatArgs(String buffer) {
		List<String> args = Arrays.asList("logcat", "-v", "threadtime");

		// for some reason, adding -b main excludes log output from AndroidRuntime runtime exceptions,
		// whereas just leaving it blank keeps them in.  So do not specify the buffer if it is "main"
		if (!buffer.equals(BUFFER_MAIN)) {
			args.add("-b");
			args.add(buffer);
		}

		return args;
	}

	public static String getLastLogLine(String buffer) {
		Process dumpLogcatProcess = null;
		BufferedReader reader = null;
		String result = null;
		try {

			List<String> args = getLogcatArgs(buffer);
			args.add("-d"); // -d just dumps the whole thing

			dumpLogcatProcess = RuntimeHelper.exec(args);
			reader = new BufferedReader(new InputStreamReader(dumpLogcatProcess
					.getInputStream()), 8192);

			String line;
			while ((line = reader.readLine()) != null) {
				result = line;
			}
		} catch (IOException e) {
			log.e(e, "unexpected exception");
		} finally {
			if (dumpLogcatProcess != null) {
				RuntimeHelper.destroy(dumpLogcatProcess);
				log.d("destroyed 1 dump logcat process");
			}
			// post-jellybean, we just kill the process, so there's no need
	        // to close the bufferedReader.  Anyway, it just hangs.
//	        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN FIXME
//	                && reader != null) {
//				try {
//					reader.close();
//				} catch (IOException e) {
//					log.e(e, "unexpected exception");
//				}
//			}
		}

		return result;
	}
}


text:
<?php

namespace Illuminate\Queue;

use Illuminate\Contracts\Queue\ClearableQueue;
use Illuminate\Contracts\Queue\Queue as QueueContract;
use Illuminate\Contracts\Redis\Factory as Redis;
use Illuminate\Queue\Jobs\RedisJob;
use Illuminate\Support\Str;

class RedisQueue extends Queue implements QueueContract, ClearableQueue
{
    /**
     * The Redis factory implementation.
     *
     * @var \Illuminate\Contracts\Redis\Factory
     */
    protected $redis;

    /**
     * The connection name.
     *
     * @var string
     */
    protected $connection;

    /**
     * The name of the default queue.
     *
     * @var string
     */
    protected $default;

    /**
     * The expiration time of a job.
     *
     * @var int|null
     */
    protected $retryAfter = 60;

    /**
     * The maximum number of seconds to block for a job.
     *
     * @var int|null
     */
    protected $blockFor = null;

    /**
     * Create a new Redis queue instance.
     *
     * @param  \Illuminate\Contracts\Redis\Factory  $redis
     * @param  string  $default
     * @param  string|null  $connection
     * @param  int  $retryAfter
     * @param  int|null  $blockFor
     * @param  bool  $dispatchAfterCommit
     * @return void
     */
    public function __construct(Redis $redis,
                                $default = 'default',
                                $connection = null,
                                $retryAfter = 60,
                                $blockFor = null,
                                $dispatchAfterCommit = false)
    {
        $this->redis = $redis;
        $this->default = $default;
        $this->blockFor = $blockFor;
        $this->connection = $connection;
        $this->retryAfter = $retryAfter;
        $this->dispatchAfterCommit = $dispatchAfterCommit;
    }

    /**
     * Get the size of the queue.
     *
     * @param  string|null  $queue
     * @return int
     */
    public function size($queue = null)
    {
        $queue = $this->getQueue($queue);

        return $this->getConnection()->eval(
            LuaScripts::size(), 3, $queue, $queue.':delayed', $queue.':reserved'
        );
    }

    /**
     * Push an array of jobs onto the queue.
     *
     * @param  array  $jobs
     * @param  mixed  $data
     * @param  string|null  $queue
     * @return void
     */
    public function bulk($jobs, $data = '', $queue = null)
    {
        $this->getConnection()->pipeline(function () use ($jobs, $data, $queue) {
            $this->getConnection()->transaction(function () use ($jobs, $data, $queue) {
                foreach ((array) $jobs as $job) {
                    $this->push($job, $data, $queue);
                }
            });
        });
    }

    /**
     * Push a new job onto the queue.
     *
     * @param  object|string  $job
     * @param  mixed  $data
     * @param  string|null  $queue
     * @return mixed
     */
    public function push($job, $data = '', $queue = null)
    {
        return $this->enqueueUsing(
            $job,
            $this->createPayload($job, $this->getQueue($queue), $data),
            $queue,
            null,
            function ($payload, $queue) {
                return $this->pushRaw($payload, $queue);
            }
        );
    }

    /**
     * Push a raw payload onto the queue.
     *
     * @param  string  $payload
     * @param  string|null  $queue
     * @param  array  $options
     * @return mixed
     */
    public function pushRaw($payload, $queue = null, array $options = [])
    {
        $this->getConnection()->eval(
            LuaScripts::push(), 2, $this->getQueue($queue),
            $this->getQueue($queue).':notify', $payload
        );

        return json_decode($payload, true)['id'] ?? null;
    }

    /**
     * Push a new job onto the queue after a delay.
     *
     * @param  \DateTimeInterface|\DateInterval|int  $delay
     * @param  object|string  $job
     * @param  mixed  $data
     * @param  string|null  $queue
     * @return mixed
     */
    public function later($delay, $job, $data = '', $queue = null)
    {
        return $this->enqueueUsing(
            $job,
            $this->createPayload($job, $this->getQueue($queue), $data),
            $queue,
            $delay,
            function ($payload, $queue, $delay) {
                return $this->laterRaw($delay, $payload, $queue);
            }
        );
    }

    /**
     * Push a raw job onto the queue after (n) seconds.
     *
     * @param  \DateTimeInterface|\DateInterval|int  $delay
     * @param  string  $payload
     * @param  string|null  $queue
     * @return mixed
     */
    protected function laterRaw($delay, $payload, $queue = null)
    {
        $this->getConnection()->zadd(
            $this->getQueue($queue).':delayed', $this->availableAt($delay), $payload
        );

        return json_decode($payload, true)['id'] ?? null;
    }

    /**
     * Create a payload string from the given job and data.
     *
     * @param  string  $job
     * @param  string  $queue
     * @param  mixed  $data
     * @return array
     */
    protected function createPayloadArray($job, $queue, $data = '')
    {
        return array_merge(parent::createPayloadArray($job, $queue, $data), [
            'id' => $this->getRandomId(),
            'attempts' => 0,
        ]);
    }

    /**
     * Pop the next job off of the queue.
     *
     * @param  string|null  $queue
     * @return \Illuminate\Contracts\Queue\Job|null
     */
    public function pop($queue = null)
    {
        $this->migrate($prefixed = $this->getQueue($queue));

        [$job, $reserved] = $this->retrieveNextJob($prefixed);

        if ($reserved) {
            return new RedisJob(
                $this->container, $this, $job,
                $reserved, $this->connectionName, $queue ?: $this->default
            );
        }
    }

    /**
     * Migrate any delayed or expired jobs onto the primary queue.
     *
     * @param  string  $queue
     * @return void
     */
    protected function migrate($queue)
    {
        $this->migrateExpiredJobs($queue.':delayed', $queue);

        if (! is_null($this->retryAfter)) {
            $this->migrateExpiredJobs($queue.':reserved', $queue);
        }
    }

    /**
     * Migrate the delayed jobs that are ready to the regular queue.
     *
     * @param  string  $from
     * @param  string  $to
     * @return array
     */
    public function migrateExpiredJobs($from, $to)
    {
        return $this->getConnection()->eval(
            LuaScripts::migrateExpiredJobs(), 3, $from, $to, $to.':notify', $this->currentTime()
        );
    }

    /**
     * Retrieve the next job from the queue.
     *
     * @param  string  $queue
     * @param  bool  $block
     * @return array
     */
    protected function retrieveNextJob($queue, $block = true)
    {
        $nextJob = $this->getConnection()->eval(
            LuaScripts::pop(), 3, $queue, $queue.':reserved', $queue.':notify',
            $this->availableAt($this->retryAfter)
        );

        if (empty($nextJob)) {
            return [null, null];
        }

        [$job, $reserved] = $nextJob;

        if (! $job && ! is_null($this->blockFor) && $block &&
            $this->getConnection()->blpop([$queue.':notify'], $this->blockFor)) {
            return $this->retrieveNextJob($queue, false);
        }

        return [$job, $reserved];
    }

    /**
     * Delete a reserved job from the queue.
     *
     * @param  string  $queue
     * @param  \Illuminate\Queue\Jobs\RedisJob  $job
     * @return void
     */
    public function deleteReserved($queue, $job)
    {
        $this->getConnection()->zrem($this->getQueue($queue).':reserved', $job->getReservedJob());
    }

    /**
     * Delete a reserved job from the reserved queue and release it.
     *
     * @param  string  $queue
     * @param  \Illuminate\Queue\Jobs\RedisJob  $job
     * @param  int  $delay
     * @return void
     */
    public function deleteAndRelease($queue, $job, $delay)
    {
        $queue = $this->getQueue($queue);

        $this->getConnection()->eval(
            LuaScripts::release(), 2, $queue.':delayed', $queue.':reserved',
            $job->getReservedJob(), $this->availableAt($delay)
        );
    }

    /**
     * Delete all of the jobs from the queue.
     *
     * @param  string  $queue
     * @return int
     */
    public function clear($queue)
    {
        $queue = $this->getQueue($queue);

        return $this->getConnection()->eval(
            LuaScripts::clear(), 4, $queue, $queue.':delayed',
            $queue.':reserved', $queue.':notify'
        );
    }

    /**
     * Get a random ID string.
     *
     * @return string
     */
    protected function getRandomId()
    {
        return Str::random(32);
    }

    /**
     * Get the queue or return the default.
     *
     * @param  string|null  $queue
     * @return string
     */
    public function getQueue($queue)
    {
        return 'queues:'.($queue ?: $this->default);
    }

    /**
     * Get the connection for the queue.
     *
     * @return \Illuminate\Redis\Connections\Connection
     */
    public function getConnection()
    {
        return $this->redis->connection($this->connection);
    }

    /**
     * Get the underlying Redis instance.
     *
     * @return \Illuminate\Contracts\Redis\Factory
     */
    public function getRedis()
    {
        return $this->redis;
    }
}


text:
package metrics

import (
	"errors"
	"io/ioutil"
	"path/filepath"
)

var (
	DefaultFileName = ".kd"
	DefaultFileText = []byte("This is a test file for checking mount status. please don't remove.")

	ErrDiffContent = errors.New("file content is not what was expected")
)

type MountStatus struct {
	MountPath string
	FileName  string
	FileText  []byte
}

func NewDefaultMountStatus(path string) *MountStatus {
	return &MountStatus{
		MountPath: path,
		FileName:  DefaultFileName,
		FileText:  DefaultFileText,
	}
}

func (m *MountStatus) Write() error {
	return ioutil.WriteFile(m.filepath(), m.FileText, 0644)
}

func (m *MountStatus) CheckContents() error {
	text, err := ioutil.ReadFile(m.filepath())
	if err != nil {
		return err
	}

	if string(text) != string(m.FileText) {
		return ErrDiffContent
	}

	return nil
}

func (m *MountStatus) filepath() string {
	return filepath.Join(m.MountPath, m.FileName)
}


text:
#ifndef	_MACHINE_GLOBALS_H_
#define	_MACHINE_GLOBALS_H_

#ifdef _KERNEL

#define	GLOBAL_LVALUE(name, type) \
	(*(type *)_global_ptr_##name())

#define	GLOBAL_RVALUE(name, type) \
	((type)_global_##name())

/* non-volatile version */
#define	GLOBAL_LVALUE_NV(name, type) \
	(*(type *)_global_ptr_##name##_nv())

#define	GLOBAL_RVALUE_NV(name, type) \
	((type)_global_##name##_nv())

#define	GLOBAL_FUNC(name) \
	static __inline void *_global_ptr_##name(void) { \
		void *val; \
		__asm __volatile("movl $gd_" #name ",%0;" \
			"addl %%fs:globaldata,%0" : "=r" (val)); \
		return (val); \
	} \
	static __inline void *_global_ptr_##name##_nv(void) { \
		void *val; \
		__asm("movl $gd_" #name ",%0;" \
			"addl %%fs:globaldata,%0" : "=r" (val)); \
		return (val); \
	} \
	static __inline int _global_##name(void) { \
		int val; \
		__asm __volatile("movl %%fs:gd_" #name ",%0" : "=r" (val)); \
		return (val); \
	} \
	static __inline int _global_##name##_nv(void) { \
		int val; \
		__asm("movl %%fs:gd_" #name ",%0" : "=r" (val)); \
		return (val); \
	} \
	static __inline void _global_##name##_set(int val) { \
		__asm __volatile("movl %0,%%fs:gd_" #name : : "r" (val)); \
	} \
	static __inline void _global_##name##_set_nv(int val) { \
		__asm("movl %0,%%fs:gd_" #name : : "r" (val)); \
	}

#if defined(SMP) || defined(KLD_MODULE) || defined(ACTUALLY_LKM_NOT_KERNEL)
/*
 * The following set of macros works for UP kernel as well, but for maximum
 * performance we allow the global variables to be accessed directly. On the
 * other hand, kernel modules should always use these macros to maintain
 * portability between UP and SMP kernels.
 */
#define	curproc		GLOBAL_RVALUE_NV(curproc, struct proc *)
#define	curpcb		GLOBAL_RVALUE_NV(curpcb, struct pcb *)
#define	npxproc		GLOBAL_LVALUE(npxproc, struct proc *)
#define	common_tss	GLOBAL_LVALUE(common_tss, struct i386tss)
#define	switchtime	GLOBAL_LVALUE(switchtime, struct timeval)
#define	switchticks	GLOBAL_LVALUE(switchticks, int)

#define	common_tssd	GLOBAL_LVALUE(common_tssd, struct segment_descriptor)
#define	tss_gdt		GLOBAL_LVALUE(tss_gdt, struct segment_descriptor *)

#ifdef USER_LDT
#define	currentldt	GLOBAL_LVALUE(currentldt, int)
#endif

#ifdef SMP
#define	cpuid		GLOBAL_RVALUE(cpuid, u_int)
#define	other_cpus	GLOBAL_LVALUE(other_cpus, u_int)
#define	inside_intr	GLOBAL_LVALUE(inside_intr, int)
#define	prv_CMAP1	GLOBAL_LVALUE(prv_CMAP1, pt_entry_t *)
#define	prv_CMAP2	GLOBAL_LVALUE(prv_CMAP2, pt_entry_t *)
#define	prv_CMAP3	GLOBAL_LVALUE(prv_CMAP3, pt_entry_t *)
#define	prv_PMAP1	GLOBAL_LVALUE(prv_PMAP1, pt_entry_t *)
#define	prv_CADDR1	GLOBAL_RVALUE(prv_CADDR1, caddr_t)
#define	prv_CADDR2	GLOBAL_RVALUE(prv_CADDR2, caddr_t)
#define	prv_CADDR3	GLOBAL_RVALUE(prv_CADDR3, caddr_t)
#define	prv_PADDR1	GLOBAL_RVALUE(prv_PADDR1, unsigned *)
#endif
#endif	/*UP kernel*/

GLOBAL_FUNC(curproc)
GLOBAL_FUNC(curpcb)
GLOBAL_FUNC(npxproc)
GLOBAL_FUNC(common_tss)
GLOBAL_FUNC(switchtime)
GLOBAL_FUNC(switchticks)

GLOBAL_FUNC(common_tssd)
GLOBAL_FUNC(tss_gdt)

#ifdef USER_LDT
GLOBAL_FUNC(currentldt)
#endif

#ifdef SMP
GLOBAL_FUNC(cpuid)
GLOBAL_FUNC(other_cpus)
GLOBAL_FUNC(inside_intr)
GLOBAL_FUNC(prv_CMAP1)
GLOBAL_FUNC(prv_CMAP2)
GLOBAL_FUNC(prv_CMAP3)
GLOBAL_FUNC(prv_PMAP1)
GLOBAL_FUNC(prv_CADDR1)
GLOBAL_FUNC(prv_CADDR2)
GLOBAL_FUNC(prv_CADDR3)
GLOBAL_FUNC(prv_PADDR1)
#endif

#define	SET_CURPROC(x)	(_global_curproc_set_nv((int)x))

#endif	/* _KERNEL */

#endif	/* !_MACHINE_GLOBALS_H_ */


text:
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# -----------------------------------------------------------------------------

import os
import sys

# -----------------------------------------------------------------------------

def convert_rfamseq_to_genseq(rfamseq_file):
    """
    Converts an rfamseq file to genseq to map genome (upid) and sequence
    accessions

    :param rfamseq_file: A genome specific rfamseq file in the form of
    upid.rfamseq, as generated from rfamseq table

    returns: void
    """
    # store output in input file directory
    dest_dir = os.path.split(rfamseq_file)[0]
    # get the input filename to keep track of the upids
    filename = os.path.basename(rfamseq_file).partition('.')[0]
    genseq_file = open(filename + '.genseq', 'w')
    rfamseq_fp = open(rfamseq_file, 'r')
    for line in rfamseq_fp:
        line = line.strip().split('\t')
        genseq_file.write(filename + '\t' + line[0] + '\n')
    genseq_file.close()
    rfamseq_fp.close()

if __name__ == '__main__':
    rfamseq_file = sys.argv[1]
    convert_rfamseq_to_genseq(rfamseq_file)


text:
package s3_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/awstesting/unit"
	"github.com/aws/aws-sdk-go/service/s3"
)

const errMsg = `<Error><Code>ErrorCode</Code><Message>message body</Message><RequestId>requestID</RequestId><HostId>hostID=</HostId></Error>`

var lastModifiedTime = time.Date(2009, 11, 23, 0, 0, 0, 0, time.UTC)

func TestCopyObjectNoError(t *testing.T) {
	const successMsg = `
<?xml version="1.0" encoding="UTF-8"?>
<CopyObjectResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LastModified>2009-11-23T0:00:00Z</LastModified><ETag>"1da64c7f13d1e8dbeaea40b905fd586c"</ETag></CopyObjectResult>`

	res, err := newCopyTestSvc(successMsg).CopyObject(&s3.CopyObjectInput{
		Bucket:     aws.String("bucketname"),
		CopySource: aws.String("bucketname/exists.txt"),
		Key:        aws.String("destination.txt"),
	})

	require.NoError(t, err)

	assert.Equal(t, fmt.Sprintf(`%q`, "1da64c7f13d1e8dbeaea40b905fd586c"), *res.CopyObjectResult.ETag)
	assert.Equal(t, lastModifiedTime, *res.CopyObjectResult.LastModified)
}

func TestCopyObjectError(t *testing.T) {
	_, err := newCopyTestSvc(errMsg).CopyObject(&s3.CopyObjectInput{
		Bucket:     aws.String("bucketname"),
		CopySource: aws.String("bucketname/doesnotexist.txt"),
		Key:        aws.String("destination.txt"),
	})

	require.Error(t, err)
	e := err.(awserr.Error)

	assert.Equal(t, "ErrorCode", e.Code())
	assert.Equal(t, "message body", e.Message())
}

func TestUploadPartCopySuccess(t *testing.T) {
	const successMsg = `
<?xml version="1.0" encoding="UTF-8"?>
<UploadPartCopyResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LastModified>2009-11-23T0:00:00Z</LastModified><ETag>"1da64c7f13d1e8dbeaea40b905fd586c"</ETag></UploadPartCopyResult>`

	res, err := newCopyTestSvc(successMsg).UploadPartCopy(&s3.UploadPartCopyInput{
		Bucket:     aws.String("bucketname"),
		CopySource: aws.String("bucketname/doesnotexist.txt"),
		Key:        aws.String("destination.txt"),
		PartNumber: aws.Int64(0),
		UploadId:   aws.String("uploadID"),
	})

	require.NoError(t, err)

	assert.Equal(t, fmt.Sprintf(`%q`, "1da64c7f13d1e8dbeaea40b905fd586c"), *res.CopyPartResult.ETag)
	assert.Equal(t, lastModifiedTime, *res.CopyPartResult.LastModified)
}

func TestUploadPartCopyError(t *testing.T) {
	_, err := newCopyTestSvc(errMsg).UploadPartCopy(&s3.UploadPartCopyInput{
		Bucket:     aws.String("bucketname"),
		CopySource: aws.String("bucketname/doesnotexist.txt"),
		Key:        aws.String("destination.txt"),
		PartNumber: aws.Int64(0),
		UploadId:   aws.String("uploadID"),
	})

	require.Error(t, err)
	e := err.(awserr.Error)

	assert.Equal(t, "ErrorCode", e.Code())
	assert.Equal(t, "message body", e.Message())
}

func TestCompleteMultipartUploadSuccess(t *testing.T) {
	const successMsg = `
<?xml version="1.0" encoding="UTF-8"?>
<CompleteMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Location>locationName</Location><Bucket>bucketName</Bucket><Key>keyName</Key><ETag>"etagVal"</ETag></CompleteMultipartUploadResult>`
	res, err := newCopyTestSvc(successMsg).CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
		Bucket:   aws.String("bucketname"),
		Key:      aws.String("key"),
		UploadId: aws.String("uploadID"),
	})

	require.NoError(t, err)

	assert.Equal(t, `"etagVal"`, *res.ETag)
	assert.Equal(t, "bucketName", *res.Bucket)
	assert.Equal(t, "keyName", *res.Key)
	assert.Equal(t, "locationName", *res.Location)
}

func TestCompleteMultipartUploadError(t *testing.T) {
	_, err := newCopyTestSvc(errMsg).CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
		Bucket:   aws.String("bucketname"),
		Key:      aws.String("key"),
		UploadId: aws.String("uploadID"),
	})

	require.Error(t, err)
	e := err.(awserr.Error)

	assert.Equal(t, "ErrorCode", e.Code())
	assert.Equal(t, "message body", e.Message())
}

func newCopyTestSvc(errMsg string) *s3.S3 {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, errMsg, http.StatusOK)
	}))
	return s3.New(unit.Session, aws.NewConfig().
		WithEndpoint(server.URL).
		WithDisableSSL(true).
		WithMaxRetries(0).
		WithS3ForcePathStyle(true))
}
//Added a line for testing
//Adding another line for Git event testing part 2
//Adding another line for Git event testing part 2.1
//Adding another line for Git event testing part 2.2


text:
"""
Linux on Hyper-V and Azure Test Code, ver. 1.0.0
Copyright (c) Microsoft Corporation

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

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

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

See the Apache Version 2.0 License for specific language governing
permissions and limitations under the License.
"""

import os
import sys
import time
import logging

from utils import constants
from utils.cmdshell import SSHClient
from report.db_utils import upload_results
from paramiko.ssh_exception import NoValidConnectionsError

from providers.amazon_service import AWSConnector
from providers.azure_service import AzureConnector
from providers.gcp_service import GCPConnector

logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
                    datefmt='%y/%m/%d %H:%M:%S', level=logging.INFO)
log = logging.getLogger(__name__)

class SetupTestEnv:
    """
    Setup test environment.
    """
    def __init__(self, provider=None, vm_count=None, test_type=None, disk_size=None, raid=None,
                 keyid=None, secret=None, token=None, subscriptionid=None, tenantid=None,
                 projectid=None, imageid=None, instancetype=None, user=None, localpath=None,
                 region=None, zone=None, sriov=False, kernel=None):
        """
        Init AWS connector to create and configure AWS ec2 instances.
        :param provider Service provider to be used e.g. azure, aws, gce.
        :param vm_count: Number of VMs to prepare
        :param test_type: vm_disk > 1 VM with disk (Orion and Sysbench)
                          no_disk > No disk attached (Redis, Memcached, Apache_bench)
                          db_disk > Second VM with disk (MariaDB, MongoDB)
                          cluster_disk > All VMs have disks (Terasort)
        :param disk_size:
        :param raid: Bool or Int (the number of disks), to specify if a RAID will be configured
        :param keyid: user key for executing remote connection
        :param secret: user secret for executing remote connection
        :param token: GCE refresh token obtained with gcloud sdk
        :param subscriptionid: Azure specific subscription id
        :param tenantid: Azure specific tenant id
        :param projectid: GCE specific project id
        :param imageid: AWS OS AMI image id or
                        Azure image references offer and sku: e.g. 'UbuntuServer#16.04.0-LTS' or
                        GCE image family, e.g. 'ubuntu-1604-lts'
        :param instancetype: AWS instance resource type e.g 'd2.4xlarge' or
                            Azure hardware profile vm size e.g. 'Standard_DS14_v2' or
                            GCE instance size e.g. 'n1-highmem-16'
        :param user: remote ssh user for the instance
        :param localpath: localpath where the logs should be downloaded, and the
                            default path for other necessary tools
        :param region: region to connect to
        :param zone: zone where other resources should be available
        :param sriov: bool for configuring SR-IOV or not
        :param kernel: kernel deb name to install provided in localpath
        :rtype Tuple
        :return: connector <Connector>,
                 vm_ips <VM private IPs dict>,
                 device <attached disk devices>,
                 ssh_client <ssh clients dict>
        """
        self.provider = provider
        self.vm_count = vm_count
        self.test_type = test_type
        self.disk_size = disk_size
        self.raid = raid
        self.keyid = keyid
        self.secret = secret
        self.token = token
        self.subscriptionid = subscriptionid
        self.tenantid = tenantid
        self.projectid = projectid
        self.imageid = imageid
        self.instancetype = instancetype
        self.user = user
        self.localpath = localpath
        self.region = region
        self.zone = zone
        self.sriov = sriov
        self.kernel = kernel

        # create and generate setup details
        try:
            self.connector = self.create_connector()
            self.vms = self.create_instances()
            self.device = self.get_disk_devices()
            self.ssh_client, self.vm_ips = self.get_instance_details()
            self.perf_tuning()
            self.reconnect_sshclient()
        except Exception as e:
            log.exception(e)
            if self.connector:
                self.connector.teardown()
            raise

    def create_connector(self):
        """
        Create connector by provider.
        :return: connector
        """
        connector = None
        if self.provider == constants.AWS:
            connector = AWSConnector(keyid=self.keyid, secret=self.secret, imageid=self.imageid,
                                     instancetype=self.instancetype, user=self.user,
                                     localpath=self.localpath, region=self.region, zone=self.zone)
        elif self.provider == constants.AZURE:
            connector = AzureConnector(clientid=self.keyid, secret=self.secret,
                                       subscriptionid=self.subscriptionid, tenantid=self.tenantid,
                                       imageid=self.imageid, instancetype=self.instancetype,
                                       user=self.user, localpath=self.localpath,
                                       location=self.region, sriov=self.sriov)
        elif self.provider == constants.GCE:
            connector = GCPConnector(clientid=self.keyid, secret=self.secret, token=self.token,
                                     projectid=self.projectid, imageid=self.imageid,
                                     instancetype=self.instancetype, user=self.user,
                                     localpath=self.localpath, zone=self.zone)
        if connector:
            connector.connect()
            return connector
        else:
            raise Exception('Unsupported provider or connector failed.')

    def create_instances(self):
        """
        Create instances.
        :return: VM instances
        """
        open(self.connector.host_key_file, 'w').close()
        vms = {}
        for i in xrange(1, self.vm_count + 1):
            vms[i] = self.connector.create_vm()
        return vms

    def reconnect_sshclient(self):
        if self.provider == constants.AWS:
            log.info('The provider is AWS, reconnect sshclient')
            for i in xrange(1, self.vm_count + 1):
                self.ssh_client[i].connect()

    def get_instance_details(self):
        """
        Create ssh client and get vm IPs
        :return: ssh_client, vm_ips
        """
        ssh_client = {}
        vm_ips = {}
        for i in xrange(1, self.vm_count + 1):
            if self.provider == constants.AWS:
                ssh_client[i] = self.connector.wait_for_ping(self.vms[i])
                # SRIOV is enabled by default on AWS for the tested platforms
                # if sriov == constants.ENABLED:
                #     ssh_client[i] = connector.enable_sr_iov(vms[i], ssh_client[i])
                self.vms[i].update()
                vm_ips[i] = self.vms[i].private_ip_address
            elif self.provider == constants.AZURE:
                ssh_client[i] = SSHClient(server=self.vms[i].name + self.connector.dns_suffix,
                                          host_key_file=self.connector.host_key_file,
                                          user=self.connector.user,
                                          ssh_key_file=os.path.join(
                                                  self.connector.localpath,
                                                  self.connector.key_name + '.pem'))
                ip = ssh_client[i].run(
                        'ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
                vm_ips[i] = ip[1].strip()
            elif self.provider == constants.GCE:
                ssh_client[i] = self.connector.wait_for_ping(self.vms[i])
                vm_ips[i] = self.vms[i]['networkInterfaces'][0]['networkIP']
        return ssh_client, vm_ips

    def attach_raid_disks(self, vm_tag, disk_args):
        device = []
        for i in xrange(self.raid):
            if self.provider == constants.AWS:
                disk_args['device'] = '/dev/sd{}'.format(chr(120 - i))
                device.append(disk_args['device'].replace('sd', 'xvd'))
            elif self.provider == constants.AZURE:
                disk_args['device'] = i
                device.append('/dev/sd{}'.format(chr(99 + i)))
            elif self.provider == constants.GCE:
                device.append('/dev/sd{}'.format(chr(98 + i)))
            self.connector.attach_disk(self.vms[vm_tag], disk_size=self.disk_size, **disk_args)
        return device

    def get_disk_devices(self):
        if not self.test_type:
            return None
        device = None
        disk_args = {}
        if self.provider == constants.AWS:
            device = constants.DEVICE_AWS.replace('sd', 'xvd')
            disk_args['iops'] = 5000
            disk_args['volume_type'] = self.connector.volume_type['ssd_io1']
            disk_args['device'] = constants.DEVICE_AWS
        elif self.provider == constants.AZURE:
            device = constants.DEVICE_AZURE
        elif self.provider == constants.GCE:
            # Note: using disk device order prediction,GCE API is not consistent in the disk naming
            # device = constants.DEVICE_GCE + disk_name
            device = constants.TEMP_DEVICE_GCE

        if self.test_type == constants.CLUSTER_DISK:
            self.connector.attach_disk(self.vms[1], disk_size=self.disk_size + 200, **disk_args)
            for i in xrange(2, self.vm_count + 1):
                self.connector.attach_disk(self.vms[i], disk_size=self.disk_size, **disk_args)
                time.sleep(3)
            return device

        vm_tag = None
        if self.test_type == constants.VM_DISK:
            vm_tag = 1
        elif self.test_type == constants.DB_DISK:
            vm_tag = 2

        if self.raid and type(self.raid) is int:
            return self.attach_raid_disks(vm_tag, disk_args)
        else:
            self.connector.attach_disk(self.vms[vm_tag], disk_size=self.disk_size, **disk_args)

        return device

    def perf_tuning(self):
        current_path = os.path.dirname(sys.modules['__main__'].__file__)
        for i in range(1, self.vm_count + 1):
            log.info('Running perf tuning on {}'.format(self.vm_ips[i]))
            self.ssh_client[i].connect()
            self.ssh_client[i].put_file(os.path.join(current_path, 'tests', 'perf_tuning.sh'),
                                        '/tmp/perf_tuning.sh')
            self.ssh_client[i].run('chmod +x /tmp/perf_tuning.sh')
            self.ssh_client[i].run("sed -i 's/\r//' /tmp/perf_tuning.sh")
            params = [self.provider]
            if '.deb' in self.kernel:
                log.info('Uploading kernel {} on {}'.format(self.kernel, self.vm_ips[i]))
                self.ssh_client[i].put_file(os.path.join(self.localpath, self.kernel),
                                            '/tmp/{}'.format(self.kernel))
                params.append('/tmp/{}'.format(self.kernel))
            self.ssh_client[i].run('/tmp/perf_tuning.sh {}'.format(' '.join(params)))
            if self.provider in [constants.AWS, constants.GCE]:
                self.ssh_client[i] = self.connector.restart_vm(self.vms[i])
            elif self.provider == constants.AZURE:
                self.vms[i] = self.connector.restart_vm(self.vms[i].name)
                # TODO add custom kernel support for all providers - only azure support
                self.ssh_client[i] = SSHClient(server=self.vms[i].name + self.connector.dns_suffix,
                                               host_key_file=self.connector.host_key_file,
                                               user=self.connector.user,
                                               ssh_key_file=os.path.join(
                                                       self.connector.localpath,
                                                       self.connector.key_name + '.pem'))
                ip = self.ssh_client[i].run(
                        'ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
                self.vm_ips[i] = ip[1].strip()

    def run_test(self, ssh_vm_conf=0, testname=None, test_cmd=None, results_path=None, raid=False,
                 ssh_raid=1, timeout=constants.TIMEOUT):
        try:
            if all(client is not None for client in self.ssh_client.values()):
                current_path = os.path.dirname(sys.modules['__main__'].__file__)
                # enable key auth between instances
                for i in xrange(1, ssh_vm_conf + 1):
                    self.ssh_client[i].put_file(os.path.join(self.localpath,
                                                             self.connector.key_name + '.pem'),
                                                '/home/{}/.ssh/id_rsa'.format(self.user))
                    self.ssh_client[i].run('chmod 0600 /home/{0}/.ssh/id_rsa'.format(self.user))
                if raid:
                    self.ssh_client[ssh_raid].put_file(os.path.join(
                            current_path, 'tests', 'raid.sh'), '/tmp/raid.sh')
                    self.ssh_client[ssh_raid].run('chmod +x /tmp/raid.sh')
                    self.ssh_client[ssh_raid].run("sed -i 's/\r//' /tmp/raid.sh")
                    self.ssh_client[ssh_raid].run('/tmp/raid.sh 0 {} {}'.format(raid, ' '.join(
                            self.device)))
                bash_testname = 'run_{}.sh'.format(testname)
                self.ssh_client[1].put_file(os.path.join(current_path, 'tests', bash_testname),
                                            '/tmp/{}'.format(bash_testname))
                self.ssh_client[1].run('chmod +x /tmp/{}'.format(bash_testname))
                self.ssh_client[1].run("sed -i 's/\r//' /tmp/{}".format(bash_testname))
                log.info('Starting background command {}'.format(test_cmd))
                channel = self.ssh_client[1].run_pty(test_cmd)
                _, pid, _ = self.ssh_client[1].run(
                        "ps aux | grep -v grep | grep {} | awk '{{print $2}}'".format(
                                bash_testname))
                self._wait_for_pid(self.ssh_client[1], bash_testname, pid, timeout=timeout)
                channel.close()
                self.ssh_client[1].get_file('/tmp/{}.zip'.format(testname), results_path)
        except Exception as e:
            log.exception(e)
            raise
        finally:
            if self.connector:
                self.connector.teardown()

    @staticmethod
    def _wait_for_pid(ssh_client, bash_testname, pid, timeout=constants.TIMEOUT):
        t = 0
        while t < timeout:
            try:
                _, new_pid, _ = ssh_client.run(
                        "ps aux | grep -v grep | grep {} | awk '{{print $2}}'".format(
                                bash_testname))
                if new_pid != pid:
                    return
            except NoValidConnectionsError:
                log.debug('NoValidConnectionsError, will retry in 60 seconds')
                time.sleep(60)
                t += 60
            time.sleep(60)
            t += 60
        else:
            raise Exception('Timeout waiting for process to end.'.format(timeout))

    def run_test_nohup(self, ssh_vm_conf=0, test_cmd=None, timeout=constants.TIMEOUT, track=None):
        try:
            if all(client is not None for client in self.ssh_client.values()):
                current_path = os.path.dirname(sys.modules['__main__'].__file__)
                # enable key auth between instances
                for i in xrange(1, ssh_vm_conf + 1):
                    self.ssh_client[i].put_file(os.path.join(self.localpath,
                                                             self.connector.key_name + '.pem'),
                                                '/home/{}/.ssh/id_rsa'.format(self.user))
                    self.ssh_client[i].run('chmod 0600 /home/{0}/.ssh/id_rsa'.format(self.user))
                log.info('Starting run nohup command {}'.format(test_cmd))
                self.ssh_client[1].run(test_cmd)
                self._wait_for_command(self.ssh_client[1], track, timeout=timeout)
        except Exception as e:
            log.exception(e)
            raise
        finally:
            log.info('Finish to run nohup command {}'.format(test_cmd))

    @staticmethod
    def _wait_for_command(ssh_client, track, timeout=constants.TIMEOUT):
        t = 0
        while t < timeout:
            try:
                _, p_count, _  = ssh_client.run(
                        "ps aux | grep -v grep | grep {} | awk '{{print $2}}' | wc -l".format(
                                track))
                if int(p_count) == 0 :
                    return
            except NoValidConnectionsError:
                log.debug('NoValidConnectionsError, will retry in 60 seconds')
                time.sleep(60)
                t += 60
            time.sleep(60)
            t += 60
        else:
            raise Exception('Timeout waiting for process to end.'.format(timeout))


text:
from django import forms
from django.conf import settings
from django.core.files import File
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy
from django.core.files.images import get_image_dimensions
from django.templatetags.static import static
from upload_image_box.exceptions import *
import imghdr

import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

# imghdr fix to detect jpeg images
"""
def test_icc_profile_images(h, f):
    if h.startswith('\xff\xd8') and h[6:17] == b'ICC_PROFILE':
        return "jpeg"
imghdr.tests.append(test_icc_profile_images)
"""

# imghdr fix to detect jpeg images -> (https://bugs.python.org/issue16512)
def test_jpeg(h, f):
    """JPEG data in JFIF or Exif format"""
    if not h.startswith(b'\xff\xd8'):#Test empty files, and incorrect start of file
        return None
    else:
        if f:#if we test a file, test end of jpeg
            f.seek(-2,2)
            if f.read(2).endswith(b'\xff\xd9'):
                return 'jpeg'
        else:#if we just test the header, consider this is a valid jpeg and not test end of file
            return 'jpeg'

imghdr.tests.append(test_jpeg)

class UibUploaderInput(forms.ClearableFileInput):

    # override default ClearableFileInput data
    initial_text = '' # ugettext_lazy('Currently')
    input_text = '' # ugettext_lazy('Change')
    clear_checkbox_label = '' # ugettext_lazy('Clear')
    template_with_clear = '' # '%(clear)s %(clear_checkbox_label)s'

    # default template is a simple div
    template_with_initial = '%(uploader_button)s%(modal_window_scheleton)s%(uploader_script)s'

    def __init__(self, attrs=None):
        # set valid checks
        self.max_file_size = 4*1024*1024 # 4MB
        self.min_file_width = 250
        self.min_file_height = 250
        self.mimetypes_allowed = ['jpeg', 'png',]

        # widget settings
	self.default_attrs = {
		'base_modal_title_text': 'Load an image',
                'base_modal_description_text': "To upload a new image click on 'Load an image' button",
		'upload_modal_title_text': 'Image upload...',
		'moving_ball_modal_title_text': 'Please wait...',
		'crop_modal_title_text': 'Crop your image',
		'preview_modal_title_text': 'Image preview',
		'crop_action_button_text': 'Crop',
		'select_image_action_button_text': 'Select image',
		'widget_button_text': 'Load image',
		'preview_action_button_text': 'Confirm image',
		'cancel_button_text': 'Cancel',
		'change_image_button_text': 'Change image',
                'crop_modal_description_text': "Crop your image!",
                'default_uploader_button': '
%(widget_button_text)s
', # default upload button
                'callback_function': '', # custom callback function
		'enable_crop': True,
                'widget_id': 'test_id', # only required field
                'static_url': static(''),
	}

        # overriding defaul attributes
        if attrs:
            self.default_attrs.update(attrs)

        self.uploader_button = self.default_attrs["default_uploader_button"]
        self.modal_window_scheleton = '<div id="%(widget_id)s" class="modal_container" data-base-modal-title-text="%(base_modal_title_text)s" data-base-modal-description-text="%(base_modal_description_text)s" data-upload-modal-title-text="%(upload_modal_title_text)s" data-crop-modal-title-text="%(crop_modal_title_text)s" data-preview-modal-title-text="%(preview_modal_title_text)s" data-crop-action-button-text="%(crop_action_button_text)s" data-preview-action-button-text="%(preview_action_button_text)s" data-cancel-button-text="%(cancel_button_text)s" data-change-image-button-text="%(change_image_button_text)s" data-enable-crop="%(enable_crop)s" data-select-image-action-button-text="%(select_image_action_button_text)s" data-crop-modal-description-text="%(crop_modal_description_text)s" data-callback-function="%(callback_function)s" data-moving-ball-modal-title-text="%(moving_ball_modal_title_text)s" data-static-url="%(static_url)s">
'
        self.uploader_script = ''
        # self.uploader_options = '

'
        super(UibUploaderInput , self).__init__(attrs=None)

    # metodo per scrivere nell'html il file input
    # questa funzione viene eseguita al rendering dell'html
    def render(self, name, value, attrs=None):
	logger.debug("attrs list: " + str(self.default_attrs))
        substitutions = {
            'uploader_button': (self.uploader_button % self.default_attrs),
            'modal_window_scheleton': (self.modal_window_scheleton % self.default_attrs),
            'uploader_script': (self.uploader_script % self.default_attrs),
            # 'uploader_options': (self.uploader_options % self.default_attrs),
        }
        template = self.template_with_initial

        return mark_safe(template % substitutions)

    # Function to validate widget, called on form.is_valid()
    def value_from_datadict(self, data, files, name):
        # if a file was uploaded
        parent_validation = super(UibUploaderInput, self).value_from_datadict(data, files, name)
        # logger.debug("files retrieved: " + str(files))
        file_object = files.get('image', None)
        logger.debug("-------------------files: " + str(files))
        logger.debug("-------------------data: " + str(data))
        logger.debug("-------------------file object: " + str(file_object))
        if parent_validation is not None and file_object is not None:
            # check image MIME/Type
            image_type = imghdr.what(file_object)
            if not image_type or image_type not in self.mimetypes_allowed:
                logger.info("imghdr wrong type: " + str(image_type))
                raise ImageExtensionUIBError

            # retrieve image info
            file_size = file_object.size
            file_w, file_h = get_image_dimensions(file_object)

            # image size check
            logger.debug("Image size: " + str(file_size) + " massima: " + str(self.max_file_size))
            if file_size > self.max_file_size:
                raise ImageSizeUIBError

            # image dimensions check
            logger.debug("Image w: " + str(file_w)+ " image h: " + str(file_h))
            if file_w < self.min_file_width or file_h < self.min_file_height:
                raise ImageDimensionsUIBError
            return file_object  # Return valid file object
        else:
            # raise corrupted file error
            raise CorruptedImageUIBError

    class Media:
        css = {
            'all': ("upload_image_box/css/widget.css",)
        }
        js = ("upload_image_box/js/widget.js",)

    # INTRO
    # =====
    #
    # 1 pulsante per aprire popup "upload image"
    # 2 all'interno del popup un ulteriore pulsante per upload immagine
    # 3 alla selezione dell'immagine ricaricare l'iframe con l'immagine uploadata
    #   e il crop di proporzioni fisse
    # 4 ora è possibile fare due cose: modificare l'immagine uploadata con
    #   un'altra (si riparte dallo step 3), oppure confermare il crop
    # 5 alla conferma del crop salvare l'immagine croppata su disco, meglio ancora se su S3
    # come fare tutto ciò come un Django widget? :o
    # Terminerei con una sufficienza (6): wow fortuna che l'ho fatto...