text:
// Beginning of functions functions for add, edit, cancel save save actions for Evn variables and Labels
$(document).on('click', '.panel-heading a', function(e){
    var $this = $(this);
    if($this.hasClass('collapsed')) {
        $this.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
    } else  {
        $this.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
    }
});

$(document).on("click",".fw-cancel", function(e){ //user click on remove text
    var propBlock = $(this).parent('span').parent('div').parent('div');
    jagg.popMessage({type:'confirm', modalStatus: true, title:'Delete Tag',content:'Are you sure you want to delete this?',
        okCallback:function(){
            propBlock.remove();
        }, cancelCallback:function(){}
    });

});

$(document).on('click', '.fw-edit', function () {
    var propBlock = $(this).parent('span').parent('div').parent('div');
    propBlock.find('.element-key-holder')[0].readOnly = false;
    propBlock.find('.element-value-holder')[0].readOnly = false;
    $(this).hide();
    $(this).parent().find('.fw-save').show();
});

$(document).on('click', '.fw-save', function () {
    var propBlock = $(this).parent('span').parent('div').parent('div');
    propBlock.find('.element-key-holder')[0].readOnly = true;
    propBlock.find('.element-value-holder')[0].readOnly = true;
    $(this).hide();
    $(this).parent().find('.fw-edit').show();
});

$(document).on('change focusout keyup', '.element-add-value', function () {
    var value = $(this).val();
    var propHolder = $(this).parent('div').parent('div');
    var key = propHolder.find('.element-add-key').val();
    var addBtn = propHolder.find('.btn-primary-add-val');
    if(!value || !key){
        addBtn.prop("disabled" , true);
    } else {
        addBtn.prop("disabled" , false);
    }
});

$(document).on('change focusout keyup', '.element-add-key', function () {
    var key = $(this).val();
    var propHolder = $(this).parent('div').parent('div');
    var value = propHolder.find('.element-add-value').val();
    var addBtn = propHolder.find('.btn-primary-add-val');

    if(propHolder.parent('div').attr("id") == "env-pane"){
        $(this).rules("add", {
            validateEnvironmentVariable: true
        });

        if(validateEnvironmentVariable(key)){
            addBtn.prop("disabled" , false);
            propHolder.find('.element-add-value').prop("disabled" , false);
        } else {
            addBtn.prop("disabled" , true);
            propHolder.find('.element-add-value').prop("disabled" , true);
        }
    }

    if(!value || !key){
        addBtn.prop("disabled" , true);
    } else {
        addBtn.prop("disabled" , false);
    }
});

$(document).on('click', '.btn-primary-add-val', function () {
    activateCreateApplication();
    var addBlock = $(this).parent().parent();
    var key = addBlock.find('.element-add-key')[0].value;
    var value = addBlock.find('.element-add-value')[0].value;
    var paneId = addBlock.parent().attr('id');
    var initialValueElement = '<input type="text" class="form-control element-add-value" placeholder="Value">\n';
    if (paneId === "env-pane") {
        initialValueElement = '<select id="value" name="value" class="form-control select2 element-add-value"></select>\n';
    }
    drawInitialEnvTagPane(addBlock, key, value, initialValueElement);
});
function drawInitialEnvTagPane(addBlock, key, value, initialValueElement){
    var panelBody = addBlock.parent();
    panelBody.append(
        '
\n'+
        '
\n'+
        'Key\n'+
        '<input type="text" class="form-control element-key-holder" id="key" placeholder="Key" value="' + key + '" disabled>\n'+
        '
\n'+
        '
\n'+
        'Value\n'+
        '<input type="text" class="form-control element-value-holder" id="value" placeholder="Value" value="' + value + '" disabled>\n'+
        '
\n'+
        '
\n'+
        '\n'+
        '\n'+
        '\n'+
        '\n'+
        '
\n'+
        '
\n'
    );
    addBlock.remove();
    panelBody.prepend(
        '
\n'+
        '
\n'+
        'Key\n'+
        '<input type="text" class="form-control element-add-key" id="key" placeholder="Key">\n'+
        '
\n'+
        '
\n'+
        'Value\n'+
        initialValueElement +
        '
\n'+
        '
\n'+
        '<button class="btn btn-primary btn-primary-add btn-primary-add-val" disabled>Add</button>\n'+
        '
\n'+
        '
\n'
    );

    var valueElem = document.getElementById("value");
    initSelect2(null, valueElem, "");
}
function drawEnvTagPane(panelBody, key, value){
    panelBody.append(
        '
\n'+
        '
\n'+
        'Key\n'+
        '<input type="text" class="form-control element-key-holder" id="key" placeholder="Key" value="' + key + '">\n'+
        '
\n'+
        '
\n'+
        'Value\n'+
        '<input type="text" class="form-control element-value-holder" id="value" placeholder="Value" value="' + value + '">\n'+
        '
\n'+
        '
\n'+
        '\n'+
        '\n'+
        '\n'+
        '\n'+
        '
\n'+
        '
\n'
    );
}

/**
 * Get a json object array with key-val pair for given pane repsented by {@code elementId}
 * @param elementId
 * @returns {Array}
 */
function getProperties(elementId){
    var propArray =[];
    var panelBody = document.getElementById(elementId);
    $(panelBody).children('.prop-key-vals-holder').each(function(){
        var property = {};
        property["key"] = $(this).find('.element-key-holder')[0].value;
        property["value"] = $(this).find('.element-value-holder')[0].value;
        propArray.push(property);
    });
    return propArray;
}


text:
package models;

import com.itextpdf.text.DocumentException;
import interfaces.Converter;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.net.URL;
import java.util.Scanner;

public final class HTMLToPDF extends Converter {

    private final static String content = "

1 2

"
            + "import "
            + "interfaces.ProgressListener as Listener"
            + "from pygments.lexers import find_lexer_class"
            + "

";

