text:
"use strict";
var vkbot = (() => {

  var BotCommand = require('./Classes/BotCommand');
  var request = require('request');
  var querystring = require('querystring');

  /**
   * Main message parsing routine.
   * @param  {String}   token          VK API access token
   * @param  {String}   bot_prefix     Bot name/prefix, used to identify messages for the bot
   * @param  {Function} callback       Routing callback function
   * @param  {Object}   that           Context in which callback should be invoked
   * @param  {Object}   longpollparams 'ts' and 'pts' parameters for VK LongPoll API.
   * @return {undefined}
   */
  function parseMessages(token, bot_prefix, callback, that, longpollparams) {
    request('https://api.vk.com/method/messages.getLongPollHistory?' + querystring.stringify({
      ts: longpollparams.ts,
      pts: longpollparams.pts,
      fields: 'display_name',
      v: '5.53',
      access_token: token
    }), (err, response, body) => {
      // handle connection errors
      if (err)
        throw new Error('Couldn\'t fetch a response from VK API. Aborting.');
      // handle VK API errors
      var messages = JSON.parse(body);
      if (messages.hasOwnProperty('error')) {
        if (messages.error.error_code == 10) {
          // handle 'ts' renewal
          renewLongPollData(token, (longpollparams) => {
            setTimeout(() => {
              // 'that' should be referenced fine
              parseMessages(token, bot_prefix, callback, that, longpollparams);
            }, 1500);
          });
        } else {
          // just print out the error code and message
          return console.warn('VK API returned an error while trying to fetch messages. Error:\n' +
            messages.error.error_code + ": " + messages.error.error_msg);
        }
      }
      // done parsing errors, let's parse dem messages
      // but first we need to save the new_pts parameter we received with an API response
      var new_pts = messages.response.new_pts;
      messages = messages.response.messages.items;
      // nothing holds us back, we can use forEach method of the messages array
      messages.forEach((message) => {
        if ((new RegExp('^' + bot_prefix)).test(message.body)) {
          console.log('\nA message for the bot received, invoking router callback...');
          callback.call(that, message); // that's it!
        };
      });
      setTimeout(() => {
        parseMessages(token, bot_prefix, callback, that, {
          ts: longpollparams.ts,
          pts: new_pts,
        });
      }, 1500); // we check for new messages every 1.5 seconds
    });
  }

  /**
   * A method used to renew 'ts' and 'pts' parameters of the VK LongPoll API.
   * @param  {String}   token    VK API access token
   * @param  {Function} callback A callback where an Object with new ts and pts will be passed
   * @param  {Object}   that     Context in which callback should be invoked
   * @return {undefined}
   */
  function renewLongPollData(token, callback, that) {
    request('https://api.vk.com/method/messages.getLongPollServer?' + querystring.stringify({
      need_pts: 1,
      v: '5.53',
      access_token: token
    }), (err, response, body) => {
      if (err) // handle connection errors
        throw new Error('An error occured while trying to fetch LongPoll data. Aborting.');
      var parsed_response = JSON.parse(body);
      if (parsed_response.hasOwnProperty('error')) // handle VK API errors
        return console.warn('VK API returned an error while trying to fetch messages. Error:\n' +
          parsed_response.error.error_code + ": " + parsed_response.error.error_msg);
      // pass an object containing new 'ts' and 'pts' to the callback
      callback.call(that, {
        ts: parsed_response.response.ts,
        pts: parsed_response.response.pts,
      });
    });
  }

  class VkBotAPI {

    /**
     * The VkBotAPI class constructor
     * @param {String} token      VK API access token
     * @param {String} bot_prefix Bot name, i.e. a prefix. Messages starting with this prefix would be processed.
     */
    constructor(token, bot_prefix, router) {
      if (typeof token === 'undefined') throw new Error('No access token specified.');
      this.token = token;
      this.bot_prefix = bot_prefix;
      this.commands = {};
      if (typeof router === 'undefined'){
        this.router = this.route;
      } else {
        this.router = router;
      }
    }

    /**
     * Adds a new bot command for the default routing method
     * @param  {String}   command_name A name of the command
     * @param  {String}   usage        A brief description
     * @param  {Function} callback     A callback that would be invoked upon routing the command.
     * @return {undefined}
     */
    addBotCommand(command_name, usage, callback) {
      if (typeof command_name === 'string' && typeof callback === 'function')
        this.commands[command_name] = new BotCommand(usage, callback);
      else throw new Error('Invalid parameters for addBotCommand(name, desc, callback)');
    }

    /**
     * Initiates bot listen sequence.
     * @return {undefined}
     */
    listen() {
      // get latest 'ts' and 'pts' via messages.getLongPollServer
      renewLongPollData(this.token, this.startParsing, this);
    }

    /**
     * This method is used as a callback for renewLongPollData(token, callback, that).
     * @param  {Object} longpollparams An Object containing 'ts' and 'pts' values
     * @return {undefined}
     */
    startParsing(longpollparams) {
      // initiate the parsing routine
      parseMessages(this.token, this.bot_prefix, this.router,
        (this.router === this.route) ? this : null, longpollparams);
    }

    /**
     * The default router.
     * Implies that the second word in a captured message is a bot command and routes it to
     * a registered via addBotCommand(command_name, usage, callback) callback function.
     * @param {Object} incmessage The VK API message object
     * @return {undefined}
     */
    route(incmessage) {
      var origin = (incmessage.hasOwnProperty('chat_id')) ? incmessage.chat_id : incmessage.user_id,
          message_origin = incmessage.user_id;
      var isChat = (incmessage.hasOwnProperty('chat_id')) ? true : false;
      var args = incmessage.body.split(' ');
      var name = args[1];
      args.splice(0,2);
      if (typeof this.commands[name] === 'undefined') // if we don't have a route for the command
        return console.warn('No available route for \'' + name + '\', skipping.'); // WHY BOTHER, SEE YA
      try {
        // we expect some errors from the user callback but we don't want them to crash the whole app
        var sendBack = this.commands[name].callback.call(null, message_origin, args, (isChat) ? origin : null);
        console.log('Routing ' + name + '...');
      } catch (err) {
        // now we can just not send anything at all
        return console.warn('An error occured in the \'' + name + '\' command callback function. \n' + err);
      }
      if (!(typeof sendBack === 'undefined')){
        request('https://api.vk.com/method/messages.send?' + querystring.stringify({
          message: sendBack,
          peer_id: (isChat) ? Number(origin) + 2000000000 : origin,
          forward_messages: incmessage.id,
          v: '5.53',
          access_token: this.token}),
        (err, resp, body) => {
            if (err) // handle connection errors
              throw new Error('Couldn\'t fetch a response from VK API. Aborting.');
              var parsed_response = JSON.parse(body);
              if (parsed_response.hasOwnProperty('error')) // handle VK API errors
                return console.warn('VK API returned an error while trying to send a message. Error:\n' +
                  parsed_response.error.error_code + ": " + parsed_response.error.error_msg);
              console.log('Message sent in a response. Message ID is: ' + parsed_response.response);
        });
      }
    }

  }

  // export the class
  return VkBotAPI;

})();

module.exports = vkbot;


text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0"
         xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0.1">
  <service name="ncdods" serviceType="DODS" base="/thredds/dodsC/"/>
  <dataset name="dmsp" ID="testData/dmsp">
    <metadata inherited="true">
      <serviceName>ncdods</serviceName>
    </metadata>
    <datasetScan name="headerOnly.OIS" ID="testData/dmsp/headerOnly.OIS"
                 path="" location="" >
      <filter logicalComp="OR">
        <!-- Only grib1 files that are older than 60 seconds -->
        <filter logicalComp="AND">
          <filter>
            <include wildcard="*.grib1"/>
          </filter>
          <filter lastModifiedLimit="60000"  />
        </filter>
        <!-- Only nc files that are less then 60 seconds old -->
        <filter logicalComp="AND">
          <filter>
            <include wildcard="*.nc"/>
          </filter>
          <filter logicalComp="NOT">
            <filter lastModifiedLimit="60000"/>
          </filter>
        </filter>
      </filter>
    </datasetScan>
  </dataset>
</catalog>

redpajama_set_name: RedPajamaGithub


text:
import { aTimeout, expect, fixture, html, oneEvent, waitUntil } from '@open-wc/testing';
import { sendKeys } from '@web/test-runner-commands';
import sinon from 'sinon';
import type SlCheckbox from './checkbox';

