text:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app->get('/public/labels', function(Request $request, Response $response) {
    $attributes = array(
        'site_id'   => filter_var($request->getAttribute('siteId'), FILTER_SANITIZE_NUMBER_INT),
    );

    // Define controller, fill up main variables
    $labelsController = new LabelsController($this->db);

    $labels = $labelsController->getPublicLabels($attributes);

    $data = array(
        'labels' => $labels
    );

    return $response->withJson($data, null, JSON_NUMERIC_CHECK);
});

$app->get('/labels', function(Request $request, Response $response) {
    if (!$request->getAttribute('isLogged')) {
        $response = $response->withStatus(401);
        $data = array('message' => 'Authorization required');
    } else {
        $attributes = array(
            'site_id'   => filter_var($request->getAttribute('siteId'), FILTER_SANITIZE_NUMBER_INT),
        );

        // Define controller, fill up main variables
        $labelsController = new LabelsController($this->db, $request->getAttribute('user'));

        $labels = $labelsController->getLabels($attributes);

        $data = array(
            'labels' => $labels
        );
    }

    return $response->withJson($data, null, JSON_NUMERIC_CHECK);
})->add($auth);

$app->get('/labels/{id}', function(Request $request, Response $response) {
    if (!$request->getAttribute('isLogged')) {
        $response = $response->withStatus(401);
        $data = array('message' => 'Authorization required');
    } else {
        $attributes = array(
            'site_id'   => filter_var($request->getAttribute('siteId'), FILTER_SANITIZE_NUMBER_INT),
            'id'        => filter_var($request->getAttribute('id'), FILTER_SANITIZE_NUMBER_INT),
        );

        // Define controller, fill up main variables
        $labelsController = new LabelsController($this->db, $request->getAttribute('user'));

        $data = array(
            'label' => $labelsController->getLabel($attributes)
        );
    }

    return $response->withJson($data, null, JSON_NUMERIC_CHECK);
})->add($auth);

