text:
title: Text
localeTitle: Текст
---
## Текст

CSS предоставляет несколько свойств, чтобы изменить внешний вид текста. Ниже описаны различные текстовые свойства.

#### Цвет текста

\`\` \`html

Это пример свойства текста CSS.
```
``` css
 p {
    color:red;
 }
```

В приведенном выше примере `color` текста элемента `<p>` изменяется на красный. Вы также можете указать цвет как значения RGB, значения HLS и шестнадцатеричные коды (для получения дополнительной информации о цветах щелкните [здесь](https://guide.freecodecamp.org/css/colors) ).

#### Выравнивание текста

Свойство `text-align` используется для установки горизонтального выравнивания текста. Он может принимать значения `left` , `right` , в `center` и `justify` . \`\` \`css п { text-align: center; }
```
Here the text is aligned to the `center` ([example](https://www.w3schools.com/css/tryit.asp?filename=trycss_text-align)).When `text-align` is set to `justify`,each line is stretched so that every line has equal width, and the left and right margins are straight ([example](https://www.w3schools.com/css/tryit.asp?filename=trycss_text-align_all)).

 #### Text Decoration
```

CSS п { text-decoration: подчеркивание; }
```
The `text-decoration` property is used to set or remove decorations from text. The value `text-decoration: none;` is often used to remove underlines from links. Other `text-decorations` include `overline`,`line-through`,and `underline` ([example](https://www.w3schools.com/css/tryit.asp?filename=trycss_text-decoration)).

 #### Text Tranformation
```

CSS п { text-transform: капитализировать; }
```
The `text-transform` property is used to convert the entire text to `uppercase`,`lowercase` or to `capitilize` each word([example](https://www.w3schools.com/css/tryit.asp?filename=trycss_text-transform)).

 #### Letter Spacing

 The `letter-spacing` property sets the space between characters in a text.
```

CSS п { расстояние между буквами: 5 пикселей; }
```
#### Line Height

 The `line-height` property sets the space between two lines of text.
```

CSS п { line-height: 5px; }
```
#### Word Spacing

 The `word-spacing` sets the space between words in a text.
```

CSS п { слово-интервал: 5 пикселей; } \`\` \`

#### Дополнительная информация:

[Текст CSS W3Schools](https://w3schools.com/css/css_text.asp)


text:
package no.kantega.publishing.admin.content.ajax;

import no.kantega.commons.client.util.RequestParameters;
import no.kantega.commons.exception.NotAuthorizedException;
import no.kantega.publishing.admin.AdminSessionAttributes;
import no.kantega.publishing.api.content.ContentIdHelper;
import no.kantega.publishing.api.content.ContentIdentifier;
import no.kantega.publishing.common.Aksess;
import no.kantega.publishing.common.data.Content;
import no.kantega.publishing.common.service.ContentManagementService;
import no.kantega.publishing.jobs.contentstate.ContentStateUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Update display period (publish and expire date) for a page
 */
@Controller
public class UpdateDisplayPeriodAction {
    private static final Logger log = LoggerFactory.getLogger(UpdateDisplayPeriodAction.class);

    @Autowired
    private ContentStateUpdater stateUpdater;

    @Autowired
    private ContentIdHelper contentIdHelper;

    @RequestMapping("/admin/publish/UpdateDisplayPeriod.action")
    public @ResponseBody Map<String, Object> handleRequest(HttpServletRequest request) throws Exception {
        Map<String, Object> model = new HashMap<>();

        RequestParameters param = new RequestParameters(request);
        ContentManagementService cms = new ContentManagementService(request);

        try {
            int associationId = param.getInt("associationId");
            if (associationId != -1) {
                ContentIdentifier cid =  ContentIdentifier.fromAssociationId(associationId);
                contentIdHelper.assureContentIdAndAssociationIdSet(cid);

                Date publishDate = param.getDateAndTime("from", Aksess.getDefaultDateFormat());
                Date expireDate = param.getDateAndTime("end", Aksess.getDefaultDateFormat());

                boolean updateChildren = param.getBoolean("updateChildren", false);

                if (publishDate != null) {
                    cms.updateDisplayPeriodForContent(cid, publishDate, expireDate, updateChildren);

                    // Update state of content immediately to not confuse user
                    stateUpdater.expireContent();
                    stateUpdater.publishContent();

                    // Update content objects stored in session so user is not confused
                    HttpSession session = request.getSession();
                    Content editedContent = (Content)session.getAttribute(AdminSessionAttributes.CURRENT_EDIT_CONTENT);
                    if (editedContent != null && editedContent.getId() == cid.getContentId()) {
                        editedContent.setPublishDate(publishDate);
                        editedContent.setExpireDate(expireDate);
                    }
                    Content displayedContent = (Content)session.getAttribute(AdminSessionAttributes.CURRENT_NAVIGATE_CONTENT);
                    if (displayedContent != null && displayedContent.getId() == cid.getContentId()) {
                        displayedContent.setPublishDate(publishDate);
                        displayedContent.setExpireDate(expireDate);
                    }
                }
            }

        } catch (NotAuthorizedException e) {
            log.error("", e);
            model.put("error", Boolean.TRUE);
        }

        return model;
    }

}

redpajama_set_name: RedPajamaGithub


text:
var fs          = require('fs'),
    path        = require('path'),
    gulp        = require('gulp'),
    gutil       = require('gulp-util'),
    mirror      = require('gulp-mirror'),
    uglify      = require('gulp-uglify'),
    rename      = require('gulp-rename'),
    header      = require('gulp-header'),
    source      = require('vinyl-source-stream'),
    sourcemaps  = require('gulp-sourcemaps'),
    buffer      = require('vinyl-buffer'),
    browserify  = require('browserify'),
    watchify    = require('watchify'),
    handleErrors = require('../util/handleErrors'),
    headerText  = fs.readFileSync(path.join(__dirname, '..', 'header.txt'), 'utf8'),
    licenseText = fs.readFileSync(path.join(__dirname, '..', '..', 'LICENSE'), 'utf8'),
    date        = new Date();

// TODO - Concat license header to dev/prod build files.
function rebundle(devBundle) {
    if (devBundle) {
        gutil.log('Starting dev rebundle...');
    }

    var debug, min;

    debug = sourcemaps.init({loadMaps: true});
    debug.pipe(sourcemaps.write('./', {sourceRoot: './'}))
        .pipe(gulp.dest(paths.out));

    min = rename({ suffix: '.min' });
    min.pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .pipe(sourcemaps.write('./', {sourceRoot: './', addComment: true}))
        .pipe(gulp.dest(paths.out));

    var stream = this.bundle()
        .on('error', handleErrors.handler)
        .pipe(handleErrors())
        .pipe(source('pixi.js'))
        .pipe(buffer())
        .pipe(header(
            headerText,
            {
                licenseText: licenseText,
                date: new Date().toISOString(),
                pkg: require('../../package.json')
            }
        ));

    if (devBundle) {
        return stream.pipe(debug).once('end', function () {
            gutil.log('Dev rebundle complete.');
        });
    }
    else {
        return stream.pipe(mirror(debug, min));
    }
}

function createBundler(args) {
    args = args || {};
    args.debug = true;
    args.standalone = 'PIXI';

    var bundle = browserify(paths.jsEntry, args),
        argv = require('minimist')(process.argv.slice(2)),
        exclude = (argv.exclude || []).concat(argv.e || []);

    if (!Array.isArray(exclude)) {
        exclude = [exclude]
    }

    for (var i = 0; i < exclude.length; ++i) {
        bundle.ignore(require.resolve('../../src/' + exclude[i]));
    }

    return bundle;
}

function watch(onUpdate) {
    var bundler = watchify(createBundler(watchify.args));

    bundler.on('update', function () {
        var bundle = rebundle.call(this, true);

        if (onUpdate) {
            bundle.on('end', onUpdate);
        }
    });

    return rebundle.call(bundler);
}

module.exports = function bundle() {
    return rebundle.call(createBundler());
};

module.exports.watch = watch;
module.exports.rebundle = rebundle;
module.exports.createBundler = createBundler;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>我的生活</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="stylesheet" href="http://g.alicdn.com/msui/sm/0.5.2/css/sm.min.css">
    <link rel="stylesheet" href="http://g.alicdn.com/msui/sm/0.5.2/css/sm-extend.min.css">

      返回

可选择列表

单选

            <input type="radio" name="my-radio">

石头

17:14

New messages from John Doe

Lorem ipsum dolor sit amet...

            <input type="radio" name="my-radio">

剪刀

17:14

New messages from John Doe

Lorem ipsum dolor sit amet...

            <input type="radio" name="my-radio">

布

17:14

New messages from John Doe

Lorem ipsum dolor sit amet...

多选

            <input type="checkbox" name="checkbox">

石头

17:14

New messages from John Doe

Lorem ipsum dolor sit amet...

            <input type="checkbox" name="checkbox">

剪刀

17:14

New messages from John Doe

Lorem ipsum dolor sit amet...

            <input type="checkbox" name="checkbox">

布

17:14

New messages from John Doe

Lorem ipsum dolor sit amet...


text:
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { Injectable, Inject } from '@angular/core';

import { DataService } from './data.service';

const APP_DATA_KEY = makeStateKey<string>('appData');

@Injectable({
  providedIn: 'root',
})
export class AppService {
  constructor(@Inject('BASE_URL') private baseUrl: string, private transferState: TransferState, private dataService: DataService) { }

  public get appData(): IApplicationConfig {
    return this.transferState.get<IApplicationConfig>(APP_DATA_KEY, null as IApplicationConfig);
  }
  getAppData(): Promise<IApplicationConfig> {
    const transferredAppData = this.transferState.get<IApplicationConfig>(APP_DATA_KEY, null as IApplicationConfig);
    if (!transferredAppData) {
      return this.dataService
        .get('app/getapplicationdata')
        .toPromise()
        .then((data: IApplicationConfig) => {
          this.transferState.set<IApplicationConfig>(APP_DATA_KEY, data);
          return data;
        });
    }
    return new Promise((resolve, reject) => {
      resolve(transferredAppData);
    });
  }
}


text:
class AliyunCli < Formula
  desc "Universal Command-Line Interface for Alibaba Cloud"
  homepage "https://github.com/aliyun/aliyun-cli"
  url "https://github.com/aliyun/aliyun-cli/archive/v3.0.60.tar.gz"
  sha256 "62b1e233945839a9d56ed5bc389b0b1de2a07497973c94e75505fcf2e1a87d98"
  license "Apache-2.0"

  bottle do
    cellar :any_skip_relocation
    sha256 "52333d5fd3383108bef05cb4326974b2ae66b544e55472ddc495b13491208c8a" => :catalina
    sha256 "0d213bac923791d42b190ccb36a39bdbf079209ff75da12f1a52f930e01a36ff" => :mojave
    sha256 "b3720314270dffa6d6a5ab0c1cf2aff33b4ca6fe0b007bf60c25add118c3b6d8" => :high_sierra
  end

  depends_on "go" => :build

  def install
    ENV["GO111MODULE"] = "off"
    ENV["GOPATH"] = buildpath
    ENV["PATH"] = "#{ENV["PATH"]}:#{buildpath}/bin"
    (buildpath/"src/github.com/aliyun/aliyun-cli").install buildpath.children
    cd "src/github.com/aliyun/aliyun-cli" do
      system "make", "metas"
      system "go", "build", "-o", bin/"aliyun", "-ldflags",
                            "-X 'github.com/aliyun/aliyun-cli/cli.Version=#{version}'", "main/main.go"
    end
  end

  test do
    version_out = shell_output("#{bin}/aliyun version")
    assert_match version.to_s, version_out

    help_out = shell_output("#{bin}/aliyun --help")
    assert_match "Alibaba Cloud Command Line Interface Version #{version}", help_out
    assert_match "", help_out
    assert_match "Usage:", help_out
    assert_match "aliyun <product> <operation> [--parameter1 value1 --parameter2 value2 ...]", help_out

    oss_out = shell_output("#{bin}/aliyun oss")
    assert_match "Object Storage Service", oss_out
    assert_match "aliyun oss [command] [args...] [options...]", oss_out
  end
end


text:
import * as React from 'react';
import * as Firebase from 'firebase';

export class TrainingContainer extends React.Component <any, any> {

	constructor(props) {
		super(props);
		var fba = Firebase.initializeApp({
	    apiKey: "AIzaSyAGcdoF9Z4JdBVGKDaNDCXS4drWVgXH0Fk",
	    authDomain: "fs-crypto.firebaseapp.com",
	    databaseURL: "https://fs-crypto.firebaseio.com",
	    projectId: "fs-crypto",
	    storageBucket: "fs-crypto.appspot.com",
	    messagingSenderId: "890617556765"
		});
		this.state = {
			fba: fba
		};
	}

	render() {
		return (

jello world

		);
	}

}


text:
<?php

namespace Octava\Bundle\BranchingBundle\Twig;

use Octava\Bundle\BranchingBundle\Helper\Git;

class BranchingExtension extends \Twig_Extension
{
    const CURRENT_BRANCH = 'octava_current_branch';
    /**
     * @var string
     */
    protected $projectDir;

    /**
     * @var string
     */
    protected $environment;

    public function __construct($projectDir, $environment)
    {
        $this->projectDir = $projectDir;
        $this->environment = $environment;
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'octava_branching_extension';
    }

    public function getFunctions()
    {
        return [
            self::CURRENT_BRANCH => new \Twig_Function(self::CURRENT_BRANCH, [$this, 'getCurrentBranch'])
        ];
    }

    public function getCurrentBranch($prefix = '', $postfix = '')
    {
        $result = null;
        if (in_array($this->environment, ['dev', 'test'])) {
            $result = sprintf(
                '%s%s (%s)%s',
                $prefix,
                Git::getCurrentBranch($this->projectDir),
                $this->environment,
                $postfix
            );
        }
        return $result;
    }
}


text:
package me.zzp.ar.ex;

/**
 * 未找到相应的方言。
 *
 * @since 1.0
 * @author redraiment
 */
public class UnsupportedDatabaseException extends RuntimeException {
  public UnsupportedDatabaseException(String product) {
    super(String.format("Unsupported Database: %s", product));
  }
}


text:
os_families = {}

step "Determine host OS's" do
  os_families = hosts.inject({}) do |result, host|
    result[host.name] = get_os_family(host)
    result
  end
end

PuppetDBExtensions.initialize_test_config(options,
            os_families)


text:
<bill session="110" type="h" number="7186" updated="2009-01-09T07:36:21-05:00">
	<status><introduced date="1222488000" datetime="2008-09-27"/></status>

	<introduced date="1222488000" datetime="2008-09-27"/>
	<titles>
		<title type="short" as="introduced">Solid Waste Rail Transfer Facilities Regulation Act of 2008</title>
		<title type="official" as="introduced">To amend title 49, United States Code, with respect to the regulation of solid waste by the Environmental Protection Agency.</title>
	</titles>
	<sponsor id="400160"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to the Committee on Transportation and Infrastructure, and in addition to the Committee on Energy and Commerce, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text></action>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to House Transportation and Infrastructure</text></action>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to House Energy and Commerce</text></action>
		<action date="1222488000" datetime="2008-09-27"><committee name="House Energy and Commerce"/><text>Referred to the Subcommittee on Environment and Hazardous Materials.</text></action>
		<action date="1222574400" datetime="2008-09-28"><committee name="House Transportation and Infrastructure"/><text>Referred to the Subcommittee on Railroads, Pipelines, and Hazardous Materials.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Almond Crisps with Amaretto-Glazed Almonds</title>
      <categories>
        <cat>Cookies</cat></categories>
      <yield>30</yield></head>
    <ingredients>
      <ing-div>
        <title>GLAZED ALMONDS</title>
        <ing>
          <amt>
            <qty>1 1/2</qty>
            <unit>teaspoons</unit></amt>
          <item>Unsalted butter</item></ing>
        <ing>
          <amt>
            <qty>3/4</qty>
            <unit>cups</unit></amt>
          <item>Slivered almonds</item></ing>
        <ing>
          <amt>
            <qty>1 1/2</qty>
            <unit>tablespoons</unit></amt>
          <item>Amaretto liquor</item></ing></ing-div>
      <ing-div>
        <title>DOUGH</title>
        <ing>
          <amt>
            <qty>1</qty>
            <unit>cup</unit></amt>
          <item>Flour, all-purpose</item></ing>
        <ing>
          <amt>
            <qty>1</qty>
            <unit>pinch</unit></amt>
          <item>Salt</item></ing>
        <ing>
          <amt>
            <qty>1/2</qty>
            <unit>cups</unit></amt>
          <item>Unsalted butter; room temp.</item></ing>
        <ing>
          <amt>
            <qty>1/2</qty>
            <unit>cups</unit></amt>
          <item>Sugar</item></ing>
        <ing>
          <amt>
            <qty>1</qty>
            <unit>small</unit></amt>
          <item>Egg; room temperature</item></ing>
        <ing>
          <amt>
            <qty>2</qty>
            <unit>teaspoons</unit></amt>
          <item>Amaretto liquor</item></ing>
        <ing>
          <amt>
            <qty/>
            <unit/></amt>
          <item>Sugar</item></ing>
        <ing>
          <amt>
            <qty/>
            <unit/></amt>
          <item>Powdered sugar, optional</item></ing></ing-div></ingredients>
    <directions>
      <step>  For almonds:  Melt butter in heavy small skillet over medium heat.  Add
  almonds and amaretto and stir until almonds are golden brown, about 5
  minutes.  Cool on paper towels.

  For dough:  Preheat oven to 350-degrees.  Lightly grease 2 large baking
  sheets.  Sift 1 cup flour with salt into small bowl.  Using electric
  mixer, cream butter with 1/2 cup sugar in large bowl until light and
  fluffy.  Blend in egg and amaretto.  Add flour and mix until dough binds.
  (Dough will be sticky.)

  Divide dough into 30 pieces.  Roll each between palms into balls, dusting
  hands with flour if necessary.  Set on baking sheets, spacing 2 inches
  apart.

  Fill small bowl with water.  Mound sugar on plate.  Dip bottom of 2-1/2"
  round glass into water and then into sugar.  Press glass down onto 1 dough
  ball, flattening into 2-1/2- to 3-inch round.  Repeat with remaining
  dough.  Sprinkle rounds lightly with sugar.

  Gently press several glazed almond slivers into each round in flower
  pattern.  Bake until edges of cookies are golden brown, 8 to 10 minutes.
  Cool on rack.  Just before serving, dust cookies with powdered sugar if
  desired.

  Source: Bon Appetit magazine, date unknown.
  Typed just for you by Karen Mintzias

  Collection of recipes from "Great Sysops of the World" from COOKFDN ops.

  File ftp://ftp.idiscover.co.uk/pub/food/mealmaster/recipes/mmgsotw1.zip

</step></directions></recipe></recipeml>


text:
<?php

namespace Magento\Framework\Code\Generator;

use Magento\Framework\Autoload\AutoloaderRegistry;

/**
 * DefinedClasses class detects if a class has been defined
 */
class DefinedClasses
{
    /**
     * Determine if a class can be loaded without using Code\Generator\Autoloader.
     *
     * @param string $className
     * @return bool
     */
    public function isClassLoadable($className)
    {
        return $this->isClassLoadableFromMemory($className) || $this->isClassLoadableFromDisc($className);
    }

    /**
     * Determine if a class exists in memory
     *
     * @param string $className
     * @return bool
     */
    public function isClassLoadableFromMemory($className)
    {
        return class_exists($className, false) || interface_exists($className, false);
    }

    /**
     * Determine if a class exists on disc
     *
     * @param string $className
     * @return bool
     */
    public function isClassLoadableFromDisc($className)
    {
        try {
            return (bool)AutoloaderRegistry::getAutoloader()->findFile($className);
        } catch (\Exception $e) {
            // Couldn't get access to the autoloader so we need to allow class_exists to call autoloader chain
            return (class_exists($className) || interface_exists($className));
        }
    }
}


text:
from __future__ import print_function
from setuptools import setup, find_packages, Command
from setuptools.command.sdist import sdist
from setuptools.command.build_py import build_py
from setuptools.command.egg_info import egg_info
from subprocess import check_call
import os
import sys
import platform

here = os.path.dirname(os.path.abspath(__file__))
node_root = os.path.join(here, 'js')
is_repo = os.path.exists(os.path.join(here, '.git'))

npm_path = os.pathsep.join([
    os.path.join(node_root, 'node_modules', '.bin'),
                os.environ.get('PATH', os.defpath),
])

from distutils import log
log.set_verbosity(log.DEBUG)
log.info('setup.py entered')
log.info('$PATH=%s' % os.environ['PATH'])

LONG_DESCRIPTION = 'A Custom Jupyter Widget Library'

def js_prerelease(command, strict=False):
    """decorator for building minified js/css prior to another command"""
    class DecoratedCommand(command):
        def run(self):
            jsdeps = self.distribution.get_command_obj('jsdeps')
            if not is_repo and all(os.path.exists(t) for t in jsdeps.targets):
                # sdist, nothing to do
                command.run(self)
                return

            try:
                self.distribution.run_command('jsdeps')
            except Exception as e:
                missing = [t for t in jsdeps.targets if not os.path.exists(t)]
                if strict or missing:
                    log.warn('rebuilding js and css failed')
                    if missing:
                        log.error('missing files: %s' % missing)
                    raise e
                else:
                    log.warn('rebuilding js and css failed (not a problem)')
                    log.warn(str(e))
            command.run(self)
            update_package_data(self.distribution)
    return DecoratedCommand

def update_package_data(distribution):
    """update package_data to catch changes during setup"""
    build_py = distribution.get_command_obj('build_py')
    # distribution.package_data = find_package_data()
    # re-init build_py options which load package_data
    build_py.finalize_options()

class NPM(Command):
    description = 'install package.json dependencies using npm'

    user_options = []

    node_modules = os.path.join(node_root, 'node_modules')

    targets = [
        os.path.join(here, 'beakerx', 'static', 'extension.js'),
        os.path.join(here, 'beakerx', 'static', 'index.js')
    ]

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def has_npm(self):
        try:
            check_call(['npm', '--version'])
            return True
        except:
            return False

    def should_run_npm_install(self):
        package_json = os.path.join(node_root, 'package.json')
        node_modules_exists = os.path.exists(self.node_modules)
        return self.has_npm()

    def run(self):
        has_npm = self.has_npm()
        if not has_npm:
            log.error("`npm` unavailable.  If you're running this command using sudo, make sure `npm` is available to sudo")

        env = os.environ.copy()
        env['PATH'] = npm_path

        if self.should_run_npm_install():
            log.info("Installing build dependencies with npm.  This may take a while...")
            check_call(['npm', 'install'], cwd=node_root, stdout=sys.stdout, stderr=sys.stderr)
            os.utime(self.node_modules, None)

        for t in self.targets:
            if not os.path.exists(t):
                msg = 'Missing file: %s' % t
                if not has_npm:
                    msg += '\nnpm is required to build a development version of widgetsnbextension'
                raise ValueError(msg)

        # update package data in case this created new files
        update_package_data(self.distribution)

version_ns = {}
with open(os.path.join(here, 'beakerx', '_version.py')) as f:
    exec(f.read(), {}, version_ns)

setup_args = {
    'name': 'beakerx',
    'version': version_ns['__version__'],
    'description': 'A Custom Jupyter Widget Library',
    'long_description': LONG_DESCRIPTION,
    'include_package_data': True,
    'data_files': [
        ('share/jupyter/nbextensions/beakerx', [
            'beakerx/static/extension.js',
            'beakerx/static/index.js',
            'beakerx/static/index.js.map',
        ]),
    ],
    'install_requires': [
        'ipywidgets>=5.1.5',
    ],
    'packages': find_packages(),
    'zip_safe': False,
    'cmdclass': {
        'build_py': js_prerelease(build_py),
        'egg_info': js_prerelease(egg_info),
        'sdist': js_prerelease(sdist, strict=True),
        'jsdeps': NPM,
    },

    'author': 'Two Sigma Open Source, LLC',
    'author_email': 'beaker-feedback@twosigma.com',
    'url': 'http://beakernotebook.com',
    'keywords': [
        'ipython',
        'jupyter',
        'widgets',
    ],
    'classifiers': [
        'Development Status :: 4 - Beta',
        'Framework :: IPython',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Topic :: Multimedia :: Graphics',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
}

setup(**setup_args)


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    /// <summary>
    /// The type WorkbookFunctionsBinom_InvRequestBuilder.
    /// </summary>
    public partial class WorkbookFunctionsBinom_InvRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsBinom_InvRequest>, IWorkbookFunctionsBinom_InvRequestBuilder
    {
        /// <summary>
        /// Constructs a new <see cref="WorkbookFunctionsBinom_InvRequestBuilder"/>.
        /// </summary>
        /// <param name="requestUrl">The URL for the request.</param>
        /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
        /// <param name="trials">A trials parameter for the OData method call.</param>
        /// <param name="probabilityS">A probabilityS parameter for the OData method call.</param>
        /// <param name="alpha">A alpha parameter for the OData method call.</param>
        public WorkbookFunctionsBinom_InvRequestBuilder(
            string requestUrl,
            IBaseClient client,
            Newtonsoft.Json.Linq.JToken trials,
            Newtonsoft.Json.Linq.JToken probabilityS,
            Newtonsoft.Json.Linq.JToken alpha)
            : base(requestUrl, client)
        {
            this.SetParameter("trials", trials, true);
            this.SetParameter("probabilityS", probabilityS, true);
            this.SetParameter("alpha", alpha, true);
        }

        /// <summary>
        /// A method used by the base class to construct a request class instance.
        /// </summary>
        /// <param name="functionUrl">The request URL to </param>
        /// <param name="options">The query and header options for the request.</param>
        /// <returns>An instance of a specific request class.</returns>
        protected override IWorkbookFunctionsBinom_InvRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
        {
            var request = new WorkbookFunctionsBinom_InvRequest(functionUrl, this.Client, options);

            if (this.HasParameter("trials"))
            {
                request.RequestBody.Trials = this.GetParameter<Newtonsoft.Json.Linq.JToken>("trials");
            }

            if (this.HasParameter("probabilityS"))
            {
                request.RequestBody.ProbabilityS = this.GetParameter<Newtonsoft.Json.Linq.JToken>("probabilityS");
            }

            if (this.HasParameter("alpha"))
            {
                request.RequestBody.Alpha = this.GetParameter<Newtonsoft.Json.Linq.JToken>("alpha");
            }

            return request;
        }
    }
}


text:
<!-- ****THIS IS A CODE GENERATED FILE DO NOT EDIT**** -->
<!-- Generated on Thu Apr 13 07:50:47 AEST 2017 -->
<md-select placeholder="Survey" [(ngModel)]="value">
    <md-option *ngFor="let type of Survey" [value]="type" >{{ type.Name }}</md-option>
</md-select>


text:
Please note I cannot release a gem version of iridium until
rake-pipeline releases a new version. This means you must specify git
dependencies in your `Gemfile`.

First create a `Gemfile`

```
source 'https://rubygems.org'

gem 'iridium', :github => 'radiumsoftware/iridium'
gem 'hydrogen', :github => 'radiumsoftware/hydrogen'
gem 'rake-pipeline', :github => 'livingsocial/rake-pipeline'
```

Now bootstrap:

```
$ bundle
$ bundle exec iridium g:application
```

Don't forget you **must use bundle exec!**

# Iridium: A Toolchain for JS Application Development

Iridium is a tool to help you with modern Javascript development. It's
here to make you a faster developer and solve common problems. It
focuses primarily on:

* CLI driven interactions
* Focus on JS/CSS/HTML
* Make JS testable

## Sensible Defaults

Iridium makes choices for you by default. These choices work well
together. All Iridium apps get all this right out of the box:

* Coffeescript
* Sass
* Spriting
* jQuery for DOM manipulation
* Handlebars for templating
* Minispade for simple modules and `require`
* Qunit or Jasmine for unit tests
* GZip assets in production
* Fully cache all assets in production
* Generate an HTML5 cache manifest for production
* i18n

## Getting Started

The first step is to use the built-in generator to create the structure:

```
$ iridium generate app todos
```

Now your application is ready. You can use the built in development server
to edit your JS/CSS files and reload the browser.

```
$ cd todos
$ iridium server
>> Thin web server (v1.4.1 codename Chromeo)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9292, CTRL+C to stop
```

Navigate to `http://localhost:9292` in your browser and you'll see a
blank canvas.

## Writing Javascript

Iridium compiles all `.coffee` files to `.js`. All files inside
`lib/` and `app/`. All files inside `app` are wrapped in minispade
modules. The module name comes from the file name. `require` calls are
rewritten to use `minispade.require`. Files inside `app/config` and
`app/config/initializers` are also compiled, but not wrapped in
modules. Files inside vendor code are not wrapped in modules. All of
the javascript + templates is concatenated into a single
`application.js`. The compiled `application.js` has this order:

1. `app/config/environment.coffee`
2. Vendored javascript in the specified order
3. The file in `app/config` matching the current environment. Example:
   `app/config/development.coffee` in development or
   `app/config/test.coffee` in tests.
4. All files in `app/config/initializers` wrapped in IFFEs
5. All the files from `lib/` wrapped in minispade modules
6. All the code in `app/javascripts` wrapped in minispade modules
7. I18n code
8. All handlebears templates compiled into Javascript.

You can inspect the final `application.js` to verify everything is
working as you expected.

Here are some examples:

| Path | Module Name | require |
| ---- | ----------- | ------- |
| `app/javascripts/foo.js` | `foo` | `require('foo')` |
| `app/javascripts/controllers/foo_contoller` | `controllers/foo_controller` | `require('controllers/foo_controller')` |
| `lib/framework.js` | `framework` | `require('framework')` |

### Vendored Javascripts

Files in `vendor/javascripts` are included before your application code.
All files in this directory are loaded before your app code in
alphabetical order unless an order is specified. You don't have to
specify the order for all files. You can declare files that should be
included before all others and not worry about the others. For example,
you have 10 files in `vendor/javascripts`. You only care that
`minispade`, `jquery`, and `jquery_ui` are loaded first. All the other
files will be included after those.

```ruby
# application.rb
Todos.configure do
  # load minispade, jquery, jquery_ui, then all other vendored files
  # Note, the symbol refers to the file name without extension.
  # example: :minispade => vendor/javascripts/minispade.js

  config.dependencies.load :minispade, :jquery, :jquery_ui
end
```

### Loading External Scripts

You may want to pull in external scripts via CDN instead of bundling
them inside your application. Configured scripts are written in as
`<script>` tags before your application code. Here's an example:

```ruby
# application.rb
Todos.configure do
  config.scripts.load "http://www.mycdn.com/script.js"
end
```

## Using SASS

Everything works as you expect. All `.scss` or `.sass` files are
compiled correctly. You can use `@import` as you'd expect.
`app/stylesheets` is added to the sass load path.

## Using Sprites

Create a directory for each set of sprites you need. Then `@import` it
as usual with compass. Here's an example. Create a directory named
`app/sprites/icons`. Dump all the individual icon png's in that
directory. Inside your stylesheet you can write:
`import('icons/*.png')` to generate the icons sprite.

## Writing Templates

Handlebars templates are named using the same semantics as application
javascript. All files `*.hanlebars` and `*.hbs` in `app/templates` are processed.
The templates are also precompiled depending on the environment.

| Path | Template Name |
| ---- | ----------- |
| `app/templates/dashboard.hbs` | `dashboard` |
| `app/templates/dashboard/settings.hbs` | `dashboard/settings` |

## Running Tests

Iridium makes testing your JS easy. It does all the manual work for you.
It compiles all the tests into `tests.js` and `tests.html`. You open
`tests.html` in your browser or use it with phantomjs. The test
command will compile your tests and check them with phantomjs. Qunit
and Jasmine are supported out of the box.

```
$ iridium test

# Running Tests:

.................................................................

2998 Test(s), 2998 Passed, 0 Error(s)
```

You can use `iridium test --debug` if you want to see `console.log`
messages in the report.

## JSLint

Coffescript is generated by default. You can write in Javscript if you
like. Iridium can run all your files through JSLint if you like.

```
$ iridium lint app/javascripts/app.js
$ iridium lint app/javascripts/models/* app/javascripts/controllers/*
$ iridium lint app/javascripts/**/*.js # this is the default!
```

## Localization (I18n)

Iridium supports localization via `i18n.js`. The i18n implementation is
taken from [here](https://github.com/fnando/i18n-js). All files in
`app/locales/*.yml` are merged into i18n translations. Here's an
example:

```yml
# app/locales/en.yml
en:
  greeting: Hello!
```

```yml
# app/locales/fi.yml
fi:
  greeting: Terve!
```

```js
I18n.locale = 'en'
I18n.t('greeting') // "Hello!"
I18n.locale = 'fi'
I18n.t('gretting') // "Terve!"
```

## Advanced Configuration

Iridium is written with Javascript developers in mind. They may not have
experience in ruby. I've tried as much as I can to shield some
complexity from newbies. Each part of Iridium is hidden by default, but
can be generated and customized.

### Configuration, Middleware, and Proxying

Your Iridium app is served as a rack app. You can inject your own
middleware as you like. Here's an example:

```ruby
# application.rb

YourApp.configure do
  # config.middleware mimics the Rack::Builder api
  config.middleware.use MyCustomMiddleware
end
```

Iridium also has basic proxy support for handling your backend API. You
should only use this proxy if the API does not support CORs or there is
some other issue with it. You may want to use this proxy in test mode to
point your app to a test server intead. Here's an example:

```
# application.rb
YourApp.configure do
  proxy "/api", "http://api.myproduct.com"
end
```

Proxies can be overwritten per env like this:

```
# application.rb
YourApp.configure do
  proxy "/api", "http://api.myproduct.com"
end

# config/test.rb
YourApp.configure do
  proxy "/api", "http://test-api.myproduct.com"
end
```

### Customizing The Unit Test Loader

Iridium uses a generated HTML file to load your test code into. You can
override this behavior by creating:
`test/support/unit_test_loader.html.erb`.

Here's what the default ERB template looks like:

```erb
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Unit Tests</title>

    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>

  <body>
    <% app.config.dependencies.each do |script| %>
      <script src="<%= script.url %>"></script>
    <% end %>

    <script src="application.js"></script>
  </body>
</html>
```

### Deploying

JS applications are simply a collection of static assets in a diretory.
This is trival to serve up with Rack. Iridium apps are rack apps for
serving up the compiled directory. The server also handles caching,
proxying, and custom middleware. All you need to do is create a
`config.ru` file and you can deploy your app! You can also deploy your
app for free on Heroku out of the box.

```ruby
# config.ru
require File.expand_path('../application', __FILE__)

run MyApp
```

Or if you don't care about that, you can run the generator:

```
$ cd my_app
$ iridium generate rackup
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
<!DOCTYPE html>

    <title>Calendula</title>
    <meta charset="utf-8" />
    <meta name="description" content="Calendula: Spécial calendrier en JavaScript" />
    <link rel="stylesheet" href="stylesheets/index.css" />
    <link rel="stylesheet" href="stylesheets/icons.css" />
    <link rel="stylesheet" href="dist/calendula.all.css" />

Calendula

Spécial calendrier en JavaScript

Design ergonomique

Animation avec l'aide de CSS

Support pour les appareils mobiles

Le manque de dépendances de bibliothèques

L'initialisation

Habillage

Localisation

            Lire la suite sur GitHub

Le téléchargement de...

L'utilisation la page

<link rel="stylesheet" href="calendula.css" />
<script src="calendula.js"></script>
...
<button id="datepicker">Choisir</button>
<script>
    var sc = new Calendula({
        theme: '',
        locale: '',
        button: document.querySelector('datepicker')
    });
</script>

L'assembly

                       Habillage:

                       Jours fériés:

                        Langues:

                        calendula.css:Octets:
                        <textarea class="source-css"></textarea>
                        Télécharger
                        Copier

                        calendula.js: Octets:
                        <textarea class="source-js"></textarea>
                        Télécharger
                        Copier


text:
<?php

namespace IntraLibrary\LibraryObject;

use \IntraLibrary\IntraLibraryException;
use \IntraLibrary\Cache;
use \IntraLibrary\Configuration;
use \IntraLibrary\Service\RESTRequest;

/**
 * TaxonomyData is used to retrieve information
 * (TaxonomyObject objects) about the available taxonomies
 *
 * @package IntraLibrary_PHP
 * @author  Janek Lasocki-Biczysko, <j.lasocki-biczysko@intrallect.com>
 *
 */
class TaxonomyData
{
    const CACHE_PREFIX_ID 	  = 'Id';
    const CACHE_PREFIX_REFID  = 'RefId';
    const CACHE_PREFIX_SOURCE = 'Source';

    private static $runtimeCache = array();

    /**
     * Get an object cached by the runtime
     *
     * @param string $key The cache key of the object to retrieve
     * @return TaxonomyObject
     */
    private static function runtimeCached($key)
    {
        return isset(self::$runtimeCache[$key]) ? self::$runtimeCache[$key] : false;
    }

    private $retrieveState;
    private $built = false;

    /**
     * Retrieve an TaxonomyObject by its ref id and source taxonomy
     *
     * @param string $objectRefId the object ref id
     * @param string $source      the source taxonomy
     * @return TaxonomyObject
     */
    public function retrieveByRefId($objectRefId, $source)
    {
        if (!$objectRefId || !$source) {
            return null;
        }

        $this->setRetrieveState($objectRefId, self::CACHE_PREFIX_REFID, 'taxon', $source);
        return $this->retrieve();
    }

    /**
     * Retrieve an TaxonomyObject by its ID
     *
     * @param integer $objectId the object id
     * @param string  $type     either taxon or taxonomy
     * @return TaxonomyObject
     */
    public function retrieveById($objectId, $type = 'taxon')
    {
        if (!$objectId) {
            return null;
        }

        $this->setRetrieveState($objectId, self::CACHE_PREFIX_ID, $type);
        return $this->retrieve();
    }

    /**
     * Retrieve an IntraLibaryTaxonomyObject taxonomy by its SOURCE identifier
     *
     * @param string $source the taxonomy source
     * @return TaxonomyObject
     */
    public function retrieveBySource($source)
    {
        if (!$source) {
            return null;
        }

        $this->setRetrieveState($source, self::CACHE_PREFIX_SOURCE, 'taxonomy');
        return $this->retrieve();
    }

    /**
     * Internal retrieve TaxonomyObject logic
     *
     * @return TaxonomyObject
     */
    private function retrieve()
    {
        // Check all caches
        $cacheKey 	= $this->getRetrieveStateCacheKey();
        $cached 	= Cache::load($cacheKey);
        if ($cached !== false) {
            return $cached;
        }

        $cached 	= self::runtimeCached($cacheKey);
        if ($cached !== false) {
            return $cached;
        }

        if (!$this->built) {

            // trigger a rebuild of the caches
            $this->getAvailableTaxonomies(true, false);
            $this->built = true;

            // and check the caches again
            return $this->retrieve();
        }

        return null;
    }

    /**
     * Get all taxonomy information available to the currrent user
     *
     * @param boolean $usingAdmin if true, will use the admin account to retrive taxonomies
     * @param boolean $useCache   if true will attempt to use cached taxonomies
     * @return array
     */
    public function getAvailableTaxonomies($usingAdmin = false, $useCache = true)
    {
        $key = $usingAdmin ? 'taxonomies//admin' : 'taxonomies//user:' . Configuration::get('username');

        if ($useCache) {
            // Check if it's cached..
            $taxonomyIds = Cache::load($key);
            if ($taxonomyIds !== false) {
                return $taxonomyIds;
            }
        }

        // Query the Taxonomy REST service
        $restReq 	= new RESTRequest();
        $response 	= $usingAdmin ? $restReq->adminGet('Taxonomy') : $restReq->get('Taxonomy');

        // Response contains usable data
        $data = $response->getData();
        if (isset($data['list']['taxonomy'])) {
            // parse the new response data
            $taxonomyIds	= $this->parseTaxonomyData($data['list']['taxonomy'], 'taxonomy');

            Cache::save($key, $taxonomyIds);

            return $taxonomyIds;
        }

        return array();
    }

    /**
     * Recursively parse response data from the webservice call, generate
     * TaxonomyObject objects and cache them.
     *
     * @SuppressWarnings(PHPMD.ShortVariable)
     *
     * @param array          $object    The data to parse
     * @param string         $type      The type of taxonomy object
     * @param TaxonomyObject $parentObj The parent object
     * @param string         $source    The taxonomy source
     * @throws IntraLibraryException if the $type is invalid
     * @return array an array of taxonomy object ids contained at the highest level of the $object data
     */
    private function parseTaxonomyData($object, $type, TaxonomyObject $parentObj = null, $source = null)
    {
        // This is an array of objects
        if (!empty($object[0])) {
            $taxonomyObjectIds = array();
            foreach ($object as $o) {
                $objectIds = $this->parseTaxonomyData($o, $type, $parentObj, $source);
                $taxonomyObjectIds = array_merge($taxonomyObjectIds, $objectIds);
            }
            return $taxonomyObjectIds;
        } elseif (!empty($object['_attributes'])) {
            $taxonomyObj = new TaxonomyObject($type, $object['_attributes']);
            $taxonomyObj->setParent($parentObj);

            // only update the 'source' if this is a TAXONOMY
            if ($type == TaxonomyObject::TAXONOMY) {
                $source = $taxonomyObj->getSource();
            }

            // if the object has a 'taxon' value, search it for children
            if (!empty($object['taxon'])) {
                $childIds = $this->parseTaxonomyData($object['taxon'], 'taxon', $taxonomyObj, $source);
                $taxonomyObj->setChildrenIds($childIds);
            }

            $this->cacheObject($taxonomyObj, $source);

            return array($taxonomyObj->getId());
        } else {
            throw new IntraLibraryException('Invalid taxon data');
        }
    }

    /**
     * Get the SOURCE of a taxonomy object
     *
     * @param TaxonomyObject $object the taxonomy object
     * @return string
     */
    public function getSource($object)
    {
        if (!$object instanceof TaxonomyObject) {
            return null;
        }

        if ($object->getType() == TaxonomyObject::TAXON) {
            $parent	= $this->retrieveById($object->getParentId(), $object->getParentType());
            return $this->getSource($parent);
        }

        if ($object->getType() == TaxonomyObject::TAXONOMY) {
            return $object->getSource();
        }

        return null;
    }

    /**
     * Get the source of an object from its ID
     *
     * @param string $objectId the object id
     * @param string $type     the object type
     * @return string
     */
    public function getSourceFromId($objectId, $type = 'taxon')
    {
        return $this->getSource($this->retrieveById($objectId, $type));
    }

    /**
     * Set the state for a retrieve action
     *
     * @param string $identifier  the identifier
     * @param string $cachePrefix the cache prefix / identifier type
     * @param string $type        the object type (taxon / taxonomy)
     * @param string $source      the taxonomy source
     * @return void
     */
    private function setRetrieveState($identifier, $cachePrefix, $type, $source = null)
    {
        $this->retrieveState = array(
            'type' => $type,
            'cachePrefix' => $cachePrefix,
            'identifier' => $identifier,
            'source' => $source
        );
    }

    /**
     * Cache an intralibrary object
     *
     * @param TaxonomyObject $object the object
     * @param string         $source the taxonomy source of this object
     * @return void
     */
    private function cacheObject(TaxonomyObject $object, $source)
    {
        $type 		= $object->getType();

        $key_id 	= $this->getCacheKey($object->getId(), self::CACHE_PREFIX_ID, $type);
        Cache::save($key_id, $object, 0);
        self::$runtimeCache[$key_id] = $object;

        if ($type == TaxonomyObject::TAXON) {
            $key_refId	= $this->getCacheKey($object->getRefId(), self::CACHE_PREFIX_REFID, $type, $source);
            Cache::save($key_refId, $object, 0);
            self::$runtimeCache[$key_refId] = $object;
        } elseif ($type == TaxonomyObject::TAXONOMY) {
            $key_source	= $this->getCacheKey($object->getSource(), self::CACHE_PREFIX_SOURCE, $type);
            Cache::save($key_source, $object, 0);
            self::$runtimeCache[$key_source] = $object;
        }
    }

    /**
     * Get a cache key based on the current retrieve state
     *
     * @return string
     */
    private function getRetrieveStateCacheKey()
    {
        $type = $cachePrefix = $identifier = $source = '';
        extract($this->retrieveState);

        return $this->getCacheKey($identifier, $cachePrefix, $type, $source);
    }

    /**
     * Get a cache key
     *
     * @param string $identifier  the identifier
     * @param string $cachePrefix the cache prefix / identifier type
     * @param string $type        the object type (taxon / taxonomy)
     * @param string $source      the taxonomy source
     * @return string
     */
    private function getCacheKey($identifier, $cachePrefix, $type, $source = '')
    {
        return "{$type}-{$cachePrefix}-{$source}_{$identifier}";
    }
}


text:
from collections import OrderedDict
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources

from google.api_core import client_options as client_options_lib
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport import mtls  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore
from google.auth.exceptions import MutualTLSChannelError  # type: ignore
from google.oauth2 import service_account  # type: ignore

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object]  # type: ignore

from google.ads.googleads.v12.services.types import asset_set_service
from google.rpc import status_pb2  # type: ignore
from .transports.base import AssetSetServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import AssetSetServiceGrpcTransport

class AssetSetServiceClientMeta(type):
    """Metaclass for the AssetSetService client.

    This provides class-level methods for building and retrieving
    support objects (e.g. transport) without polluting the client instance
    objects.
    """

    _transport_registry = (
        OrderedDict()
    )  # type: Dict[str, Type[AssetSetServiceTransport]]
    _transport_registry["grpc"] = AssetSetServiceGrpcTransport

    def get_transport_class(
        cls, label: str = None,
    ) -> Type[AssetSetServiceTransport]:
        """Returns an appropriate transport class.

        Args:
            label: The name of the desired transport. If none is
                provided, then the first transport in the registry is used.

        Returns:
            The transport class to use.
        """
        # If a specific transport is requested, return that one.
        if label:
            return cls._transport_registry[label]

        # No transport is requested; return the default (that is, the first one
        # in the dictionary).
        return next(iter(cls._transport_registry.values()))

class AssetSetServiceClient(metaclass=AssetSetServiceClientMeta):
    """Service to manage asset set"""

    @staticmethod
    def _get_default_mtls_endpoint(api_endpoint):
        """Converts api endpoint to mTLS endpoint.

        Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
        "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
        Args:
            api_endpoint (Optional[str]): the api endpoint to convert.
        Returns:
            str: converted mTLS api endpoint.
        """
        if not api_endpoint:
            return api_endpoint

        mtls_endpoint_re = re.compile(
            r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
        )

        m = mtls_endpoint_re.match(api_endpoint)
        name, mtls, sandbox, googledomain = m.groups()
        if mtls or not googledomain:
            return api_endpoint

        if sandbox:
            return api_endpoint.replace(
                "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
            )

        return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")

    DEFAULT_ENDPOINT = "googleads.googleapis.com"
    DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__(  # type: ignore
        DEFAULT_ENDPOINT
    )

    @classmethod
    def from_service_account_info(cls, info: dict, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
            info.

        Args:
            info (dict): The service account private key info.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            AssetSetServiceClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_info(
            info
        )
        kwargs["credentials"] = credentials
        return cls(*args, **kwargs)

    @classmethod
    def from_service_account_file(cls, filename: str, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
        file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            AssetSetServiceClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_file(
            filename
        )
        kwargs["credentials"] = credentials
        return cls(*args, **kwargs)

    from_service_account_json = from_service_account_file

    @property
    def transport(self) -> AssetSetServiceTransport:
        """Returns the transport used by the client instance.

        Returns:
            AssetSetServiceTransport: The transport used by the client
                instance.
        """
        return self._transport

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        """Releases underlying transport's resources.

        .. warning::
            ONLY use as a context manager if the transport is NOT shared
            with other clients! Exiting the with block will CLOSE the transport
            and may cause errors in other clients!
        """
        self.transport.close()

    @staticmethod
    def asset_set_path(customer_id: str, asset_set_id: str,) -> str:
        """Returns a fully-qualified asset_set string."""
        return "customers/{customer_id}/assetSets/{asset_set_id}".format(
            customer_id=customer_id, asset_set_id=asset_set_id,
        )

    @staticmethod
    def parse_asset_set_path(path: str) -> Dict[str, str]:
        """Parses a asset_set path into its component segments."""
        m = re.match(
            r"^customers/(?P<customer_id>.+?)/assetSets/(?P<asset_set_id>.+?)$",
            path,
        )
        return m.groupdict() if m else {}

    @staticmethod
    def common_billing_account_path(billing_account: str,) -> str:
        """Returns a fully-qualified billing_account string."""
        return "billingAccounts/{billing_account}".format(
            billing_account=billing_account,
        )

    @staticmethod
    def parse_common_billing_account_path(path: str) -> Dict[str, str]:
        """Parse a billing_account path into its component segments."""
        m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_folder_path(folder: str,) -> str:
        """Returns a fully-qualified folder string."""
        return "folders/{folder}".format(folder=folder,)

    @staticmethod
    def parse_common_folder_path(path: str) -> Dict[str, str]:
        """Parse a folder path into its component segments."""
        m = re.match(r"^folders/(?P<folder>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_organization_path(organization: str,) -> str:
        """Returns a fully-qualified organization string."""
        return "organizations/{organization}".format(organization=organization,)

    @staticmethod
    def parse_common_organization_path(path: str) -> Dict[str, str]:
        """Parse a organization path into its component segments."""
        m = re.match(r"^organizations/(?P<organization>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_project_path(project: str,) -> str:
        """Returns a fully-qualified project string."""
        return "projects/{project}".format(project=project,)

    @staticmethod
    def parse_common_project_path(path: str) -> Dict[str, str]:
        """Parse a project path into its component segments."""
        m = re.match(r"^projects/(?P<project>.+?)$", path)
        return m.groupdict() if m else {}

    @staticmethod
    def common_location_path(project: str, location: str,) -> str:
        """Returns a fully-qualified location string."""
        return "projects/{project}/locations/{location}".format(
            project=project, location=location,
        )

    @staticmethod
    def parse_common_location_path(path: str) -> Dict[str, str]:
        """Parse a location path into its component segments."""
        m = re.match(
            r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path
        )
        return m.groupdict() if m else {}

    def __init__(
        self,
        *,
        credentials: Optional[ga_credentials.Credentials] = None,
        transport: Union[str, AssetSetServiceTransport, None] = None,
        client_options: Optional[client_options_lib.ClientOptions] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
    ) -> None:
        """Instantiates the asset set service client.

        Args:
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            transport (Union[str, AssetSetServiceTransport]): The
                transport to use. If set to None, a transport is chosen
                automatically.
            client_options (google.api_core.client_options.ClientOptions): Custom options for the
                client. It won't take effect if a ``transport`` instance is provided.
                (1) The ``api_endpoint`` property can be used to override the
                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
                environment variable can also be used to override the endpoint:
                "always" (always use the default mTLS endpoint), "never" (always
                use the default regular endpoint) and "auto" (auto switch to the
                default mTLS endpoint if client certificate is present, this is
                the default value). However, the ``api_endpoint`` property takes
                precedence if provided.
                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
                is "true", then the ``client_cert_source`` property can be used
                to provide client certificate for mutual TLS transport. If
                not provided, the default SSL client certificate will be used if
                present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
                set, no client certificate will be used.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.

        Raises:
            google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
                creation failed for any reason.
        """
        if isinstance(client_options, dict):
            client_options = client_options_lib.from_dict(client_options)
        if client_options is None:
            client_options = client_options_lib.ClientOptions()

        # Create SSL credentials for mutual TLS if needed.
        if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in (
            "true",
            "false",
        ):
            raise ValueError(
                "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
            )
        use_client_cert = (
            os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true"
        )

        client_cert_source_func = None
        is_mtls = False
        if use_client_cert:
            if client_options.client_cert_source:
                is_mtls = True
                client_cert_source_func = client_options.client_cert_source
            else:
                is_mtls = mtls.has_default_client_cert_source()
                if is_mtls:
                    client_cert_source_func = mtls.default_client_cert_source()
                else:
                    client_cert_source_func = None

        # Figure out which api endpoint to use.
        if client_options.api_endpoint is not None:
            api_endpoint = client_options.api_endpoint
        else:
            use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
            if use_mtls_env == "never":
                api_endpoint = self.DEFAULT_ENDPOINT
            elif use_mtls_env == "always":
                api_endpoint = self.DEFAULT_MTLS_ENDPOINT
            elif use_mtls_env == "auto":
                api_endpoint = (
                    self.DEFAULT_MTLS_ENDPOINT
                    if is_mtls
                    else self.DEFAULT_ENDPOINT
                )
            else:
                raise MutualTLSChannelError(
                    "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
                    "values: never, auto, always"
                )

        # Save or instantiate the transport.
        # Ordinarily, we provide the transport, but allowing a custom transport
        # instance provides an extensibility point for unusual situations.
        if isinstance(transport, AssetSetServiceTransport):
            # transport is a AssetSetServiceTransport instance.
            if credentials or client_options.credentials_file:
                raise ValueError(
                    "When providing a transport instance, "
                    "provide its credentials directly."
                )
            if client_options.scopes:
                raise ValueError(
                    "When providing a transport instance, provide its scopes "
                    "directly."
                )
            self._transport = transport
        else:
            Transport = type(self).get_transport_class(transport)
            self._transport = Transport(
                credentials=credentials,
                credentials_file=client_options.credentials_file,
                host=api_endpoint,
                scopes=client_options.scopes,
                client_cert_source_for_mtls=client_cert_source_func,
                quota_project_id=client_options.quota_project_id,
                client_info=client_info,
                always_use_jwt_access=True,
            )

    def mutate_asset_sets(
        self,
        request: Union[asset_set_service.MutateAssetSetsRequest, dict] = None,
        *,
        customer_id: str = None,
        operations: Sequence[asset_set_service.AssetSetOperation] = None,
        retry: OptionalRetry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> asset_set_service.MutateAssetSetsResponse:
        r"""Creates, updates or removes asset sets. Operation
        statuses are returned.

        Args:
            request (Union[google.ads.googleads.v12.services.types.MutateAssetSetsRequest, dict]):
                The request object. Request message for
                [AssetSetService.MutateAssetSets][google.ads.googleads.v12.services.AssetSetService.MutateAssetSets].
            customer_id (str):
                Required. The ID of the customer
                whose asset sets are being modified.

                This corresponds to the ``customer_id`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            operations (Sequence[google.ads.googleads.v12.services.types.AssetSetOperation]):
                Required. The list of operations to
                perform on individual asset sets.

                This corresponds to the ``operations`` field
                on the ``request`` instance; if ``request`` is provided, this
                should not be set.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.
            timeout (float): The timeout for this request.
            metadata (Sequence[Tuple[str, str]]): Strings which should be
                sent along with the request as metadata.

        Returns:
            google.ads.googleads.v12.services.types.MutateAssetSetsResponse:
                Response message for an asset set
                mutate.

        """
        # Create or coerce a protobuf request object.
        # Quick check: If we got a request object, we should *not* have
        # gotten any keyword arguments that map to the request.
        has_flattened_params = any([customer_id, operations])
        if request is not None and has_flattened_params:
            raise ValueError(
                "If the `request` argument is set, then none of "
                "the individual field arguments should be set."
            )

        # Minor optimization to avoid making a copy if the user passes
        # in a asset_set_service.MutateAssetSetsRequest.
        # There's no risk of modifying the input as we've already verified
        # there are no flattened fields.
        if not isinstance(request, asset_set_service.MutateAssetSetsRequest):
            request = asset_set_service.MutateAssetSetsRequest(request)
            # If we have keyword arguments corresponding to fields on the
            # request, apply these.
            if customer_id is not None:
                request.customer_id = customer_id
            if operations is not None:
                request.operations = operations

        # Wrap the RPC method; this adds retry and timeout information,
        # and friendly error handling.
        rpc = self._transport._wrapped_methods[
            self._transport.mutate_asset_sets
        ]

        # Certain fields should be provided within the metadata header;
        # add these here.
        metadata = tuple(metadata) + (
            gapic_v1.routing_header.to_grpc_metadata(
                (("customer_id", request.customer_id),)
            ),
        )

        # Send the request.
        response = rpc(
            request, retry=retry, timeout=timeout, metadata=metadata,
        )

        # Done; return the response.
        return response

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution("google-ads",).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

__all__ = ("AssetSetServiceClient",)


text:
<html>
<head>
<link rel="stylesheet" href="./resources/empty.css">
<script src="../../http/tests/inspector/inspector-test.js"></script>
<script src="../../http/tests/inspector/debugger-test.js"></script>
<script src="./autocomplete-test.js"></script>
<script src="../editor/editor-test.js"></script>
<script>
function test()
{
    InspectorTest.showScriptSource("empty.css", onSourceFrame);

    var textEditor;
    var dumpSuggestions;
    function onSourceFrame(sourceFrame)
    {
        textEditor = sourceFrame.textEditor;
        dumpSuggestions = InspectorTest.dumpSuggestions.bind(InspectorTest, textEditor);
        InspectorTest.runTestSuite(testSuite);
    }

    var testSuite = [
        function testClassNameAutocomplete(next)
        {
            dumpSuggestions([
                ".red { color: red }",
                ".blue { color: blue }",
                ".|"
            ]);
            next();
        },

        function testPropertyNameAutocomplete(next)
        {
            dumpSuggestions([
                ".red { color: red }",
                ".blue { c|"
            ]);
            dumpSuggestions([
                ".my-class { -|webkit-border: 1px solid black; -webkit-color: blue;",
                "text-align: }"
            ]);
            next();
        },

        function testPropertyValueAutocomplete(next)
        {
            dumpSuggestions([
                ".red { border-style: |",
                "/* some other words to mess up */"
            ]);
            dumpSuggestions([
                ".red { border-style: d|",
                "/* dial drummer dig */"
            ]);
            dumpSuggestions([
                ".red { border-style: z|",
                "/* zipper zorro zion */"
            ]);
            dumpSuggestions([
                ".red { border-style/* comment */: /* comment */|"
            ]);
            dumpSuggestions([
                ".my-class { -webkit-border: 1px solid black; -webkit-color: blue;",
                "text-align: |}"
            ]);
            next();
        },

        function verifySuggestionsOnColumnTypedIn(next)
        {
            textEditor.element.focus();
            textEditor.setText([
                ".green {",
                "   display"
            ].join("\n"));
            textEditor.setSelection(WebInspector.TextRange.createFromLocation(1, 10));
            InspectorTest.dumpTextWithSelection(textEditor);
            var suggestions = [];
            InspectorTest.addSniffer(WebInspector.TextEditorAutocompleteController.prototype, "_onSuggestionsShownForTest", function(words) { suggestions = words; });
            InspectorTest.addSniffer(WebInspector.TextEditorAutocompleteController.prototype, "autocomplete", onTypedIn);
            InspectorTest.typeIn(textEditor, ":");

            function onTypedIn()
            {
                InspectorTest.addResult("Suggestions displayed on ':' symbol typed in:");
                InspectorTest.addResult("[" + suggestions.join(", ") + "]");
                next();
            }
        },
    ];
}
</script>
</head>

<body onload="runTest();">
<p>
The test verifies autocomplete suggestions for CSS file.
</p>
</body>
</html>


text:
$(window).load(init);

function init() {
    switch (window.eu.id) {
        case "aNr_schedule":
            schedule.initialize();
            break;
    }
}

var schedule = {
    initialize: function () {
        var self = this;

        // fetch details of modules, alerts and reminders
        this.getMAR(function (modulesList) {
            // fill up alerts and reminders
            self._fillAlertsAndReminders(modulesList);

            // fetch existing schedule information
            self.fetch(function (data) {
                self._onScheduleFetch(data);
            });
        });

        $("#alerts,#reminders").select2();

        // form validation and submit handler
        $("#scheduleForm").validate({
            highlight: function (element, errorClass, validClass) {
                $(element).parent().addClass("has-error");
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).parent().removeClass("has-error");
            },
            submitHandler: function (form) {
                // method to submit this form
                self.save();

                return false;
            },
            invalidHandler: function (ev, validator) {
                if (validator.numberOfInvalids()) {
                    $("#errorMessage-1").show();
                } else {
                    $("#errorMessage-1").hide();
                }
            }
        });
    },

    // fill up list of alerts and reminders
    _fillAlertsAndReminders: function (mar) {
        var $alerts = $("#alerts"),
            $reminders = $("#reminders"),
            $alertOptgroup,
            $reminderOptgroup;

        $.each(mar, function (key, value) {
            if (value.alerts.length > 0) {
                $alertOptgroup = createElement("<optgroup/>", $alerts, { 'label': value.name });
                fillDropDown($alertOptgroup, value.alerts, "name", "id");
            }

            if (value.reminders.length > 0) {
                $reminderOptgroup = createElement("<optgroup/>", $reminders, { 'label': value.name });
                fillDropDown($reminderOptgroup, value.reminders, "name", "id");
            }
        });
    },

    // method to execute when a schedule is fetched
    _onScheduleFetch: function (scheduleDetails) {
        this.id = scheduleDetails['id'];

        scheduleDetails.alerts = this.getCSV_fromBinDec(scheduleDetails.alerts);
        scheduleDetails.reminders = this.getCSV_fromBinDec(scheduleDetails.reminders);

        $.each(scheduleDetails, function (key, value) {
            switch(key) {
                case "alerts":
                    $("#alerts").select2("val", value.split(","));
                    break;

                case "reminders":
                    $("#reminders").select2("val", value.split(","));
                    break;

                default:
                    key = $("#" + key);

                    if (key.is("input[type='checkbox']")) {
                        key.prop("checked", +value);
                    } else {
                        key.val(value);
                    }
                    break;
            }
        });
    },

    id: null,

    // get a list of modules with their respective alerts and reminders
    getMAR: function (callback) {
        var self = this;

        $.ajax({
            type: "GET",
            async: true,
            url: "/embarc-utils/php/main.php?util=anr&fx=getMAR",
            success: function (data) {
                try {
                    data = getJSONFromString(data);
                } catch (ex) {
                    console.log("Invalid list of alerts & reminders received from server");
                    return;
                }

                if (callback) callback.apply(self, [data]);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("unable to fetch list of modules, alerts and reminders " + errorThrown);
            }
        });
    },

    // fetch existing schedule for current user
    fetch: function (fetchCallback) {
        var self = this;

        $.ajax({
            type: "GET",
            async: true,
            url: "/embarc-utils/php/main.php?util=anr&fx=get",
            success: function (data, textStatus, jqXHR) {
                try {
                    data = getJSONFromString(data);
                } catch (ex) {
                    console.log("Invalid schedule received from server");
                    return;
                }

                if (fetchCallback) fetchCallback.apply(self, [data]);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("unable to fetch schedule from server " + errorThrown);
            }
        });

    },

    // save a schedule
    save: function () {
        // hide error & success messages
        $("#successMessage-1").hide();
        $("#errorMessage-1").hide();

        var jsdata = createObject(["scheduleForm"]);

        jsdata.alerts = this.getBinDec_fromCSV(jsdata.alerts);
        jsdata.reminders = this.getBinDec_fromCSV(jsdata.reminders);

        $.ajax({
            type: "POST",
            async: true,
            data: jsdata,
            url: "/embarc-utils/php/main.php?util=anr&fx=save" + (this.id?("&id=" + this.id): ""),
            success: function (data, textStatus, jqXHR) {
                if (data == "SUCCESS") {
                    $("#successMessage-1").show();
                } else {
                    $("#errorMessage-1").show();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("unable to save schedule " + errorThrown);
            }
        });

    },

    // convert a list of comma seperated values to binary number
    getBinDec_fromCSV: function (csvstr) {
        var temp = 0,
            i = 0;

        csvstr = csvstr.split(",");
        for (; i < csvstr.length; i++) {
            temp |= +csvstr[i];
        }

        return temp;
    },

    // convert a binary number to a list of comma separated values
    getCSV_fromBinDec: function (number) {
        number = parseInt(number, 10);

        var temp = [],
            c = 1;

        while (number) {
            if (number & 1) temp.push(c);
            number = number >> 1;
            c++;
        }

        return temp.join(",");
    },
};

/**
* Contributions
*
*
* jQuery
* URL: http://jquery.com/
* GitHub: https://github.com/jquery/jquery
*
* Bootstrap
* URL: http://getbootstrap.com/
* GitHub: https://github.com/twbs/bootstrap/
*
* select2.js
* URL: http://ivaynberg.github.io/select2/
* GitHub: https://github.com/ivaynberg/select2
*
* jQuery.validate
* URL: http://jqueryvalidation.org/
* GitHub: https://github.com/jzaefferer/jquery-validation
*/


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Ortega, Vizoso & Contu, Docums Mycol. , mém. hors sér. 21(no. 82): 23 (1991)

#### Original name
Collybia benoistii Boud., 1901

### Remarks
null


text:
package nl.ebpi.yaidom.indexed

import java.net.URI

import scala.collection.immutable
import scala.reflect.ClassTag
import scala.reflect.classTag

import nl.ebpi.yaidom.core.Path
import nl.ebpi.yaidom.queryapi.ClarkElemApi
import nl.ebpi.yaidom.queryapi.Nodes
import nl.ebpi.yaidom.queryapi.XmlBaseSupport

/**
 * An element within its context. In other words, an element as a pair containing the root element (of an underlying element type)
 * and a path (from that root element) to this element. More precisely, this element implementation contains an underlying root element,
 * a Path, and an underlying element found from the root element following the Path. It also contains an optional URI
 * of the containing document, if any.
 *
 * '''See the documentation of the mixed-in query API trait(s) for more details on the uniform query API offered by this class.'''
 *
 * An `IndexedClarkElem(rootElem)` can be seen as one '''immutable snapshot''' of an XML tree. All queries (using the `ElemApi` uniform
 * query API) on that snapshot return results within the same snapshot. Take care not to mix up query results from different
 * snapshots. (This could have been modeled in an alternative design of the class, using a member type, but such a design has
 * not been chosen.)
 *
 * Using IndexedClarkElem objects, it is easy to get the ancestry or siblings of an element, as elements of the underlying element type.
 *
 * Be careful not to create any '''memory leaks'''. After all, an element, even a leaf element, typically keeps the entire underlying
 * document element tree as state. Hence the underlying document element tree will always remain in memory if at least
 * one indexed element contains it in its state. (Yet with mutable org.w3c.dom element trees, it is also easy to cause
 * memory leaks. See http://apmblog.compuware.com/2011/04/20/the-top-java-memory-problems-part-1/.)
 *
 * Having an IndexedClarkElem, it is always possible to re-create the root element as IndexedClarkElem, because
 * the underlying root element is always available. On the other hand, creating an IndexedClarkElem is expensive. Class
 * IndexedClarkElem is optimized for fast querying, at the expense of costly recursive creation.
 *
 * The optional parent base URI is stored for very fast (optional) base URI computation. This is helpful in
 * an XBRL context, where URI resolution against a base URI is typically a very frequent operation.
 *
 * ==IndexedClarkElem examples==
 *
 * The following example code shows how to query for elements with a known ancestry,
 * regardless of the element implementation, if efficiency is not important:
 *
 * {{{
 * val iBookstore = IndexedClarkElem(bookstore)
 *
 * val iTheBookAuthors =
 *   for {
 *     iAuthor <- iBookstore.filterElems(withLocalName("Author"))
 *     bookPath <- iAuthor.path.findAncestorPath(_.elementNameOption.map(_.localPart) == Some("Book"))
 *     iBook <- iBookstore.findElem(_.path == bookPath)
 *     if iBook.getChildElem(withLocalName("Title")).elem.text.startsWith("Programming in Scala")
 *   } yield iAuthor
 * }}}
 *
 * ==IndexedClarkElem more formally==
 *
 * '''In order to use this class, this more formal section can safely be skipped.'''
 *
 * The ``IndexedClarkElem`` class can be understood in a precise mathematical sense, as shown below.
 *
 * Some properties of IndexedClarkElems are as follows:
 * {{{
 * // All elements (obtained from querying other elements) have the same rootElem
 *
 * iElem.findAllElemsOrSelf.map(_.rootElem).distinct == List(iElem.rootElem)
 *
 * // The correspondence between rootElem, path and elem
 *
 * iElem.findAllElemsOrSelf.forall(e => e.rootElem.findElemOrSelfByPath(e.path).get == e.elem)
 * }}}
 *
 * The correspondence between queries on IndexedClarkElems and the same queries on the underlying elements is as follows:
 * {{{
 * // Let p be a function from underlying element type E to Boolean
 *
 * IndexedClarkElem(rootElem).filterElemsOrSelf(e => p(e.elem)).map(_.elem) ==
 *   rootElem.filterElemsOrSelf(p)
 * }}}
 *
 * Analogous properties hold for the other query methods.
 *
 * @tparam U The underlying element type
 *
 * @author Chris de Vreeze
 */
final class IndexedClarkElem[U <: ClarkElemApi[U]] private (
  val docUriOption: Option[URI],
  val parentBaseUriOption: Option[URI],
  val rootElem: U,
  childElems: immutable.IndexedSeq[IndexedClarkElem[U]],
  val path: Path,
  val elem: U,
  val uriResolver: XmlBaseSupport.UriResolver) extends Nodes.Elem with IndexedClarkElemLike[IndexedClarkElem[U], U] {

  private implicit val uTag: ClassTag[U] = classTag[U]

  /**
   * Asserts internal consistency of the element. That is, asserts that the redundant fields are mutually consistent.
   * These assertions are not invoked during element construction, for performance reasons. Test code may invoke this
   * method. Users of the API do not need to worry about this method. (In fact, looking at the implementation of this
   * class, it can be reasoned that these assertions must hold.)
   */
  private[yaidom] def assertConsistency(): Unit = {
    assert(elem == rootElem.getElemOrSelfByPath(path), "Corrupt element!")
    assert(childElems.map(_.elem) == elem.findAllChildElems, "Corrupt element!")
    assert(childElems.forall(_.docUriOption eq this.docUriOption), "Corrupt element!")
  }

  final def findAllChildElems: immutable.IndexedSeq[IndexedClarkElem[U]] = childElems

  final override def equals(obj: Any): Boolean = obj match {
    case other: IndexedClarkElem[U] =>
      (other.docUriOption == this.docUriOption) && (other.rootElem == this.rootElem) && (other.path == this.path)
    case _ => false
  }

  final override def hashCode: Int = (docUriOption, rootElem, path).hashCode

  final def baseUriOption: Option[URI] = {
    XmlBaseSupport.findBaseUriByParentBaseUri(parentBaseUriOption, elem)(uriResolver)
  }

  /**
   * Returns the document URI, falling back to the empty URI if absent.
   */
  final def docUri: URI = docUriOption.getOrElse(new URI(""))

  /**
   * Returns the base URI, falling back to the empty URI if absent.
   */
  final def baseUri: URI = baseUriOption.getOrElse(new URI(""))
}

object IndexedClarkElem {

  /**
   * Builder of `IndexedClarkElem` objects. The builder has a chosen URI resolver strategy. Typically these
   * builders are long-lived global objects. Each element created with this builder will have the same URI resolver,
   * viz. the one passed as constructor argument of the builder.
   */
  final case class Builder[U <: ClarkElemApi[U]](
    val underlyingType: ClassTag[U],
    override val uriResolver: XmlBaseSupport.UriResolver) extends IndexedClarkElemApi.Builder[IndexedClarkElem[U], U] {

    override def build(rootElem: U): IndexedClarkElem[U] =
      build(None, rootElem)

    override def build(docUriOption: Option[URI], rootElem: U): IndexedClarkElem[U] =
      build(docUriOption, rootElem, Path.Empty)

    override def build(rootElem: U, path: Path): IndexedClarkElem[U] = {
      build(None, rootElem, path)
    }

    /**
     * Expensive recursive factory method for "indexed elements".
     */
    override def build(docUriOption: Option[URI], rootElem: U, path: Path): IndexedClarkElem[U] = {
      // Expensive call, so invoked only once
      val elem = rootElem.findElemOrSelfByPath(path).getOrElse(
        sys.error(s"Could not find the element with path $path from root ${rootElem.resolvedName}"))

      val parentBaseUriOption: Option[URI] =
        path.parentPathOption.flatMap(pp => XmlBaseSupport.findBaseUriByDocUriAndPath(docUriOption, rootElem, pp)(uriResolver)).orElse(docUriOption)

      build(docUriOption, parentBaseUriOption, rootElem, path, elem)
    }

    private def build(
      docUriOption: Option[URI],
      parentBaseUriOption: Option[URI],
      rootElem: U,
      path: Path,
      elem: U): IndexedClarkElem[U] = {

      val baseUriOption =
        XmlBaseSupport.findBaseUriByParentBaseUri(parentBaseUriOption, elem)(uriResolver)

      // Recursive calls
      val childElems = elem.findAllChildElemsWithPathEntries map {
        case (e, entry) =>
          build(docUriOption, baseUriOption, rootElem, path.append(entry), e)
      }

      new IndexedClarkElem(docUriOption, parentBaseUriOption, rootElem, childElems, path, elem, uriResolver)
    }
  }

  /**
   * Calls `Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(rootElem)`
   */
  def apply[U <: ClarkElemApi[U]: ClassTag](rootElem: U): IndexedClarkElem[U] = {
    Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(rootElem)
  }

  /**
   * Calls `Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(docUriOption, rootElem)`
   */
  def apply[U <: ClarkElemApi[U]: ClassTag](docUriOption: Option[URI], rootElem: U): IndexedClarkElem[U] = {
    Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(docUriOption, rootElem)
  }

  /**
   * Calls `Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(Some(docUri), rootElem)`
   */
  def apply[U <: ClarkElemApi[U]: ClassTag](docUri: URI, rootElem: U): IndexedClarkElem[U] = {
    Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(Some(docUri), rootElem)
  }

  /**
   * Calls `Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(rootElem, path)`
   */
  def apply[U <: ClarkElemApi[U]: ClassTag](rootElem: U, path: Path): IndexedClarkElem[U] = {
    Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(rootElem, path)
  }

  /**
   * Calls `Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(docUriOption, rootElem, path)`
   */
  def apply[U <: ClarkElemApi[U]: ClassTag](docUriOption: Option[URI], rootElem: U, path: Path): IndexedClarkElem[U] = {
    Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(docUriOption, rootElem, path)
  }

  /**
   * Calls `Builder(XmlBaseSupport.JdkUriResolver).build(Some(docUri), rootElem, path)`
   */
  def apply[U <: ClarkElemApi[U]: ClassTag](docUri: URI, rootElem: U, path: Path): IndexedClarkElem[U] = {
    Builder[U](classTag[U], XmlBaseSupport.JdkUriResolver).build(Some(docUri), rootElem, path)
  }
}