    public static void main(String[] args) {
        String save = "./example123.pdf";
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(
                save))) {

            Converter conv = new HTMLToPDF();
            conv.convertDocumentFromContent(content, out);

        } catch (DocumentException | IOException e) {
            System.out.println("Can't open the folder");
        }
    }

    /**
     * @param content Valid HTML in a string
     * @param saveLoc A valid location to save the converted pdf
     */
    @Override
    public synchronized void convertDocumentFromContent(String content,
                                                        String saveLoc) throws IOException, DocumentException {

        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(
                saveLoc))) {

            ITextRenderer render = new ITextRenderer();
            render.setDocumentFromString(content);
            render.layout();
            render.createPDF(out);
        }
    }

    /**
     * @param content Valid HTML in a string
     * @param out     A (buffered) stream to write the pdf
     */
    @Override
    public synchronized void convertDocumentFromContent(String content,
                                                        OutputStream out) throws IOException, DocumentException {

        ITextRenderer render = new ITextRenderer();
        render.setDocumentFromString(content);
        render.layout();
        render.createPDF(out);
    }

    /**
     * @param content A url specifying a network location of the HTML file to
     *                read
     * @param out     A (buffered) stream to write the pdf
     */
    @Override
    public synchronized void convertDocumentFromURL(URL content,
                                                    OutputStream out) throws IOException, DocumentException {

        try (Scanner scanner = new Scanner(content.openStream())) {

            ITextRenderer render = new ITextRenderer();
            render.setDocument(scanner.useDelimiter("\\A").next());
            render.layout();
            render.createPDF(out);
        }
    }

    /**
     * @param content A url specifying a network location of the HTML file to
     *                read
     * @param saveLoc A valid location to save the pdf
     */
    @Override
    public synchronized void convertDocumentFromURL(URL content, String saveLoc)
            throws IOException, DocumentException {

        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(
                saveLoc)); Scanner scanner = new Scanner(content.openStream())) {

            ITextRenderer render = new ITextRenderer();
            render.setDocument(scanner.useDelimiter("\\A").next());
            render.layout();
            render.createPDF(out);
        }
    }

    /**
     * @param input   A (Buffered) input stream to read the file from
     * @param saveLoc A valid location to save the pdf
     */
    @Override
    public synchronized void convertDocumentFromStream(InputStream input,
                                                       String saveLoc) throws IOException, DocumentException {

        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(
                saveLoc)); Scanner scanner = new Scanner(input)) {

            ITextRenderer render = new ITextRenderer();
            render.setDocumentFromString(scanner.useDelimiter("\\A").next());
            render.layout();
            render.createPDF(out);
        }
    }

    /**
     * @param input A (Buffered) input stream to read the file from
     * @param out   A (buffered) stream to write the pdf
     */
    @Override
    public synchronized void convertDocumentFromStream(InputStream input,
                                                       OutputStream out) throws IOException, DocumentException {

        try (Scanner scanner = new Scanner(input)) {

            ITextRenderer render = new ITextRenderer();
            render.setDocumentFromString(scanner.useDelimiter("\\A").next());
            render.layout();
            render.createPDF(out);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.Management.Network.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// SKU of a public IP address.
    /// </summary>
    public partial class PublicIPAddressSku
    {
        /// <summary>
        /// Initializes a new instance of the PublicIPAddressSku class.
        /// </summary>
        public PublicIPAddressSku()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the PublicIPAddressSku class.
        /// </summary>
        /// <param name="name">Name of a public IP address SKU. Possible values
        /// include: 'Basic', 'Standard'</param>
        public PublicIPAddressSku(string name = default(string))
        {
            Name = name;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets name of a public IP address SKU. Possible values
        /// include: 'Basic', 'Standard'
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Tempest: Tempest::PeekReader Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Tempest

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

Public Member Functions |
List of all members

Tempest::PeekReader Class Reference

Inheritance diagram for Tempest::PeekReader:

  <map id="Tempest::PeekReader_map" name="Tempest::PeekReader_map">
<area href="class_tempest_1_1_i_device.html" alt="Tempest::IDevice" shape="rect" coords="0,56,164,80"/>
<area href="class_tempest_1_1_abstract_i_o_device.html" alt="Tempest::AbstractIODevice" shape="rect" coords="0,0,164,24"/>
</map>

Public Member Functions

 	PeekReader (IDevice &dev)

size_t 	readData (char *dest, size_t count)

void 	skip (size_t count)

size_t 	peek (size_t skip, char *dest, size_t maxSize) const

void 	commit ()

 Public Member Functions inherited from Tempest::IDevice

virtual char 	peek () const

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

io/iodevice.h

Tempest

PeekReader

Generated by

     1.8.12


text:
@extends('admin.posts.form')

@section('title')
    <h2>{!! trans('back/blog.post-edit') !!}</h2>
@stop

@section('form')
    {!! Form::model($post, ['route' => ['admin.posts.update', $post->id], 'method' => 'put', 'class' => 'form-horizontal form-label-left']) !!}
@endsection


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <createDate>2017-09-08T10:26:41Z</createDate>
    <introducedDate>2017-09-07</introducedDate>
    <committees>
      <billCommittees>
        <item>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-09-07T19:37:31Z</date>
            </item>
          </activities>
          <subcommittees />
          <name>Veterans' Affairs Committee</name>
          <type>Standing</type>
          <systemCode>ssva00</systemCode>
          <chamber>Senate</chamber>
        </item>
      </billCommittees>
    </committees>
    <recordedVotes />
    <calendarNumbers />
    <congress>115</congress>
    <title>Rural Veterans Travel Enhancement Act of 2017</title>
    <committeeReports />
    <titles>
      <item>
        <titleType>Short Titles as Introduced</titleType>
        <chamberCode />
        <title>Rural Veterans Travel Enhancement Act of 2017</title>
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Official Title as Introduced</titleType>
        <chamberCode />
        <title>A bill to amend title 38, United States Code, to make permanent the authority of the Secretary of Veterans Affairs to transport individuals to and from facilities of the Department of Veterans Affairs in connection with rehabilitation, counseling, examination, treatment, and care, and for other purposes.</title>
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Display Title</titleType>
        <chamberCode />
        <title>Rural Veterans Travel Enhancement Act of 2017</title>
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <chamberCode />
        <title>Rural Veterans Travel Enhancement Act of 2017</title>
        <parentTitleType />
        <chamberName />
      </item>
    </titles>
    <relatedBills>
      <item>
        <latestTitle>Rural Veterans Travel Enhancement Act of 2017</latestTitle>
        <latestAction>
          <actionDate>2017-09-08</actionDate>
          <text>Referred to the Subcommittee on Health.</text>
        </latestAction>
        <type>HR</type>
        <congress>115</congress>
        <relationshipDetails>
          <item>
            <type>Identical bill</type>
            <identifiedBy>CRS</identifiedBy>
          </item>
        </relationshipDetails>
        <number>3720</number>
      </item>
    </relatedBills>
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Armed Forces and National Security</name>
        </policyArea>
        <legislativeSubjects />
      </billSubjects>
    </subjects>
    <policyArea>
      <name>Armed Forces and National Security</name>
    </policyArea>
    <updateDate>2017-10-12T04:46:37Z</updateDate>
    <notes />
    <originChamber>Senate</originChamber>
    <summaries>
      <billSummaries />
    </summaries>
    <version>1.0.0</version>
    <billNumber>1775</billNumber>
    <cosponsors>
      <item>
        <lastName>MURRAY</lastName>
        <fullName>Sen. Murray, Patty [D-WA]</fullName>
        <party>D</party>
        <sponsorshipDate>2017-09-07</sponsorshipDate>
        <bioguideId>M001111</bioguideId>
        <middleName />
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <firstName>PATTY</firstName>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <lisID>1409</lisID>
          <bioguideId>M001111</bioguideId>
          <gpoId>8237</gpoId>
        </identifiers>
        <state>WA</state>
      </item>
    </cosponsors>
    <laws />
    <sponsors>
      <item>
        <party>D</party>
        <bioguideId>T000464</bioguideId>
        <firstName>Jon</firstName>
        <fullName>Sen. Tester, Jon [D-MT]</fullName>
        <state>MT</state>
        <identifiers>
          <lisID>1829</lisID>
          <bioguideId>T000464</bioguideId>
          <gpoId>8258</gpoId>
        </identifiers>
        <byRequestType />
        <lastName>Tester</lastName>
        <middleName />
      </item>
    </sponsors>
    <cboCostEstimates />
    <latestAction>
      <text>Read twice and referred to the Committee on Veterans' Affairs.</text>
      <links />
      <actionDate>2017-09-07</actionDate>
    </latestAction>
    <billType>S</billType>
    <actions>
      <actionByCounts>
        <senate>2</senate>
      </actionByCounts>
      <actionTypeCounts>
        <introducedInSenate>1</introducedInSenate>
        <referredToCommittee>1</referredToCommittee>
      </actionTypeCounts>
      <item>
        <actionDate>2017-09-07</actionDate>
        <committee>
          <systemCode>ssva00</systemCode>
          <name>Veterans' Affairs Committee</name>
        </committee>
        <links />
        <sourceSystem>
          0
          <name>Senate</name>
        </sourceSystem>
        <text>Read twice and referred to the Committee on Veterans' Affairs.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <committee />
        <text>Introduced in Senate</text>
        <actionDate>2017-09-07</actionDate>
        <links />
        <actionCode>10000</actionCode>
        <type>IntroReferral</type>
      </item>
    </actions>
    <amendments />
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
namespace NServiceBus.AcceptanceTests.Config
{
    using NServiceBus.AcceptanceTesting;
    using NServiceBus.AcceptanceTests.EndpointTemplates;
    using NServiceBus.Settings;
    using NUnit.Framework;

    public class When__startup_is_complete : NServiceBusAcceptanceTest
    {
        [Test]
        public void Configure_and_setting_should_be_available_via_DI()
        {
            var context = Scenario.Define<Context>()
                    .WithEndpoint<StartedEndpoint>()
                    .Done(c => c.IsDone)
                    .Run();

            Assert.True(context.ConfigureIsAvailable,"Configure should be available in DI");
            Assert.True(context.SettingIsAvailable, "Setting should be available in DI");
        }

        public class Context : ScenarioContext
        {
            public bool IsDone { get; set; }
            public bool ConfigureIsAvailable { get; set; }
            public bool SettingIsAvailable { get; set; }
        }

        public class StartedEndpoint : EndpointConfigurationBuilder
        {
            public StartedEndpoint()
            {
                EndpointSetup<DefaultServer>();
            }

            class AfterConfigIsComplete:IWantToRunWhenBusStartsAndStops
            {
                public Context Context { get; set; }

                public Configure Configure { get; set; }

                public ReadOnlySettings Settings { get; set; }

                public void Start()
                {
                    Context.ConfigureIsAvailable = Configure != null;

                    Context.SettingIsAvailable = Settings != null;

                    Context.IsDone = true;
                }

                public void Stop()
                {
                }
            }
        }
    }

}


text:
def get_temp_file(basename)
  require 'tempfile'
  f = Tempfile.new(basename)
  path = f.path
  f.close!()
  path
end

def supported_realms
  [:sg,:us]
end

# Returns the config for integration testing
def integration_test_config_filename
  filename = "#{File.dirname(__FILE__)}/../../#{RGovData::Config::BASE_NAME}"
  STDERR.puts "Running integration tests with config: #{filename}"
  filename
end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace必须指向Repository接口 -->
<mapper namespace="com.agileEAP.infrastructure.repository.DictRepository">
	<sql id="columns">
		ID as id,
		Name as name,
		Text as text,
		ParentID as parentID,
		SortOrder as sortOrder,
		Description as description
	</sql>

    <sql id="whereParams">
        <if test="id  != null">
            and ID =#{id}
        </if>
        <if test="name  != null">
            and Name like '${name}%'
        </if>
        <if test="text  != null">
            and Text like '${text}%'
        </if>
        <if test="parentID  != null">
            and ParentID =#{parentID}
        </if>
        <if test="beginSortOrder!=null">
            <![CDATA[ and  SortOrder >=#{ beginSortOrder}]]>
        </if>
    	    <if test="endSortOrder!=null">
            <![CDATA[ and  SortOrder <=#{ endSortOrder}]]>
         </if>
        <if test="description  != null">
            and Description like '${description}%'
        </if>
    </sql>

    <select id="get" parameterType="String" resultType="com.agileEAP.infrastructure.entity.Dict">
    	select
        <include refid="columns" />
    	from AB_Dict
    	where ID=#{id}
    </select>

    <insert id="save" parameterType="com.agileEAP.infrastructure.entity.Dict">
    	insert into  AB_Dict (
    	ID,Name,Text,ParentID,SortOrder,Description)
    	values (#{id},#{name},#{text},#{parentID},#{sortOrder},#{description})
    </insert>

    <insert id="update" parameterType="com.agileEAP.infrastructure.entity.Dict">
    	update AB_Dict set
    	Name=#{name},Text=#{text},ParentID=#{parentID},SortOrder=#{sortOrder},Description=#{description}
    	where ID=#{id}
    </insert>

    <delete id="delete" parameterType="String">
         delete from  AB_Dict where ID=#{id}
    </delete>

    <delete id="batchDelete" parameterType="list">
    	<![CDATA[
    		delete from AB_Dict where ID in
    	]]>
    	<foreach collection="list" item="id" open="(" separator="," close=")">
    		#{id}
    	</foreach>
    </delete>

	<select id="search" parameterType="map" resultType="com.agileEAP.infrastructure.entity.Dict">
		select
        <include refid="columns" />
		from AB_Dict where 1=1
        <include refid="whereParams"/>
	</select>

    <select id="count" parameterType="map" resultType="long">
		select count(*)
		from AB_Dict where 1=1
		<include refid="whereParams"/>
	</select>

    <select id="searchByPage" parameterType="map" resultType="com.agileEAP.infrastructure.entity.Dict">
		select
        <include refid="columns" />
		from AB_Dict where 1=1
        <include refid="whereParams"/>
    </select>
</mapper>


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft">
//   Copyright (c) 2013 Microsoft Corporation
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

namespace Microsoft.Research.DataOnboarding.Utilities.Model
{
    /// <summary>
    /// Class that represents Metadata.
    /// </summary>
    public class MetadataDetail
    {
        public string Name { get; set; }

        public string Type { get; set; }

        public bool IsRequired { get; set; }

        public string Description { get; set; }

        public string Value { get; set; }

        public float? MinimumAllowedValue { get; set; }

        public float? MaximumAllowedValue { get; set; }
    }

}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>BESA.Remote</title>
<meta name="date" content="2012-06-19">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

BESA.Remote

Interfaces

AdmRemoteInterfaceBESA

Classes

AdmRemoteImpBESA

DistributedInitBESA

PingSocketThread

PingThread

PongSocketThread

PongThread

RemoteAdmBESA

SocketServer

SocketServerThread

Exceptions

DistributedExceptionBESA


text:
<?xml version="1.0" encoding="UTF-8"?>
<pools
xmlns="urn:didata.com:api:cloud:types" pageNumber="1" pageCount="2"
totalCount="2" pageSize="250">
<pool id="4d360b1f-bc2c-4ab7-9884-1f03ba2768f7" datacenterId="NA9">
<networkDomainId>553f26b6-2a73-42c3-a78b-
6116f11291d0</networkDomainId>
<name>myDevelopmentPool.1</name>
<description>Pool for load balancing development application
servers.</description>
<loadBalanceMethod>ROUND_ROBIN</loadBalanceMethod>
<healthMonitor id="01683574-d487-11e4-811f-005056806999"
name="CCDEFAULT.Http"/>
<healthMonitor id="0168546c-d487-11e4-811f-005056806999"
name="CCDEFAULT.Https"/>
<serviceDownAction>RESELECT</serviceDownAction>
<slowRampTime>10</slowRampTime>
<state>NORMAL</state>
<createTime>2015-06-04T09:15:07.000Z</createTime>
</pool>
<pool id="afb1fb1a-eab9-43f4-95c2-36a4cdda6cb8" datacenterId="NA9">
<networkDomainId>553f26b6-2a73-42c3-a78b-
6116f11291d0</networkDomainId>
<name>myProductionPool.1</name>
<description>Pool for load balancing production application
servers.</description>
<loadBalanceMethod>ROUND_ROBIN</loadBalanceMethod>
<healthMonitor id="01683574-d487-11e4-811f-005056806999"
name="CCDEFAULT.Http"/>
<healthMonitor id="0168546c-d487-11e4-811f-005056806999"
name="CCDEFAULT.Https"/>
<serviceDownAction>NONE</serviceDownAction>
<slowRampTime>10</slowRampTime>
<state>NORMAL</state>
<createTime>2015-06-03T14:11:17.000Z</createTime>
</pool>
</pools>


text:
import io
import os
import re
import tempfile
import time
import warnings
from contextlib import contextmanager
from typing import Optional

from selenium.webdriver.common.alert import Alert
from selenium.common.exceptions import (
    ElementClickInterceptedException,
    NoSuchElementException,
    WebDriverException,
    StaleElementReferenceException,
    TimeoutException,
    MoveTargetOutOfBoundsException,
)
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC  # NOQA: N812
from selenium.webdriver.support.ui import WebDriverWait

from splinter.driver import DriverAPI, ElementAPI
from splinter.driver.find_links import FindLinks
from splinter.driver.xpath_utils import _concat_xpath_from_str
from splinter.element_list import ElementList
from splinter.driver.webdriver.cookie_manager import CookieManager
from splinter.exceptions import ElementDoesNotExist
from splinter.retry import _retry

# Patch contextmanager onto Selenium's Alert
def alert_enter(self):
    return self

def alert_exit(self, type, value, traceback):  # NOQA: A002
    pass

Alert.__enter__ = alert_enter
Alert.__exit__ = alert_exit
Alert.fill_with = Alert.send_keys

class switch_window:  # NOQA: N801
    def __init__(self, browser, window_handle):
        self.browser = browser
        self.window_handle = window_handle

    def __enter__(self):
        self.current_window_handle = self.browser.driver.current_window_handle
        self.browser.driver.switch_to.window(self.window_handle)

    def __exit__(self, type, value, traceback):  # NOQA: A002
        if self.current_window_handle in self.browser.driver.window_handles:
            self.browser.driver.switch_to.window(self.current_window_handle)

class Window:
    """ A class representing a browser window """

    def __init__(self, browser, name):
        self._browser = browser
        self.name = name

    @property
    def title(self):
        """ The title of this window """
        with switch_window(self._browser, self.name):
            return self._browser.title

    @property
    def url(self):
        """ The url of this window """
        with switch_window(self._browser, self.name):
            return self._browser.url

    @property
    def index(self):
        """ The index of this window in browser.windows """
        return self._browser.driver.window_handles.index(self.name)

    @property
    def prev(self):
        """ Return the previous window """
        prev_index = self.index - 1
        prev_handle = self._browser.driver.window_handles[prev_index]
        return Window(self._browser, prev_handle)

    @property  # NOQA: A003
    def next(self):  # NOQA: A003
        """ Return the next window """
        next_index = (self.index + 1) % len(self._browser.driver.window_handles)
        next_handle = self._browser.driver.window_handles[next_index]
        return Window(self._browser, next_handle)

    def is_current():
        doc = "Whether this window is currently the browser's active window."

        def fget(self):
            return self._browser.driver.current_window_handle == self.name

        def fset(self, value):
            if value is True:
                self._browser.driver.switch_to.window(self.name)
            else:
                raise TypeError("can only set to True")

        return locals()

    is_current = property(**is_current())

    def new_tab(self, url):
        """ Open new tab in current window """
        if self._browser.driver.name == 'firefox':
            self._browser.driver.get('about:config')
            self._browser.driver.execute_script('document.getElementById("warningButton").click();')
            self._browser.driver.execute_script(
                """
                Components.classes['@mozilla.org/preferences-service;1']
                    .getService(Components.interfaces.nsIPrefBranch)
                    .setIntPref('browser.link.open_newwindow', 3);
                """)

        self._browser.driver.execute_script("window.open('%s', '_blank');" % url)

        if self._browser.driver.name == 'firefox':
            self._browser.driver.execute_script(
                """
                Components.classes['@mozilla.org/preferences-service;1']
                    .getService(Components.interfaces.nsIPrefBranch)
                    .setIntPref('browser.link.open_newwindow', 2);
                """)
            self._browser.driver.back()

    def close(self):
        """ Close this window. If this window is active, switch to previous window """
        target = self.prev if (self.is_current and self.prev != self) else None

        with switch_window(self._browser, self.name):
            self._browser.driver.close()

        if target is not None:
            target.is_current = True

    def close_others(self):
        self.is_current = True
        for window in self._browser.windows:
            if window != self:
                window.close()

    def __eq__(self, other):
        return self._browser == other._browser and self.name == other.name

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return "<Window %s: %s>" % (self.name, self.url)

class Windows:

    """ A class representing all open browser windows """

    def __init__(self, browser):
        self._browser = browser

    def __len__(self):
        return len(self._browser.driver.window_handles)

    def __getitem__(self, key):
        window_handles = self._browser.driver.window_handles
        try:
            return Window(self._browser, window_handles[key])
        except TypeError:
            if key not in window_handles:
                raise KeyError(key)
            return Window(self._browser, key)

    def current():
        doc = "The currently active window"

        def fget(self):
            current_handle = self._browser.driver.current_window_handle
            return Window(self._browser, current_handle) if current_handle else None

        def fset(self, value):
            self._browser.driver.switch_to.window(value.name)

        return locals()

    current = property(**current())

    def __repr__(self):
        return str(
            [
                Window(self._browser, handle)
                for handle in self._browser.driver.window_handles
            ]
        )

def _find(self, finder, finder_kwargs=None):
    """Search for elements. Returns a list of results.

    Arguments:
        finder: The function to use for the element search.
        finder_kwargs: Keyword Arguments for the finder function.

    Returns:
        list

    """
    finder_kwargs = finder_kwargs or {}

    elements = None
    elem_list = []

    try:
        elements = finder(**finder_kwargs)
        if not isinstance(elements, list):
            elements = [elements]

    except (
        NoSuchElementException,
        StaleElementReferenceException,
    ):
        # This exception is sometimes thrown if the page changes
        # quickly
        pass

    if elements:
        elem_list = [self.element_class(element, self, finder_kwargs) for element in elements]

    return elem_list

def find_by(
    self,
    finder,
    finder_kwargs=None,
    original_find: str = None,
    original_query: str = None,
    wait_time: int = None,
):
    """Wrapper for finding elements.

    Must be attached to a class.

    Returns:
        ElementList

    """
    elem_list = []

    find_by = original_find or finder_kwargs['by']
    query = original_query or finder_kwargs.get('value')

    # Zero second wait time means only check once
    if wait_time == 0:
        elem_list = _find(self, finder, finder_kwargs)
    else:
        wait_time = wait_time or self.wait_time
        end_time = time.time() + wait_time

        while time.time() < end_time:
            elem_list = _find(self, finder, finder_kwargs)

            if elem_list:
                break

    return ElementList(elem_list, find_by=find_by, query=query)

class BaseWebDriver(DriverAPI):
    driver = None
    find_by = find_by

    def __init__(self, driver=None, wait_time=2):
        self.wait_time = wait_time

        self.links = FindLinks(self)

        self.driver = driver
        self._find_elements = self.driver.find_elements

        self.element_class = WebDriverElement

        self._cookie_manager = CookieManager(self.driver)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.quit()

    @property
    def title(self):
        return self.driver.title

    @property
    def html(self):
        return self.driver.page_source

    @property
    def url(self):
        return self.driver.current_url

    @property
    def status_code(self):
        raise NotImplementedError

    def visit(self, url):
        self.driver.get(url)

    def back(self):
        self.driver.back()

    def forward(self):
        self.driver.forward()

    def reload(self):
        self.driver.refresh()

    def execute_script(self, script, *args):
        return self.driver.execute_script(script, *args)

    def evaluate_script(self, script, *args):
        return self.driver.execute_script("return %s" % script, *args)

    def is_element_visible_by_css(self, css_selector, wait_time=None):
        warnings.warn(
            f'browser.is_element_visible_by_css({css_selector}, {wait_time}) is deprecated.'
            f' Use browser.find_by_css({css_selector}).is_visible({wait_time}) instead.',
            FutureWarning,
        )
        return self.find_by_css(css_selector, wait_time).is_visible(wait_time)

    def is_element_not_visible_by_css(self, css_selector, wait_time=None):
        warnings.warn(
            f'browser.is_element_not_visible_by_css({css_selector}, {wait_time}) is deprecated.'
            f' Use browser.find_by_css({css_selector}).is_not_visible({wait_time}) instead.',
            FutureWarning,
        )
        return self.find_by_css(css_selector, wait_time).is_not_visible(wait_time)

    def is_element_visible_by_xpath(self, xpath, wait_time=None):
        warnings.warn(
            f'browser.is_element_visible_by_xpath({xpath}, {wait_time}) is deprecated.'
            f' Use browser.find_by_xpath({xpath}).is_visible({wait_time}) instead.',
            FutureWarning,
        )
        return self.find_by_xpath(xpath, wait_time).is_visible(wait_time)

    def is_element_not_visible_by_xpath(self, xpath, wait_time=None):
        warnings.warn(
            f'browser.is_element_not_visible_by_xpath({xpath}, {wait_time}) is deprecated.'
            f' Use browser.find_by_xpath({xpath}).is_not_visible({wait_time}) instead.',
            FutureWarning,
        )
        return self.find_by_xpath(xpath, wait_time).is_not_visible(wait_time)

    def is_element_present(self, finder, selector, wait_time=None):
        wait_time = wait_time or self.wait_time
        end_time = time.time() + wait_time

        while time.time() < end_time:
            if finder(selector, wait_time=wait_time):
                return True
        return False

    def is_element_not_present(self, finder, selector, wait_time=None):
        wait_time = wait_time or self.wait_time
        end_time = time.time() + wait_time

        while time.time() < end_time:
            if not finder(selector, wait_time=0):
                return True
        return False

    def is_element_present_by_css(self, css_selector, wait_time=None):
        return self.is_element_present(self.find_by_css, css_selector, wait_time)

    def is_element_not_present_by_css(self, css_selector, wait_time=None):
        return self.is_element_not_present(self.find_by_css, css_selector, wait_time)

    def is_element_present_by_xpath(self, xpath, wait_time=None):
        return self.is_element_present(self.find_by_xpath, xpath, wait_time)

    def is_element_not_present_by_xpath(self, xpath, wait_time=None):
        return self.is_element_not_present(self.find_by_xpath, xpath, wait_time)

    def is_element_present_by_tag(self, tag, wait_time=None):
        return self.is_element_present(self.find_by_tag, tag, wait_time)

    def is_element_not_present_by_tag(self, tag, wait_time=None):
        return self.is_element_not_present(self.find_by_tag, tag, wait_time)

    def is_element_present_by_name(self, name, wait_time=None):
        return self.is_element_present(self.find_by_name, name, wait_time)

    def is_element_not_present_by_name(self, name, wait_time=None):
        return self.is_element_not_present(self.find_by_name, name, wait_time)

    def is_element_present_by_value(self, value, wait_time=None):
        return self.is_element_present(self.find_by_value, value, wait_time)

    def is_element_not_present_by_value(self, value, wait_time=None):
        return self.is_element_not_present(self.find_by_value, value, wait_time)

    def is_element_present_by_text(self, text, wait_time=None):
        return self.is_element_present(self.find_by_text, text, wait_time)

    def is_element_not_present_by_text(self, text, wait_time=None):
        return self.is_element_not_present(self.find_by_text, text, wait_time)

    def is_element_present_by_id(self, id, wait_time=None):  # NOQA: A002
        return self.is_element_present(self.find_by_id, id, wait_time)

    def is_element_not_present_by_id(self, id, wait_time=None):  # NOQA: A002
        return self.is_element_not_present(self.find_by_id, id, wait_time)

    def get_alert(self, wait_time=None):
        wait_time = wait_time or self.wait_time

        try:
            alert = WebDriverWait(self.driver, wait_time).until(EC.alert_is_present())
            return alert
        except TimeoutException:
            return None

    def _is_text_present(self, text):
        try:
            self.find_by_tag("body").text.index(text)
            return True
        except (NoSuchElementException, StaleElementReferenceException, ValueError):
            # NoSuchElementException will be thrown if the body tag isn't present
            # Can occur if the page isn't fully loaded yet.
            # StaleElementReferenceException will be thrown if the page changes quickly
            pass
        return False

    def is_text_present(self, text, wait_time=None):
        wait_time = wait_time or self.wait_time
        end_time = time.time() + wait_time

        while time.time() < end_time:
            if self._is_text_present(text):
                return True
        return False

    def is_text_not_present(self, text, wait_time=None):
        wait_time = wait_time or self.wait_time
        end_time = time.time() + wait_time

        while time.time() < end_time:
            if not self._is_text_present(text):
                return True
        return False

    @contextmanager
    def get_iframe(self, frame_reference):

        # If a WebDriverElement is provided, send the underlying element
        if isinstance(frame_reference, WebDriverElement):
            frame_reference = frame_reference._element

        self.driver.switch_to.frame(frame_reference)

        try:
            yield self
        finally:
            self.driver.switch_to.frame(None)

    def find_option_by_value(self, value):
        return self.find_by_xpath(
            '//option[@value="%s"]' % value,
            original_find="option by value",
            original_query=value,
        )

    def find_option_by_text(self, text):
        return self.find_by_xpath(
            '//option[normalize-space(text())="%s"]' % text,
            original_find="option by text",
            original_query=text,
        )

    def find_by_css(self, css_selector, wait_time=None):
        return self.find_by(
            self.driver.find_elements,
            finder_kwargs={'by': By.CSS_SELECTOR, 'value': css_selector},
            original_find="css",
            original_query=css_selector,
            wait_time=wait_time,
        )

    def find_by_xpath(self, xpath, original_find="xpath", original_query=None, wait_time=None):
        original_query = original_query or xpath
        return self.find_by(
            self.driver.find_elements,
            finder_kwargs={'by': By.XPATH, 'value': xpath},
            original_find=original_find,
            original_query=original_query,
            wait_time=wait_time,
        )

    def find_by_name(self, name, wait_time=None):
        return self.find_by(
            self.driver.find_elements,
            finder_kwargs={'by': By.NAME, 'value': name},
            original_find='name',
            wait_time=wait_time,
        )

    def find_by_tag(self, tag, wait_time=None):
        return self.find_by(
            self.driver.find_elements,
            finder_kwargs={'by': By.TAG_NAME, 'value': tag},
            original_find='tag_name',
            wait_time=wait_time,
        )

    def find_by_value(self, value, wait_time=None):
        elem = self.find_by_xpath(
            '//*[@value="{}"]'.format(value),
            original_find="value",
            original_query=value,
            wait_time=wait_time,
        )
        if elem:
            return elem
        return self.find_by_xpath('//*[.="%s"]' % value)

    def find_by_text(self, text=None, wait_time=None):
        xpath_str = _concat_xpath_from_str(text)
        return self.find_by_xpath(
            xpath_str,
            original_find="text",
            original_query=text,
            wait_time=wait_time,
        )

    def find_by_id(self, id, wait_time=None):  # NOQA: A002
        return self.find_by(
            self.driver.find_element,
            finder_kwargs={'by': By.ID, 'value': id},
            original_find='id',
            wait_time=wait_time,
        )

    def fill(self, name, value):
        field = self.find_by_name(name).first
        field.value = value

    attach_file = fill

    def fill_form(self, field_values, form_id=None, name=None, ignore_missing=False):
        form = None

        if name is not None:
            form = self.find_by_name(name)
        if form_id is not None:
            form = self.find_by_id(form_id)

        for name, value in field_values.items():
            try:
                if form:
                    elements = form.find_by_name(name)
                else:
                    elements = self.find_by_name(name)
                element = elements.first
                if (
                    element["type"] in ["text", "password", "tel"]
                    or element.tag_name == "textarea"
                ):
                    element.value = value
                elif element["type"] == "checkbox":
                    if value:
                        element.check()
                    else:
                        element.uncheck()
                elif element["type"] == "radio":
                    for field in elements:
                        if field.value == value:
                            field.click()
                elif element._element.tag_name == "select":
                    element.select(value)
                else:
                    element.value = value
            except ElementDoesNotExist as e:
                if not ignore_missing:
                    raise ElementDoesNotExist(e)

    def type(self, name, value, slowly=False):  # NOQA: A003
        element = self.find_by_name(name).first._element
        if slowly:
            return TypeIterator(element, value)
        element.send_keys(value)
        return value

    def choose(self, name, value):
        fields = self.find_by_name(name)
        for field in fields:
            if field.value == value:
                field.click()

    def check(self, name):
        self.find_by_name(name).first.check()

    def uncheck(self, name):
        self.find_by_name(name).first.uncheck()

    def screenshot(self, name="", suffix=".png", full=False, unique_file=True):
        filename = '{}{}'.format(name, suffix)

        if unique_file:
            (fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
            # Don't hold the file
            os.close(fd)

        if full:
            ori_window_size = self.driver.get_window_size()
            self.full_screen()

        self.driver.get_screenshot_as_file(filename)

        if full:
            self.recover_screen(ori_window_size)

        return filename

    def html_snapshot(self, name="", suffix=".html", encoding='utf-8', unique_file=True):
        filename = '{}{}'.format(name, suffix)

        if unique_file:
            (fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
            # Don't hold the file
            os.close(fd)

        with io.open(filename, 'w', encoding=encoding) as f:
            f.write(self.html)

        return filename

    def select(self, name, value):
        self.find_by_xpath(
            '//select[@name="%s"]//option[@value="%s"]' % (name, value)
        ).first._element.click()

    def select_by_text(self, name, text):
        self.find_by_xpath(
            '//select[@name="%s"]/option[text()="%s"]' % (name, text)
        ).first._element.click()

    def quit(self):  # NOQA: A003
        try:
            self.driver.quit()
        except WebDriverException:
            pass

    def full_screen(self):
        width = self.driver.execute_script("return Math.max(document.body.scrollWidth, document.body.offsetWidth);")
        height = self.driver.execute_script("return Math.max(document.body.scrollHeight, document.body.offsetHeight);")
        self.driver.set_window_size(width, height)

    def recover_screen(self, size):
        width = size.get('width')
        height = size.get('height')
        self.driver.set_window_size(width, height)

    @property
    def cookies(self):
        return self._cookie_manager

    @property
    def windows(self):
        return Windows(self)

class TypeIterator(object):
    def __init__(self, element, keys):
        self._element = element
        self._keys = keys

    def __iter__(self):
        for key in self._keys:
            self._element.send_keys(key)
            yield key

class ShadowRootElement(ElementAPI):
    find_by = find_by

    def __init__(self, element, parent):
        self._element = element
        self.parent = parent

        self.driver = self.parent.driver
        self.wait_time = self.parent.wait_time
        self.element_class = self.parent.element_class

    def _find(self, by: By, selector, wait_time=None):
        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': by, 'value': selector},
            wait_time=wait_time,
        )

    def find_by_css(self, selector, wait_time=None):
        return self._find(By.CSS_SELECTOR, selector, wait_time)

    def find_by_id(self, selector, wait_time=None):
        return self._find(By.ID, selector, wait_time)

    def find_by_name(self, selector, wait_time=None):
        return self._find(By.NAME, selector, wait_time)

    def find_by_tag(self, selector, wait_time=None):
        return self._find(By.TAG_NAME, selector, wait_time)

class WebDriverElement(ElementAPI):
    find_by = find_by

    def __init__(self, element, parent, finder_kwargs):
        self._element = element
        self.parent = parent

        self._find_elements = self._element.find_elements
        self._finder_kwargs = finder_kwargs

        self.driver = self.parent.driver
        self.wait_time = self.parent.wait_time
        self.element_class = self.parent.element_class

        self.links = FindLinks(self)

    def _get_value(self):
        return self["value"] or self._element.text

    def _set_value(self, value):
        if self._element.get_attribute("type") != "file":
            self._element.clear()
        self._element.send_keys(value)

    value = property(_get_value, _set_value)

    def __getitem__(self, attr):
        return self._element.get_attribute(attr)

    @property
    def text(self):
        return self._element.text

    @property
    def tag_name(self):
        return self._element.tag_name

    def clear(self):
        if self._element.get_attribute("type") in [
            "email",
            "number",
            "password",
            "search",
            "tel",
            "text",
            "textarea",
            "url",
        ]:
            self._element.clear()

    def fill(self, value):
        self.value = value

    def select(self, value=None, text=None):
        finder = None
        search_value = None

        if text:
            finder = 'text()'
            search_value = text
        elif value:
            finder = '@value'
            search_value = value

        self.find_by_xpath(
            './/option[{}="{}"]'.format(finder, search_value)
        )._element.click()

    def select_by_text(self, text):
        self.select(text=text)

    def type(self, value, slowly=False):  # NOQA: A003
        if slowly:
            return TypeIterator(self._element, value)

        self._element.send_keys(value)
        return value

    def click(self):
        """Click an element.

        If the element is not interactive due to being covered by another
         element, the click will retry for self.parent.wait_time amount of
         time.
        """
        end_time = time.time() + self.parent.wait_time
        error = None
        while time.time() < end_time:
            try:
                return self._element.click()
            except (
                ElementClickInterceptedException,
                WebDriverException,
            ) as e:
                error = e

        raise error

    def check(self):
        if not self.checked:
            self.click()

    def uncheck(self):
        if self.checked:
            self.click()

    @property
    def checked(self):
        return self._element.is_selected()

    selected = checked

    @property
    def visible(self):
        return self._element.is_displayed()

    @property
    def html(self):
        return self["innerHTML"]

    @property
    def outer_html(self):
        return self["outerHTML"]

    def _refresh_element(self, wait_time: Optional[int] = None):
        """Search for the element and update the internal reference.

        Returns:
            WebDriverElement

        Raises:
            ElementDoesNotExist
        """
        element_list = self.find_by(
            self.parent._find_elements,
            finder_kwargs=self._finder_kwargs,
            original_find=self._finder_kwargs['by'],
            wait_time=wait_time,
        )

        # Ensure the correct element is picked and replace old element
        for elem in element_list:
            new_element = elem._element

            if new_element == self._element:
                self._element = new_element
                return self

        raise ElementDoesNotExist("Element was removed from DOM.")

    def is_visible(self, wait_time=None):
        wait_time = wait_time or self.wait_time

        def search() -> bool:
            # Element is refreshed to account for changes to the page.
            self._refresh_element(wait_time=0)

            try:
                result = self.visible
            # StaleElementReferenceException occurs if element is found
            # but changes before visible is checked
            except StaleElementReferenceException:
                return False

            if result:
                return True

            return False

        return _retry(search, timeout=wait_time)

    def is_not_visible(self, wait_time=None):
        wait_time = wait_time or self.wait_time

        def search() -> bool:
            # Element is refreshed to account for changes to the page.
            self._refresh_element(wait_time=0)

            try:
                result = self.visible
            # StaleElementReferenceException occurs if element is found
            # but changes before visible is checked
            except StaleElementReferenceException:
                return False

            if result:
                return False

            return True

        return _retry(search, timeout=wait_time)

    def find_by_css(self, selector, wait_time=None):
        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': By.CSS_SELECTOR, 'value': selector},
            original_find="css",
            wait_time=wait_time,
        )

    def find_by_xpath(self, selector, wait_time=None, original_find="xpath", original_query=None):
        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': By.XPATH, 'value': selector},
            original_find=original_find,
            original_query=original_query,
            wait_time=wait_time,
        )

    def find_by_name(self, selector, wait_time=None):
        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': By.NAME, 'value': selector},
            original_find="name",
            wait_time=wait_time,
        )

    def find_by_tag(self, selector, wait_time=None):
        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': By.TAG_NAME, 'value': selector},
            original_find="tag",
            wait_time=wait_time,
        )

    def find_by_value(self, value, wait_time=None):
        selector = '[value="{}"]'.format(value)

        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': By.CSS_SELECTOR, 'value': selector},
            original_find="value",
            original_query=value,
            wait_time=wait_time,
        )

    def find_by_text(self, text, wait_time=None):
        # Add a period to the xpath to search only inside the parent.
        xpath_str = '.{}'.format(_concat_xpath_from_str(text))

        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': By.XPATH, 'value': xpath_str},
            original_find="text",
            original_query=text,
            wait_time=wait_time,
        )

    def find_by_id(self, selector, wait_time=None):
        return self.find_by(
            self._element.find_elements,
            finder_kwargs={'by': By.ID, 'value': selector},
            original_find="id",
            wait_time=wait_time,
        )

    def has_class(self, class_name):
        return bool(
            re.search(r"(?:^|\s)" + re.escape(class_name) + r"(?:$|\s)", self["class"])
        )

    def scroll_to(self):
        """Scroll to the current element."""
        self.driver.execute_script("arguments[0].scrollIntoView(true);", self._element)

    def mouse_over(self):
        """Perform a mouse over the element."""
        self.scroll_to()
        ActionChains(self.driver).move_to_element(self._element).perform()

    def mouse_out(self):
        """Perform a mouse out the element."""
        self.scroll_to()
        size = self._element.size

        try:
            # Fails on left edge of viewport
            ActionChains(self.driver).move_to_element_with_offset(
                self._element, -10, -10).click().perform()
        except MoveTargetOutOfBoundsException:
            try:
                ActionChains(self.driver).move_to_element_with_offset(
                    self._element, size['width'] + 10, 10).click().perform()
            except MoveTargetOutOfBoundsException:
                ActionChains(self.driver).move_to_element_with_offset(
                    self._element, 10, size['height'] + 10).click().perform()

    def double_click(self):
        """Perform a double click in the element."""
        self.scroll_to()
        ActionChains(self.driver).double_click(self._element).perform()

    def right_click(self):
        """Perform a right click in the element."""
        self.scroll_to()
        ActionChains(self.driver).context_click(self._element).perform()

    def drag_and_drop(self, droppable):
        """Drag an element to another element."""
        self.scroll_to()
        ActionChains(self.driver).drag_and_drop(self._element, droppable._element).perform()

    def _full_screen(self):
        width = self.driver.execute_script("return Math.max(document.body.scrollWidth, document.body.offsetWidth);")
        height = self.driver.execute_script("return Math.max(document.body.scrollHeight, document.body.offsetHeight);")
        self.driver.set_window_size(width, height)

    def screenshot(self, name='', suffix='.png', full=False, unique_file=True):

        filename = '{}{}'.format(name, suffix)

        if unique_file:
            (fd, filename) = tempfile.mkstemp(prefix=name, suffix=suffix)
            # don't hold the file
            os.close(fd)

        if full:
            ori_window_size = self.driver.get_window_size()
            self._full_screen()

        self._element.screenshot(filename)

        if full:
            # Restore screen size
            width = ori_window_size.get('width')
            height = ori_window_size.get('height')
            self.driver.set_window_size(width, height)

        return filename

    @property
    def shadow_root(self) -> ShadowRootElement:
        shadow_root = self._element.shadow_root
        return ShadowRootElement(shadow_root, self)


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Minimal JS Front-End App Example</title>

Public Library: Update a book record

  <form id="Book" action="">

      Select book:
        <select name="selectBook"><option value=""> --- </option></select>

ISBN: <output name="isbn" />

Title: <input name="title" />

Year: <input name="year" />

<button type="button" name="commit">Save Changes</button>

  </form>
  Back to main menu


text:
package eu.f3rog.blade.compiler.mvp;

import java.util.Set;

import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;

import eu.f3rog.blade.compiler.BaseProcessorModule;
import eu.f3rog.blade.compiler.builder.ClassManager;
import eu.f3rog.blade.compiler.util.ProcessorError;

/**
 * Class {@link MvpProcessorModule}
 *
 * @author FrantisekGazo
 */
public final class MvpProcessorModule
        extends BaseProcessorModule {

    @Override
    public void prepare() throws ProcessorError {
        try {
            // check if dagger dependency is present
            Class inject = Class.forName("javax.inject.Inject");
            Class membersInjector = Class.forName("dagger.internal.MembersInjectors");
        } catch (Exception e) {
            throw new ProcessorError(null, MvpErrorMsg.Missing_dagger_dependency);
        }
    }

    @Override
    public void process(TypeElement bladeElement) throws ProcessorError {
        ClassManager.getInstance()
                .getHelper(bladeElement)
                .tryGetModule(PresenterHelperModule.class);
    }

    @Override
    public void process(RoundEnvironment roundEnv) throws ProcessorError {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Inject.class);
        for (final Element e : elements) {
            // process only field injections
            if (e.getKind() != ElementKind.FIELD) {
                continue;
            }

            TypeElement typeElement = (TypeElement) e.getEnclosingElement();

            PresenterHelperModule module = ClassManager.getInstance()
                    .getHelper(typeElement)
                    .tryGetModule(PresenterHelperModule.class);
            if (module != null) {
                module.add((VariableElement) e);
            }
        }
    }

}


text:
var _ = require('underscore');

module.exports = function (storageDriver, mongoFieldService) {
    return {
        entity: function (entityTypeId, persistenceEntityTypeId) {
            return {
                fields: function (fields) {
                    if (!storageDriver.mongooseModels) {
                        return;
                    }

                    storageDriver.serializers[entityTypeId] = _.chain(fields.evaluateProperties()).map(function (field, fieldName) {
                        if (field.fieldType.notPersisted) {
                            return undefined;
                        }
                        var serializers, fieldType;
                        if (fieldType = mongoFieldService.fieldTypes[field.fieldType.id]) {
                            serializers = {toBsonValue: fieldType.toBsonValue, fromBsonValue: fieldType.fromBsonValue};
                        } else {
                            serializers = {toBsonValue: _.identity, fromBsonValue: _.identity};
                        }
                        return [fieldName, serializers];
                    }).filter(_.identity).object().value();
                }
            }
        }
    }
};


text:
package com.rethinkdb.gen.exc;

import java.util.Optional;
import com.rethinkdb.ast.ReqlAst;
import com.rethinkdb.model.Backtrace;

public class ReqlInternalError extends ReqlRuntimeError {

    Optional<Backtrace> backtrace = Optional.empty();
    Optional<ReqlAst> term = Optional.empty();

    public ReqlInternalError() {
    }

    public ReqlInternalError(String message) {
        super(message);
    }

    public ReqlInternalError(String format, Object... args) {
        super(String.format(format, args));
    }

    public ReqlInternalError(String message, Throwable cause) {
        super(message, cause);
    }

    public ReqlInternalError(Throwable cause) {
        super(cause);
    }

    public ReqlInternalError(String msg, ReqlAst term, Backtrace bt) {
        super(msg);
        this.backtrace = Optional.ofNullable(bt);
        this.term = Optional.ofNullable(term);
    }

    public ReqlInternalError setBacktrace(Backtrace backtrace) {
        this.backtrace = Optional.ofNullable(backtrace);
        return this;
    }

    public Optional<Backtrace> getBacktrace() {
        return backtrace;
    }

    public ReqlInternalError setTerm(ReqlAst term) {
        this.term = Optional.ofNullable(term);
        return this;
    }

    public Optional<ReqlAst> getTerm() {
        return this.term;
    }
}


text: load File.expand_path('../../tasks/release.rake', __FILE__)


text:
import React from 'react'
import Grid from 'react-bootstrap/lib/Grid'
import Panel from 'react-bootstrap/lib/Panel'
import Row from 'react-bootstrap/lib/Row'
import {injectIntl} from 'react-intl'
import OperationTable from './OperationTable'
import {setTitle} from '../lib/utils'

class Operations extends React.Component {
  render() {
    setTitle('Operations')
    const {formatMessage} = this.props.intl
    return (
      <Grid>
        <Row>
          <Panel header={formatMessage({id: 'operations'})}>
            <OperationTable compact={false} limit={50} usePaging />
          </Panel>
        </Row>
      </Grid>
    )
  }
}

export default injectIntl(Operations)


text:
@interface XEFormCheckCell : XEFormDefaultCell

@end


text:
package org.apache.hadoop.hive.metastore.txn;

import org.apache.commons.lang3.Functions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.MetastoreTaskThread;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

import static org.apache.commons.lang3.Functions.FailableRunnable;

/**
 * Performs background tasks for Transaction management in Hive.
 * Runs inside Hive Metastore Service.
 */
public class AcidHouseKeeperService implements MetastoreTaskThread {

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

  private Configuration conf;
  private boolean isCompactorEnabled;
  private TxnStore txnHandler;

  @Override
  public void setConf(Configuration configuration) {
    conf = configuration;
    isCompactorEnabled = MetastoreConf.getBoolVar(conf, MetastoreConf.ConfVars.COMPACTOR_INITIATOR_ON);
    txnHandler = TxnUtils.getTxnStore(conf);
  }

  @Override
  public Configuration getConf() {
    return conf;
  }

  @Override
  public long runFrequency(TimeUnit unit) {
    return MetastoreConf.getTimeVar(conf, MetastoreConf.ConfVars.ACID_HOUSEKEEPER_SERVICE_INTERVAL, unit);
  }

  @Override
  public void run() {
    TxnStore.MutexAPI.LockHandle handle = null;
    try {
      handle = txnHandler.getMutexAPI().acquireLock(TxnStore.MUTEX_KEY.HouseKeeper.name());
      LOG.info("Starting to run AcidHouseKeeperService.");
      long start = System.currentTimeMillis();
      cleanTheHouse();
      LOG.debug("Total time AcidHouseKeeperService took: {} seconds.", elapsedSince(start));
    } catch (Throwable t) {
      LOG.error("Unexpected error in thread: {}, message: {}", Thread.currentThread().getName(), t.getMessage(), t);
    } finally {
      if (handle != null) {
        handle.releaseLocks();
      }
    }
  }

  private void cleanTheHouse() {
    performTask(txnHandler::performTimeOuts, "Cleaning timed out txns and locks");
    performTask(txnHandler::performWriteSetGC, "Cleaning obsolete write set entries");
    performTask(txnHandler::cleanTxnToWriteIdTable, "Cleaning obsolete TXN_TO_WRITE_ID entries");
    if (isCompactorEnabled) {
      performTask(txnHandler::purgeCompactionHistory, "Cleaning obsolete compaction history entries");
    }
  }

  private void performTask(FailableRunnable<MetaException> task, String description) {
    long start = System.currentTimeMillis();
    Functions.run(task);
    LOG.debug("{} took {} seconds.", description, elapsedSince(start));
  }

  private long elapsedSince(long start) {
    return (System.currentTimeMillis() - start) / 1000;
  }
}


text:
package org.batfish.datamodel.matchers;

import javax.annotation.Nonnull;
import org.batfish.datamodel.ospf.OspfNeighbor;
import org.hamcrest.FeatureMatcher;
import org.hamcrest.Matcher;

final class OspfNeighborMatchersImpl {

  static final class HasRemoteOspfNeighbor extends FeatureMatcher<OspfNeighbor, OspfNeighbor> {
    HasRemoteOspfNeighbor(@Nonnull Matcher<? super OspfNeighbor> subMatcher) {
      super(subMatcher, "OspfNeighbor with remoteOspfNeighbor", "remoteOspfNeighbor");
    }

    @Override
    protected OspfNeighbor featureValueOf(OspfNeighbor actual) {
      return actual.getRemoteOspfNeighbor();
    }
  }
}


text:
namespace Diadoc.Console.Command
{
	class SelectBoxCommand : ConsoleCommandBase
	{
		public SelectBoxCommand(ConsoleContext consoleContext, string command = "box") : base(consoleContext, command, CommandType.AuthenticationRequired)
		{
			Usage = "[ <boxId> ]";
			Description = "Select box";
		}

		protected override void PerformRunCommand(string[] args)
		{
			var boxId = args.Length > 0 ? args[0] : null;

			if (boxId == null)
			{
				OutputHelpers.ShowBoxes(ConsoleContext);
				return;
			}

			ConsoleContext.SetCurrentBoxWithBoxId(InputHelpers.AutocompleteBoxId(ConsoleContext, boxId));
			System.Console.WriteLine($"Текущий ящик, BoxId: {ConsoleContext.CurrentBoxId}, OrgId: {ConsoleContext.CurrentOrgId}");
			ConsoleContext.Events = null;
		}
	}
}


text:
function docNode=addMaterialLevel_FEB_v1p2(docNode,FEB_struct)

%%
febio_spec = docNode.getDocumentElement;

ElementAddNode = docNode.createElement('Material');
febio_spec.appendChild(ElementAddNode);
MATNode = docNode.getElementsByTagName('Material').item(0);

% Adding material fields
disp('Adding Material level')
A=[FEB_struct.Geometry.ElementMat{:}];
mat_ind=unique(A);
parent_node =MATNode;

if FEB_struct.disp_opt==1;
    hw = waitbar(0,'Adding material level...');
end
for i=1:1:numel(mat_ind)

    %Adding material node
    material_node = docNode.createElement('material'); %create material entry
    material_node = parent_node.appendChild(material_node); %add material entry

    %Checking material type
    Mat_i=FEB_struct.Materials{i};
    mat_type=Mat_i.type;
    switch mat_type
        case {'uncoupled solid mixture','solid mixture'}

            %%

            %Mat ID
            attr = docNode.createAttribute('id'); %Create attribute
            attr.setNodeValue(num2str(mat_ind(i))); %Set text
            material_node.setAttributeNode(attr); %Add attribute

            %Mat Name
            attr = docNode.createAttribute('name'); %Create attribute
            attr.setNodeValue(['mat_',num2str(i)]); %Set text
            material_node.setAttributeNode(attr); %Add attribute

            %Mat Type
            attr = docNode.createAttribute('type'); %Create attribute
            attr.setNodeValue(mat_type); %Set text
            material_node.setAttributeNode(attr); %Add attribute

            %Mat properties and attributes
            if isfield(Mat_i,'props')
                mat_props=Mat_i.props;
                mat_prop_vals=Mat_i.vals;

                %Access property attributes
                if isfield(Mat_i,'PropAttrName')
                    mat_prop_attr_name=Mat_i.PropAttrName;
                    mat_prop_attr_val=Mat_i.PropAttrVal;
                else
                    mat_prop_attr_name=[];
                    mat_prop_attr_val=[];
                end

                %Material properties
                for q=1:1:numel(mat_props)
                    mat_prop=mat_props{q};
                    mat_prop_val=mat_prop_vals{q};
                    prop_node = docNode.createElement(mat_prop); %create entry
                    prop_node = material_node.appendChild(prop_node); %add entry
                    t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                    prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child

                    %Add potential property attributes (e.g. property load curves)
                    if ~isempty(mat_prop_attr_name)
                        if q<=numel(mat_prop_attr_name)
                            currentPropAttrName=mat_prop_attr_name{q};
                            if ~isempty(currentPropAttrName)
                                currentPropAttrVal=mat_prop_attr_val{q};

                                t_form=repmat('%6.7e, ',1,size(currentPropAttrVal,2));
                                t_form=t_form(1:end-2);

                                attr = docNode.createAttribute(currentPropAttrName); %Create attribute
                                attr.setNodeValue(sprintf(t_form,currentPropAttrVal)); %Set text
                                prop_node.setAttributeNode(attr); %Add attribute
                            end
                        end
                    end

                end
            end

            %Mat aniso_type
            if isfield(Mat_i,'aniso_type')
                mat_aniso_type=Mat_i.aniso_type;
                switch mat_aniso_type
                    case 'none'

                    case 'fiber'
                        prop_node = docNode.createElement('fiber'); %create entry
                        prop_node = solid_node.appendChild(prop_node); %add entry
                        attr = docNode.createAttribute('type'); %Create attribute
                        attr.setNodeValue('user'); %Set text
                        prop_node.setAttributeNode(attr); %Add attribute
                    case 'mat_axis'
                        prop_node = docNode.createElement('mat_axis'); %create entry
                        prop_node = solid_node.appendChild(prop_node); %add entry
                        attr = docNode.createAttribute('type'); %Create attribute
                        attr.setNodeValue('vector'); %Set text
                        prop_node.setAttributeNode(attr); %Add attribute
                end
            end
            %%

            for j=1:1:numel(FEB_struct.Materials{i}.Mats)

                solid_node = docNode.createElement('solid'); %create entry
                solid_node = material_node.appendChild(solid_node); %add entry

                %Mat Type
                attr = docNode.createAttribute('type'); %Create attribute
                attr.setNodeValue(Mat_i.Mats{j}.type); %Set text
                solid_node.setAttributeNode(attr); %Add attribute

                %Mat ID
                attr = docNode.createAttribute('id'); %Create attribute
                attr.setNodeValue(num2str(j)); %Set text
                solid_node.setAttributeNode(attr); %Add attribute

                %%
                %                 mat_props=Mat_i.Mats{j}.props;
                %                 mat_prop_vals=Mat_i.Mats{j}.vals;
                %                 %Material properties
                %                 for q=1:1:numel(mat_props)
                %                     mat_prop=mat_props{q};
                %                     mat_prop_val=mat_prop_vals{q};
                %                     prop_node = docNode.createElement(mat_prop); %create entry
                %                     prop_node = solid_node.appendChild(prop_node); %add entry
                %                     t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                %                     prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child
                %                 end

                %Mat properties and attributes
                if isfield(Mat_i.Mats{j},'props')
                    mat_props=Mat_i.Mats{j}.props;
                    mat_prop_vals=Mat_i.Mats{j}.vals;

                    %Access property attributes
                    if isfield(Mat_i.Mats{j},'PropAttrName')
                        mat_prop_attr_name=Mat_i.Mats{j}.PropAttrName;
                        mat_prop_attr_val=Mat_i.Mats{j}.PropAttrVal;
                    else
                        mat_prop_attr_name=[];
                        mat_prop_attr_val=[];
                    end

                    %Material properties
                    for q=1:1:numel(mat_props)
                        mat_prop=mat_props{q};
                        mat_prop_val=mat_prop_vals{q};
                        prop_node = docNode.createElement(mat_prop); %create entry
                        prop_node = solid_node.appendChild(prop_node); %add entry
                        t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                        prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child

                        %Add potential property attributes (e.g. property load curves)
                        if ~isempty(mat_prop_attr_name)
                            if q<=numel(mat_prop_attr_name)
                                currentPropAttrName=mat_prop_attr_name{q};
                                if ~isempty(currentPropAttrName)
                                    currentPropAttrVal=mat_prop_attr_val{q};

                                    t_form=repmat('%6.7e, ',1,size(currentPropAttrVal,2));
                                    t_form=t_form(1:end-2);

                                    attr = docNode.createAttribute(currentPropAttrName); %Create attribute
                                    attr.setNodeValue(sprintf(t_form,currentPropAttrVal)); %Set text
                                    prop_node.setAttributeNode(attr); %Add attribute
                                end
                            end
                        end
                    end
                end

                %%
                %Fiber spec
                mat_aniso_type=Mat_i.Mats{j}.aniso_type;
                switch mat_aniso_type
                    case 'none'

                    case 'fiber'
                        prop_node = docNode.createElement('fiber'); %create entry
                        prop_node = solid_node.appendChild(prop_node); %add entry
                        attr = docNode.createAttribute('type'); %Create attribute
                        attr.setNodeValue('user'); %Set text
                        prop_node.setAttributeNode(attr); %Add attribute
                    case 'mat_axis'
                        prop_node = docNode.createElement('mat_axis'); %create entry
                        prop_node = solid_node.appendChild(prop_node); %add entry
                        attr = docNode.createAttribute('type'); %Create attribute
                        attr.setNodeValue('vector'); %Set text
                        prop_node.setAttributeNode(attr); %Add attribute
                end

            end
        case 'multigeneration'

            if ~isfield(FEB_struct.Materials{i},'start_times')

                %% BEFORE FEBIO 2.0
                %Mat ID
                attr = docNode.createAttribute('id'); %Create attribute
                attr.setNodeValue(num2str(mat_ind(i))); %Set text
                material_node.setAttributeNode(attr); %Add attribute

                %Mat Name
                attr = docNode.createAttribute('name'); %Create attribute
                attr.setNodeValue(['mat_',num2str(i)]); %Set text
                material_node.setAttributeNode(attr); %Add attribute

                %Mat Type
                attr = docNode.createAttribute('type'); %Create attribute
                attr.setNodeValue(mat_type); %Set text
                material_node.setAttributeNode(attr); %Add attribute

                for j=1:1:numel(FEB_struct.Materials{i}.Mats)

                    solid_node = docNode.createElement('solid'); %create entry
                    solid_node = material_node.appendChild(solid_node); %add entry

                    %Mat Type
                    attr = docNode.createAttribute('type'); %Create attribute
                    attr.setNodeValue(Mat_i.Mats{j}.type); %Set text
                    solid_node.setAttributeNode(attr); %Add attribute

                    %Mat Generation
                    attr = docNode.createAttribute('gen'); %Create attribute
                    attr.setNodeValue(num2str(j)); %Set text
                    solid_node.setAttributeNode(attr); %Add attribute

                    %Mat ID
                    attr = docNode.createAttribute('id'); %Create attribute
                    attr.setNodeValue(num2str(j)); %Set text
                    solid_node.setAttributeNode(attr); %Add attribute

                    %%
                    %                     mat_props=Mat_i.Mats{j}.props;
                    %                     mat_prop_vals=Mat_i.Mats{j}.vals;
                    %                     %Material properties
                    %                     for q=1:1:numel(mat_props)
                    %                         mat_prop=mat_props{q};
                    %                         mat_prop_val=mat_prop_vals{q};
                    %                         prop_node = docNode.createElement(mat_prop); %create entry
                    %                         prop_node = solid_node.appendChild(prop_node); %add entry
                    %                         t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                    %                         prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child
                    %                     end

                    %Mat properties and attributes
                    if isfield(Mat_i.Mats{j},'props')
                        mat_props=Mat_i.Mats{j}.props;
                        mat_prop_vals=Mat_i.Mats{j}.vals;

                        %Access property attributes
                        if isfield(Mat_i.Mats{j},'PropAttrName')
                            mat_prop_attr_name=Mat_i.Mats{j}.PropAttrName;
                            mat_prop_attr_val=Mat_i.Mats{j}.PropAttrVal;
                        else
                            mat_prop_attr_name=[];
                            mat_prop_attr_val=[];
                        end

                        %Material properties
                        for q=1:1:numel(mat_props)
                            mat_prop=mat_props{q};
                            mat_prop_val=mat_prop_vals{q};
                            prop_node = docNode.createElement(mat_prop); %create entry
                            prop_node = solid_node.appendChild(prop_node); %add entry
                            t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                            prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child

                            %Add potential property attributes (e.g. property load curves)
                            if ~isempty(mat_prop_attr_name)
                                if q<=numel(mat_prop_attr_name)
                                    currentPropAttrName=mat_prop_attr_name{q};
                                    if ~isempty(currentPropAttrName)
                                        currentPropAttrVal=mat_prop_attr_val{q};

                                        t_form=repmat('%6.7e, ',1,size(currentPropAttrVal,2));
                                        t_form=t_form(1:end-2);

                                        attr = docNode.createAttribute(currentPropAttrName); %Create attribute
                                        attr.setNodeValue(sprintf(t_form,currentPropAttrVal)); %Set text
                                        prop_node.setAttributeNode(attr); %Add attribute
                                    end
                                end
                            end
                        end
                    end

                    %%

                    %Fiber spec
                    mat_aniso_type=Mat_i.Mats{j}.aniso_type;
                    switch mat_aniso_type
                        case 'none'

                        case 'fiber'
                            prop_node = docNode.createElement('fiber'); %create entry
                            prop_node = solid_node.appendChild(prop_node); %add entry
                            attr = docNode.createAttribute('type'); %Create attribute
                            attr.setNodeValue('user'); %Set text
                            prop_node.setAttributeNode(attr); %Add attribute
                        case 'mat_axis'
                            prop_node = docNode.createElement('mat_axis'); %create entry
                            prop_node = solid_node.appendChild(prop_node); %add entry
                            attr = docNode.createAttribute('type'); %Create attribute
                            attr.setNodeValue('vector'); %Set text
                            prop_node.setAttributeNode(attr); %Add attribute
                    end

                end
            else

                %% AS OF FEBIO 2.0

                %Mat ID
                attr = docNode.createAttribute('id'); %Create attribute
                attr.setNodeValue(num2str(mat_ind(i))); %Set text
                material_node.setAttributeNode(attr); %Add attribute

                %Mat Name
                attr = docNode.createAttribute('name'); %Create attribute
                attr.setNodeValue(['mat_',num2str(i)]); %Set text
                material_node.setAttributeNode(attr); %Add attribute

                %Mat Type
                attr = docNode.createAttribute('type'); %Create attribute
                attr.setNodeValue(mat_type); %Set text
                material_node.setAttributeNode(attr); %Add attribute

                for j=1:1:numel(FEB_struct.Materials{i}.Mats)

                    generation_node = docNode.createElement('generation'); %create entry
                    generation_node = material_node.appendChild(generation_node); %add entry

                    %Generation ID
                    attr = docNode.createAttribute('id'); %Create attribute
                    attr.setNodeValue(num2str(j)); %Set text
                    generation_node.setAttributeNode(attr); %Add attribute

                    %Define start time
                    start_time_node = docNode.createElement('start_time'); %create entry
                    start_time_node = generation_node.appendChild(start_time_node); %add entry
                    start_time_val=Mat_i.start_times(j);
                    t_form=repmat('%6.7e, ',1,size(start_time_val,2)); t_form=t_form(1:end-2);
                    start_time_node.appendChild(docNode.createTextNode(sprintf(t_form,start_time_val))); %append data text child

                    %Define solid
                    solid_node = docNode.createElement('solid'); %create entry
                    solid_node = generation_node.appendChild(solid_node); %add entry

                    %Mat Type
                    attr = docNode.createAttribute('type'); %Create attribute
                    attr.setNodeValue(Mat_i.Mats{j}.type); %Set text
                    solid_node.setAttributeNode(attr); %Add attribute

                    %%
                    %                     mat_props=Mat_i.Mats{j}.props;
                    %                     mat_prop_vals=Mat_i.Mats{j}.vals;
                    %
                    %                     %Material properties
                    %                     for q=1:1:numel(mat_props)
                    %                         mat_prop=mat_props{q};
                    %                         mat_prop_val=mat_prop_vals{q};
                    %                         prop_node = docNode.createElement(mat_prop); %create entry
                    %                         prop_node = solid_node.appendChild(prop_node); %add entry
                    %                         t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                    %                         prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child
                    %                     end

                    %Mat properties and attributes
                    if isfield(Mat_i.Mats{j},'props')
                        mat_props=Mat_i.Mats{j}.props;
                        mat_prop_vals=Mat_i.Mats{j}.vals;

                        %Access property attributes
                        if isfield(Mat_i.Mats{j},'PropAttrName')
                            mat_prop_attr_name=Mat_i.Mats{j}.PropAttrName;
                            mat_prop_attr_val=Mat_i.Mats{j}.PropAttrVal;
                        else
                            mat_prop_attr_name=[];
                            mat_prop_attr_val=[];
                        end

                        %Material properties
                        for q=1:1:numel(mat_props)
                            mat_prop=mat_props{q};
                            mat_prop_val=mat_prop_vals{q};
                            prop_node = docNode.createElement(mat_prop); %create entry
                            prop_node = solid_node.appendChild(prop_node); %add entry
                            t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                            prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child

                            %Add potential property attributes (e.g. property load curves)
                            if ~isempty(mat_prop_attr_name)
                                if q<=numel(mat_prop_attr_name)
                                    currentPropAttrName=mat_prop_attr_name{q};
                                    if ~isempty(currentPropAttrName)
                                        currentPropAttrVal=mat_prop_attr_val{q};

                                        t_form=repmat('%6.7e, ',1,size(currentPropAttrVal,2));
                                        t_form=t_form(1:end-2);

                                        attr = docNode.createAttribute(currentPropAttrName); %Create attribute
                                        attr.setNodeValue(sprintf(t_form,currentPropAttrVal)); %Set text
                                        prop_node.setAttributeNode(attr); %Add attribute
                                    end
                                end
                            end
                        end
                    end

                    %%

                    %Fiber spec
                    mat_aniso_type=Mat_i.Mats{j}.aniso_type;
                    switch mat_aniso_type
                        case 'none'

                        case 'fiber'
                            prop_node = docNode.createElement('fiber'); %create entry
                            prop_node = solid_node.appendChild(prop_node); %add entry
                            attr = docNode.createAttribute('type'); %Create attribute
                            attr.setNodeValue('user'); %Set text
                            prop_node.setAttributeNode(attr); %Add attribute
                        case 'mat_axis'
                            prop_node = docNode.createElement('mat_axis'); %create entry
                            prop_node = solid_node.appendChild(prop_node); %add entry
                            attr = docNode.createAttribute('type'); %Create attribute
                            attr.setNodeValue('vector'); %Set text
                            prop_node.setAttributeNode(attr); %Add attribute
                    end

                end
            end

            %%
        otherwise

            %Mat ID
            attr = docNode.createAttribute('id'); %Create attribute
            attr.setNodeValue(num2str(mat_ind(i))); %Set text
            material_node.setAttributeNode(attr); %Add attribute

            %Mat Name
            attr = docNode.createAttribute('name'); %Create attribute
            attr.setNodeValue(['mat_',num2str(i)]); %Set text
            material_node.setAttributeNode(attr); %Add attribute

            %Mat Type
            attr = docNode.createAttribute('type'); %Create attribute
            attr.setNodeValue(mat_type); %Set text
            material_node.setAttributeNode(attr); %Add attribute

            mat_aniso_type=Mat_i.aniso_type;

            %%

            %Mat properties and attributes
            if isfield(Mat_i,'props')
                mat_props=Mat_i.props;
                mat_prop_vals=Mat_i.vals;

                %Access property attributes
                if isfield(Mat_i,'PropAttrName')
                    mat_prop_attr_name=Mat_i.PropAttrName;
                    mat_prop_attr_val=Mat_i.PropAttrVal;
                else
                    mat_prop_attr_name=[];
                    mat_prop_attr_val=[];
                end

                %Material properties
                for q=1:1:numel(mat_props)
                    mat_prop=mat_props{q};
                    mat_prop_val=mat_prop_vals{q};
                    prop_node = docNode.createElement(mat_prop); %create entry
                    prop_node = material_node.appendChild(prop_node); %add entry
                    t_form=repmat('%6.7e, ',1,size(mat_prop_val,2)); t_form=t_form(1:end-2);
                    prop_node.appendChild(docNode.createTextNode(sprintf(t_form,mat_prop_val))); %append data text child

                    %Add potential property attributes (e.g. property load curves)
                    if ~isempty(mat_prop_attr_name)
                        if q<=numel(mat_prop_attr_name)
                            currentPropAttrName=mat_prop_attr_name{q};
                            if ~isempty(currentPropAttrName)
                                currentPropAttrVal=mat_prop_attr_val{q};

                                t_form=repmat('%6.7e, ',1,size(currentPropAttrVal,2));
                                t_form=t_form(1:end-2);

                                attr = docNode.createAttribute(currentPropAttrName); %Create attribute
                                attr.setNodeValue(sprintf(t_form,currentPropAttrVal)); %Set text
                                prop_node.setAttributeNode(attr); %Add attribute
                            end
                        end
                    end

                end
            end

            %%
            %Fiber spec
            switch mat_aniso_type
                case 'none' %No fibre type specified, do nothing

                case 'fiber'
                    prop_node = docNode.createElement('fiber'); %create entry
                    prop_node = material_node.appendChild(prop_node); %add entry
                    attr = docNode.createAttribute('type'); %Create attribute
                    attr.setNodeValue('user'); %Set text
                    prop_node.setAttributeNode(attr); %Add attribute
                case 'mat_axis'
                    prop_node = docNode.createElement('mat_axis'); %create entry
                    prop_node = material_node.appendChild(prop_node); %add entry
                    attr = docNode.createAttribute('type'); %Create attribute
                    attr.setNodeValue('vector'); %Set text
                    prop_node.setAttributeNode(attr); %Add attribute
            end
    end
    %     prop_node.appendChild(docNode.createTextNode(' ')); %append data text child
    if FEB_struct.disp_opt==1;
        waitbar(i/numel(mat_ind),hw,'Adding material level...');
    end
end
if FEB_struct.disp_opt==1;
    close(hw);
    drawnow;
end