describe('<sl-checkbox>', () => {
  it('should be disabled with the disabled attribute', async () => {
    const el = await fixture<SlCheckbox>(html` <sl-checkbox disabled></sl-checkbox> `);
    const checkbox = el.shadowRoot!.querySelector('input')!;

    expect(checkbox.disabled).to.be.true;
  });

  it('should be valid by default', async () => {
    const el = await fixture<SlCheckbox>(html` <sl-checkbox></sl-checkbox> `);

    expect(el.invalid).to.be.false;
  });

  it('should fire sl-change when clicked', async () => {
    const el = await fixture<SlCheckbox>(html` <sl-checkbox></sl-checkbox> `);
    setTimeout(() => el.shadowRoot!.querySelector('input')!.click());
    const event = await oneEvent(el, 'sl-change');
    expect(event.target).to.equal(el);
    expect(el.checked).to.be.true;
  });

  it('should fire sl-change when toggled via keyboard', async () => {
    const el = await fixture<SlCheckbox>(html` <sl-checkbox></sl-checkbox> `);
    const input = el.shadowRoot!.querySelector('input')!;
    input.focus();
    setTimeout(() => sendKeys({ press: ' ' }));
    const event = await oneEvent(el, 'sl-change');
    expect(event.target).to.equal(el);
    expect(el.checked).to.be.true;
  });

  it('should not fire sl-change when checked is set by javascript', async () => {
    const el = await fixture<SlCheckbox>(html` <sl-checkbox></sl-checkbox> `);
    el.addEventListener('sl-change', () => expect.fail('event fired'));
    el.checked = true;
    await el.updateComplete;
    el.checked = false;
    await el.updateComplete;
  });

  describe('when submitting a form', () => {
    it('should submit the correct value', async () => {
      const form = await fixture<HTMLFormElement>(html`
        <form>
          <sl-checkbox name="a" value="1" checked></sl-checkbox>
          <sl-button type="submit">Submit</sl-button>
        </form>
      `);
      const button = form.querySelector('sl-button')!;
      const submitHandler = sinon.spy((event: SubmitEvent) => {
        formData = new FormData(form);
        event.preventDefault();
      });
      let formData: FormData;

      form.addEventListener('submit', submitHandler);
      button.click();

      await waitUntil(() => submitHandler.calledOnce);

      expect(formData!.get('a')).to.equal('1');
    });

    it('should show a constraint validation error when setCustomValidity() is called', async () => {
      const form = await fixture<HTMLFormElement>(html`
        <form>
          <sl-checkbox name="a" value="1" checked></sl-checkbox>
          <sl-button type="submit">Submit</sl-button>
        </form>
      `);
      const button = form.querySelector('sl-button')!;
      const checkbox = form.querySelector('sl-checkbox')!;
      const submitHandler = sinon.spy((event: SubmitEvent) => event.preventDefault());

      // Submitting the form after setting custom validity should not trigger the handler
      checkbox.setCustomValidity('Invalid selection');
      form.addEventListener('submit', submitHandler);
      button.click();

      await aTimeout(100);

      expect(submitHandler).to.not.have.been.called;
    });
  });
});


text:
using System;

namespace Avalonia.Controls
{
    /// <summary>
    /// Represents resource provider in a tree.
    /// </summary>
    public interface IResourceNode : IResourceProvider
    {
        /// <summary>
        /// Gets the parent resource node, if any.
        /// </summary>
        IResourceNode ResourceParent { get; }
    }
}


text:
GitHub random
=============

My random project


text:
var express = require("express"),
    socket = require("socket.io");

var app = express.createServer(),
    io = socket.listen( app );

// Express app Configuration
app.configure(function() {
  // Uses Express defaults
  app.set( "views", __dirname + "/views" );
  app.set( "view engine", "jade" );
  app.use( express.bodyParser() );
  app.use( express.methodOverride() );
  app.use( app.router );
  app.use( express.static(__dirname + "/public") );
});

// Routes
app.get( "/", function( req, res ) {
  res.render( "index", {
    title: "Platoon"
  });
});

// Connection Pool
var connections = {
  // uid: object
};

io.set( "log level", 1 );
// When socket is connected, initialize new unit in platoon,
// begin relay of WebRTC captures
io.sockets.on( "connection", function( client ) {

  // Receive "join" events for new units,
  // dispatch "joined" with any instructions
  client.on( "join", function( data ) {
    // Contains a connection uid to add to the pool
    // console.log( data );

    connections[ data.id ] = true;

    // Emit "joined" notice to all other connections,
    // Will create new unit and output canvas
    io.sockets.emit( "joined", data );
  });

  client.on( "stream", function( data ) {
    io.sockets.emit( "stream", data );
  });
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);


text:
import Ember from "ember";
import moment from "moment";

export default Ember.Route.extend({
  model() {
    const disabledDates = [],
      todayDate = new Date(),
      tommorrowDate = new Date(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate() +1),
      nextWeekDate = new Date(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate() +7),
      yesterdayDate = new Date(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate() - 1),
      newYorkDate = moment.tz('America/New_York').toDate(),
      berlinDate = moment.tz('Europe/Berlin').toDate(),
      moscowDate = moment.tz('Europe/Moscow').toDate();

    const datesList = Ember.A([new Date(), new Date()]);
    disabledDates.push(tommorrowDate);

    return {
      newYorkDate,
      berlinDate,
      yesterdayDate,
      nextWeekDate,
      moscowDate,
      disabledDates,
      todayDate,
      minDate: moment().subtract(2, 'days').startOf('day').toDate(),
      maxDate: moment().add(2, 'days').startOf('day').toDate(),
      datesList
    };
  }
});


text:
curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl
chmod +x ./kubectl
sudo mv ./kubectl /usr/local/bin/kubectl


text:
struct Matrices
{
	Matrices(): mModel(1), mNormal(1)
	{

	}
	glm::mat4 mModel;
	glm::mat4 mNormal;
};
class Transform
{
public:
	Transform() :mPosition(0), mAngle(0), mScale(1) {}
	~Transform() {}
	Matrices const & getMatrices();
	glm::mat4 const & getModelMatrix();
	glm::mat4 const & getNormalMatrix();
	glm::vec3 const & getPosition();
	glm::vec3 const & getEulerAngle();
	glm::vec3 const & getScale();
	void setPosition(glm::vec3 const & p);
	void addPosition(glm::vec3 const & p);
	void setPosition(float x, float y, float z);
	void addPosition(float x, float y, float z);
	void setAngle(glm::vec3 const & ang);
	void setAngle(float x, float y, float z);
	void addAngle(glm::vec3 const & ang);
	void setScale(glm::vec3 const & scale);
	void setScale(float x, float y, float z);
	void addScale(glm::vec3 const & scale);
	void CacNewTransform();
	glm::vec3 mPosition;
	glm::vec3 mAngle;
	glm::vec3 mScale;
	Matrices mMatrices;
};


text:
PDO PgSQL pgsqlCopyToArray and pgsqlCopyToFile
--SKIPIF--
<?php # vim:se ft=php:
if (!extension_loaded('pdo') || !extension_loaded('pdo_pgsql')) die('skip not loaded');
require dirname(__FILE__) . '/config.inc';
require dirname(__FILE__) . '/../../../ext/pdo/tests/pdo_test.inc';
PDOTest::skip();
?>
--FILE--
<?php
require dirname(__FILE__) . '/../../../ext/pdo/tests/pdo_test.inc';
$db = PDOTest::test_factory(dirname(__FILE__) . '/common.phpt');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);

$db->exec('CREATE TABLE test (a integer not null primary key, b text, c integer)');

$db->beginTransaction();

echo "Preparing test table for CopyTo tests\n";
$stmt = $db->prepare("INSERT INTO test (a, b, c) values (?, ?, ?)");

for($i=0;$i<3;$i++) {
	$firstParameter = $i;
	$secondParameter = "test insert {$i}";
	$thirdParameter = NULL;
	$stmt->bindValue(1, $firstParameter);
	$stmt->bindValue(2, $secondParameter);
	$stmt->bindValue(3, $thirdParameter);
	$stmt->execute();
}

$db->commit();

echo "Testing pgsqlCopyToArray() with default parameters\n";
var_dump($db->pgsqlCopyToArray('test'));
echo "Testing pgsqlCopyToArray() with different field separator and not null indicator\n";
var_dump($db->pgsqlCopyToArray('test',";","NULL"));
echo "Testing pgsqlCopyToArray() with only selected fields\n";
var_dump($db->pgsqlCopyToArray('test',";","NULL",'a,c'));

echo "Testing pgsqlCopyToArray() with error\n";
try {
	var_dump($db->pgsqlCopyToArray('test_error'));
} catch (Exception $e) {
	echo "Exception: {$e->getMessage()}\n";
}

echo "Testing pgsqlCopyToFile() with default parameters\n";

$filename="test_pgsqlCopyToFile.csv";
var_dump($db->pgsqlCopyToFile('test',$filename));
echo file_get_contents($filename);
echo "Testing pgsqlCopyToFile() with different field separator and not null indicator\n";
var_dump($db->pgsqlCopyToFile('test',$filename,";","NULL"));
echo file_get_contents($filename);
echo "Testing pgsqlCopyToFile() with only selected fields\n";
var_dump($db->pgsqlCopyToFile('test',$filename,";","NULL",'a,c'));
echo file_get_contents($filename);

echo "Testing pgsqlCopyToFile() with error\n";
try {
	var_dump($db->pgsqlCopyToFile('test_error',$filename));
} catch (Exception $e) {
	echo "Exception: {$e->getMessage()}\n";
}