$app->post('/labels/add', function(Request $request, Response $response) {
    if (!$request->getAttribute('isLogged')) {
        $response = $response->withStatus(401);
        $data = array('message' => 'Authorization required');
    } else {
        // Fetching post parameters
        $body = $request->getParsedBody();

        $user = $request->getAttribute('user');

        $attributes = array(
            'name'      => filter_var($body['name'], FILTER_SANITIZE_STRING),
            'output'    => filter_var($body['output'], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
            'site_id'   => filter_var($request->getAttribute('siteId'), FILTER_SANITIZE_NUMBER_INT),
        );

        // Define controller, fill up main variables
        $labelsController = new LabelsController($this->db, $user);

        // Trying to register user
        $checkLabel = $labelsController->addLabel($attributes);

        if (!$checkLabel) {
            $response = $response->withStatus(400);
            $data = array(
                'message' => $labelsController->getMessage(),
                'fields' => $labelsController->getFields(),
            );

            Log::save($this->db, [
                'module'    => 'labels',
                'type'      => 'add',
                'user_id'   => $user->id,
                'info'      => 'Label creation failed ' . $labelsController->getMessage() . ''
            ]);
        } else {
            // Passing success message
            $data = array(
                'state' => 'success',
                'message' => 'Success! New label added.',
            );

            Log::save($this->db, [
                'module'    => 'labels',
                'type'      => 'add',
                'user_id'   => $user->id,
                'info'      => 'Label added ' . $attributes['name'] . ''
            ]);
        }
    }

    return $response->withJson($data, null, JSON_NUMERIC_CHECK);
})->add($auth);

$app->post('/labels/edit', function(Request $request, Response $response) {
    if (!$request->getAttribute('isLogged')) {
        $response = $response->withStatus(401);
        $data = array('message' => 'Authorization required');
    } else {
        // Fetching post parameters
        $body = $request->getParsedBody();

        $user = $request->getAttribute('user');

        $attributes = array(
            'id'        => filter_var($body['id'], FILTER_SANITIZE_NUMBER_INT),
            'name'      => filter_var($body['name'], FILTER_SANITIZE_STRING),
            'output'    => filter_var($body['output'], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
        );

        // Define controller, fill up main variables
        $labelsController = new LabelsController($this->db, $user);

        // Trying to register user
        $checkLabel = $labelsController->editLabel($attributes);

        if (!$checkLabel) {
            $response = $response->withStatus(400);
            $data = array(
                'message' => $labelsController->getMessage(),
                'fields' => $labelsController->getFields(),
            );

            Log::save($this->db, [
                'module'    => 'labels',
                'type'      => 'edit',
                'user_id'   => $user->id,
                'info'      => 'Label update failed ' . $labelsController->getMessage() . ''
            ]);
        } else {
            // Passing success message
            $data = array(
                'state' => 'success',
                'message' => 'Label updated.',
            );

            Log::save($this->db, [
                'module'    => 'labels',
                'type'      => 'edit',
                'user_id'   => $user->id,
                'info'      => 'Label updated ' . $attributes['name'] . ''
            ]);
        }
    }

    return $response->withJson($data, null, JSON_NUMERIC_CHECK);
})->add($auth);

$app->delete('/labels/delete/{id}', function(Request $request, Response $response) {
    if (!$request->getAttribute('isLogged')) {
        $response = $response->withStatus(401);
        $data = array('message' => 'Authorization required');
    } else {
        $user = $request->getAttribute('user');

        $attributes = array(
            'id' => $request->getAttribute('id'),
        );

        // Define controller, fill up main variables
        $labelsController = new LabelsController($this->db, $user);

        $checkLabel = $labelsController->deleteLabel($attributes['id']);

        if (!$checkLabel) {
            $response = $response->withStatus(400);
            $data = array(
                'message' => $labelsController->getMessage(),
            );

            Log::save($this->db, [
                'module'    => 'labels',
                'type'      => 'delete',
                'user_id'   => $user->id,
                'info'      => 'Label deletion failed [' . $attributes['id'] . '] ' . $labelsController->getMessage() . ''
            ]);
        } else {
            // Passing success message
            $data = array(
                'state' => 'success',
                'message' => 'Label removed',
            );

            Log::save($this->db, [
                'module'    => 'labels',
                'type'      => 'delete',
                'user_id'   => $user->id,
                'info'      => 'Label removed [' . $attributes['id'] . ']'
            ]);
        }
    }

    return $response->withJson($data, null, JSON_NUMERIC_CHECK);
})->add($auth);

class LabelsController
{
    private $db;
    private $user;
    public $fields;
    public $message;

    public function __construct($db, $user = null) {
        $this->db = $db;
        $this->user = $user;
    }

    public function getMessage() {
        // Return all messages and strip
 at the end of the line
        return rtrim($this->message, '
');
    }

    public function getFields() {
        // Return unique fields
        return array_unique($this->fields);
    }

    public function getPublicLabels($attributes) {
        $q = $this->db->prepare(
            'SELECT `name`, `output` '.
            'FROM `mo_labels` '.
            'WHERE `deleted` = 0 '.
            'AND `site_id` = :site_id '.
            'ORDER BY `name` ASC '
        );

        $q->bindParam(':site_id', $attributes['site_id'], PDO::PARAM_INT);

        $q->execute();

        $labels = $q->fetchAll();

        $publicLabels = [];
        foreach($labels as $v) {
            $publicLabels[$v['name']] = html_entity_decode($v['output'], ENT_QUOTES);
        }

        return $publicLabels;
    }

    public function getLabels($attributes) {
        $q = $this->db->prepare(
            'SELECT `id`, `name`, `output` '.
            'FROM `mo_labels` '.
            'WHERE `deleted` = 0 '.
            'AND `site_id` = :site_id '.
            'ORDER BY `name` ASC '
        );

        $q->bindParam(':site_id', $attributes['site_id'], PDO::PARAM_INT);

        try {
            $q->execute();
        } catch(Exception $e) {
            ddump($e->getMessage());
        }

        $labels = $q->fetchAll();

        foreach($labels as &$v) {
            $v['output'] = $this->stripLabel($v['output']);
        }

        return $labels;
    }

    public function getLabel($attributes) {
        $q = $this->db->prepare(
            'SELECT `id`, `name`, `output` '.
            'FROM `mo_labels` '.
            'WHERE `id` = :id '.
            'AND `site_id` = :site_id '.
            'AND `deleted` = 0 '.
            'LIMIT 1'
        );

        $q->bindParam(':id', $attributes['id'], PDO::PARAM_INT);
        $q->bindParam(':site_id', $attributes['site_id'], PDO::PARAM_INT);

        $q->execute();

        $label = $q->fetch();

        $label['output'] = html_entity_decode($label['output'], ENT_QUOTES);

        return $label;
    }

    public function checkIfLabelExist($attributes, $id = 0) {
        $q = $this->db->prepare(
            'SELECT `id` '.
            'FROM `mo_labels` '.
            'WHERE `name` = :name '.
            'AND `site_id` = :site_id '.
            'AND `deleted` = 0 '.
            'AND `id` != :id '.
            'LIMIT 1'
        );
        $q->bindParam(':name', $attributes['name'], PDO::PARAM_STR);
        $q->bindParam(':site_id', $attributes['site_id'], PDO::PARAM_INT);
        $q->bindParam(':id', $id, PDO::PARAM_INT);
        $q->execute();

        if ($q->fetch()) {
            return true;
        }

        return false;
    }

    public function addLabel($attributes) {
        $formData = $this->checkForm($attributes, 'add');

        // In case check failed, $message should have the error
        if (!$formData) {
            return false;
        }

        $q = $this->db->prepare(
            'INSERT INTO `mo_labels` SET '.
            '`site_id` = :site_id, '.
            '`name` = :name, '.
            '`output` = :output '
        );

        $q->bindParam(':site_id', $attributes['site_id'], PDO::PARAM_INT);
        $q->bindParam(':name', $attributes['name'], PDO::PARAM_STR);
        $q->bindParam(':output', $attributes['output'], PDO::PARAM_STR);

        $q->execute();

        return true;
    }

    public function editLabel($attributes) {
        $formData = $this->checkForm($attributes, 'edit');

        // In case check failed, $message should have the error
        if (!$formData) {
            return false;
        }

        $q = $this->db->prepare(
            'UPDATE `mo_labels` SET '.
            '`name` = :name, '.
            '`output` = :output '.
            'WHERE `id` = :id '
        );

        $q->bindParam(':name', $attributes['name'], PDO::PARAM_STR);
        $q->bindParam(':output', $attributes['output'], PDO::PARAM_STR);
        $q->bindParam(':id', $attributes['id'], PDO::PARAM_INT);

        $q->execute();

        return true;
    }

    private function checkForm($attributes, $type) {
        if (!$attributes['name']) {
            $this->message .= 'Name is empty
';
            $this->fields[] = 'name';
        } else if (strlen($attributes['name']) > 100) {
            $this->message .= 'Name is too long
';
            $this->fields[] = 'name';
        } else if (preg_match('/-|\s/',$attributes['name'])) {
            $this->message .= 'Name must not have spaces or dashes, please use underscore
';
            $this->fields[] = 'name';
        } else if ($type === 'add' && $this->checkIfLabelExist($attributes)) {
            $this->message .= 'Label with this key name is already in use
';
            $this->fields[] = 'name';
        } else if ($type === 'edit' && $this->checkIfLabelExist($attributes, $attributes['id'])) {
            $this->message .= 'Label with this key name is already in use
';
            $this->fields[] = 'name';
        }

        if ($this->message) {
            return false;
        }

        return true;
    }

    public function deleteLabel($id) {
        $this->db->query('UPDATE `mo_labels` SET `deleted` = 1 WHERE `id` = ' . (int)$id . ' LIMIT 1');

        return true;
    }

    private function stripLabel($label) {
        // Turn blaber into html code
        $label = html_entity_decode($label, ENT_QUOTES, 'UTF-8');

        $label = strip_tags($label);

        if (strlen($label) >= 100) {
            $label = mb_convert_encoding(substr($label, 0, 100), 'UTF-8') . '...';
        }

        return $label;
    }
}

class LabelsFactory
{
    public static function all(PDO $db, int $siteId) {
        $labelsController = new LabelsController($db);

        $attributes = [
            'site_id'   => $siteId
        ];

        $labels = $labelsController->getPublicLabels($attributes);

        return $labels;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Loon.Utils.Collection;
using Microsoft.Xna.Framework;

namespace Loon.Core.Input
{
    public class LTouch
    {

        private int modifiers;
        private Point startLocation;
        private Point currentLocation;

        private bool consumed = false;

        public bool Consumed
        {
            get { return consumed; }
            set { consumed = value; }
        }

        public const int SHIFT_DOWN = 1 << 0;

        public const int CTRL_DOWN = 1 << 1;

        public const int ALT_DOWN = 1 << 2;

        internal protected int type;

        internal protected float x0, y0;

        internal protected int button;

        internal protected int pointer;

        internal protected int id;

        protected LTouch(LTouch touch)
        {
            this.type = touch.type;
            this.x0 = touch.x0;
            this.y0 = touch.y0;
            this.button = touch.button;
            this.pointer = touch.pointer;
            this.id = touch.id;
        }

        public LTouch(byte[] o)
        {
            In(o);
        }

        internal LTouch()
        {
        }

        public LTouch(float x, float y, int pointer, int id)
        {
            this.Set(x, y, pointer, id);
        }

        public void Set(float x, float y, int pointer, int id)
        {
            this.x0 = x;
            this.y0 = y;
            this.pointer = pointer;
            this.id = id;
        }

        public void Set(Point currentLocation, int modifiers)
        {
            Set(currentLocation, Touch.LEFT, modifiers);
        }

        public void Set(Point currentLocation, int button, int modifiers)
        {
            Set(currentLocation, currentLocation, button, modifiers);
        }

        public void Set(Point startLocation, Point currentLocation, int modifiers)
        {
            Set(startLocation, currentLocation, -1, modifiers);
        }

        public void Set(Point startLocation, Point currentLocation, int mouseButton, int modifiers)
        {
            this.startLocation = startLocation;
            this.currentLocation = currentLocation;
            this.modifiers = modifiers;
            this.button = mouseButton;
            this.x0 = currentLocation.X;
            this.y0 = currentLocation.Y;
        }

        public Point StartLocation
        {
            get { return startLocation; }
        }

        public Point CurrentLocation
        {
            get { return currentLocation; }
        }

        public bool IsCtrlDown
        {
            get { return (modifiers & CTRL_DOWN) > 0; }
        }

        public bool IsShiftDown
        {
            get { return (modifiers & SHIFT_DOWN) > 0; }
        }

        public bool IsAltDown
        {
            get { return (modifiers & ALT_DOWN) > 0; }
        }

        public void Offset(float x, float y)
        {
            this.x0 = x;
            this.y0 = y;
        }

        public void OffsetX(float x)
        {
            this.x0 += x;
        }

        public void OffsetY(float y)
        {
            this.y0 += y;
        }

        public bool Equals(LTouch e)
        {
            if (e == null)
            {
                return false;
            }
            if (e == this)
            {
                return true;
            }
            if (e.type == type && e.x0 == x0 && e.y0 == y0 && e.button == button
                    && e.pointer == pointer && e.id == id)
            {
                return true;
            }
            return false;
        }

        public int GetButton()
        {
            return button;
        }

        public int GetPointer()
        {
            return pointer;
        }

        public int GetCode()
        {
            return type;
        }

        public int GetID()
        {
            return id;
        }

        public int X()
        {
            return (int)x0;
        }

        public int Y()
        {
            return (int)y0;
        }

        public float GetX()
        {
            return x0;
        }

        public float GetY()
        {
            return y0;
        }

        public bool IsDown()
        {
            return button == Touch.TOUCH_DOWN;
        }

        public bool IsUp()
        {
            return button == Touch.TOUCH_UP;
        }

        public bool IsMove()
        {
            return button == Touch.TOUCH_MOVE;
        }

        public bool IsDrag()
        {
            return LInputFactory.isDraging;
        }

        public bool IsLeft()
        {
            return type == Touch.LEFT;
        }

        public bool IsMiddle()
        {
            return type == Touch.MIDDLE;
        }

        public bool IsRight()
        {
            return type == Touch.RIGHT;
        }

        public byte[] Out()
        {
            ArrayByte touchByte = new ArrayByte();
            touchByte.WriteInt(X());
            touchByte.WriteInt(Y());
            touchByte.WriteInt(GetButton());
            touchByte.WriteInt(GetPointer());
            touchByte.WriteInt(GetCode());
            return touchByte.GetData();
        }

        public void In(byte[] o)
        {
            ArrayByte touchByte = new ArrayByte(o);
            x0 = touchByte.ReadInt();
            y0 = touchByte.ReadInt();
            button = touchByte.ReadInt();
            pointer = touchByte.ReadInt();
            type = touchByte.ReadInt();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Component } from "react";
import PropTypes from "prop-types";
import { get } from "lodash";
import { FormattedMessage, injectIntl } from "react-intl";
import Immutable from "immutable";
import moment from "@app/utils/dayjs";

import { formDescription } from "uiTheme/radium/typography";
import ApiUtils from "@app/utils/apiUtils/apiUtils";
import metrics from "@app/metrics";

import Modal from "components/Modals/Modal";
import Spinner from "components/Spinner";

import { getEdition, getAboutMode } from "@inject/utils/versionUtils";
import timeUtils from "utils/timeUtils";

import { TabsNavigationItem } from "dremio-ui-lib";
import { clusterData, dremioLogo } from "./AboutModal.less";

const numDaysBack = 7;

const isBeta = process.env.DREMIO_BETA === "true";

@injectIntl
export default class AboutModal extends Component {
  static propTypes = {
    isOpen: PropTypes.bool,
    hide: PropTypes.func,
    intl: PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      inProgress: false,
      metricsInProgress: false,
      versionInfo: {},
      activeTab: "build",
      tabs: this.tabDetails,
      users: [],
      jobs: [],
      average: {
        user: 0,
        job: 0,
      },
    };
  }

  tabDetails = Immutable.fromJS([
    {
      name: "build",
      label: this.props.intl.formatMessage({ id: "Common.BuildInfo" }),
    },
    {
      name: "metrics",
      label: this.props.intl.formatMessage({ id: "Common.ClusterData" }),
    },
  ]);

  componentDidMount() {
    if (getAboutMode() === "full") {
      this.fetchInfo();
      this.getMetrics();
    }
  }

  handleTabChange = (activeTab) => {
    this.setState({ activeTab });
  };

  fetchInfo = () => {
    this.setState({
      inProgress: true,
    });
    return ApiUtils.fetchJson(
      "info",
      (versionInfo) => {
        this.setState({
          inProgress: false,
          versionInfo,
        });
      },
      () => this.setState({ inProgress: false })
    );
  };

  getMetrics = () => {
    this.setState(
      {
        metricsInProgress: true,
      },
      async () => {
        const userData = await metrics.fetchUserStats(numDaysBack);
        const jobData = await metrics.fetchDailyJobStats(numDaysBack);
        const dates = this.getDates();
        const users = [];
        const jobs = [];
        const sum = {
          user: 0,
          job: 0,
        };
        for (let i = 0; i < dates.length; i++) {
          if (userData.userStatsByDate) {
            const userList = userData.userStatsByDate.filter(
              (item) => item.date === dates[i]
            );
            if (userList.length !== 0) {
              users.push(userList[0].total);
              sum.user += userList[0].total;
            } else {
              users.push(0);
            }
          }
          if (jobData.jobStats) {
            const jobList = jobData.jobStats.filter(
              (item) => item.date === dates[i]
            );
            if (jobList.length !== 0) {
              jobs.push(jobList[0].total);
              sum.job += jobList[0].total;
            } else {
              jobs.push(0);
            }
          }
        }
        this.setState({
          users,
          jobs,
          average: {
            user: Math.round(sum.user / 7),
            job: Math.round(sum.job / 7),
          },
          metricsInProgress: false,
        });
      }
    );
  };

  renderTabs() {
    if (getAboutMode() === "versionOnly") {
      return null;
    }

    return (

        {this.state.tabs.map((item) => (
          <TabsNavigationItem
            name={item.get("name")}
            key={item.get("name")}
            activeTab={this.state.activeTab}
            onClick={() => this.handleTabChange(item.get("name"))}
          >
            {item.get("label")}
          </TabsNavigationItem>
        ))}

    );
  }

  renderTabsContent = (activeTab) => {
    if (getAboutMode() === "versionOnly") {
      return (

            <FormattedMessage id="App.Edition" />

{getEdition()}

      );
    }

    return activeTab === "build"
      ? this.renderVersion()
      : this.renderCluterData();
  };

  renderVersion() {
    const { versionInfo, inProgress } = this.state;

    const buildTime = timeUtils.formatTime(
      versionInfo.buildTime,
      la(timeUtils.INVALID_DATE_MSG),
      window.navigator.locale,
      timeUtils.formats.ISO
    );
    const commitTime = timeUtils.formatTime(
      get(versionInfo, "commit.time"),
      la(timeUtils.INVALID_DATE_MSG),
      window.navigator.locale,
      timeUtils.formats.ISO
    );

    return inProgress ? (
      <Spinner style={{ top: 0 }} />
    ) : (

          <FormattedMessage id="App.Build" />

{versionInfo.version}

          <FormattedMessage id="App.Edition" />

{getEdition()}

          <FormattedMessage id="App.BuildTime" />

{buildTime}

          <FormattedMessage id="App.ChangeHash" />

{get(versionInfo, "commit.hash")}

          <FormattedMessage id="App.ChangeTime" />

{commitTime}

    );
  }

  getDates(format) {
    const dates = [];
    for (let i = 0; i < 7; i++) {
      dates.push(
        moment()
          .subtract(i, "days")
          .format(format ? format : "YYYY-MM-DD")
      );
    }
    return dates;
  }

  renderCluterData = () => {
    const { users, jobs, average, metricsInProgress } = this.state;

    return metricsInProgress ? (
      <Spinner style={{ top: 0 }} />
    ) : (

            Date
            Unique Users
            Jobs Executed

          {this.getDates("MM/DD/YYYY").map((item, i) => (

              {item}
              {users[i] !== undefined ? users[i] : 0}
              {jobs[i] !== undefined ? jobs[i] : 0}

          ))}

            Average
            {average.user}
            {average.job}

    );
  };

  render() {
    const { isOpen, hide, intl } = this.props;
    const { activeTab } = this.state;
    const betaStyles = isBeta ? { background: "rgb(52, 66, 83)" } : {};

    return (
      <Modal
        size="small"
        title={this.props.intl.formatMessage({ id: "App.AboutHeading" })}
        isOpen={isOpen}
        hide={hide}
        modalHeight={isBeta ? "560px" : "540px"}
      >

            <dremio-icon
              name={isBeta ? "corporate/dremio-beta-light" : "corporate/dremio"}
              alt={la("Dremio Narwhal")}
              class={`${dremioLogo} dremioLogoWithText`}
            />

                {intl.formatMessage({
                  id: isBeta ? "App.DremioBeta" : "App.Dremio",
                })}

              {this.renderTabs()}

{this.renderTabsContent(activeTab)}

              {intl.formatMessage({ id: "App.Copyright" })}

              {isBeta && intl.formatMessage({ id: "App.ProductionWarning" })}

      </Modal>
    );
  }
}

const styles = {
  container: {
    display: "flex",
    width: "100%",
    height: "100%",
    padding: 20,
  },
  pane: {
    flex: 2,
    marginLeft: "20px",
    display: "flex",
    flexDirection: "column",
  },

  logoPane: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    display: "flex",
  },

  dtStyle: {
    fontWeight: "500",
    marginTop: 15,
    fontSize: "14px",
  },
  base: {
    height: 38,
    borderBottom: "1px solid #f3f3f3",
    display: "flex",
  },
};


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using Selenium;

namespace SeleniumRemoteControlMsTest
{
    /// <summary>
    /// Summary description for CodedUITest1
    /// </summary>
    [CodedUITest]
    public class SeleniumMsTestLiveAccountLogin2
    {

        private ISelenium selenium;
        private StringBuilder verificationErrors;

        //Constructor
        public SeleniumMsTestLiveAccountLogin2()
        {

        }

        [TestInitialize()]
        public void MyTestInitialize()
        {
            selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://login.live.com/");
            selenium.Start();
            selenium.SetSpeed("800");
            verificationErrors = new StringBuilder();
        }

        [TestMethod]
        public void TestLiveLogin2()
        {
            selenium.Open("/login.srf?wa=wsignin1.0&rpsnv=12&ct=1388204572&rver=6.4.6456.0&wp=MBI&wreply=http:%2F%2Fmail.live.com%2Fdefault.aspx&lc=1033&id=64855&mkt=en-us&cbcxt=mai&snsc=1");
            selenium.WindowMaximize();
            selenium.Type("id=i0116", "SomeUser@live.com");
            selenium.Type("id=i0118", "SomePassword");
            selenium.CaptureScreenshot(@"C:\Temp\Screenshot-001.png");
            selenium.Click("id=idSIButton9");
            selenium.WaitForPageToLoad("30000");
            Thread.Sleep(4000);
            selenium.CaptureScreenshot(@"C:\Temp\Screenshot-002.png");
            selenium.Click("id=c_meun");
            Thread.Sleep(1000);
            selenium.Click("id=c_signout");
            selenium.WaitForPageToLoad("30000");
            Thread.Sleep(4000);
            selenium.CaptureScreenshot(@"C:\Temp\Screenshot-003.png");
            Thread.Sleep(2000);
        }

        [TestCleanup()]
        public void MyTestCleanup()
        {
            if (selenium != null)
            {
                selenium.Close();
                selenium.Stop();
            }
            selenium = null;
        }

        #region Additional test attributes

        // You can use the following additional attributes as you write your tests:

        ////Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //    // To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
        //    // For more information on generated code, see http://go.microsoft.com/fwlink/?LinkId=179463
        //}

        ////Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //    // To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
        //    // For more information on generated code, see http://go.microsoft.com/fwlink/?LinkId=179463
        //}

        #endregion

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }
        private TestContext testContextInstance;
    }
}


text:
import functools

import nova.api.openstack
from nova.api.openstack.compute import admin_actions
from nova.api.openstack.compute import admin_password
from nova.api.openstack.compute import agents
from nova.api.openstack.compute import aggregates
from nova.api.openstack.compute import assisted_volume_snapshots
from nova.api.openstack.compute import availability_zone
from nova.api.openstack.compute import config_drive
from nova.api.openstack.compute import console_output
from nova.api.openstack.compute import create_backup
from nova.api.openstack.compute import deferred_delete
from nova.api.openstack.compute import evacuate
from nova.api.openstack.compute import extended_availability_zone
from nova.api.openstack.compute import extended_server_attributes
from nova.api.openstack.compute import extended_status
from nova.api.openstack.compute import extended_volumes
from nova.api.openstack.compute import extension_info
from nova.api.openstack.compute import fixed_ips
from nova.api.openstack.compute import flavor_access
from nova.api.openstack.compute import flavor_manage
from nova.api.openstack.compute import flavor_rxtx
from nova.api.openstack.compute import flavors
from nova.api.openstack.compute import flavors_extraspecs
from nova.api.openstack.compute import floating_ip_dns
from nova.api.openstack.compute import floating_ip_pools
from nova.api.openstack.compute import floating_ips
from nova.api.openstack.compute import floating_ips_bulk
from nova.api.openstack.compute import hide_server_addresses
from nova.api.openstack.compute import instance_usage_audit_log
from nova.api.openstack.compute import keypairs
from nova.api.openstack.compute import lock_server
from nova.api.openstack.compute import migrate_server
from nova.api.openstack.compute import multinic
from nova.api.openstack.compute import pause_server
from nova.api.openstack.compute import remote_consoles
from nova.api.openstack.compute import rescue
from nova.api.openstack.compute import security_groups
from nova.api.openstack.compute import server_metadata
from nova.api.openstack.compute import server_usage
from nova.api.openstack.compute import servers
from nova.api.openstack.compute import shelve
from nova.api.openstack.compute import simple_tenant_usage
from nova.api.openstack.compute import suspend_server
from nova.api.openstack import wsgi
import nova.conf

CONF = nova.conf.CONF

def _create_controller(main_controller, controller_list,
                      action_controller_list):
    """This is a helper method to create controller with a
    list of extended controller. This is for backward compatible
    with old extension interface. Finally, the controller for the
    same resource will be merged into single one controller.
    """

    controller = wsgi.ResourceV21(main_controller())
    for ctl in controller_list:
        controller.register_extensions(ctl())
    for ctl in action_controller_list:
        controller.register_actions(ctl())
    return controller

agents_controller = functools.partial(
    _create_controller, agents.AgentController, [], [])

aggregates_controller = functools.partial(
    _create_controller, aggregates.AggregateController, [], [])

assisted_volume_snapshots_controller = functools.partial(
    _create_controller,
    assisted_volume_snapshots.AssistedVolumeSnapshotsController, [], [])

availability_zone_controller = functools.partial(
    _create_controller, availability_zone.AvailabilityZoneController, [], [])

keypairs_controller = functools.partial(
    _create_controller, keypairs.KeypairController, [], [])

fixed_ips_controller = functools.partial(_create_controller,
    fixed_ips.FixedIPController, [], [])

flavor_controller = functools.partial(_create_controller,
    flavors.FlavorsController,
    [
        flavor_rxtx.FlavorRxtxController,
        flavor_access.FlavorActionController
    ],
    [
        flavor_manage.FlavorManageController,
        flavor_access.FlavorActionController
    ]
)

flavor_access_controller = functools.partial(_create_controller,
    flavor_access.FlavorAccessController, [], [])

flavor_extraspec_controller = functools.partial(_create_controller,
    flavors_extraspecs.FlavorExtraSpecsController, [], [])

floating_ip_dns_controller = functools.partial(_create_controller,
    floating_ip_dns.FloatingIPDNSDomainController, [], [])

floating_ip_dnsentry_controller = functools.partial(_create_controller,
    floating_ip_dns.FloatingIPDNSEntryController, [], [])

floating_ip_pools_controller = functools.partial(_create_controller,
    floating_ip_pools.FloatingIPPoolsController, [], [])

floating_ips_controller = functools.partial(_create_controller,
    floating_ips.FloatingIPController, [], [])

floating_ips_bulk_controller = functools.partial(_create_controller,
    floating_ips_bulk.FloatingIPBulkController, [], [])

instance_usage_audit_log_controller = functools.partial(_create_controller,
    instance_usage_audit_log.InstanceUsageAuditLogController, [], [])

server_controller = functools.partial(_create_controller,
    servers.ServersController,
    [
        config_drive.ConfigDriveController,
        extended_availability_zone.ExtendedAZController,
        extended_server_attributes.ExtendedServerAttributesController,
        extended_status.ExtendedStatusController,
        extended_volumes.ExtendedVolumesController,
        hide_server_addresses.Controller,
        keypairs.Controller,
        security_groups.SecurityGroupsOutputController,
        server_usage.ServerUsageController,
    ],
    [
        admin_actions.AdminActionsController,
        admin_password.AdminPasswordController,
        console_output.ConsoleOutputController,
        create_backup.CreateBackupController,
        deferred_delete.DeferredDeleteController,
        evacuate.EvacuateController,
        floating_ips.FloatingIPActionController,
        lock_server.LockServerController,
        migrate_server.MigrateServerController,
        multinic.MultinicController,
        pause_server.PauseServerController,
        remote_consoles.RemoteConsolesController,
        rescue.RescueController,
        security_groups.SecurityGroupActionController,
        shelve.ShelveController,
        suspend_server.SuspendServerController
    ]
)

server_metadata_controller = functools.partial(_create_controller,
    server_metadata.ServerMetadataController, [], [])

simple_tenant_usage_controller = functools.partial(_create_controller,
    simple_tenant_usage.SimpleTenantUsageController, [], [])

# NOTE(alex_xu): This is structure of this route list as below:
# (
#     ('Route path': {
#         'HTTP method: [
#             'Controller',
#             'The method of controller is used to handle this route'
#         ],
#         ...
#     }),
#     ...
# )
#
# Also note that this is ordered tuple. For example, the '/servers/detail'
# should be in the front of '/servers/{id}', otherwise the request to
# '/servers/detail' always matches to '/servers/{id}' as the id is 'detail'.
ROUTE_LIST = (
    # NOTE: '/os-volumes_boot' is a clone of '/servers'. We may want to
    # deprecate it in the future.
    ('/flavors', {
        'GET': [flavor_controller, 'index'],
        'POST': [flavor_controller, 'create']
    }),
    ('/flavors/detail', {
        'GET': [flavor_controller, 'detail']
    }),
    ('/flavors/{id}', {
        'GET': [flavor_controller, 'show'],
        'DELETE': [flavor_controller, 'delete']
    }),
    ('/flavors/{id}/action', {
        'POST': [flavor_controller, 'action']
    }),
    ('/flavors/{flavor_id}/os-extra_specs', {
        'GET': [flavor_extraspec_controller, 'index'],
        'POST': [flavor_extraspec_controller, 'create']
    }),
    ('/flavors/{flavor_id}/os-extra_specs/{id}', {
        'GET': [flavor_extraspec_controller, 'show'],
        'PUT': [flavor_extraspec_controller, 'update'],
        'DELETE': [flavor_extraspec_controller, 'delete']
    }),
    ('/flavors/{flavor_id}/os-flavor-access', {
        'GET': [flavor_access_controller, 'index']
    }),
    ('/os-agents', {
        'GET': [agents_controller, 'index'],
        'POST': [agents_controller, 'create']
    }),
    ('/os-agents/{id}', {
        'PUT': [agents_controller, 'update'],
        'DELETE': [agents_controller, 'delete']
    }),
    ('/os-aggregates', {
        'GET': [aggregates_controller, 'index'],
        'POST': [aggregates_controller, 'create']
    }),
    ('/os-aggregates/{id}', {
        'GET': [aggregates_controller, 'show'],
        'PUT': [aggregates_controller, 'update'],
        'DELETE': [aggregates_controller, 'delete']
    }),
    ('/os-aggregates/{id}/action', {
        'POST': [aggregates_controller, 'action'],
    }),
    ('/os-assisted-volume-snapshots', {
        'POST': [assisted_volume_snapshots_controller, 'create']
    }),
    ('/os-assisted-volume-snapshots/{id}', {
        'DELETE': [assisted_volume_snapshots_controller, 'delete']
    }),
    ('/os-availability-zone', {
        'GET': [availability_zone_controller, 'index']
    }),
    ('/os-availability-zone/detail', {
        'GET': [availability_zone_controller, 'detail'],
    }),
    ('/os-fixed-ips/{id}', {
        'GET': [fixed_ips_controller, 'show']
    }),
    ('/os-fixed-ips/{id}/action', {
        'POST': [fixed_ips_controller, 'action'],
    }),
    ('/os-floating-ip-dns', {
        'GET': [floating_ip_dns_controller, 'index']
    }),
    ('/os-floating-ip-dns/{id}', {
        'PUT': [floating_ip_dns_controller, 'update'],
        'DELETE': [floating_ip_dns_controller, 'delete']
    }),
    ('/os-floating-ip-dns/{domain_id}/entries/{id}', {
        'GET': [floating_ip_dnsentry_controller, 'show'],
        'PUT': [floating_ip_dnsentry_controller, 'update'],
        'DELETE': [floating_ip_dnsentry_controller, 'delete']
    }),
    ('/os-floating-ip-pools', {
        'GET': [floating_ip_pools_controller, 'index'],
    }),
    ('/os-floating-ips', {
        'GET': [floating_ips_controller, 'index'],
        'POST': [floating_ips_controller, 'create']
    }),
    ('/os-floating-ips/{id}', {
        'GET': [floating_ips_controller, 'show'],
        'DELETE': [floating_ips_controller, 'delete']
    }),
    ('/os-floating-ips-bulk', {
        'GET': [floating_ips_bulk_controller, 'index'],
        'POST': [floating_ips_bulk_controller, 'create']
    }),
    ('/os-floating-ips-bulk/{id}', {
        'GET': [floating_ips_bulk_controller, 'show'],
        'PUT': [floating_ips_bulk_controller, 'update']
    }),
    ('/os-instance_usage_audit_log', {
        'GET': [instance_usage_audit_log_controller, 'index']
    }),
    ('/os-instance_usage_audit_log/{id}', {
        'GET': [instance_usage_audit_log_controller, 'show']
    }),
    ('/os-keypairs', {
        'GET': [keypairs_controller, 'index'],
        'POST': [keypairs_controller, 'create']
    }),
    ('/os-keypairs/{id}', {
        'GET': [keypairs_controller, 'show'],
        'DELETE': [keypairs_controller, 'delete']
    }),
    ('/os-simple-tenant-usage', {
        'GET': [simple_tenant_usage_controller, 'index']
    }),
    ('/os-simple-tenant-usage/{id}', {
        'GET': [simple_tenant_usage_controller, 'show']
    }),
    ('/os-volumes_boot', {
        'GET': [server_controller, 'index'],
        'POST': [server_controller, 'create']
    }),
    ('/os-volumes_boot/detail', {
        'GET': [server_controller, 'detail']
    }),
    ('/os-volumes_boot/{id}', {
        'GET': [server_controller, 'show'],
        'PUT': [server_controller, 'update'],
        'DELETE': [server_controller, 'delete']
    }),
    ('/os-volumes_boot/{id}/action', {
        'POST': [server_controller, 'action']
    }),
    ('/servers', {
        'GET': [server_controller, 'index'],
        'POST': [server_controller, 'create']
    }),
    ('/servers/detail', {
        'GET': [server_controller, 'detail']
    }),
    ('/servers/{id}', {
        'GET': [server_controller, 'show'],
        'PUT': [server_controller, 'update'],
        'DELETE': [server_controller, 'delete']
    }),
    ('/servers/{id}/action', {
        'POST': [server_controller, 'action']
    }),
    ('/servers/{server_id}/metadata', {
        'GET': [server_metadata_controller, 'index'],
        'POST': [server_metadata_controller, 'create'],
        'PUT': [server_metadata_controller, 'update_all'],
    }),
    ('/servers/{server_id}/metadata/{id}', {
        'GET': [server_metadata_controller, 'show'],
        'PUT': [server_metadata_controller, 'update'],
        'DELETE': [server_metadata_controller, 'delete'],
    }),
)

class APIRouterV21(nova.api.openstack.APIRouterV21):
    """Routes requests on the OpenStack API to the appropriate controller
    and method. The URL mapping based on the plain list `ROUTE_LIST` is built
    at here. The stevedore based API loading will be replaced by this.
    """
    def __init__(self):
        self._loaded_extension_info = extension_info.LoadedExtensionInfo()
        super(APIRouterV21, self).__init__()

        for path, methods in ROUTE_LIST:
            for method, controller_info in methods.items():
                # TODO(alex_xu): In the end, I want to create single controller
                # instance instead of create controller instance for each
                # route.
                controller = controller_info[0]()
                action = controller_info[1]
                self.map.create_route(path, method, controller, action)

    def _register_extension(self, ext):
        return self.loaded_extension_info.register_extension(ext.obj)

    @property
    def loaded_extension_info(self):
        return self._loaded_extension_info


text:
import uuid
from msrest.pipeline import ClientRawResponse

from .. import models

class UsageDetailsOperations(object):
    """UsageDetailsOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An objec model deserializer.
    :ivar api_version: Version of the API to be used with the client request. The current version is 2017-11-30. Constant value: "2017-11-30".
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2017-11-30"

        self.config = config

    def list(
            self, scope, expand=None, filter=None, skiptoken=None, top=None, custom_headers=None, raw=False, **operation_config):
        """Lists the usage details for a scope by billing period. Usage details
        are available via this API only for May 1, 2014 or later.

        :param scope: The scope of the usage details. The scope can be
         '/subscriptions/{subscriptionId}' for a subscription, or
         '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'
         for a billing perdiod.
        :type scope: str
        :param expand: May be used to expand the
         properties/additionalProperties or properties/meterDetails within a
         list of usage details. By default, these fields are not included when
         listing usage details.
        :type expand: str
        :param filter: May be used to filter usageDetails by
         properties/usageEnd (Utc time), properties/usageStart (Utc time),
         properties/resourceGroup, properties/instanceName or
         properties/instanceId. The filter supports 'eq', 'lt', 'gt', 'le',
         'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'.
        :type filter: str
        :param skiptoken: Skiptoken is only used if a previous operation
         returned a partial result. If a previous response contains a nextLink
         element, the value of the nextLink element will include a skiptoken
         parameter that specifies a starting point to use for subsequent calls.
        :type skiptoken: str
        :param top: May be used to limit the number of results to the most
         recent N usageDetails.
        :type top: int
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of UsageDetail
        :rtype:
         ~azure.mgmt.consumption.models.UsageDetailPaged[~azure.mgmt.consumption.models.UsageDetail]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.consumption.models.ErrorResponseException>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/{scope}/providers/Microsoft.Consumption/usageDetails'
                path_format_arguments = {
                    'scope': self._serialize.url("scope", scope, 'str', skip_quote=True)
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if expand is not None:
                    query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                if skiptoken is not None:
                    query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str')
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1)
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                raise models.ErrorResponseException(self._deserialize, response)

            return response

        # Deserialize response
        deserialized = models.UsageDetailPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.UsageDetailPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized


text:
package by.stqa.pft.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import by.stqa.pft.addressbook.model.ContactData;
import by.stqa.pft.addressbook.model.Contacts;
import by.stqa.pft.addressbook.model.GroupData;
import by.stqa.pft.addressbook.model.Groups;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * Created by Artsiom on 4/12/2017.
 */
public class  ContactAddToGroupTest extends TestBase {

  @BeforeMethod
  public void ensurePrecondition() {
    Groups groups = app.db().groups();
    app.goTo().homePage();
    if (app.db().contacts().size() == 0) {
      app.contact().create(new ContactData().withFirstname("Donald").withLastname("Trump").withAddress("Washington")
              .withHomephone("80297027079").withMobilephone("+19737382899").withWorkphone("911").withEmail("donald@gmail.com")
              .withEmail2("trump@yahoo.com").withEmail3("donald_trump@tut.by").inGroup(groups.iterator().next()));
      app.goTo().homePage();
    }
    if (app.db().groups().size() == 0){
      app.goTo().groupPage();
      app.group().create(new GroupData().withName("test3").withHeader("test2").withFooter("test1"));
      app.goTo().groupPage();
    }
  }

  @Test
  public void testContactAddToGroup(){
    Contacts before = app.db().contacts();
    app.goTo().homePage();
    Groups group = app.db().groups();
    ContactData modifiedContact = before.iterator().next();
    GroupData addedGroup = group.iterator().next();
    app.contact().selectContactById(modifiedContact.getId());
    app.contact().addContactToGroup(addedGroup.getId());
    Contacts after = app.db().contacts();
    assertThat(after, equalTo(before.without(modifiedContact).withAdded(modifiedContact.inGroup(addedGroup))));
  }
}


text:
require 'test_helper'

module Tilia
  module CalDav
    class ShareableCalendarTest < Minitest::Test
      def setup
        props = {
          'id' => 1
        }

        @backend = Backend::MockSharing.new(
          [props]
        )
        @backend.update_shares(
          1,
          [
            {
              'href' => 'mailto:removeme@example.org',
              'commonName' => 'To be removed',
              'readOnly' => true
            }
          ],
          []
        )

        @instance = ShareableCalendar.new(@backend, props)
      end

      def test_update_shares
        @instance.update_shares(
          [ # 1 Hash in Array
            'href' => 'mailto:test@example.org',
            'commonName' => 'Foo Bar',
            'summary' => 'Booh',
            'readOnly' => false
          ],
          ['mailto:removeme@example.org']
        )

        assert_equal(
          [ # 1 Hash in Array
            'href' => 'mailto:test@example.org',
            'commonName' => 'Foo Bar',
            'summary' => 'Booh',
            'readOnly' => false,
            'status' => SharingPlugin::STATUS_NORESPONSE
          ],
          @instance.shares
        )
      end

      def test_publish
        assert(@instance.publish_status = true)
        refute(@instance.publish_status = false)
      end
    end
  end
end


text:
//Current Drupal Versions
var drupal6_version = "6.34";
var drupal7_version = "7.34";

//Send version request to background page
chrome.extension.sendMessage({'get_version' : 'true'}, function(response) {});

//Update panel with version information
chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.popup) {
		var version = request.popup;
		document.getElementById("label").appendChild(document.createTextNode(chrome.i18n.getMessage("drupal_version")));
		if (version == "Hidden")
			document.getElementById("version").appendChild(document.createTextNode(chrome.i18n.getMessage("hidden")));
		else
			document.getElementById("version").appendChild(document.createTextNode(version));
		if ( (( version != "Hidden") && ( !version.match(/-/))) && ( version.match(/Below/) || lowerVersion(version,drupal6_version) || ((parseInt(version) >= parseInt("7")) && lowerVersion(version,drupal7_version) ) ) )
			document.getElementById("outdated").appendChild(document.createTextNode(chrome.i18n.getMessage("outdated")));
		else if ( ( version.match(/\-/)) && ( lowerVersion(version.match(/\-([0-9.]+)/)[1],drupal6_version) || ((parseInt(version.match(/\-([0-9.]+)/)[1]) >= parseInt("7")) && lowerVersion(version.match(/\-([0-9.]+)/)[1],drupal7_version) ) ) )
			document.getElementById("outdated").appendChild(document.createTextNode(chrome.i18n.getMessage("outdated")));
	}
  });

//Checks if version in use is lower than the current version
function lowerVersion(in_use_version,current_version) {
	if ( (parseInt(in_use_version.match(/([0-9])\.[0-9]+/)[1]) < parseInt(current_version.match(/([0-9])\.[0-9]+/)[1])) )
		return true;
	else if ( (parseInt(in_use_version.match(/([0-9])\.[0-9]+/)[1]) == parseInt(current_version.match(/([0-9])\.[0-9]+/)[1])) && (parseInt(in_use_version.match(/[0-9]\.([0-9]+)/)[1]) < parseInt(current_version.match(/[0-9]\.([0-9]+)/)[1])) )
		return true;
	else
		return false;
}


text:
SilverStripe SQRL Authenticator
=================
SilverStripe implementation of [GRC's SQRL authentication](https://www.grc.com/sqrl/sqrl.htm) system, at this time this module is very experimental and has allot of work yet to go. For more information on SQRL see [here](https://www.grc.com/sqrl/sqrl.htm) and [here](http://sqrl.pl/guide/).

## Requirements
* SilverStripe 3.1+

## Installation
* Download the module from here https://github.com/UndefinedOffset/silverstripe-sqrl/archive/master.zip
* Extract the downloaded archive into your site root so that the destination folder is called sqrl, opening the extracted folder should contain _config.php in the root along with other files/folders
* Run dev/build?flush=all to regenerate the manifest

If you prefer you may also install using composer:
```
composer require undefinedoffset/silverstripe-sqrl
```


text:
namespace {

base::FilePath GetPythonPath() {
  // Every environment should have python3.
  return base::FilePath(FILE_PATH_LITERAL("python3"));
}

const base::FilePath kTestDataPath = base::FilePath(
    FILE_PATH_LITERAL("chrome/test/data/media/engagement/preload"));

const char kMediaEngagementTestDataPath[] = "chrome/test/data/media/engagement";

const std::u16string kAllowedTitle = u"Allowed";

const std::u16string kDeniedTitle = u"Denied";

const base::FilePath kEmptyDataPath = kTestDataPath.AppendASCII("empty.pb");

const std::vector<base::Feature> kFeatures = {
    media::kMediaEngagementBypassAutoplayPolicies,
    media::kPreloadMediaEngagementData};

}  // namespace

// Class used to test that origins with a high Media Engagement score
// can bypass autoplay policies.
class MediaEngagementAutoplayBrowserTest
    : public testing::WithParamInterface<bool>,
      public InProcessBrowserTest {
 public:
  MediaEngagementAutoplayBrowserTest() {
    http_server_.ServeFilesFromSourceDirectory(kMediaEngagementTestDataPath);
    http_server_origin2_.ServeFilesFromSourceDirectory(
        kMediaEngagementTestDataPath);

    // Enable or disable MEI based on the test parameter.
    if (GetParam()) {
      scoped_feature_list_.InitWithFeatures(kFeatures, {});
    } else {
      scoped_feature_list_.InitWithFeatures({}, kFeatures);
    }
  }

  ~MediaEngagementAutoplayBrowserTest() override = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitchASCII(
        switches::kAutoplayPolicy,
        switches::autoplay::kDocumentUserActivationRequiredPolicy);
  }

  void SetUp() override {
    ASSERT_TRUE(http_server_.Start());
    ASSERT_TRUE(http_server_origin2_.Start());

    InProcessBrowserTest::SetUp();

    // Clear any preloaded MEI data.
    ApplyEmptyPreloadedList();
  }

  void LoadTestPage(const std::string& page) {
    NavigateParams params(browser()->profile(), http_server_.GetURL("/" + page),
                          ui::PageTransition::PAGE_TRANSITION_LINK);
    params.user_gesture = false;
    params.is_renderer_initiated = false;
    ui_test_utils::NavigateToURL(&params);
  }

  void LoadTestPageSecondaryOrigin(const std::string& page) {
    NavigateParams params(browser()->profile(),
                          http_server_origin2_.GetURL("/" + page),
                          ui::PageTransition::PAGE_TRANSITION_LINK);
    params.user_gesture = false;
    params.is_renderer_initiated = false;
    ui_test_utils::NavigateToURL(&params);
  }

  void LoadSubFrame(const std::string& page) {
    EXPECT_TRUE(content::ExecuteScriptWithoutUserGesture(
        GetWebContents(), "document.getElementsByName('subframe')[0].src = \"" +
                              http_server_origin2_.GetURL("/" + page).spec() +
                              "\""));
  }

  void SetScores(const url::Origin& origin, int visits, int media_playbacks) {
    MediaEngagementScore score = GetService()->CreateEngagementScore(origin);
    score.SetVisits(visits);
    score.SetMediaPlaybacks(media_playbacks);
    score.Commit();
  }

  url::Origin PrimaryOrigin() const {
    return url::Origin::Create(http_server_.GetURL("/"));
  }

  url::Origin SecondaryOrigin() const {
    return url::Origin::Create(http_server_origin2_.GetURL("/"));
  }

  void ExpectAutoplayAllowedIfEnabled() {
    if (GetParam()) {
      ExpectAutoplayAllowed();
    } else {
      ExpectAutoplayDenied();
    }
  }

  void ExpectAutoplayAllowed() { EXPECT_EQ(kAllowedTitle, WaitAndGetTitle()); }

  void ExpectAutoplayDenied() { EXPECT_EQ(kDeniedTitle, WaitAndGetTitle()); }

  void ApplyPreloadedOrigin(const url::Origin& origin) {
    base::ScopedAllowBlockingForTesting allow_blocking;

    // Get two temporary files.
    base::FilePath input_path;
    base::FilePath output_path;
    EXPECT_TRUE(base::CreateTemporaryFile(&input_path));
    EXPECT_TRUE(base::CreateTemporaryFile(&output_path));

    // Write JSON file with the server origin in it.
    base::ListValue list;
    list.Append(origin.Serialize());
    std::string json_data;
    base::JSONWriter::Write(list, &json_data);
    EXPECT_TRUE(base::WriteFile(input_path, json_data));

    // Get the source root. The make_dafsa.py script is in here.
    base::FilePath src_root;
    EXPECT_TRUE(
        base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &src_root));

    // Get the generated root. The protobuf-generated files are in here.
    base::FilePath gen_root;
    EXPECT_TRUE(
        base::PathService::Get(base::DIR_GEN_TEST_DATA_ROOT, &gen_root));

    // Launch the generator and wait for it to finish.
    base::CommandLine cmd(GetPythonPath());
    cmd.AppendArgPath(src_root.Append(
        FILE_PATH_LITERAL("tools/media_engagement_preload/make_dafsa.py")));
    cmd.AppendArgPath(gen_root);
    cmd.AppendArgPath(input_path);
    cmd.AppendArgPath(output_path);
    base::Process process = base::LaunchProcess(cmd, base::LaunchOptions());
    EXPECT_TRUE(process.WaitForExit(nullptr));

    // Load the preloaded list.
    EXPECT_TRUE(
        MediaEngagementPreloadedList::GetInstance()->LoadFromFile(output_path));
  }

  void ApplyEmptyPreloadedList() {
    // Get the path relative to the source root.
    base::FilePath source_root;
    EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root));

    base::ScopedAllowBlockingForTesting allow_blocking;
    EXPECT_TRUE(MediaEngagementPreloadedList::GetInstance()->LoadFromFile(
        source_root.Append(kEmptyDataPath)));
  }

 private:
  std::u16string WaitAndGetTitle() {
    content::TitleWatcher title_watcher(GetWebContents(), kAllowedTitle);
    title_watcher.AlsoWaitForTitle(kDeniedTitle);
    return title_watcher.WaitAndGetTitle();
  }

  MediaEngagementService* GetService() {
    return MediaEngagementService::Get(browser()->profile());
  }

  content::WebContents* GetWebContents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

  net::EmbeddedTestServer http_server_;
  net::EmbeddedTestServer http_server_origin2_;

  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       BypassAutoplayHighEngagement) {
  SetScores(PrimaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       DoNotBypassAutoplayLowEngagement) {
  SetScores(PrimaryOrigin(), 1, 1);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       DoNotBypassAutoplayNoEngagement) {
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       DoNotBypassAutoplayFrameHighEngagement_NoDelegation) {
  SetScores(PrimaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_iframe_test.html");
  LoadSubFrame("engagement_autoplay_iframe_test_frame.html");
  ExpectAutoplayDenied();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       DoNotBypassAutoplayFrameLowEngagement_NoDelegation) {
  SetScores(SecondaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_iframe_test.html");
  LoadSubFrame("engagement_autoplay_iframe_test_frame.html");
  ExpectAutoplayDenied();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       BypassAutoplayFrameHighEngagement_Delegation) {
  SetScores(PrimaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_iframe_delegation.html");
  LoadSubFrame("engagement_autoplay_iframe_test_frame.html");
  ExpectAutoplayAllowedIfEnabled();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       DoNotBypassAutoplayFrameLowEngagement_Delegation) {
  SetScores(SecondaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_iframe_delegation.html");
  LoadSubFrame("engagement_autoplay_iframe_test_frame.html");
  ExpectAutoplayDenied();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       DoNotBypassAutoplayFrameNoEngagement) {
  LoadTestPage("engagement_autoplay_iframe_test.html");
  LoadSubFrame("engagement_autoplay_iframe_test_frame.html");
  ExpectAutoplayDenied();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       ClearEngagementOnNavigation) {
  SetScores(PrimaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();

  LoadTestPageSecondaryOrigin("engagement_autoplay_test.html");
  ExpectAutoplayDenied();
  SetScores(SecondaryOrigin(), 20, 20);

  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();

  LoadTestPageSecondaryOrigin("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();
}

// Test have high score threshold.
IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       HasHighScoreThreshold) {
  SetScores(PrimaryOrigin(), 20, 16);
  SetScores(PrimaryOrigin(), 20, 10);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();
}

// Disabled due to being flaky. crbug.com/1212507
#if BUILDFLAG(IS_MAC)
#define MAYBE_UsePreloadedData_Allowed DISABLED_UsePreloadedData_Allowed
#else
#define MAYBE_UsePreloadedData_Allowed UsePreloadedData_Allowed
#endif
IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       MAYBE_UsePreloadedData_Allowed) {
  // Autoplay should be blocked by default if we have a bad score.
  SetScores(PrimaryOrigin(), 0, 0);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();

  // Load the preloaded data and we should now be able to autoplay.
  ApplyPreloadedOrigin(PrimaryOrigin());
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();

  // If we now have a high MEI score we should still be allowed to autoplay.
  SetScores(PrimaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();

  // If we clear the preloaded data we should still be allowed to autoplay.
  ApplyEmptyPreloadedList();
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       UsePreloadedData_Denied) {
  // Autoplay should be blocked by default if we have a bad score.
  SetScores(PrimaryOrigin(), 0, 0);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();

  // Load the preloaded data but we are not in that dataset so we should not be
  // allowed to autoplay.
  ApplyPreloadedOrigin(SecondaryOrigin());
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();

  // If we now have a high MEI score we should now be allowed to autoplay.
  SetScores(PrimaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();

  // If we clear the preloaded data we should still be allowed to autoplay.
  ApplyEmptyPreloadedList();
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest,
                       PreloadedDataAndHighVisits) {
  // Autoplay should be denied due to a low score.
  SetScores(PrimaryOrigin(), 20, 0);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();

  // Load the preloaded data and even though we are in the dataset we should not
  // be allowed to play.
  ApplyPreloadedOrigin(PrimaryOrigin());
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();
}

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTest, TopFrameNavigation) {
  SetScores(SecondaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();

  LoadTestPageSecondaryOrigin("engagement_autoplay_test.html");
  ExpectAutoplayAllowedIfEnabled();
}

class MediaEngagementAutoplayBrowserTestHttpsOnly
    : public MediaEngagementAutoplayBrowserTest {
 public:
  MediaEngagementAutoplayBrowserTestHttpsOnly() {
    feature_list_.InitAndEnableFeature(media::kMediaEngagementHTTPSOnly);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_P(MediaEngagementAutoplayBrowserTestHttpsOnly,
                       BypassAutoplayHighEngagement) {
  SetScores(PrimaryOrigin(), 20, 20);
  LoadTestPage("engagement_autoplay_test.html");
  ExpectAutoplayDenied();
}

INSTANTIATE_TEST_SUITE_P(All,
                         MediaEngagementAutoplayBrowserTest,
                         testing::Bool());

INSTANTIATE_TEST_SUITE_P(All,
                         MediaEngagementAutoplayBrowserTestHttpsOnly,
                         testing::Bool());


text:
'use strict';

var output = {
  tests: {},
  successCriteria: {},
  stats: {
    tests: 0,
    cases: 0
  }
};
quail.run({
  accessibilityTests: [window.assessmentName],
  html: jQuery('html'),
  // Called when an individual Case in a test is resolved.
  caseResolve: function caseResolve(eventName, test, _case) {
    var name = test.get('name');
    if (!output.tests[name]) {
      output.tests[name] = {
        id: name,
        title: test.get('title'),
        description: test.get('description'),
        type: test.get('type'),
        testability: test.get('testability'),
        guidelines: test.get('guidelines') || {},
        tags: test.get('tags'),
        cases: []
      };
    }
    // Push the case into the results for this test.
    output.tests[name].cases.push({
      status: _case.get('status'),
      selector: _case.get('selector'),
      html: _case.get('html')
    });
    // Increment the cases count.
    output.stats.cases++;
  },
  // Called when all the Cases in a Test are resolved.
  testComplete: function testComplete() {
    // console.log('Finished testing ' + test.get('name') + '.');
    // Increment the tests count.
    output.stats.tests++;
  },
  // Called when all the Tests in a TestCollection are completed.
  testCollectionComplete: function testCollectionComplete(eventName, testCollection) {
    console.log(testCollection);
  }
});


text:
package v1alpha3

import (
	"context"
	"crypto/tls"
	"fmt"
	"net"
	"path/filepath"
	"testing"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	admissionv1beta1 "k8s.io/api/admission/v1beta1"
	//+kubebuilder:scaffold:imports
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/rest"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/envtest"
	"sigs.k8s.io/controller-runtime/pkg/envtest/printer"
	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"
)

// These tests use Ginkgo (BDD-style Go testing framework). Refer to
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.

var cfg *rest.Config
var k8sClient client.Client
var testEnv *envtest.Environment
var ctx context.Context
var cancel context.CancelFunc

func TestAPIs(t *testing.T) {
	RegisterFailHandler(Fail)

	RunSpecsWithDefaultAndCustomReporters(t,
		"Webhook Suite",
		[]Reporter{printer.NewlineReporter{}})
}

var _ = BeforeSuite(func() {
	logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

	ctx, cancel = context.WithCancel(context.TODO())

	By("bootstrapping test environment")
	testEnv = &envtest.Environment{
		CRDDirectoryPaths:     []string{filepath.Join("..", "..", "config", "crd", "bases")},
		ErrorIfCRDPathMissing: false,
		WebhookInstallOptions: envtest.WebhookInstallOptions{
			Paths: []string{filepath.Join("..", "..", "config", "webhook")},
		},
	}

	var err error
	// cfg is defined in this file globally.
	cfg, err = testEnv.Start()
	Expect(err).NotTo(HaveOccurred())
	Expect(cfg).NotTo(BeNil())

	scheme := runtime.NewScheme()
	err = AddToScheme(scheme)
	Expect(err).NotTo(HaveOccurred())

	err = admissionv1beta1.AddToScheme(scheme)
	Expect(err).NotTo(HaveOccurred())

	//+kubebuilder:scaffold:scheme

	k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
	Expect(err).NotTo(HaveOccurred())
	Expect(k8sClient).NotTo(BeNil())

	// start webhook server using Manager
	webhookInstallOptions := &testEnv.WebhookInstallOptions
	mgr, err := ctrl.NewManager(cfg, ctrl.Options{
		Scheme:             scheme,
		Host:               webhookInstallOptions.LocalServingHost,
		Port:               webhookInstallOptions.LocalServingPort,
		CertDir:            webhookInstallOptions.LocalServingCertDir,
		LeaderElection:     false,
		MetricsBindAddress: "0",
	})
	Expect(err).NotTo(HaveOccurred())

	err = (&FQDNNetworkPolicy{}).SetupWebhookWithManager(mgr)
	Expect(err).NotTo(HaveOccurred())

	//+kubebuilder:scaffold:webhook

	go func() {
		defer GinkgoRecover()
		err = mgr.Start(ctx)
		Expect(err).NotTo(HaveOccurred())
	}()

	// wait for the webhook server to get ready
	dialer := &net.Dialer{Timeout: time.Second}
	addrPort := fmt.Sprintf("[%s]:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort)
	Eventually(func() error {
		conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true})
		if err != nil {
			return err
		}
		conn.Close()
		return nil
	}).Should(Succeed())

}, 60)

var _ = AfterSuite(func() {
	cancel()
	By("tearing down the test environment")
	err := testEnv.Stop()
	Expect(err).NotTo(HaveOccurred())
})


text:
require 'drb'

describe "DRb::DRbServer.verbose" do
  it "needs to be reviewed for spec completeness"
end

describe "DRb::DRbServer.verbose=" do
  it "needs to be reviewed for spec completeness"
end

describe "DRb::DRbServer#verbose" do
  it "needs to be reviewed for spec completeness"
end

describe "DRb::DRbServer#verbose=" do
  it "needs to be reviewed for spec completeness"
end


text:
<?php

namespace Build\Core\Support\Facades;

use Illuminate\Support\Facades\Facade;

class Asset extends Facade
{

    /**
     * Get the registered name of the facade.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'build.asset';
    }
}


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

<title>SignatureProperty (java-taxii API)</title>
<meta name="date" content="2014-10-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.mitre.taxii.messages.xmldsig

Class SignatureProperty

java.lang.Object

org.mitre.taxii.messages.xmldsig.SignatureProperty

All Implemented Interfaces:

org.jvnet.jaxb2_commons.lang.Equals, org.jvnet.jaxb2_commons.lang.HashCode

public class SignatureProperty
extends java.lang.Object
implements org.jvnet.jaxb2_commons.lang.Equals, org.jvnet.jaxb2_commons.lang.HashCode

Java class for SignaturePropertyType complex type.

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

 <complexType name="SignaturePropertyType">
   <complexContent>
     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
       <choice maxOccurs="unbounded">
         <any processContents='lax' namespace='##other'/>
       </choice>
       <attribute name="Target" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
       <attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" />
     </restriction>
   </complexContent>
 </complexType>

Field Summary

Fields

Modifier and Type
Field and Description

protected java.util.List<java.lang.Object>
content

protected java.lang.String
id

protected java.lang.String
target

Constructor Summary

Constructors

Constructor and Description

SignatureProperty()

Default no-arg constructor

SignatureProperty(java.util.List<java.lang.Object> content,
                 java.lang.String target,
                 java.lang.String id)

Fully-initialising value constructor

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object object)

boolean
equals(org.jvnet.jaxb2_commons.locator.ObjectLocator thisLocator,
      org.jvnet.jaxb2_commons.locator.ObjectLocator thatLocator,
      java.lang.Object object,
      org.jvnet.jaxb2_commons.lang.EqualsStrategy strategy)

java.util.List<java.lang.Object>
getContent()

Gets the value of the content property.

java.lang.String
getId()

Gets the value of the id property.

java.lang.String
getTarget()

Gets the value of the target property.

int
hashCode()

int
hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator locator,
        org.jvnet.jaxb2_commons.lang.HashCodeStrategy strategy)

void
setId(java.lang.String value)

Sets the value of the id property.

void
setTarget(java.lang.String value)

Sets the value of the target property.

SignatureProperty
withContent(java.util.Collection<java.lang.Object> values)

SignatureProperty
withContent(java.lang.Object... values)

SignatureProperty
withId(java.lang.String value)

SignatureProperty
withTarget(java.lang.String value)

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Field Detail

content

protected java.util.List<java.lang.Object> content

target

protected java.lang.String target

id

protected java.lang.String id

Constructor Detail

SignatureProperty

public SignatureProperty()

Default no-arg constructor

SignatureProperty

public SignatureProperty(java.util.List<java.lang.Object> content,
                 java.lang.String target,
                 java.lang.String id)

Fully-initialising value constructor

Method Detail

getContent

public java.util.List<java.lang.Object> getContent()

Gets the value of the content property.

 This accessor method returns a reference to the live list,
 not a snapshot. Therefore any modification you make to the
 returned list will be present inside the JAXB object.
 This is why there is not a set method for the content property.

 For example, to add a new item, do as follows:

    getContent().add(newItem);

 Objects of the following type(s) are allowed in the list
 String
 Element
 Object

getTarget

public java.lang.String getTarget()

Gets the value of the target property.

Returns:

possible object is
     String

setTarget

public void setTarget(java.lang.String value)

Sets the value of the target property.

Parameters:

value - allowed object is
     String

getId

public java.lang.String getId()

Gets the value of the id property.

Returns:

possible object is
     String

setId

public void setId(java.lang.String value)

Sets the value of the id property.

Parameters:

value - allowed object is
     String

equals

public boolean equals(org.jvnet.jaxb2_commons.locator.ObjectLocator thisLocator,
             org.jvnet.jaxb2_commons.locator.ObjectLocator thatLocator,
             java.lang.Object object,
             org.jvnet.jaxb2_commons.lang.EqualsStrategy strategy)

Specified by:

equals in interface org.jvnet.jaxb2_commons.lang.Equals

equals

public boolean equals(java.lang.Object object)

Overrides:

equals in class java.lang.Object

hashCode

public int hashCode(org.jvnet.jaxb2_commons.locator.ObjectLocator locator,
           org.jvnet.jaxb2_commons.lang.HashCodeStrategy strategy)

Specified by:

hashCode in interface org.jvnet.jaxb2_commons.lang.HashCode

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

withContent

public SignatureProperty withContent(java.lang.Object... values)

withContent

public SignatureProperty withContent(java.util.Collection<java.lang.Object> values)

withTarget

public SignatureProperty withTarget(java.lang.String value)

withId

public SignatureProperty withId(java.lang.String value)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package leafcutter.unit;

import static org.junit.Assert.*;

import org.junit.Test;

import leafcutter.event.ScheduleActivityDecision;
import leafcutter.task.DecisionTask;
import leafcutter.task.ExecutionHistory;

public class ScheduleActivityExceptionCatcherTestCase {

    @Test
    public void noNullTaskTest() {
	try {
	    new ScheduleActivityDecision(null, "temp", "temp");
	    fail("An IllegalArgumentException should have been thrown.");
	} catch (IllegalArgumentException exc) {
	    // We're expecting this exception
	    assertTrue(true);
	}
    }

    @Test
    public void noNullActivtyNameTest() {
	try {
	    new ScheduleActivityDecision(new DecisionTask("temp", new ExecutionHistory()), null, "temp");
	    fail("An IllegalArgumentException should have been thrown.");
	} catch (IllegalArgumentException exc) {
	    // We're expecting this exception
	    assertTrue(true);
	}
    }

    @Test
    public void noNullDataTest() {
	try {
	    new ScheduleActivityDecision(new DecisionTask("temp", new ExecutionHistory()), "temp", null);
	    fail("An IllegalArgumentException should have been thrown.");
	} catch (IllegalArgumentException exc) {
	    // We're expecting this exception
	    assertTrue(true);
	}
    }

}


text:
package org.elasticsearch.xpack.core.security.authz.privilege;

import org.elasticsearch.xpack.core.security.authz.permission.ClusterPermission;

import java.util.Set;

/**
 * A {@link NamedClusterPrivilege} that can be used to define an access to cluster level actions.
 */
public class ActionClusterPrivilege implements NamedClusterPrivilege {
    private final String name;
    private final Set<String> allowedActionPatterns;
    private final Set<String> excludedActionPatterns;
    private final ClusterPermission permission;

    /**
     * Constructor for {@link ActionClusterPrivilege} defining what cluster actions are accessible for the user with this privilege.
     *
     * @param name                  name for the cluster privilege
     * @param allowedActionPatterns a set of cluster action patterns that are allowed for the user with this privilege.
     */
    public ActionClusterPrivilege(final String name, final Set<String> allowedActionPatterns) {
        this(name, allowedActionPatterns, Set.of());
    }

    /**
     * Constructor for {@link ActionClusterPrivilege} that defines what cluster actions are accessible for the
     * user with this privilege after excluding the action patterns {@code excludedActionPatterns} from the allowed action patterns
     * {@code allowedActionPatterns}
     *
     * @param name                   name for the cluster privilege
     * @param allowedActionPatterns  a set of cluster action patterns
     * @param excludedActionPatterns a set of cluster action patterns
     */
    public ActionClusterPrivilege(final String name, final Set<String> allowedActionPatterns, final Set<String> excludedActionPatterns) {
        this.name = name;
        this.allowedActionPatterns = allowedActionPatterns;
        this.excludedActionPatterns = excludedActionPatterns;
        this.permission = buildPermission(ClusterPermission.builder()).build();
    }

    @Override
    public String name() {
        return name;
    }

    public Set<String> getAllowedActionPatterns() {
        return allowedActionPatterns;
    }

    public Set<String> getExcludedActionPatterns() {
        return excludedActionPatterns;
    }

    @Override
    public ClusterPermission.Builder buildPermission(final ClusterPermission.Builder builder) {
        return builder.add(this, allowedActionPatterns, excludedActionPatterns);
    }

    @Override
    public ClusterPermission permission() {
        return permission;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PNetR;

namespace Ghost.Server.Objects
{
    public class ObjectManager
    {
        public void AddToWorld(BaseObject @object)
        {
            //throw new NotImplementedException();
        }

        public NetworkedSceneObjectView CreateSceneObject(ushort guid)
        {
            throw new NotImplementedException();
        }

        public bool TryGet<T>(Player player, out T @object)
            where T : BaseObject
        {
            throw new NotImplementedException();
        }
    }
}


text:
namespace SkodaShop.Web.Controllers
{
    using System.Web.Mvc;

    public class FAQController : Controller
    {
        // GET: FAQ
        public ActionResult Question()
        {
            return this.View();
        }
    }
}


text:
package eu.cloudopting.tosca.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.io.FileUtils;
import org.apache.xalan.extensions.XPathFunctionResolverImpl;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.jaxp.DocumentBuilderFactoryImpl;
import org.apache.xerces.jaxp.DocumentBuilderImpl;
import org.apache.xml.dtm.ref.DTMNodeList;
import org.apache.xpath.jaxp.XPathFactoryImpl;
import org.apache.xpath.jaxp.XPathImpl;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

@Service
public class CustomizationUtils {

	private final Logger log = LoggerFactory.getLogger(CustomizationUtils.class);

	private DocumentBuilderImpl db;
	private XPathImpl xpath;
	private HashMap<Long, DocumentImpl> xToscaHash = new HashMap<Long, DocumentImpl>();

	@Autowired
	private CSARUtils csarUtils;

	@Value("${spring.jcr.repo_http}")
	private String jackHttp;

	public CustomizationUtils() {
		super();
		XPathFactoryImpl xpathFactory = (XPathFactoryImpl) XPathFactoryImpl.newInstance();
		this.xpath = (XPathImpl) xpathFactory.newXPath();
		this.xpath.setNamespaceContext(new eu.cloudopting.tosca.xml.coNamespaceContext());

		this.xpath.setXPathFunctionResolver(new XPathFunctionResolverImpl());
		DocumentBuilderFactoryImpl dbf = new DocumentBuilderFactoryImpl();
		dbf.setNamespaceAware(true);

		try {
			this.db = (DocumentBuilderImpl) dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e2) {
			log.error("ParserConfigurationException in CustomizationUtils.CustomizationUtils");
			e2.printStackTrace();
		}
	}

	public String generateCustomizedTosca(Long idApp, String csarPath, JSONObject data, String organizationkey, String serviceName) {
		log.debug("CustomizationUtils.generateCustomizedTosca starting.");

		DocumentImpl theDoc = new DocumentImpl();
		// DocumentImpl theDoc = null;
		try {
			// theDoc = (DocumentImpl)getToscaTemplateDesc(idApp,
			// csarPath).clone();
			// getToscaTemplateDesc(idApp, csarPath).cloneNode(true);
			theDoc = (DocumentImpl) this.db.newDocument();
			Node an = theDoc.importNode(getToscaTemplateDesc(idApp, csarPath).getDocumentElement(), true);
			theDoc.appendChild(an);
			// theDoc.loadXML(getToscaTemplateDesc(idApp,
			// csarPath).saveXML(null));
			// theDoc = (DocumentImpl) this.db.parse(new InputSource(new
			// ByteArrayInputStream(getToscaTemplateDesc(idApp,
			// csarPath).saveXML(null).getBytes())));
		} catch (DOMException e1) {
			log.error("DOMException in CustomizationUtils.generateCustomizedTosca importing nodes.");
			e1.printStackTrace();
		}
		// log.debug(getToscaTemplateDesc(idApp, csarPath).saveXML(null));
		// theDoc.load(getToscaTemplateDesc(idApp, csarPath).saveXML(null));

		JSONObject properties = getUserInputs(theDoc, "xpath");
		log.debug("CustomizationUtils.generateCustomizedTosca xpath: " + properties.toString());

		Iterator dataNames = data.keys();
		while (dataNames.hasNext()) {
			String dataKey = dataNames.next().toString();
			log.debug("CustomizationUtils.generateCustomizedTosca dataKey: " + dataKey);
			DTMNodeList nodes = null;
			switch (dataKey) {
			case "co_is_trial":
			case "co_buy_platform":

				break;
			default:
				try {
					String xPathProcInt = properties.getString(dataKey);
					// xPathProcInt =
					// "//ns:NodeTemplate[@id='ClearoPostgreSQLDB']/ns:Properties/co:PostgreSQLDatabaseProperties/co:password";
					log.debug("CustomizationUtils.generateCustomizedTosca xPathProcInt: " + xPathProcInt);
					nodes = (DTMNodeList) this.xpath.evaluate(xPathProcInt, theDoc, XPathConstants.NODESET);
					log.debug("CustomizationUtils.generateCustomizedTosca nodes length: " + new Integer(nodes.getLength()).toString());
					log.debug("CustomizationUtils.generateCustomizedTosca dataKey: " + data.getString(dataKey));
					nodes.item(0).removeChild(nodes.item(0).getFirstChild());
					nodes.item(0).setTextContent(data.getString(dataKey));
				} catch (XPathExpressionException e) {
					log.error("XPathExpressionException in CustomizationUtils.generateCustomizedTosca.");
					e.printStackTrace();
				} catch (JSONException e) {
					log.error("JSONException in CustomizationUtils.generateCustomizedTosca.");
					e.printStackTrace();
				}
				log.debug("CustomizationUtils.generateCustomizedTosca nodes: " + nodes.toString());

				break;
			}

		}
		theDoc = getServUrl(theDoc, organizationkey, serviceName);
		// TODO need to fix that fact that now these do the same thing one will get to return the doc from URL
		theDoc = getServPath(theDoc, organizationkey, serviceName);
		log.debug("CustomizationUtils.generateCustomizedTosca theDoc: " + theDoc.saveXML(null));
		log.debug("CustomizationUtils.generateCustomizedTosca --------ORIGINAL--------: \n" + getToscaTemplateDesc(idApp, csarPath).saveXML(null));
		return theDoc.saveXML(null);
	}

	public JSONObject getCustomizationFormData(Long idApp, String csarPath) {
		log.debug("CustomizationUtils.getCustomizationFormData starting.");
		JSONObject jret = null;
		try {
			jret = new JSONObject(
					"{\"type\": \"object\",\"title\": \"Compute\",\"properties\": {\"idApp\":  {\"title\": \"Application ID\",\"type\": \"string\"}}}");
		} catch (JSONException e) {
			log.error("JSONException in CustomizationUtils.getCustomizationFormData creating a JSONObject.");
			e.printStackTrace();
		}
		DocumentImpl theDoc = getToscaTemplateDesc(idApp, csarPath);

		JSONObject properties = getUserInputs(theDoc, "form");
		log.debug("CustomizationUtils.getCustomizationFormData properties: " + properties.toString());

		// maybe keeping a hash for it so sequent calls can go faster (there
		// will be the instance generation)

		// csarUtils.getToscaTemplate("csisp/Clearo.czar", "/cloudOptingData/");
		// TODO dummy data return for now
		try {
			/*
			 * jret = new JSONObject(
			 * "{\"type\": \"object\",\"title\": \"Compute\",\"properties\": {\"node_id\":  {\"title\": \"Node ID\",\"type\": \"string\"},\"node_label\":  {\"title\": \"Node Label\",\"type\": \"string\",\"description\": \"Email will be used for evil.\"},\"memory\":  {\"title\": \"Memory\",\"type\": \"string\",\"enum\": [\"512\",\"1024\",\"2048\"]},\"cpu\": {\"title\": \"CPU\",\"type\": \"integer\",\"maxLength\": 20,\"validationMessage\": \"Dont be greedy!\"}},\"required\": [\"node_id\",\"node_label\",\"memory\", \"cpu\"]}"
			 * );
			 */
			jret = new JSONObject("{\"type\": \"object\",\"title\": \"Customize the service\"}");
			log.debug("CustomizationUtils.getCustomizationFormData jret: " + jret.toString());
			log.debug("CustomizationUtils.getCustomizationFormData properties: " + properties.toString());

			properties.put("co_is_trial", new JSONObject("{\"title\":\"Is trial\",\"type\":\"boolean\"}"));
			properties.put("co_buy_platform",
					new JSONObject("{\"title\":\"Buy also the cloud platform?\",\"type\":\"boolean\"}"));

			jret.put("properties", properties);

		} catch (JSONException e) {
			log.error("JSONException in CustomizationUtils.getCustomizationFormData creating a JSONObject.");
			e.printStackTrace();
		}
		return jret;

	}

	private JSONObject getUserInputs(DocumentImpl theDoc, String what) {
		log.debug("CustomizationUtils.getUserInputs starting.");
		log.debug("CustomizationUtils.getUserInputs theDoc: " + theDoc.saveXML(null));

		JSONObject properties = new JSONObject();
		DTMNodeList nodes = null;
		String xPathProcInt = "//processing-instruction('userInput')";
		try {
			nodes = (DTMNodeList) this.xpath.evaluate(xPathProcInt, theDoc, XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			log.error("XPathExpressionException in CustomizationUtils.getUserInputs evaluating xpath.");
			log.debug(e.getMessage());
			e.printStackTrace();
		}

		log.debug("CustomizationUtils.getUserInputs nodes with PI: " + new Integer(nodes.getLength()).toString());
		for (int i = 0; i < nodes.getLength(); ++i) {
			log.debug(nodes.item(i).getNodeValue());
			try {
				JSONObject field = new JSONObject(nodes.item(i).getNodeValue());
				String fieldName = field.keys().next().toString();
				log.debug("CustomizationUtils.getUserInputs fieldName: " + fieldName);
				switch (what) {
				case "form":
					properties.put(fieldName, field.getJSONObject(fieldName).getJSONObject(what));
					break;
				default:
					properties.put(fieldName, field.getJSONObject(fieldName).getString(what));
					break;
				}

			} catch (DOMException | JSONException e) {
				log.error("DOMException | JSONException in CustomizationUtils.getUserInputs.");
				e.printStackTrace();
			}

		}
		return properties;
	}

	private DocumentImpl getServUrl(DocumentImpl theDoc, String organizationkey, String serviceName) {
		log.debug("CustomizationUtils.getServUrl starting.");
		log.debug("CustomizationUtils.getServUrl theDoc: " + theDoc.saveXML(null));

		JSONObject properties = new JSONObject();
		DTMNodeList nodes = null;
		String xPathProcInt = "//processing-instruction('servUrl')";
		try {
			nodes = (DTMNodeList) this.xpath.evaluate(xPathProcInt, theDoc, XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			log.error("XPathExpressionException in CustomizationUtils.getServUrl evaluating xpath.");
			log.debug(e.getMessage());
			e.printStackTrace();
		}

		log.debug("CustomizationUtils.getServUrl nodes with PI: " + new Integer(nodes.getLength()).toString());
		for (int i = 0; i < nodes.getLength(); ++i) {
			log.debug("CustomizationUtils.getServUrl Item NodeValue: " + nodes.item(i).getNodeValue() + ", NodeName: " + nodes.item(i).getNodeName());
			Node father = nodes.item(i).getParentNode();
			log.debug("CustomizationUtils.getServUrl Item father NodeName: " + father.getNodeName());
			try {
				String fileName = new String(nodes.item(i).getNodeValue());
				log.debug("CustomizationUtils.getServUrl fileName: " + fileName);
				father.removeChild(nodes.item(i));
				father.setTextContent(jackHttp+organizationkey + "/" + serviceName + "/template/" + fileName);
			} catch (DOMException e) {
				log.error("DOMException in CustomizationUtils.getServUrl.");
				e.printStackTrace();
			}

		}
		return theDoc;
	}

	private DocumentImpl getServPath(DocumentImpl theDoc, String organizationkey, String serviceName) {
		log.debug("CustomizationUtils.getServUrl starting.");
		log.debug("CustomizationUtils.getServUrl theDoc: " + theDoc.saveXML(null));

		JSONObject properties = new JSONObject();
		DTMNodeList nodes = null;
		String xPathProcInt = "//processing-instruction('servPath')";
		try {
			nodes = (DTMNodeList) this.xpath.evaluate(xPathProcInt, theDoc, XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			log.error("XPathExpressionException in CustomizationUtils.getServPath evaluating xpath.");
			log.debug(e.getMessage());
			e.printStackTrace();
		}

		log.debug("CustomizationUtils.getServPath nodes with PI: " + new Integer(nodes.getLength()).toString());
		for (int i = 0; i < nodes.getLength(); ++i) {
			log.debug("CustomizationUtils.getServPath Item NodeValue: " + nodes.item(i).getNodeValue() + ", NodeName: " + nodes.item(i).getNodeName());
			Node father = nodes.item(i).getParentNode();
			log.debug("CustomizationUtils.getServPath Item father NodeName: " + father.getNodeName());
			try {
				String fileName = new String(nodes.item(i).getNodeValue());
				log.debug("CustomizationUtils.getServPath fileName: " + fileName);
				father.removeChild(nodes.item(i));
				father.setTextContent(jackHttp+organizationkey + "/" + serviceName + "/template/" + fileName);
			} catch (DOMException e) {
				log.error("DOMException in CustomizationUtils.getServPath.");
				e.printStackTrace();
			}

		}
		return theDoc;
	}

	private DocumentImpl getToscaTemplateDesc(Long idApp, String csarPath) {
		log.debug("CustomizationUtils.getToscaTemplateDesc starting.");

		DocumentImpl theDoc = this.xToscaHash.get(idApp);
		if (theDoc == null) {
			// need to read the Application and get the TOSCA file
			// Applications application = applicationService.findOne(idApp);
			// String csarPath = application.getApplicationToscaTemplate();
			log.debug("CustomizationUtils.getToscaTemplateDesc csarPath: " + csarPath);

			// unzip the csar
			String destinationPath = "/cloudOptingData/" + idApp;
			csarUtils.unzipToscaCsar(csarPath, destinationPath);

			// read the definition file
			String xmlDefinitionContent = csarUtils.getDefinitionFile(destinationPath);
			InputSource source = new InputSource(new StringReader(xmlDefinitionContent));
			DocumentImpl document = null;
			try {
				document = (DocumentImpl) this.db.parse(source);
				this.xToscaHash.put(idApp, document);
				theDoc = document;
				FileUtils.forceDelete(new File(destinationPath));
			} catch (SAXException e1) {
				log.error("SAXException in CustomizationUtils.getToscaTemplateDesc.");
				e1.printStackTrace();
			} catch (IOException e1) {
				log.error("IOException in CustomizationUtils.getToscaTemplateDesc.");
				e1.printStackTrace();
			}

		}
		log.debug("CustomizationUtils.getToscaTemplateDesc theDoc: " + theDoc.saveXML(null));
		return theDoc;
	}

}