echo "Testing pgsqlCopyToFile() to unwritable file\n";
try {
	var_dump($db->pgsqlCopyToFile('test', 'nonexistent/foo.csv'));
} catch (Exception $e) {
	echo "Exception: {$e->getMessage()}\n";
}

if(isset($filename)) {
	@unlink($filename);
}
?>
--EXPECT--
Preparing test table for CopyTo tests
Testing pgsqlCopyToArray() with default parameters
array(3) {
  [0]=>
  string(19) "0	test insert 0	\N
"
  [1]=>
  string(19) "1	test insert 1	\N
"
  [2]=>
  string(19) "2	test insert 2	\N
"
}
Testing pgsqlCopyToArray() with different field separator and not null indicator
array(3) {
  [0]=>
  string(21) "0;test insert 0;NULL
"
  [1]=>
  string(21) "1;test insert 1;NULL
"
  [2]=>
  string(21) "2;test insert 2;NULL
"
}
Testing pgsqlCopyToArray() with only selected fields
array(3) {
  [0]=>
  string(7) "0;NULL
"
  [1]=>
  string(7) "1;NULL
"
  [2]=>
  string(7) "2;NULL
"
}
Testing pgsqlCopyToArray() with error
Exception: SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "test_error" does not exist
Testing pgsqlCopyToFile() with default parameters
bool(true)
0	test insert 0	\N
1	test insert 1	\N
2	test insert 2	\N
Testing pgsqlCopyToFile() with different field separator and not null indicator
bool(true)
0;test insert 0;NULL
1;test insert 1;NULL
2;test insert 2;NULL
Testing pgsqlCopyToFile() with only selected fields
bool(true)
0;NULL
1;NULL
2;NULL
Testing pgsqlCopyToFile() with error
Exception: SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "test_error" does not exist
Testing pgsqlCopyToFile() to unwritable file
Exception: SQLSTATE[HY000]: General error: 7 Unable to open the file for writing


text:
package req

import "github.com/doubledutch/dd-vote/api/models/table"

// UserRequest is sent by the client when logging in
type UserRequest struct {
	Firstname string `json:"firstName" binding:"required"`
	Lastname  string `json:"lastName" binding:"required"`
	ClientID  uint   `json:"userId" binding:"required"`
}

// AdminLoginRequest is sent by the client when logging in as an admin
type AdminLoginRequest struct {
	Email     string `json:"email" binding:"required"`
	Password  string `json:"password" binding:"required"`
	GroupUUID string `json:"groupId" binding:"required"`
}

// IsValid returns whether the request has valid data
func (req *UserRequest) IsValid() bool {
	return len(req.Firstname) > 0 && len(req.Lastname) > 0
}

// ToUser converts a UserRequest object to User
func (req *UserRequest) ToUser() table.User {
	var user table.User
	user.ClientID = req.ClientID
	user.Firstname = req.Firstname
	user.Lastname = req.Lastname
	return user
}

// ToUser converts an AdminLoginRequest object to User
func (req *AdminLoginRequest) ToUser() table.User {
	var user table.User
	user.Email = req.Email
	user.Password = req.Password
	return user
}


text: My Personal portfolio


text:
require_relative 'rank'

module Poker
  module Ranks
    class HighCard < Rank
      def matches?
        true
      end
    end
  end
end


text:
namespace grndr { namespace ogl {

struct Texture2D {

  GLuint id = 0;

  static GLuint current_id;

  static void gen_textures(GLsizei n, GLuint* textures);
  static void delete_textures(GLsizei n, const GLuint* textures);
  static void bind_zero();

  void create();
  void destroy();

  void bind();

  void tex_parameteri(GLenum pname, GLint param);

  void upload_rgb8(int width, int height, const unsigned char* image);
  void upload_rgba8(int width, int height, const unsigned char* image);

};

}} // namespace grndr::ogl


text:
import { Namespace as NS } from 'xmpp-constants';

export default function (JXT) {

    let Utils = JXT.utils;

    let SMFeature = JXT.define({
        name: 'streamManagement',
        namespace: NS.SMACKS_3,
        element: 'sm'
    });

    JXT.define({
        name: 'smEnable',
        eventName: 'stream:management:enable',
        namespace: NS.SMACKS_3,
        element: 'enable',
        topLevel: true,
        fields: {
            resume: Utils.boolAttribute('resume')
        }
    });

    JXT.define({
        name: 'smEnabled',
        eventName: 'stream:management:enabled',
        namespace: NS.SMACKS_3,
        element: 'enabled',
        topLevel: true,
        fields: {
            id: Utils.attribute('id'),
            resume: Utils.boolAttribute('resume')
        }
    });

    JXT.define({
        name: 'smResume',
        eventName: 'stream:management:resume',
        namespace: NS.SMACKS_3,
        element: 'resume',
        topLevel: true,
        fields: {
            h: Utils.numberAttribute('h', false, 0),
            previd: Utils.attribute('previd')
        }
    });

    JXT.define({
        name: 'smResumed',
        eventName: 'stream:management:resumed',
        namespace: NS.SMACKS_3,
        element: 'resumed',
        topLevel: true,
        fields: {
            h: Utils.numberAttribute('h', false, 0),
            previd: Utils.attribute('previd')
        }
    });

    JXT.define({
        name: 'smFailed',
        eventName: 'stream:management:failed',
        namespace: NS.SMACKS_3,
        element: 'failed',
        topLevel: true
    });

    JXT.define({
        name: 'smAck',
        eventName: 'stream:management:ack',
        namespace: NS.SMACKS_3,
        element: 'a',
        topLevel: true,
        fields: {
            h: Utils.numberAttribute('h', false, 0)
        }
    });

    JXT.define({
        name: 'smRequest',
        eventName: 'stream:management:request',
        namespace: NS.SMACKS_3,
        element: 'r',
        topLevel: true
    });

    JXT.extendStreamFeatures(SMFeature);
}


text:
package org.wildfly.camel.examples.jms.transacted;

import java.io.InputStream;
import java.util.Random;

import org.apache.camel.CamelContext;

public class OrderGenerator {

    private int count = 1;
    private Random random = new Random();

    public InputStream generateOrder(CamelContext camelContext) {
        String name = String.format("/orders/order-%d.xml", random.nextInt(5) + 1);

        return camelContext.getClassResolver().loadResourceAsStream(name);
    }

    public String generateFileName() {
        return "order" + count++ + ".xml";
    }

}


text:
<?php

namespace Magento\Weee\Model\Total\Quote;

use Magento\Tax\Model\Calculation;

class WeeeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Pricing\PriceCurrencyInterface
     */
    protected $priceCurrency;

    /**
     * Setup tax helper with an array of methodName, returnValue
     *
     * @param array $taxConfig
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Helper\Data
     */
    protected function setupTaxHelper($taxConfig)
    {
        $taxHelper = $this->getMock('Magento\Tax\Helper\Data', [], [], '', false);

        foreach ($taxConfig as $method => $value) {
            $taxHelper->expects($this->any())->method($method)->will($this->returnValue($value));
        }

        return $taxHelper;
    }

    /**
     * Setup calculator to return tax rates
     *
     * @param array $taxRates
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Tax\Model\Calculation
     */
    protected function setupTaxCalculation($taxRates)
    {
        $storeTaxRate = $taxRates['store_tax_rate'];
        $customerTaxRate = $taxRates['customer_tax_rate'];

        $taxCalculation = $this->getMock('Magento\Tax\Model\Calculation', [], [], '', false);

        $rateRequest = new \Magento\Framework\Object();
        $defaultRateRequest = new \Magento\Framework\Object();

        $taxCalculation->expects($this->any())->method('getRateRequest')->will($this->returnValue($rateRequest));
        $taxCalculation
            ->expects($this->any())
            ->method('getRateOriginRequest')
            ->will($this->returnValue($defaultRateRequest));

        $taxCalculation
            ->expects($this->any())
            ->method('getRate')
            ->will($this->onConsecutiveCalls($storeTaxRate, $customerTaxRate));

        return $taxCalculation;
    }

    /**
     * Setup weee helper with an array of methodName, returnValue
     *
     * @param array $weeeConfig
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Weee\Helper\Data
     */
    protected function setupWeeeHelper($weeeConfig)
    {
        $weeeHelper = $this->getMock('Magento\Weee\Helper\Data', [], [], '', false);

        foreach ($weeeConfig as $method => $value) {
            $weeeHelper->expects($this->any())->method($method)->will($this->returnValue($value));
        }

        return $weeeHelper;
    }

    /**
     * Setup an item mock
     *
     * @param float $itemQty
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Quote\Item
     */
    protected function setupItemMock($itemQty)
    {
        $itemMock = $this->getMock(
            'Magento\Sales\Model\Quote\Item',
            [
                'getProduct',
                'getQuote',
                'getAddress',
                'getTotalQty',
                '__wakeup',
            ],
            [],
            '',
            false
        );

        $productMock = $this->getMock('Magento\Catalog\Model\Product', [], [], '', false);
        $itemMock->expects($this->any())->method('getProduct')->will($this->returnValue($productMock));
        $itemMock->expects($this->any())->method('getTotalQty')->will($this->returnValue($itemQty));

        return $itemMock;
    }

    /**
     * Setup address mock
     *
     * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Quote\Item $itemMock
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function setupAddressMock($itemMock)
    {
        $addressMock = $this->getMock(
            'Magento\Sales\Model\Quote\Address',
            [
                '__wakeup',
                'getAllNonNominalItems',
                'getQuote',
            ],
            [],
            '',
            false
        );

        $quoteMock = $this->getMock('Magento\Sales\Model\Quote', [], [], '', false);
        $storeMock = $this->getMock('Magento\Store\Model\Store', [], [], '', false);
        $this->priceCurrency = $this->getMockBuilder('Magento\Framework\Pricing\PriceCurrencyInterface')->getMock();
        $this->priceCurrency->expects($this->any())->method('round')->willReturnArgument(0);
        $this->priceCurrency->expects($this->any())->method('convert')->willReturnArgument(0);
        $quoteMock->expects($this->any())->method('getStore')->will($this->returnValue($storeMock));

        $addressMock->expects($this->any())->method('getAllNonNominalItems')->will($this->returnValue([$itemMock]));
        $addressMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));

        return $addressMock;
    }

    /**
     * Verify that correct fields of item has been set
     *
     * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Quote\Item $item
     * @param $itemData
     */
    public function verifyItem(\Magento\Sales\Model\Quote\Item $item, $itemData)
    {
        foreach ($itemData as $key => $value) {
            $this->assertEquals($value, $item->getData($key), 'item ' . $key . ' is incorrect');
        }
    }

    /**
     * Verify that correct fields of address has been set
     *
     * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Model\Quote\Address $address
     * @param $addressData
     */
    public function verifyAddress(\Magento\Sales\Model\Quote\Address $address, $addressData)
    {
        foreach ($addressData as $key => $value) {
            $this->assertEquals($value, $address->getData($key), 'address ' . $key . ' is incorrect');
        }
    }

    /**
     * Test the collect function of the weee collector
     *
     * @param array $taxConfig
     * @param array $weeeConfig
     * @param array $taxRates
     * @param array $itemData
     * @param float $itemQty
     * @param array $addressData
     * @dataProvider collectDataProvider
     */
    public function testCollect($taxConfig, $weeeConfig, $taxRates, $itemData, $itemQty, $addressData = [])
    {
        $itemMock = $this->setupItemMock($itemQty);
        $addressMock = $this->setupAddressMock($itemMock);

        $taxHelper = $this->setupTaxHelper($taxConfig);
        $weeeHelper = $this->setupWeeeHelper($weeeConfig);
        $calculator = $this->setupTaxCalculation($taxRates);

        $arguments = [
            'taxData' => $taxHelper,
            'calculation' => $calculator,
            'weeeData' => $weeeHelper,
            'priceCurrency' => $this->priceCurrency,
        ];

        $helper = new \Magento\TestFramework\Helper\ObjectManager($this);
        $this->weeeCollector = $helper->getObject('Magento\Weee\Model\Total\Quote\Weee', $arguments);

        $this->weeeCollector->collect($addressMock);

        $this->verifyItem($itemMock, $itemData);
        $this->verifyAddress($addressMock, $addressData);
    }

    /**
     * Data provider for testCollect
     *
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     * Multiple datasets
     *
     * @return array
     */
    public function collectDataProvider()
    {
        $data = [];

        // 1. This collector does not compute tax.  Instead it sets up various fields for the tax calculation
        // 2. When the Weee is not taxable, this collector will change the address data as follows:
        //     accumulate the totals into 'weee_total_excl_tax' and 'weee_base_total_excl_tax'

        $data['price_incl_tax_weee_taxable_unit_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => true,
                'getCalculationAgorithm' => Calculation::CALC_UNIT_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => true,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
            ],
        ];

        $data['price_incl_tax_weee_taxable_unit_not_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => true,
                'getCalculationAgorithm' => Calculation::CALC_UNIT_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => false,
                'isTaxable' => true,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
            ],
        ];

        $data['price_excl_tax_weee_taxable_unit_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => false,
                'getCalculationAgorithm' => Calculation::CALC_UNIT_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => true,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
            ],
        ];

        $data['price_incl_tax_weee_non_taxable_unit_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => true,
                'getCalculationAgorithm' => Calculation::CALC_UNIT_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => false,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
                'weee_total_excl_tax' => 20,
                'weee_base_total_excl_tax' => 20,
            ],
        ];

        $data['price_excl_tax_weee_non_taxable_unit_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => false,
                'getCalculationAgorithm' => Calculation::CALC_UNIT_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => false,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
                'weee_total_excl_tax' => 20,
                'weee_base_total_excl_tax' => 20,
            ],
        ];

        $data['price_incl_tax_weee_taxable_row_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => true,
                'getCalculationAgorithm' => Calculation::CALC_ROW_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => true,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
            ],
        ];

        $data['price_excl_tax_weee_taxable_row_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => false,
                'getCalculationAgorithm' => Calculation::CALC_ROW_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => true,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
            ],
        ];

        $data['price_incl_tax_weee_non_taxable_row_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => true,
                'getCalculationAgorithm' => Calculation::CALC_ROW_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => false,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
                'weee_total_excl_tax' => 20,
                'weee_base_total_excl_tax' => 20,
            ],
        ];

        $data['price_excl_tax_weee_non_taxable_row_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => false,
                'getCalculationAgorithm' => Calculation::CALC_ROW_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => true,
                'isTaxable' => false,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
                'weee_total_excl_tax' => 20,
                'weee_base_total_excl_tax' => 20,
            ],
        ];

        $data['price_excl_tax_weee_non_taxable_row_not_included_in_subtotal'] = [
            'tax_config' => [
                'priceIncludesTax' => false,
                'getCalculationAgorithm' => Calculation::CALC_ROW_BASE,
            ],
            'weee_config' => [
                'isEnabled' => true,
                'includeInSubtotal' => false,
                'isTaxable' => false,
                'getApplied' => [],
                'getProductWeeeAttributes' => [
                    new \Magento\Framework\Object(
                        [
                            'name' => 'Recycling Fee',
                            'amount' => 10,
                        ]
                    ),
                ],
            ],
            'tax_rates' => [
                'store_tax_rate' => 8.25,
                'customer_tax_rate' => 8.25,
            ],
            'item' => [
                'weee_tax_applied_amount' => 10,
                'base_weee_tax_applied_amount' => 10,
                'weee_tax_applied_row_amount' => 20,
                'base_weee_tax_applied_row_amnt' => 20,
                'weee_tax_applied_amount_incl_tax' => 10,
                'base_weee_tax_applied_amount_incl_tax' => 10,
                'weee_tax_applied_row_amount_incl_tax' => 20,
                'base_weee_tax_applied_row_amnt_incl_tax' => 20,
            ],
            'item_qty' => 2,
            'address_data' => [
                'subtotal_incl_tax' => 20,
                'base_subtotal_incl_tax' => 20,
                'weee_total_excl_tax' => 20,
                'weee_base_total_excl_tax' => 20,
            ],
        ];

        return $data;
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="description" content="Blunt Talk">
    <meta property="og:url" content="https://www.starz.com/sc/features/blunttalk/facebook/generic/index.html">
    <meta property="og:title" content="Blunt Talk">
    <meta property="og:description" content="Exclusive content from Blunt Talk, premiering on STARZ August 22 at 9PM ET/PT.">
    <meta property="og:image" content="https://www.starz.com/sc/features/blunttalk/facebook/generic/img/111x7f.jpg">
    <title>Blunt Talk</title>
    <link href="css/main.css" rel="stylesheet" type="text/css">

About

Cast

Inside Look

Social

@@include('parts/about.html')

@@include('parts/cast.html')

@@include('parts/insidelook.html')

@@include('parts/social.html')

STARZ and related channels and services marks are the property of Starz Entertainment, LLC. Blunt Talk © 2015 MRC II Distribution Company, LP. All rights reserved.


text:
from multiprocessing import Process
import time
import htcondor
import redis
import json
import config
import logging

def setup_redis_connection():
    r = redis.StrictRedis(host=config.redis_host, port=config.redis_port, db=config.redis_db, password=config.redis_password)
    return r

def resources_producer(testrun=False, testfile=None):
    resource_attributes = ["Name", "Machine", "JobId", "GlobalJobId", "MyAddress", "State", "Activity", "VMType", "MycurrentTime", "EnteredCurrentState", "Start", "RemoteOwner", "SlotType", "TotalSlots"]

    sleep_interval = config.machine_collection_interval
    collector_data_key = config.collector_data_key
    while(True):
        try:
            condor_resource_dict_list = []
            if not testrun:
                condor_c = htcondor.Collector()
                any_ad = htcondor.AdTypes.Any
                condor_resources = condor_c.query(ad_type=any_ad, constraint=True, projection=resource_attributes)
                for resource in condor_resources:
                    r_dict = dict(resource)
                    if "Start" in r_dict:
                        r_dict["Start"] = str(r_dict["Start"])
                    condor_resource_dict_list.append(r_dict)
                #logging.debug(condor_resource_dict_list)

            #For Unit Testing only:
            else:
                res_file = open(testfile, 'r')
                condor_string = res_file.read()[0:-1] #strip newline
                condor_resources = json.loads(condor_string)
                for resource in condor_resources:
                    r_dict = dict(resource)
                    if "Start" in r_dict:
                        r_dict["Start"] = str(r_dict["Start"])
                    condor_resource_dict_list.append(r_dict)

            condor_resources = json.dumps(condor_resource_dict_list)

            redis_con = setup_redis_connection()
            logging.error("Setting condor-resources in redis...")
            redis_con.set(collector_data_key, condor_resources)
            if(testrun):
                return True
            time.sleep(sleep_interval)

        except Exception as e:
            logging.error(e)
            logging.error("Error connecting to condor or redis...")
            if(testrun):
                return False
            time.sleep(sleep_interval)

        except(SystemExit, KeyboardInterrupt):
            return False

def collector_command_consumer(testrun=False):
    collector_commands_key = config.collector_commands_key
    sleep_interval = config.command_sleep_interval

    while(True):
        try:
            redis_con = setup_redis_connection()
            command_string = redis_con.lpop(collector_commands_key)

            if command_string is not None:
                command_dict = json.loads(command_string)
                #execute command
                # use htcondor class's send_command function to send condor_off -peaceful to Startd and Master
                # order matters here, we need to issue the command to Startd first then Master
                # We will need the class ad for the machine found by using ad = Collector.locate(...)
                # then do htcondor.send_command(ad=ad, dc=htcondor.DaemonCommands.DaemonsOffPeaceful, target="-daemon Startd")
                #  htcondor.send_command(ad=ad, dc=htcondor.DaemonCommands.DaemonsOffPeaceful, target="-daemon Master")
                # may not need the target

                #need to get machine identifier out of command
                machine_name = command_dict['machine_name'].encode('ascii','ignore')
                command = command_dict['command']
                if command == "condor_off":
                    condor_c = htcondor.Collector()
                    logging.info("getting machine ads for %s" % machine_name)
                    startd_ad = condor_c.locate(htcondor.DaemonTypes.Startd, machine_name)
                    logging.info("found startd.. locating master")
                    master_machine_name = machine_name.split("@")[1]
                    master_ad = condor_c.locate(htcondor.DaemonTypes.Master, master_machine_name)

                    logging.info("Ads found, issuing condor_off commands...")
                    htcondor.send_command(startd_ad, htcondor.DaemonCommands.SetPeacefulShutdown)
                    htcondor.send_command(master_ad, htcondor.DaemonCommands.SetPeacefulShutdown)
                    if(testrun):
                        return True

                else:
                    logging.error("Unrecognized command")
                    if(testrun):
                        return False

            else:
                logging.info("No command in redis list, begining sleep interval...")
                #only sleep if there was no command
                if(testrun):
                    return False
                time.sleep(sleep_interval)

        except Exception as e:
            logging.error("Failure connecting to redis or executing condor command...")
            logging.error(e)
            if(testrun):
                return False
            time.sleep(sleep_interval)

        except(SystemExit, KeyboardInterrupt):
            return False

if __name__ == '__main__':

    logging.basicConfig(filename=config.collector_log_file,level=logging.DEBUG)
    processes = []

    p_resource_producer = Process(target=resources_producer)
    p_command_consumer = Process(target=collector_command_consumer)
    processes.append(p_resource_producer)
    processes.append(p_command_consumer)

    # Wait for keyboard input to exit
    try:
        for process in processes:
            process.start()
        while(True):
            for process in processes:
                if not process.is_alive():
                    logging.error("%s process died!" % process.name)
                    logging.error("Restarting %s process...")
                    process.start()
                time.sleep(1)
            time.sleep(10)
    except (SystemExit, KeyboardInterrupt):
        logging.error("Caught KeyboardInterrupt, shutting down threads and exiting...")

    for process in processes:
        try:
            process.join()
        except:
            logging.error("failed to join process %s" % process.name)


text:
    1
    21  package org.apache.struts.chain.commands.servlet;
    22
    23  import junit.framework.TestCase;
    24
    25  import org.apache.struts.Globals;
    26  import org.apache.struts.chain.contexts.ServletActionContext;
    27  import org.apache.struts.mock.MockActionServlet;
    28  import org.apache.struts.mock.MockHttpServletRequest;
    29  import org.apache.struts.mock.MockHttpServletResponse;
    30  import org.apache.struts.mock.MockServletConfig;
    31  import org.apache.struts.mock.MockServletContext;
    32
    33  /* JUnitTest case for class: org.apache.struts.chain.commands.servlet.SetOriginalURI */
    34  public class TestSetOriginalURI extends TestCase {
    35      SetOriginalURI command = null;
    36
    37      public TestSetOriginalURI(String _name) {
    38          super(_name);
    39      }
    40
    41      /* setUp method for test case */
    42      protected void setUp() throws Exception {
    43          this.command = new SetOriginalURI();
    44      }
    45
    46      /* tearDown method for test case */
    47      protected void tearDown() {
    48      }
    49
    50      public void testSetOriginalURI()
    51          throws Exception {
    52          MockHttpServletRequest request =
    53              new MockHttpServletRequest("foo/", "bar.do", null, null);
    54          MockServletConfig servletConfig = new MockServletConfig();
    55          MockServletContext servletContext = new MockServletContext();
    56          MockActionServlet servlet =
    57              new MockActionServlet(servletContext, servletConfig);
    58
    59          servlet.initInternal();
    60
    61          ServletActionContext saContext =
    62              new ServletActionContext(servletContext, request,
    63                  new MockHttpServletResponse());
    64
    65          saContext.setActionServlet(servlet);
    66
    67          boolean result = command.execute(saContext);
    68
    69          assertTrue(!result);
    70
    71          String uri = (String) request.getAttribute(Globals.ORIGINAL_URI_KEY);
    72
    73          assertTrue("Original uri not correct: " + uri, "bar.do".equals(uri));
    74
    75          request.setPathElements("foo/", "bar2.do", null, null);
    76          uri = (String) request.getAttribute(Globals.ORIGINAL_URI_KEY);
    77          assertTrue("Original uri not correct: " + uri, "bar.do".equals(uri));
    78      }
    79
    80      /* Executes the test case */
    81      public static void main(String[] argv) {
    82          String[] testCaseList = { TestSetOriginalURI.class.getName() };
    83
    84          junit.textui.TestRunner.main(testCaseList);
    85      }
    86  }

------------------------------------------------------------------------

This page was automatically generated by [Maven](http://maven.apache.org/)


text:
// Copyright (c) PocketCampus.Org 2014-15
// See LICENSE file for more details
// File author: Solal Pirelli

using System.Threading;
using System.Threading.Tasks;
using PocketCampus.Events.Models;
using ThriftSharp;

namespace PocketCampus.Events.Services
{
    /// <summary>
    /// The Events service.
    /// </summary>
    [ThriftService( "EventsService" )]
    public interface IEventsService
    {
        /// <summary>
        /// Asynchronously gets an event item.
        /// </summary>
        [ThriftMethod( "getEventItem" )]
        Task<EventItemResponse> GetEventItemAsync( [ThriftParameter( 1, "iRequest" )] EventItemRequest request, CancellationToken cancellationToken );

        /// <summary>
        /// Asynchronously gets an event pool.
        /// </summary>
        [ThriftMethod( "getEventPool" )]
        Task<EventPoolResponse> GetEventPoolAsync( [ThriftParameter( 1, "iRequest" )]EventPoolRequest request, CancellationToken cancellationToken );

        /// <summary>
        /// Asynchronously requests an e-mail with the items marked as favorite by the user.
        /// </summary>
        [ThriftMethod( "sendStarredItemsByEmail" )]
        Task<FavoriteEmailResponse> SendFavoriteItemsByEmailAsync( [ThriftParameter( 1, "iRequest" )] FavoriteEmailRequest request );
    }
}


text:
package org.apache.activemq.openwire.generator;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The main task that controls the OpenWire code generation routines.
 */
public class GeneratorTask extends Task {

    private static final Logger LOG = LoggerFactory.getLogger(GeneratorTask.class);

    private String baseDir = "./src/main/java";

    public static void main(String[] args) {

        Project project = new Project();
        project.init();

        GeneratorTask generator = new GeneratorTask();
        generator.setProject(project);

        try {
            if (args.length >= 1) {
                generator.setBaseDir(args[1]);
            }

            generator.execute();
        } catch (Exception e) {
            System.out.println("Error generating source:");
            e.printStackTrace();
        }
    }

    //----- Perform the generation by finding generators ---------------------//

    @Override
    public void execute() throws BuildException {

        LOG.info("===========================================================");
        LOG.info("Running OpenWire Generator");
        LOG.info("===========================================================");
        LOG.info("Base Diractory = {}", getBaseDir());

        try {
            List<OpenWireTypeDescriptor> descriptors = new ArrayList<OpenWireTypeDescriptor>();

            Set<Class<?>> openWireTypes = GeneratorUtils.findOpenWireTypes();
            for (Class<?> openWireType : openWireTypes) {
                LOG.info("Found OpenWire Type: {}", openWireType.getSimpleName());
                descriptors.add(new OpenWireTypeDescriptor(openWireType));
            }

            List<Generator> generators = getOpenWireGenerators();

            for (Generator generator : generators) {
                generator.setBaseDir(getBaseDir());

                generator.run(descriptors);
            }
        } catch (Exception ex) {
            throw new BuildException(ex);
        } finally {
            LOG.info("===========================================================");
        }
    }

    /**
     * Returns the active generators to run with.  Can be overridden by an extension.
     *
     * @return list of generators to use.
     */
    protected List<Generator> getOpenWireGenerators() {
        return Generators.BUILTIN;
    }

    /**
     * @return the baseDir
     */
    public String getBaseDir() {
        return baseDir;
    }

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


text:
module LocomotiveWeather
  VERSION = "0.0.2"
end


text:
Command-line options
====================

.. toctree::
   :maxdepth: 2

The SNMP Simulator suite consists of a handful of command-line tools that
take command-line options.

Common options
--------------

**--debug-snmp**
++++++++++++++++

The *--debug-snmp* option makes the daemon emitting detailed log of SNMP
protocol related debugging. Debugging can be enabled for all or for just
some of the SNMP engine subsystems by adding their names to the
*--debug-snmp* option.

Recognized SNMP debugging options include:

* *io* -- report raw network traffic
* *msgproc* -- report SNMP message processing
* *secmod* -- report SNMP security module operations
* *mibbuild* -- report on MIB loading and processing
* *mibinstrum* -- report agent MIB operatrions
* *acl* -- report MIB access access control operations
* *proxy* -- report on SNMP version translation operations
* *app* -- application-specific debugging
* *all* -- enable full SNMP debugging

SNMP debugging is fully disabled by default.

**--debug-asn1**
++++++++++++++++

SNMP is backed by the
`ASN.1 <https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One>`_
for data representation and serialization purposes. The *--debug-asn1* option
makes the tools emitting detailed log of ASN.1 data de/serialization. Debugging
can be enabled for either encoder or decoder, or for everything ASN.1 related
by adding their names to the *--debug-asn1* option.

Recognized ASN.1 debugging options include:

* *encoder* -- debug data serialization
* *decoder* -- debug data deserialization
* *all* -- enable full ASN.1 debugging

ASN.1 debugging is fully disabled by default.

**--logging-method**
++++++++++++++++++++

Some of the SNMP Simulator tools can log using one of the following methods.
The default is *stderr*.

**--logging-method=syslog**
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The *syslog* logging method requires the following sub-options:

.. code-block:: bash

    --logging-method=syslog:facility[:address[:port:[tcp|udp]]]]

Where:

* *facility* -- one of the recognized syslog service
  `facilities <https://en.wikipedia.org/wiki/Syslog#Facility>`_
* *address* -- can be either an absolute path to a local socket or network
  address where syslog service is listening (optional)
* *port* -- if network address of the syslog service is used for *address*,
  *port* be a TCP or UDP port number (optional)
* *tcp* or *udp* -- TCP (stream) or UDP (datagram) protocol to use for
  syslog service communication (optional)

**--logging-method=file**
~~~~~~~~~~~~~~~~~~~~~~~~~

The *file* logging method redirects daemon logging into a local file. The
log file could be made automatically rotated based on time or size criteria.

The following sub-options are supported:

.. code-block:: bash

    --logging-method=file:path[:criterion]

Where:

* *path* -- path to a log file
* *criterion* -- should consist of a number followed by one of the specifiers:

  - *k* -- rotate when file size exceeds N kilobytes
  - *m* -- rotate when file size exceeds N megabytes
  - *g* -- rotate when file size exceeds N gigabytes
  - *S* -- rotate when file age exceeds N seconds
  - *M* -- rotate when file age exceeds N minutes
  - *H* -- rotate when file age exceeds N hours
  - *D* -- rotate when file age exceeds N days

**--logging-method=stdout/stderr**
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When *stdout* or *stderr* logging methods are used, daemon log messages are
directed to either process standard output or standard error stream.

**--logging-method=null**
~~~~~~~~~~~~~~~~~~~~~~~~~

The *null* logging method completely inhibits all daemon logging.

**--log-level**
+++++++++++++++

The *--log-level* option limits the minimum severity of the log messages
to actually log.

Recognized log levels are:

* *debug* -- log at all levels
* *info* - log informational and error messages only
* *error* - log error messages only

SNMP command responders
-----------------------

SNMP Simulator can be run as *snmpsim-command-responder* (full version) or
*snmpsim-command-responder-lite* (lightweight version). Both programs
take the following common command-line options.

Common command responders options
---------------------------------

The lightweight SNMP command responder implementation is limited to SNMP v1
and v2c protocol versions. Full SNMP command responder implementation supports
all SNMP versions.

The following options are respected by both SNMP command responder
applications.

**--daemonize**
+++++++++++++++

Unless *--daemonize* option is given, the daemon will remain an interactive
process. With the *--daemonize* option, the daemon will detach itself from
user terminal, close down standard I/O streams etc.

**--process-user** & **--process-group**
++++++++++++++++++++++++++++++++++++++++

It is generally safer to run daemons under a non-privileged user. However,
it may be necessary to, at least, start SNMP Simulator parts as root
to let the process bind to privileged ports (161/udp for SNMP by default).

In this case it may make sense to drop process privileges upon
initialization by becoming *--process-user* belonging to *--process-group*.

**--pid-file**
++++++++++++++

Especially when running in *--daemonize* mode, it might be handy to keep
track of UNIX process ID allocated to the running daemon. Primarily, this
can be used for killing or restarting the process.

The *--pid-file* option can be used to specify a disk file where daemon
would store its PID.

Default is not to create PID file.

**--cache-dir**
+++++++++++++++

Specifies path to directory for temporary indices used for fast simulation
data lookup. The indices for all .snmprec files will be built on process
start unless they already exist and not outdated.

Default is `$TEMPDIR/snmpsim`.

**--reporting-method**
++++++++++++++++++++++

SNMP command responder applications can collect and periodically emit
various activity metrics.

The default is *null* that disables activity collection and reporting.

**--reporting-method=fulljson**
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The *fulljson* activity reporting method collects and reports highly
detailed activity metrics. It may become expensive when simulating thousands
of transport endpoints or SNMP agents.

The *fulljson* reporting method supports the following sub-options:

.. code-block:: bash

    --reporting-method=fulljson:reports-dir

Where:

* *reports-dir* -- location on the filesystem where this reporting module
  should dump collected metrics.

**--reporting-method=minimaljson**
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The *minimaljson* activity reporting method collects and reports minimal
activity metrics. Essentially, it collapses individual metrics for transport
endpoints, agents, data files into one.

The *minimaljson* reporting method supports the following sub-options:

.. code-block:: bash

    --reporting-method=minimaljson:reports-dir

Where:

* *reports-dir* -- location on the filesystem where this reporting module
  should dump collected metrics.

**--variation-modules-dir**
+++++++++++++++++++++++++++

Specifies path to the directory where SNMP simulator should look for variation
modules. All modules found there will be imported and initialized for
further use from the .snmprec files.

Default search path is dependent on the platform. On Linux it is:

* `$HOME/.snmpsim/variation`
* `/usr/snmpsim/variation`
* `/usr/share/snmpsim/variation`
* `<program dir>/variation`

**--variation-module-options**
++++++++++++++++++++++++++++++

Some variation modules accept configuration options. These options could be
given in the form of `:`-separated positional arguments:

.. code-block:: bash

   --variation-module-options=<module[=alias][:args]

If the same variation module needs to be used with different set of
configuration parameters, one or more aliases could be created. Each instance
of the variation module could then be referenced from the .snmprec files
by alias.

Example:

.. code-block:: bash

    --variation-module-options=sql=mydb:dbtype:sqlite3,database:/tmp/snmpsim.db

**--force-index-rebuild**
+++++++++++++++++++++++++

Force rebuilding indices for all the .snmprec files regardless of their age and
status. With this option, the rebuild happens on every *snmpsim-command-responder*
process startup.

The default is off.

**--validate-data**
+++++++++++++++++++

Normally, SNMP simulator does not evaluate simulation values configured in the
.snmprec files (however it evaluates the OIDs when building look up indices).
With this option SNMP simulator will also evaluate simulation data on process
startup.

The default is off.

**--max-varbinds**
++++++++++++++++++

Maximum number of SNMP objects to serve in response to the *GETBULK* command
per each requested variable-binding.

The default is *64*.

**--transport-id-offset**
+++++++++++++++++++++++++

With SNMP, transport endpoints (network addresses and ports) are identified by
OIDs. Each kind of network transport (e.g. IPv4-over-UDP) has its own OID
prefix, while the instances of it are identified by a longer OID.

When *snmpsim-command-responder* is asked to initialize a transport endpoint,
it will take the prefix OID and append a single sub-OID number starting from
this offset.

The default is one.

**--data-dir**
++++++++++++++

Specifies path to the directory where SNMP simulator should look for simulation
data in form of *.snmprec*, *.snmprec.bz2*, *.snmpwalk* or *.sapwalk* files.
All files found beneath *--data-dir* will be considered as sources of SNMP
simulation data and their paths will be used for SNMP configuration purposes.

Default search path is dependent on the platform. On Linux it is:

* `$HOME/.snmpsim/data`
* `/usr/snmpsim/data`
* `/usr/share/snmpsim/data`
* `<program dir>/data`

**--agent-udpv4-endpoint**
++++++++++++++++++++++++++

Bind SNMP agent to the given UDP-over-IPv4 transport endpoint in the form of
*IP:port*.

Each occurrence of this option creates a new transport endpoint. All SNMP
engines created afterwards (by *--v3-engine-id* option) up to the next
*--agent-* option will reside behind this transport endpoint.

.. code-block:: bash

   $ snmpsim-command-responder --agent-udpv4-endpoint=127.0.0.1:161

.. note::

   Binding ports less than 1024 on UNIX requires superuser privileges.

**--agent-udpv6-endpoint**
++++++++++++++++++++++++++

Bind SNMP agent to the given UDP-over-IPv6 transport endpoint in the form of
*[IP]:port*.

Each occurrence of this option creates a new transport endpoint. All SNMP
engines created afterwards (by *--v3-engine-id* option) up to the next
*--agent-* option will reside behind this transport endpoint.

.. code-block:: bash

   $ snmpsim-command-responder --agent-udpv4-endpoint=[::1]:161

.. note::

   Binding ports less than 1024 on UNIX requires superuser privileges.

Full version command responder options
--------------------------------------

Full version of SNMP command responder is based on SNMPv3 architecture,
it is capable of handling all SNMP versions i.e. 1, 2c qnd 3.

Full version of SNMP command responder understand all options of the lite
version, plus the following SNMPv3-specific options.

**--args-from-file**
++++++++++++++++++++

All command-line options to *snmpsim-command-responder* could be stored in a
file and passes through this option. File could be easier to manage, and does
not impose any limit on the length of the command line.

**--v3-only**
+++++++++++++

SNMP simulator serves simulation data over both SNMP v1/v2c and SNMPv3
protocols. With the *--v3-only* flag in effect, SNMPv1/v2c agents will
not be configured what saves a bit of memory and startup time.

Default is to configure SNMPv1/v2c and SNMPv3.

**--v3-engine-id**
++++++++++++++++++

SNMP engine identifier that creates a new, independent instance of SNMP
engine. All the following *--v3-* options up to another *--v3-engine-id*
option apply to the SNMP engine being configured.

.. code-block:: bash

   snmpsim-command-responder --v3-engine-id=0102030405070809 ...

.. note::

   The *-v3-engine-id* option expects a hex string or `auto` for automaic
   value.

The default is an autogenerated value.

**--v3-context-engine-id**
++++++++++++++++++++++++++

SNMP entity can have access to many instances of the same collection of
MIB objects. Each such collection is called *context*. A context is identified
by the Context Engine ID and a Context Name that identifies the specific
context.

In other words, to identify an individual item of SNMP management information,
four elements are required:

1. a ContextEngineID
2. a ContextName
3. an object type, and
4. its instance identification

The default for *--v3-context-engine-id* option is the same value
as *--v3-engine-id*.

**--v3-user**
+++++++++++++

SNMP USM user name to use for SNMPv3 authentication and authorization purposes.

**--v3-auth-key**
+++++++++++++++++

SNMP USM message authentication key.

.. note::

    Must be 8 or more characters.

**--v3-auth-proto**
+++++++++++++++++++

SNMPv3 message authentication protocol to use. Valid values are:

+--------+----------------+-------------+
| *ID*   |  *Algorithm*   | *Reference* |
+--------+----------------+-------------+
| NONE   | -              | RFC3414     |
+--------+----------------+-------------+
| MD5    | HMAC MD5       | RFC3414     |
+--------+----------------+-------------+
| SHA    | HMAC SHA-1 128 | RFC3414     |
+--------+----------------+-------------+
| SHA224 | HMAC SHA-2 224 | RFC7860     |
+--------+----------------+-------------+
| SHA256 | HMAC SHA-2 256 | RFC7860     |
+--------+----------------+-------------+
| SHA384 | HMAC SHA-2 384 | RFC7860     |
+--------+----------------+-------------+
| SHA512 | HMAC SHA-2 512 | RFC7860     |
+--------+----------------+-------------+

**--v3-priv-key**
+++++++++++++++++

SNMP USM message encryption key.

.. note::

    Must be 8 or more characters.

**--v3-priv-proto**
+++++++++++++++++++

SNMPv3 message encryption protocol to use. Valid values are:

+------------+------------------------+----------------------+
| *ID*       | *Algorithm*            | *Reference*          |
+------------+------------------------+----------------------+
| NONE       | -                      | RFC3414              |
+------------+------------------------+----------------------+
| DES        | DES                    | RFC3414              |
+------------+------------------------+----------------------+
| AES        | AES CFB 128            | RFC3826              |
+------------+------------------------+----------------------+
| AES192     | AES CFB 192            | RFC Draft            |
+------------+------------------------+----------------------+
| AES256     | AES CFB 256            | RFC Draft            |
+------------+------------------------+----------------------+
| AES192BLMT | AES CFB 192 Blumenthal | RFC Draft            |
+------------+------------------------+----------------------+
| AES256BLMT | AES CFB 256 Blumenthal | RFC Draft            |
+------------+------------------------+----------------------+
| 3DES       | Triple DES EDE         | RFC Draft            |
+------------+------------------------+----------------------+


text:
<Record>
<Term>Brucellosis</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Gram-Negative Bacterial Infections</ParentTerm>
<ClassificationPath>Bacterial Infections and Mycoses/Bacterial Infections/Gram-Negative Bacterial Infections/Brucellosis</ClassificationPath>
<BroaderTerm>Bacterial Infections</BroaderTerm>
<BroaderTerm>Gram-Negative Bacterial Infections</BroaderTerm>
<BroaderTerm>Brucellosis</BroaderTerm>
<BroaderTerm>Bacterial Infections and Mycoses</BroaderTerm>
<ChildTerm>Brucellosis, Bovine</ChildTerm>
<Synonym>Brucellosis</Synonym>
<Synonym>Brucelloses</Synonym>
<Synonym>Undulant Fever</Synonym>
<Synonym>Undulant Fevers</Synonym>
<Synonym>Malta Fever</Synonym>
<Description>Infection caused by bacteria of the genus BRUCELLA mainly involving the MONONUCLEAR PHAGOCYTE SYSTEM. This condition is characterized by fever, weakness, malaise, and weight loss.</Description>
<Source>MeSH</Source>
</Record>


text:
package com.intellij.vcs.log.ui.actions.history;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.AnActionExtensionProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.vcs.log.VcsFullCommitDetails;
import com.intellij.vcs.log.VcsLogDiffHandler;
import com.intellij.vcs.log.history.FileHistoryUi;
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ShowDiffBeforeWithLocalFromHistoryActionProvider extends FileHistorySingleCommitAction implements AnActionExtensionProvider {
  @Override
  public boolean isActive(@NotNull AnActionEvent e) {
    return e.getData(VcsLogInternalDataKeys.FILE_HISTORY_UI) != null;
  }

  @Override
  protected boolean isEnabled(@NotNull FileHistoryUi ui, @Nullable VcsFullCommitDetails detail, @NotNull AnActionEvent e) {
    FilePath filePath = e.getData(VcsDataKeys.FILE_PATH);
    VcsLogDiffHandler handler = e.getData(VcsLogInternalDataKeys.LOG_DIFF_HANDLER);

    if (filePath == null || filePath.getVirtualFile() == null || handler == null) {
      return false;
    }

    if (detail != null) {
      return detail.getParents().size() == 1;
    }

    return true;
  }

  @Override
  protected void performAction(@NotNull Project project,
                               @NotNull FileHistoryUi ui,
                               @NotNull VcsFullCommitDetails detail,
                               @NotNull AnActionEvent e) {
    if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;
    if (detail.getParents().size() != 1) return;

    FilePath path = e.getRequiredData(VcsDataKeys.FILE_PATH);
    VcsLogDiffHandler handler = e.getRequiredData(VcsLogInternalDataKeys.LOG_DIFF_HANDLER);

    handler.showDiffWithLocal(detail.getRoot(), ui.getBeforePath(detail), detail.getParents().get(0), path);
  }
}


text:
<?php

namespace PhpParser\Node\Stmt\TraitUseAdaptation;

use PhpParser\Node;

/**
 * @property Node\Name   $trait     Trait name
 * @property string      $method    Method name
 * @property Node\Name[] $insteadof Overwritten traits
 */
class Precedence extends Node\Stmt\TraitUseAdaptation
{
    /**
     * Constructs a trait use precedence adaptation node.
     *
     * @param Node\Name   $trait       Trait name
     * @param string      $method      Method name
     * @param Node\Name[] $insteadof   Overwritten traits
     * @param array       $attributes  Additional attributes
     */
    public function __construct(Node\Name $trait, $method, array $insteadof, array $attributes = array()) {
        parent::__construct(
            array(
                'trait'     => $trait,
                'method'    => $method,
                'insteadof' => $insteadof,
            ),
            $attributes
        );
    }
}


text:
package org.jetbrains.plugins.scala.lang.macros.evaluator.impl

import org.jetbrains.plugins.scala.lang.macros.evaluator.{MacroContext, MacroImpl, ScalaMacroTypeable}
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunction
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory
import org.jetbrains.plugins.scala.lang.psi.types.ScType

/**
  * generates HList types without tagging
  *
  * example:
  * case class Foo(age: Int, name: String) ->
  * -> Generic.Aux[Main.this.Foo, shapeless.this.::[Int, shapeless.this.::[String, shapeless.this.HNil]]]
  */
object ShapelessMaterializeGeneric extends ScalaMacroTypeable with ShapelessUtils {

  override val boundMacro: Seq[MacroImpl] = MacroImpl("materialize", "shapeless.Generic") :: Nil

  override def checkMacro(macros: ScFunction, context: MacroContext): Option[ScType] = {
    if (context.expectedType.isEmpty) return None
    val targetType = extractTargetType(context)
    val fields      = extractFields(targetType).map(_._2)
    val reprTpStr   = hlistText(fields)
    val genericStr  = s"$fqGeneric.Aux[${targetType.canonicalText}, $reprTpStr]"
    ScalaPsiElementFactory.createTypeFromText(genericStr, context.place, null)
  }
}


text:
<bill session="115" type="hr" number="332" updated="2017-06-28T17:00:10Z">
  <state datetime="2017-05-17">REFERRED</state>
  <status>
    <introduced datetime="2017-05-17"/>
  </status>
  <introduced datetime="2017-05-17"/>
  <titles>
    <title type="official" as="introduced">Supporting the goals and ideals of the International Day Against Homophobia and Transphobia.</title>
    <title type="display">Supporting the goals and ideals of the International Day Against Homophobia and Transphobia.</title>
  </titles>
  <sponsor bioguide_id="L000551"/>
  <cosponsors>
    <cosponsor bioguide_id="B000574" joined="2017-05-17"/>
    <cosponsor bioguide_id="B001285" joined="2017-05-17"/>
    <cosponsor bioguide_id="C001084" joined="2017-05-17"/>
    <cosponsor bioguide_id="C001101" joined="2017-05-17"/>
    <cosponsor bioguide_id="C001067" joined="2017-06-13"/>
    <cosponsor bioguide_id="D000598" joined="2017-06-13"/>
    <cosponsor bioguide_id="D000617" joined="2017-05-17"/>
    <cosponsor bioguide_id="D000627" joined="2017-05-17"/>
    <cosponsor bioguide_id="D000610" joined="2017-05-17"/>
    <cosponsor bioguide_id="E000288" joined="2017-05-17"/>
    <cosponsor bioguide_id="E000179" joined="2017-05-17"/>
    <cosponsor bioguide_id="E000297" joined="2017-06-13"/>
    <cosponsor bioguide_id="F000462" joined="2017-05-17"/>
    <cosponsor bioguide_id="G000574" joined="2017-05-17"/>
    <cosponsor bioguide_id="G000551" joined="2017-05-17"/>
    <cosponsor bioguide_id="G000535" joined="2017-05-17"/>
    <cosponsor bioguide_id="H001050" joined="2017-05-17"/>
    <cosponsor bioguide_id="H000324" joined="2017-05-17"/>
    <cosponsor bioguide_id="H001047" joined="2017-05-17"/>
    <cosponsor bioguide_id="H001068" joined="2017-06-20"/>
    <cosponsor bioguide_id="J000298" joined="2017-05-17"/>
    <cosponsor bioguide_id="J000288" joined="2017-05-17"/>
    <cosponsor bioguide_id="K000375" joined="2017-05-17"/>
    <cosponsor bioguide_id="K000389" joined="2017-05-17"/>
    <cosponsor bioguide_id="K000380" joined="2017-05-17"/>
    <cosponsor bioguide_id="K000381" joined="2017-05-17"/>
    <cosponsor bioguide_id="L000560" joined="2017-05-17"/>
    <cosponsor bioguide_id="L000263" joined="2017-05-17"/>
    <cosponsor bioguide_id="L000579" joined="2017-05-17"/>
    <cosponsor bioguide_id="L000480" joined="2017-05-17"/>
    <cosponsor bioguide_id="L000562" joined="2017-06-21"/>
    <cosponsor bioguide_id="M001185" joined="2017-05-17"/>
    <cosponsor bioguide_id="M001143" joined="2017-05-17"/>
    <cosponsor bioguide_id="M001200" joined="2017-05-17"/>
    <cosponsor bioguide_id="M000312" joined="2017-05-17"/>
    <cosponsor bioguide_id="M001137" joined="2017-05-17"/>
    <cosponsor bioguide_id="N000179" joined="2017-05-17"/>
    <cosponsor bioguide_id="N000147" joined="2017-05-17"/>
    <cosponsor bioguide_id="P000034" joined="2017-05-17"/>
    <cosponsor bioguide_id="P000613" joined="2017-05-17"/>
    <cosponsor bioguide_id="P000593" joined="2017-06-13"/>
    <cosponsor bioguide_id="P000597" joined="2017-05-17"/>
    <cosponsor bioguide_id="P000607" joined="2017-05-17"/>
    <cosponsor bioguide_id="P000598" joined="2017-05-17"/>
    <cosponsor bioguide_id="Q000023" joined="2017-05-17"/>
    <cosponsor bioguide_id="R000606" joined="2017-05-17"/>
    <cosponsor bioguide_id="R000486" joined="2017-05-17"/>
    <cosponsor bioguide_id="S001156" joined="2017-05-17"/>
    <cosponsor bioguide_id="S001145" joined="2017-05-17"/>
    <cosponsor bioguide_id="S001165" joined="2017-05-17"/>
    <cosponsor bioguide_id="S000480" joined="2017-05-17"/>
    <cosponsor bioguide_id="S000510" joined="2017-05-17"/>
    <cosponsor bioguide_id="S001175" joined="2017-05-17"/>
    <cosponsor bioguide_id="S001193" joined="2017-05-17"/>
    <cosponsor bioguide_id="W000797" joined="2017-05-17"/>
    <cosponsor bioguide_id="W000822" joined="2017-05-17"/>
    <cosponsor bioguide_id="Y000062" joined="2017-05-17"/>
  </cosponsors>
  <actions>
    <action datetime="2017-05-17">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-05-17" state="REFERRED">
      <text>Referred to the Committee on Foreign Affairs, and in addition to the Committees on Energy and Commerce, and Education and the Workforce, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
    </action>
    <action datetime="2017-05-17">
      <text>Referred to House Foreign Affairs</text>
    </action>
    <action datetime="2017-05-17">
      <text>Referred to House Energy and Commerce</text>
    </action>
    <action datetime="2017-05-17">
      <text>Referred to House Education and the Workforce</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSED" name="House Education and the Workforce" activity="Referral"/>
    <committee subcommittee="" code="HSIF" name="House Energy and Commerce" activity="Referral"/>
    <committee subcommittee="" code="HSFA" name="House Foreign Affairs" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Civil rights and liberties, minority issues"/>
    <term name="Commemorative events and holidays"/>
    <term name="Elementary and secondary education"/>
    <term name="Foreign aid and international relief"/>
    <term name="Health care quality"/>
    <term name="Higher education"/>
    <term name="Human rights"/>
    <term name="School administration"/>
    <term name="Sex, gender, sexual orientation discrimination"/>
  </subjects>
  <amendments/>
  <summary date="2017-05-17T04:00:00Z" status="Introduced in House">Expresses support for the goals and ideals of an International Day Against Homophobia and Transphobia.

Encourages: (1) health care providers to offer culturally and clinically competent care to the lesbian, gay, bisexual, or transgender (LGBT) community; (2) schools to support the creation of gay-straight alliances to achieve safer learning environments; (3) individuals to learn about national resources for those who identify as LGBT; and (4) the federal government, states, international funding organizations, and U.S. bilateral and multilateral aid efforts to prioritize the health and human rights of LGBT people.</summary>
  <committee-reports/>
</bill>


text:
"""test_kill_bolt.py"""
import logging
import test_template

NON_TMASTER_SHARD = 1
HERON_BOLT = 'identity-bolt_3'

class TestKillBolt(test_template.TestTemplate):

  def execute_test_case(self):
    logging.info("Executing kill bolt")
    bolt_pid = self.get_pid(
        'container_%d_%s' % (NON_TMASTER_SHARD, HERON_BOLT), self.params['workingDirectory'])
    self.kill_process(bolt_pid)