text:
=========
DOM Nodes
=========

*xml4h* provides node objects and convenience methods that make it easier to
work with an in-memory XML document object model (DOM).

This section of the document covers the main features of *xml4h* nodes.
For the full API-level documentation see :ref:`api-nodes`.

.. _node-traversal:

Traversing Nodes
----------------

*xml4h* aims to provide a simple and intuitive API for traversing and
manipulating the XML DOM. To that end it includes a number of convenience
methods for performing common tasks:

- Get the :class:`~xml4h.nodes.Document` or root :class:`~xml4h.nodes.Element`
  from any node via the ``document`` and ``root`` attributes respectively.
- You can get the ``name`` attribute of nodes that have a name, or look up
  the different name components with ``prefix`` to get the namespace prefix
  (if any) and ``local_name`` to get the name portion without the prefix.
- Nodes that have a value expose it via the ``value`` attribute.
- A node's ``parent`` attribute returns its parent, while the ``ancestors``
  attribute returns a list containing its parent, grand-parent,
  great-grand-parent etc.
- A node's ``children`` attribute returns the child nodes that belong to it,
  while the ``siblings`` attribute returns all other nodes that belong to its
  parent. You can also get the ``siblings_before`` or ``siblings_after`` the
  current node.
- Look up a node's namespace URI with ``namespace_uri`` or the alias
  ``ns_uri``.
- Check what type of :class:`~xml4h.nodes.Node` you have with Boolean
  attributes like ``is_element``, ``is_text``, ``is_entity`` etc.

.. _magical-node-traversal:

"Magical" Node Traversal
------------------------

To make it easy to traverse XML documents with a known structure *xml4h*
performs some minor magic when you look up attributes or keys on Document
and Element nodes.  If you like, you can take advantage of magical traversal
to avoid peppering your code with ``find`` and ``xpath`` searches, or with
``child`` and ``children`` node attribute lookups.

The principle is simple:

- Child elements are available as Python attributes of the parent element
  class.
- XML element attributes are available as a Python dict in the owning element.

Here is an example of retrieving information from our Monty Python films
document using element names as Python attributes (``MontyPythonFilms``,
``Film``, ``Title``) and XML attribute names as Python keys (``year``)::

    >>> # Parse an example XML document about Monty Python films
    >>> import xml4h
    >>> doc = xml4h.parse('tests/data/monty_python_films.xml')

    >>> for film in doc.MontyPythonFilms.Film:
    ...     print(film['year'] + ' : ' + film.Title.text)  # doctest:+ELLIPSIS
    1971 : And Now for Something Completely Different
    1974 : Monty Python and the Holy Grail
    ...

Python class attribute lookups of child elements work very well when your XML
document contains only camel-case tag names ``LikeThisOne`` or ``LikeThat``.
However, if your document contains lower-case tag names there is a chance the
element names will clash with existing Python attribute or method names in the
*xml4h* classes.

To work around this potential issue you can add an underscore (``_``)
character at the end of a magical attribute lookup to avoid the naming clash;
*xml4h* will remove that character before looking for a child element. For
example, to look up a child of the element ``elem1`` which is named ``child``,
the code ``elem1.child_`` will return the child element whereas ``elem1.child``
would access the :meth:`~xml4h.nodes.Node.child` Node method instead.

.. note::
   Not all XML child element tag names are accessible using magical traversal.
   Names with leading underscore characters will not work, and nor will names
   containing hyphens because they are not valid Python attribute names. If you
   have to deal with XML names like this use the full API methods like
   :meth:`~xml4h.nodes.Node.child` and :meth:`~xml4h.nodes.Node.children`
   instead.

All the gory details about how magical traversal works are documented at
:class:`~xml4h.nodes.NodeAttrAndChildElementLookupsMixin`.  Depending on how
you feel about magical behaviour this feature might feel like a great
convenience, or black magic that makes you wary. The right attitude probably
lies somewhere in the middle...

.. warning::
   The behaviour of namespaced XML elements and attributes is inconsistent.
   You can do magical traversal of elements regardless of what namespace the
   elements are in, but to look up XML attributes with a namespace prefix
   you must include that prefix in the name e.g. ``prefix:attribute-name``.

Searching with Find and XPath
-----------------------------

There are two ways to search for elements within an *xml4h* document: ``find``
and ``xpath``.

The find methods provided by the library are easy to use but can only perform
relatively simple searches that return :class:`~xml4h.nodes.Element` results,
whereas you need to be familiar with XPath query syntax to search effectively
with the ``xpath`` method but you can perform more complex searches and get
results other than just elements.

Find Methods
............

*xml4h* provides three different find methods:

- :meth:`~xml4h.nodes.Node.find` searches descendants of the current node for
  elements matching the given constraints. You can search by element name,
  by namespace URI, or with no constraints at all::

      >>> # Find ALL elements in the document
      >>> elems = doc.find()
      >>> [e.name for e in elems]  # doctest:+ELLIPSIS
      ['MontyPythonFilms', 'Film', 'Title', 'Description', 'Film', 'Title', 'Description',...

      >>> # Find the seven <Film> elements in the XML document
      >>> film_elems = doc.find('Film')
      >>> [e.Title.text for e in film_elems]  # doctest:+ELLIPSIS
      ['And Now for Something Completely Different', 'Monty Python and the Holy Grail',...

  Note that the :meth:`~xml4h.nodes.Node.find` method only finds descendants
  of the node you run it on::

      >>> # Find <Title> elements in a single <Film> element; there's only one
      >>> film_elem = doc.find('Film', first_only=True)
      >>> film_elem.find('Title')
      [<xml4h.nodes.Element: "Title">]

- :meth:`~xml4h.nodes.Node.find_first` searches descendants of the current
  node but only returns the first result element, not a list. If there are no
  matching element results this method returns *None*::

      >>> # Find the first <Film> element in the document
      >>> doc.find_first('Film')
      <xml4h.nodes.Element: "Film">

      >>> # Search for an element that does not exist
      >>> print(doc.find_first('OopsWrongName'))
      None

  If you were paying attention you may have noticed in the example above that
  you can make the :meth:`~xml4h.nodes.Node.find` method do exactly same thing
  as :meth:`~xml4h.nodes.Node.find_first` by passing the keyword argument
  ``first_only=True``.

- :meth:`~xml4h.nodes.Node.find_doc` is a convenience method that searches the
  entire document no matter which node you run it on::

      >>> # Normal find only searches descendants of the current node
      >>> len(film_elem.find('Title'))
      1

      >>> # find_doc searches the entire document
      >>> len(film_elem.find_doc('Title'))
      7

  This method is exactly like calling ``xml4h_node.document.find()``, which is
  actually what happens behind the scenes.

XPath Querying
..............

*xml4h* provides a single XPath search method which is available on
:class:`~xml4h.nodes.Document` and :class:`~xml4h.nodes.Element` nodes:

:meth:`~xml4h.nodes.XPathMixin.xpath` takes an XPath query string and returns
the result which may be a list of elements, a list of attributes, a list of
values, or a single value. The result depends entirely on the kind of query you
perform.

.. note::
   XPath querying is currently only available if you use the *lxml* or
   *ElementTree* implementation libraries. You can check whether the XPath
   feature is available with :meth:`~xml4h.nodes.Node.has_feature`.

.. note::
   Although *ElementTree* supports XPath queries, this support is
   `very limited <http://effbot.org/zone/element-xpath.htm>`_ and most of the
   example XPath queries below **will not work**. If you want to use XPath, you
   should install *lxml* for better support.

XPath queries are powerful and complex so we cannot describe them in detail
here, but we can at least present some useful examples. Here are queries that
perform the same work as the find queries we saw above::

      >>> # Query for ALL elements in the document
      >>> elems = doc.xpath('//*')  # doctest:+ELLIPSIS
      >>> [e.name for e in elems]  # doctest:+ELLIPSIS
      ['MontyPythonFilms', 'Film', 'Title', 'Description', 'Film', 'Title', 'Description',...

      >>> # Query for the seven <Film> elements in the XML document
      >>> film_elems = doc.xpath('//Film')
      >>> [e.Title.text for e in film_elems]  # doctest:+ELLIPSIS
      ['And Now for Something Completely Different', 'Monty Python and the Holy Grail',...

      >>> # Query for the first <Film> element in the document (returns list)
      >>> doc.xpath('//Film[1]')
      [<xml4h.nodes.Element: "Film">]

      >>> # Query for <Title> elements in a single <Film> element; there's only one
      >>> film_elem = doc.xpath('Film[1]')[0]
      >>> film_elem.xpath('Title')
      [<xml4h.nodes.Element: "Title">]

You can also do things with XPath queries that you simply cannot with the
*find* method, such as find all the attributes of a certain name or apply
rich constraints to the query::

      >>> # Query for all year attributes
      >>> doc.xpath('//@year')
      ['1971', '1974', '1979', '1982', '1983', '2009', '2012']

      >>> # Query for the title of the film released in 1982
      >>> doc.xpath('//Film[@year="1982"]/Title/text()')
      ['Monty Python Live at the Hollywood Bowl']

Namespaces and XPath
....................

Finally, let's discuss how you can run XPath queries on documents with
namespaces, because unfortunately this is not a simple subject.

First, you need to understand that if you are working with a namespaced
document your XPath queries must refer to those namespaces or they will not
find anything::

    >>> # Parse a namespaced version of the Monty Python Films doc
    >>> ns_doc = xml4h.parse('tests/data/monty_python_films.ns.xml')
    >>> print(ns_doc.xml())  #doctest:+ELLIPSIS
    <?xml version="1.0" encoding="utf-8"?>
    <MontyPythonFilms source="http://en.wikipedia.org/wiki/Monty_Python" xmlns="uri:monty-python" xmlns:work="uri:artistic-work">
        <work:Film year="1971">
            <Title>And Now for Something Completely Different</Title>
            ...

    >>> # XPath queries without prefixes won't find namespaced elements
    >>> ns_doc.xpath('//Film')
    []

To refer to namespaced nodes in your query the namespace must have a prefix
alias assigned to it. You can specify prefixes when you call the *xpath* method
by providing a ``namespaces`` keyword argument with a dictionary of
alias-to-URI mappings::

    >>> # Specify explicit prefix alias mappings
    >>> films = ns_doc.xpath('//x:Film', namespaces={'x': 'uri:artistic-work'})
    >>> len(films)
    7

Or, preferably, if your document node already has prefix mappings you can use
them directly::

    >>> # Our root node already has a 'work' prefix defined...
    >>> ns_doc.root['xmlns:work']
    'uri:artistic-work'

    >>> # ...so we can use this prefix directly
    >>> films = ns_doc.root.xpath('//work:Film')
    >>> len(films)
    7

Another gotcha is when a document has a default namespace. The default
namespace applies to every descendent node without its own namespace, but XPath
doesn't have a good way of dealing with this since there is no such thing as
a "default namespace" prefix alias.

*xml4h* helps out by providing just such an alias: the underscore (``_``)::

    >>> # Our document root has a default namespace
    >>> ns_doc.root.ns_uri
    'uri:monty-python'

    >>> # You need a prefix alias that refers to the default namespace
    >>> ns_doc.xpath('//Title')
    []

    >>> # You could specify it explicitly...
    >>> titles = ns_doc.xpath('//x:Title',
    ...                       namespaces={'x': ns_doc.root.ns_uri})
    >>> len(titles)
    7

    >>> # ...or use xml4h's special default namespace prefix: _
    >>> titles = ns_doc.xpath('//_:Title')
    >>> len(titles)
    7

Filtering Node Lists
--------------------

Many *xml4h* node attributes return a list of nodes as a
:class:`~xml4h.nodes.NodeList` object which confers some special filtering
powers.  You get this special node list object from attributes like
``children``, ``ancestors``, and ``siblings``, and from the ``find`` search
method if it has element results.

Here are some examples of how you can easily filter a
:class:`~xml4h.nodes.NodeList` to get just the
nodes you need:

- Get the first child node using the ``filter`` method::

      >>> # Filter to get just the first child
      >>> doc.root.children.filter(first_only=True)
      <xml4h.nodes.Element: "Film">

      >>> # The document has 7 <Film> element children of the root
      >>> len(doc.root.children)
      7

- Get the first child node by treating ``children`` as a callable::

      >>> doc.root.children(first_only=True)
      <xml4h.nodes.Element: "Film">

  When you treat the node list as a callable it calls the ``filter`` method
  behind the scenes, but since doing it the callable way is quicker and
  clearer in code we will use that approach from now on.

- Get the first child node with the ``child`` filtering method, which accepts
  the same constraints as the ``filter`` method::

      >>> doc.root.child()
      <xml4h.nodes.Element: "Film">

      >>> # Apply filtering with child
      >>> print(doc.root.child('WrongName'))
      None

- Get the first of a set of children with the ``first`` attribute::

      >>> doc.root.children.first
      <xml4h.nodes.Element: "Film">

- Filter the node list by name::

      >>> for n in doc.root.children('Film'):
      ...     print(n.Title.text)
      And Now for Something Completely Different
      Monty Python and the Holy Grail
      Monty Python's Life of Brian
      Monty Python Live at the Hollywood Bowl
      Monty Python's The Meaning of Life
      Monty Python: Almost the Truth (The Lawyer's Cut)
      A Liar's Autobiography: Volume IV

      >>> len(doc.root.children('WrongName'))
      0

  .. note::
     Passing a node name as the first argument will match the *local* name of
     a node. You can match the full node name, which might include a prefix
     for example, with a call like: ``.children(name='SomeName')``.

- Filter with a custom function::

      >>> # Filter to films released in the year 1979
      >>> for n in doc.root.children('Film',
      ...         filter_fn=lambda node: node.attributes['year'] == '1979'):
      ...     print(n.Title.text)
      Monty Python's Life of Brian

Manipulating Nodes and Elements
-------------------------------

*xml4h* provides simple methods to manipulate the structure and content of an
XML DOM. The methods available depend on the kind of node you are interacting
with, and by far the majority are for working with
:class:`~xml4h.nodes.Element` nodes.

Delete a Node
.............

Any node can be removes from its owner document with
:meth:`~xml4h.nodes.Node.delete`::

    >>> # Before deleting a Film element there are 7 films
    >>> len(doc.MontyPythonFilms.Film)
    7

    >>> doc.MontyPythonFilms.children('Film')[-1].delete()
    >>> len(doc.MontyPythonFilms.Film)
    6

.. note::
   By default deleting a node also destroys it, but it can optionally be left
   intact after removal from the document by including the ``destroy=False``
   option.

Name and Value Attributes
.........................

Many nodes have low-level name and value properties that can be read from and
written to.  Nodes with names and values include Text, CDATA, Comment,
ProcessingInstruction, Attribute, and Element nodes.

Here is an example of accessing the low-level name and value properties of a
Text node::

    >>> text_node = doc.MontyPythonFilms.child('Film').child('Title').child()
    >>> text_node.is_text
    True

    >>> text_node.name
    '#text'
    >>> text_node.value
    'And Now for Something Completely Different'

And here is the same for an Attribute node::

    >>> # Access the name/value properties of an Attribute node
    >>> year_attr = doc.MontyPythonFilms.child('Film').attribute_node('year')
    >>> year_attr.is_attribute
    True

    >>> year_attr.name
    'year'
    >>> year_attr.value
    '1971'

The name attribute of a node is not necessarily a plain string, in the case of
nodes within a defined namespaced the ``name`` attribute may comprise two
components: a ``prefix`` that represents the namespace, and a ``local_name``
which is the plain name of the node ignoring the namespace. For more
information on namespaces see :ref:`xml4h-namespaces`.

Import a Node and its Descendants
.................................

In addition to manipulating nodes in a single XML document directly, you can
also import a node (and all its descendant) from another document using a node
clone or transplant operation.

There are two ways to import a node and its descendants:

- Use the :meth:`~xml4h.nodes.Node.clone_node` Node method or
  :meth:`~xml4h.builder.Builder.clone` Builder method to copy a node into your
  document without removing it from its original document.
- Use the :meth:`~xml4h.nodes.Node.transplant_node` Node method or
  :meth:`~xml4h.builder.Builder.transplant` Builder method to transplant a node
  into your document and remove it from its original document.

Here is an example of transplanting a node into a document (which also happens
to undo the damage we did to our example DOM in the ``delete()`` example
above)::

    >>> # Build a new document containing a Film element
    >>> film_builder = (xml4h.build('DeletedFilm')
    ...     .element('Film').attrs(year='1971')
    ...         .element('Title')
    ...             .text('And Now for Something Completely Different').up()
    ...         .element('Description').text(
    ...             "A collection of sketches from the first and second TV"
    ...             " series of Monty Python's Flying Circus purposely"
    ...             " re-enacted and shot for film.")
    ...     )

    >>> # Transplant the Film element from the new document
    >>> node_to_transplant = film_builder.root.child('Film')
    >>> doc.MontyPythonFilms.transplant_node(node_to_transplant)
    >>> len(doc.MontyPythonFilms.Film)
    7

When you transplant a node from another document it is removed from that
document::

    >>> # After transplanting the Film node it is no longer in the original doc
    >>> len(film_builder.root.find('Film'))
    0

If you need to leave the original document unchanged when importing a node use
the clone methods instead.

Working with Elements
.....................

Element nodes have the most methods to access and manipulate their content,
which is fitting since this is the most useful type of node and you will deal
with elements regularly.

The leaf elements in XML documents often have one or more
:class:`~xml4h.nodes.Text` node children that contain the element's data
content. While you could iterate over such text nodes as child nodes, *xml4h*
provides the more convenient text accessors you would expect::

    >>> title_elem = doc.MontyPythonFilms.Film[0].Title
    >>> orig_title = title_elem.text
    >>> orig_title
    'And Now for Something Completely Different'

    >>> title_elem.text = 'A new, and wrong, title'
    >>> title_elem.text
    'A new, and wrong, title'

    >>> # Let's put it back the way it was...
    >>> title_elem.text = orig_title

Elements also have attributes that can be manipulated in a number of ways.

Look up an element's attributes with:

- the :meth:`~xml4h.nodes.Element.attributes` attribute (or aliases ``attrib``
  and ``attrs``) that return an ordered dictionary of attribute names and
  values::

      >>> film_elem = doc.MontyPythonFilms.Film[0]
      >>> film_elem.attributes
      <xml4h.nodes.AttributeDict: [('year', '1971')]>

- or by obtaining an element's attributes as :class:`~xml4h.nodes.Attribute`
  nodes, though that is only likely to be useful in unusual circumstances::

      >>> film_elem.attribute_nodes
      [<xml4h.nodes.Attribute: "year">]

      >>> # Get a specific attribute node by name or namespace URI
      >>> film_elem.attribute_node('year')
      <xml4h.nodes.Attribute: "year">

- and there's also the "magical" keyword lookup technique discussed in
  :ref:`magical-node-traversal` for quickly grabbing attribute values.

Set attribute values with:

- the :meth:`~xml4h.nodes.Element.set_attributes` method, which allows you to
  add attributes without replacing existing ones. This method also supports
  defining XML attributes as a dictionary, list of name/value pairs, or
  keyword arguments::

      >>> # Set/add attributes as a dictionary
      >>> film_elem.set_attributes({'a1': 'v1'})

      >>> # Set/add attributes as a list of name/value pairs
      >>> film_elem.set_attributes([('a2', 'v2')])

      >>> # Set/add attributes as keyword arguments
      >>> film_elem.set_attributes(a3='v3', a4=4)

      >>> film_elem.attributes
      <xml4h.nodes.AttributeDict: [('a1', 'v1'), ('a2', 'v2'), ('a3', 'v3'), ('a4', '4'), ('year', '1971')]>

- the setter version of the :attr:`~xml4h.nodes.Element.attributes` attribute,
  which replaces any existing attributes with the new set::

      >>> film_elem.attributes = {'year': '1971', 'note': 'funny'}
      >>> film_elem.attributes
      <xml4h.nodes.AttributeDict: [('note', 'funny'), ('year', '1971')]>

Delete attributes from an element by:

- using Python's delete-in-dict technique::

      >>> del(film_elem.attributes['note'])
      >>> film_elem.attributes
      <xml4h.nodes.AttributeDict: [('year', '1971')]>

- or by calling the ``delete()`` method on an :class:`~xml4h.nodes.Attribute`
  node.

Finally, the :class:`~xml4h.nodes.Element` class provides a number of methods
for programmatically adding child nodes, for cases where you would rather work
directly with nodes instead of using a :ref:`builder`.

The most complex of these methods is :meth:`~xml4h.nodes.Element.add_element`
which allows you to add a named child element, and to optionally to set the new
element's namespace, text content, and attributes all at the same time. Let's
try an example::

    >>> # Add a Film element with an attribute
    >>> new_film_elem = doc.MontyPythonFilms.add_element(
    ...     'Film', attributes={'year': 'never'})

    >>> # Add a Description element with text content
    >>> desc_elem = new_film_elem.add_element(
    ...     'Description', text='Just testing...')

    >>> # Add a Title element with text *before* the description element
    >>> title_elem = desc_elem.add_element(
    ...     'Title', text='The Film that Never Was', before_this_element=True)

    >>> print(doc.MontyPythonFilms.Film[-1].xml())
    <Film year="never">
        <Title>The Film that Never Was</Title>
        <Description>Just testing...</Description>
    </Film>

There are similar methods for handling simpler cases like adding text nodes,
comments etc. Here is an example of adding text nodes::

    >>> # Add a text node
    >>> title_elem = doc.MontyPythonFilms.Film[-1].Title
    >>> title_elem.add_text(', and Never Will Be')

    >>> title_elem.text
    'The Film that Never Was, and Never Will Be'

Refer to the :class:`~xml4h.nodes.Element` documentation for more information
about the other methods for adding nodes.

.. _wrap-unwrap-nodes:

Wrapping and Unwrapping *xml4h* Nodes
-------------------------------------

You can easily convert to or from *xml4h*'s wrapped version of an
implementation node. For example, if you prefer the *lxml* library's
`ElementMaker <http://lxml.de/tutorial.html#the-e-factory>`_ document builder
approach to the :ref:`xml4h Builder <builder>`, you can create a document
in *lxml*...

::

    >>> from lxml.builder import ElementMaker
    >>> E = ElementMaker()
    >>> lxml_doc = E.DocRoot(
    ...     E.Item(
    ...         E.Name('Item 1'),
    ...         E.Value('Value 1')
    ...     ),
    ...     E.Item(
    ...         E.Name('Item 2'),
    ...         E.Value('Value 2')
    ...     )
    ... )
    >>> lxml_doc  # doctest:+ELLIPSIS
    <Element DocRoot at ...

...and then convert (or, more accurately, wrap) the *lxml* nodes with the
appropriate adapter to make them *xml4h* versions::

    >>> # Convert lxml Document to xml4h version
    >>> xml4h_doc = xml4h.LXMLAdapter.wrap_document(lxml_doc)
    >>> xml4h_doc.children
    [<xml4h.nodes.Element: "Item">, <xml4h.nodes.Element: "Item">]

    >>> # Get an element within the lxml document
    >>> lxml_elem = list(lxml_doc)[0]
    >>> lxml_elem  # doctest:+ELLIPSIS
    <Element Item at ...

    >>> # Convert lxml Element to xml4h version
    >>> xml4h_elem = xml4h.LXMLAdapter.wrap_node(lxml_elem, lxml_doc)
    >>> xml4h_elem  # doctest:+ELLIPSIS
    <xml4h.nodes.Element: "Item">

You can reach the underlying XML implementation document or node at any time
from an *xml4h* node::

    >>> # Get an xml4h node's underlying implementation node
    >>> xml4h_elem.impl_node  # doctest:+ELLIPSIS
    <Element Item at ...
    >>> xml4h_elem.impl_node == lxml_elem
    True

    >>> # Get the underlying implementatation document from any node
    >>> xml4h_elem.impl_document  # doctest:+ELLIPSIS
    <Element DocRoot at ...
    >>> xml4h_elem.impl_document == lxml_doc
    True


text:
'*******************************************************************************************'
'                                                                                '
' Download Free Evaluation Version From:     https://bytescout.com/download/web-installer   '
'                                                                                '
' Also available as Web API! Get free API Key https://app.pdf.co/signup                     '
'                                                                                '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                '
' https://www.bytescout.com                                                                 '
' https://www.pdf.co                                                                        '
'*******************************************************************************************'

Imports Bytescout.PDFExtractor

Class Program
	Friend Shared Sub Main(args As String())

		' Create Bytescout.PDFExtractor.TextExtractor instance
		Dim extractor As New TextExtractor()
		extractor.RegistrationName = "demo"
		extractor.RegistrationKey = "demo"

		' Load sample PDF document
        extractor.LoadDocumentFromFile(".\columns.pdf")

		' Extract text by columns (useful if PDF document is designed in column layout like a newspaper)
		extractor.ExtractColumnByColumn = true

		' Save extracted text to file
		extractor.SaveTextToFile(".\result.txt")

		' Cleanup
		extractor.Dispose()

		' Open result file in default associated application (for demo purposes)
		System.Diagnostics.Process.Start(".\result.txt")

	End Sub
End Class

redpajama_set_name: RedPajamaGithub


text:
var Factorial = require('./Factorial');

var Bernstein = function (n, i)
{
    return Factorial(n) / Factorial(i) / Factorial(n - i);
};

module.exports = Bernstein;


text:
IMPLEMENT_DYNAMIC(CPropertiesDlg, CDialog)
CPropertiesDlg::CPropertiesDlg(CPtcMsgSimControlModule *pcmPtcMsg,
                               CWnd                    *pParent /*=NULL*/) :
   CDialog(CPropertiesDlg::IDD, pParent),
   m_pspRouter(pcmPtcMsg),
   m_pspScm(pcmPtcMsg)
{
   m_pcmPtcMsg = pcmPtcMsg;
}

CPropertiesDlg::~CPropertiesDlg()
{
}

void CPropertiesDlg::DoDataExchange(CDataExchange *pDX)
{
   CDialog::DoDataExchange(pDX);
}

CFooBar::CFooBar(CWnd *pParent /*=NULL*/)
   : CDialog(CFooBar::IDD, pParent),
   m_parent(pParent)
{
   //{{AFX_DATA_INIT(CRouterBrowser)
   //}}AFX_DATA_INIT

   m_nFoo = 0;
   m_nBar = 0;
}


text:
<?php

/**
 * Example of the ecommOrderAdd() API call
 * @link http://apidocs.mailchimp.com/api/1.3/ecommOrderAdd.func.php
 * @author Ben Tadiar <ben@handcraftedbyben.co.uk>
 */

// Require the bootstrap
require_once(dirname(__FILE__) . '/../bootstrap.php');

// Retrieve the ecommerce manager object
$ecommManager = $mailchimp->getManager('Ecommerce');

$orderID = ''; // Unique order ID, generated by your ecommerce platform
$campaignID = ''; // Campaign ID (mc_cid) to track order with
$emailID = ''; // Email ID (mc_eid) to attach order to
$storeID = ''; // Unique, user-defined ID for the store sending the order in

// Create an ecommerce order object
$order = new \MailChimp\Object\Ecommerce\Order($orderID, $campaignID, $emailID, $storeID);

// Define item options
$productID = 123;
$productName = 'ItemOne';
$categoryID = 456;
$categoryName = 'Miscellaneous';
$unitPrice = 100.00;
$quantity = 1;

// Add an item using the options above
$order->addItem($productID, $productName, $categoryID, $categoryName, $unitPrice, $quantity);

// Set shipping and tax (to be calculated by your ecommerce platform)
$order->setShipping(10.00);
$order->setTax(15.00);

// Import Ecommerce Order Information to be used for Segmentation
$ecommAdd = $ecommManager->ecommOrderAdd($order);

// Dump the output
var_dump($ecommAdd);


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>SuperMgr后台框架</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <meta content="" name="description" />
    <meta content="" name="author" />

    <link rel="stylesheet" href="../../content/ui/global/bootstrap/css/bootstrap.min.css">

    <link href="../../content/ui/global/font-awesome/css/font-awesome.css" rel="stylesheet" />

    <link rel="stylesheet" href="../../content/adminlte/dist/css/AdminLTE.css">
    <link rel="stylesheet" href="../../content/adminlte/dist/css/skins/_all-skins.min.css">
    <link href="../../content/min/css/supershopui.common.min.css" rel="stylesheet" />
    <link href="/content/supermgr/Base/css/common.css" rel="stylesheet" />

    <link href="/content/plugins/wizard/wizard.css" rel="stylesheet" />
    <link href="/content/plugins/wdtree/tree.css" rel="stylesheet" />

    <link href="/Content/plugins/jqgrid/jqgrid.css" rel="stylesheet" />

    <link rel="stylesheet" href="/content/plugins/iCheck/all.css">
    <link href="../../content/ui/global/bootstrap-switch/css/bootstrap-switch.css" rel="stylesheet" />

            订单设置

 Home

订单设置

        <form role="form">

订单设置!

提示:第一次使用请先进行订单相关配置。

                        限时抢购*

                            <input id="EnCode" type="text" class="form-control" placeholder="限时抢购超过__分钟未付款,订单自动关闭" isvalid="yes" checkexpession="NotNull"/>

                                 分

                        下单

                            <input id="Icon" type="text" class="form-control" placeholder="下单超过__天未付款,订单自动关闭" isvalid="yes" checkexpession="NotNull"/>

                                 天

                        发货*

                            <input id="Icon" type="text" class="form-control" placeholder="发货超过__天未收货,订单自动完成" isvalid="yes" checkexpession="NotNull" />

                                 天

                        订单完成*

                            <input id="Icon" type="text" class="form-control" placeholder="订单完成超过__天自动结束交易,不能申请售后" isvalid="yes" checkexpession="NotNull" />

                                 天

                        订单短信通知*

                            是
                            <input type="radio" name="r1" class="minimal" checked>

                            否
                            <input type="radio" name="r1" class="minimal">
                            (订单支付后系统发短信通知发货人)

                        订单发票税率*

                            <input id="Icon" type="text" class="form-control" placeholder="0" isvalid="yes" checkexpession="NotNull" />

                                %

                <button type="submit" class="btn btn-success">保存</button>

        </form>


text:
readonly REPO_NAME="${1}"
readonly TAG_NAME="${2}"
readonly TOKEN="${ACCESS_TOKEN}"
# Get GitHub user and GitHub repo from REPO_NAME
IFS='_' read -ra array <<< "${REPO_NAME}"
github_user="${array[1]}"
github_repo="${array[2]}"
if [[ -z "${github_user}" ]]
then
  github_user="GoogleCloudPlatform"
  github_repo="${REPO_NAME}"
fi
# Create request.json with request parameters
echo "{\"tag_name\": \"${TAG_NAME}\",\"name\": \"${TAG_NAME}\"}" > request.json
# Create a request for creating a release on GitHub page
readonly resp_file="response.json"
response_code="$(curl -# -X POST \
  -H "Content-Type:application/json" \
  -H "Accept:application/json" \
  -w "%{http_code}" \
  --data-binary "@/workspace/request.json" \
  "https://api.github.com/repos/${github_user}/${github_repo}/releases?access_token=${TOKEN}" \
  -o "${resp_file}")"
# Check status code
if [[ "${response_code}" != 201 ]]; then
  cat "${resp_file}"
  exit 1
fi
# Get release id from response.json
release_id="$(grep -wm 1 "id" /workspace/response.json \
  | grep -Eo "[[:digit:]]+")"
# Get JAR version from pom.xml
jar_version="$(grep -m 1 "<version>" /workspace/pom.xml \
  | grep -Eo "[[:digit:]]+.[[:digit:]]+.[[:digit:]]+")"
jar_name="healthcare-imaging-performance-test-${jar_version}.jar"
# Upload JAR to GitHub releases page
response_code="$(curl -# -X POST -H "Authorization: token ${TOKEN}" \
  -H "Content-Type:application/octet-stream" \
  -w "%{http_code}" \
  --data-binary "@/workspace/target/${jar_name}" \
  "https://uploads.github.com/repos/${github_user}/${github_repo}/releases/${release_id}/assets?name=${jar_name}" \
  -o "${resp_file}")"
# Check status code
if [[ "${response_code}" != 201 ]]; then
  cat "${resp_file}"
  exit 2
fi


text:
from contextlib import contextmanager

from pip._vendor.contextlib2 import ExitStack

from pip._internal.utils.typing import MYPY_CHECK_RUNNING

if MYPY_CHECK_RUNNING:
    from typing import Iterator, ContextManager, TypeVar

    _T = TypeVar('_T', covariant=True)

class CommandContextMixIn(object):
    def __init__(self):
        # type: () -> None
        super(CommandContextMixIn, self).__init__()
        self._in_main_context = False
        self._main_context = ExitStack()

    @contextmanager
    def main_context(self):
        # type: () -> Iterator[None]
        assert not self._in_main_context

        self._in_main_context = True
        try:
            with self._main_context:
                yield
        finally:
            self._in_main_context = False

    def enter_context(self, context_provider):
        # type: (ContextManager[_T]) -> _T
        assert self._in_main_context

        return self._main_context.enter_context(context_provider)


text:
/**
 * windows-cpu - Tests for windows-cpu functionality
 * @author Kyle Ross <kylerross1324@gmail.com>
 * @requires mocha
 * @requires should
 */

var should = require('should'),
    cpu;

beforeEach(function() {
    cpu = require('../');
});

describe('totalLoad function', function() {
    it('should call the callback with an array of number(s)', function(done) {
        cpu.totalLoad(function(error, results) {
            if (error) {
                done(error);
            } else {

                console.log('should call the callback with an array of number(s) results: ', results);

                results.should.be.an.Array;

                if (results.length <= 0) {
                    done('results length should be greater than 0');
                }

                results.forEach(function(v) {
                    v.should.be.an.Number.and.be.within(0, 100);
                });
                done();
            }
        });
    });
});

describe('nodeLoad function', function() {
    it('should call the callback with an object', function(done) {
        cpu.nodeLoad(function(error, results) {
            if (error) {
                done(error);
            } else {

                console.log('should call the callback with an object results: ', results);

                results.should.be.an.Object.with.properties('load', 'found');

                results.load.should.be.an.Number.and.be.within(0, 100);
                results.found.should.be.an.Array;

                if (results.found.length <= 0) {
                    done('results.found length should be greater than 0');
                }

                results.found.forEach(function(v) {
                    v.should.be.an.Object.with.properties('pid', 'process', 'load');
                    v.pid.should.be.an.Number;
                    v.process.should.be.a.String.and.not.be.empty;
                    v.load.should.be.an.Number;
                });
                done();
            }
        });
    });
});

describe('processLoad function', function() {
    it('should call the callback with an object', function(done) {
        cpu.processLoad(function(error, results) {
            if (error) {
                done(error);
            } else {

                console.log('should call the callback with an object results: ', results);

                results.should.be.an.Object.with.properties('load', 'found');

                results.load.should.be.an.Number.and.be.within(0, 100);
                results.found.should.be.an.Array;

                if (results.found.length <= 0) {
                    done('results.found length should be greater than 0');
                }

                results.found.should.have.a.lengthOf(1);

                results.found.forEach(function(v) {
                    v.should.be.an.Object.with.properties('pid', 'process', 'load');
                    v.pid.should.be.an.Number;
                    v.process.should.be.a.String.and.not.be.empty;
                    v.load.should.be.an.Number;
                });
                done();
            }
        });
    });
});

describe('findLoad function', function() {

   var loadIntervalPtr;
   var loadInterval = 1;
   var loadCounter = 1;

    before(function(){

        loadIntervalPtr = setInterval(function(){
          var randomOpResult = ((Math.random() * Math.random()) * 100) % 10;
          if (loadCounter % 50 == 0)
            console.log('loadCounter: ', loadCounter);
          loadCounter++;
        }, loadInterval);

      });

      after(function(){
        clearInterval(loadIntervalPtr);
      });

    it('should call the callback with an object', function(done) {
        cpu.findLoad('system', function(error, results) {
            if (error) {
                done(error);
            } else {

                console.log('should call the callback with an object, for this process results: ', results);

                results.should.be.an.Object.with.properties('load', 'found');

                results.load.should.be.an.Number.and.be.within(0, 100);
                results.found.should.be.an.Array;

                if (results.found.length <= 0) {
                    done('results.found length should be greater than 0');
                }

                results.found.forEach(function(v) {
                    v.should.be.an.Object.with.properties('pid', 'process', 'load');
                    v.pid.should.be.an.Number;
                    v.process.should.be.a.String.and.not.be.empty;
                    v.load.should.be.an.Number;
                });
                done();
            }
        });
    });

     it('should call the callback with an object, for this process', function(done) {
        cpu.findLoad(process.pid, function(error, results) {
            if (error) {
                done(error);
            } else {

                console.log('should call the callback with an object, for this process results: ', results);

                results.should.be.an.Object.with.properties('load', 'found');

                results.load.should.be.an.Number.and.be.within(0, 100);
                results.found.should.be.an.Array;

                if (results.found.length <= 0) {
                    done('results.found length should be greater than 0');
                }

                results.found.forEach(function(v) {
                    v.should.be.an.Object.with.properties('pid', 'process', 'load');
                    v.pid.should.be.an.Number;
                    v.process.should.be.a.String.and.not.be.empty;
                    v.load.should.be.an.Number;
                });
                done();
            }
        });
    });

    it('should call the callback with an error', function(done) {
        cpu.findLoad('someprocess', function(error, results) {
            if (error) {
                done();
            } else {
                done('Result should have been an error.');
            }
        });
    });
});

describe('cpuInfo function', function() {
    it('should call the callback with an array', function(done) {
        cpu.cpuInfo(function(error, results) {
            if (error) {
                done(error);
            } else {
                results.should.be.an.Array;

                if (results.length <= 0) {
                    done('results length should be greater than 0');
                }

                results.forEach(function(v) {
                    v.should.be.a.String.and.not.be.empty;
                });
                done();
            }
        });
    });
});

describe('totalMemoryUsage function', function() {
    it('should call the callback with an object', function(done) {
        cpu.totalMemoryUsage(function(error, results) {
            if (error) {
                done(error);
            } else {
                results.should.be.an.Object.with.properties('usageInKb', 'usageInMb' , 'usageInGb');

                results.usageInKb.should.be.an.Number;
                results.usageInMb.should.be.an.Number;
                results.usageInGb.should.be.an.Number;

                done();
            }
        });
    });
});


text:
var assert = require('assert')
  , PubSub = require('../pubsub.js')
  , browser = new require('mock-browser').mocks.MockBrowser
  , window = browser.createWindow()
  , $ = require('jquery')(window)
  ;

describe('Pubsub', function () {
  describe('#exports', function () {
    it('should exports in global', function () {
      var pubsub = PubSub.create().exports();
      assert.strictEqual(pubsub, global.pubsub);
      delete global.pubsub;
    });

    describe('when space is given', function () {
      it('should exports in global', function () {
        var pubsub = PubSub.create().exports('hoge');
        assert.strictEqual(pubsub, global.hoge);
        delete global.hoge;
      });
    });
  });
  describe('#publish', function () {
    describe('when registed one subscriber', function () {
      it('should call a subscriber given a arguments when gave #publish one argument', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context, a) {
          actual.a += a;
        });

        pubsub.publish('event', null, 1);
        assert.strictEqual(1, actual.a);
      });

      it('should call a subscriber given multiple arguments when gave #publish multiple arguments', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0, b: 0, c: 0}
          ;

        pubsub.subscribe('event', function (context, a, b, c) {
          actual.a += a;
          actual.b += b;
          actual.c += c;
        });

        pubsub.publish('event', null, 1, 2, 3);
        assert.strictEqual(1, actual.a);
        assert.strictEqual(2, actual.b);
        assert.strictEqual(3, actual.c);
      });
    });

    describe('when registed multiple subscriber', function () {
      it('should call subscribers given a arguments when gave #publish one argument', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context, a) {
          actual.a += a;
        });

        pubsub.subscribe('event', function (context, a) {
          actual.a += a;
        });

        pubsub.publish('event', null, 1);
        assert.strictEqual(2, actual.a);
      });

      it('should call subscribers given multiple arguments when gave #publish multiple arguments', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0, b: 0, c: 0}
          ;

        pubsub.subscribe('event', function (context, a, b, c) {
          actual.a += a;
          actual.b += b;
          actual.c += c;
        });

        pubsub.subscribe('event', function (context, a, b, c) {
          actual.a += a;
          actual.b += b;
          actual.c += c;
        });

        pubsub.publish('event', null, 1, 2, 3);
        assert.strictEqual(2, actual.a);
        assert.strictEqual(4, actual.b);
        assert.strictEqual(6, actual.c);
      });
    });

    describe('when given not Context and not Null', function () {
      it('should raise TypeError', function () {
        var pubsub = PubSub.create
          ;

        assert.throws(function () {
          pubsub.publish('event', []);
        },
        TypeError);
      });
    });
  });

  describe('#subscribe', function () {
    describe('when given globalContext', function () {
      it('should not be able to call pubsub#publish in the null pettern', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context) {
          context && context.publish('event2', null, 1);
        });

        pubsub.subscribe('event2', function (context, a) {
          actual.a += a;
        });

        pubsub.publish('event', null, 1);
        assert.strictEqual(0, actual.a);
      });

      it('should be able to call pubsub#publish in the globalContext pettern', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context) {
          context.publish('event2', null, 1);
        });

        pubsub.subscribe('event2', function (context, a) {
          actual.a += a;
        });

        pubsub.publish('event', pubsub.globalContext, 1);
        assert.strictEqual(1, actual.a);
      });

      it('should be able to call context#publish in the local context pettern', function () {
        var pubsub = PubSub.create()
          , localContext = pubsub.Context.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context) {
          context.publish('event', null, 1);
        });

        localContext.subscribe('event', function (context, a) {
          actual.a += a;
        });

        pubsub.publish('event', localContext, 1);
        assert.strictEqual(1, actual.a);
      });
    });
  });

  describe('#subscribeOnce', function () {
    describe('when given globalContext', function () {
      it('should be performed only once', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribeOnce('event', function (context, num) {
          actual.a += num;
        });

        pubsub.publish('event', null, 1);
        pubsub.publish('event', null, 1);
        assert.strictEqual(1, actual.a);
      });

      describe('when subscribeOnce is execute more than once', function () {
        it('should be performed only once', function () {
          var pubsub = PubSub.create()
            , res = []
            , i
            , iz
            ;

          for (i = 0, iz = 3; i < iz; i++) {
            pubsub.subscribeOnce('event', function (n) {
              return function () {
                res.push(n);
              };
            }(i));
          }

          pubsub.publish('event', null);
          pubsub.publish('event', null);
          assert.deepEqual([0, 1, 2], res);
        });
      });
    });

    describe('when given localContext', function () {
      it('should be performed only once', function () {
        var pubsub = PubSub.create()
          , localContext = pubsub.Context.create()
          , actual = {a: 0}
          ;

        localContext.subscribeOnce('evented', function (context, num) {
          actual.a += num;
        });

        pubsub.subscribe('event', function (context, num) {
          context.publish('evented', null, num);
          context.publish('evented', null, num);
        });

        pubsub.publish('event', localContext, 1);
        assert.strictEqual(1, actual.a);
      });

      describe('when subscribeOnce is execute more than once', function () {
        it('should be performed only once', function () {
          var pubsub = PubSub.create()
            , localContext = pubsub.Context.create()
            , res = []
            , i
            , iz
            ;

          for (i = 0, iz = 3; i < iz; i++) {
            localContext.subscribeOnce('evented', function (n) {
              return function () {
                res.push(n);
              };
            }(i));
          }

          pubsub.subscribe('event', function (context, num) {
            context.publish('evented');
          });

          pubsub.publish('event', localContext);
          assert.deepEqual([0, 1, 2], res);
        });
      });
    });
  });

  describe('#unsubscribe', function () {
    describe('when only the event name is specified', function () {
      it('should canceled subscribers of the specified event', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context) {
          actual.a += 1;
        });

        pubsub.subscribe('event', function (context) {
          actual.a += 1;
        });

        pubsub.unsubscribe('event');
        pubsub.publish('event', null);
        assert.strictEqual(0, actual.a);
      });

      it('should canceled subscribers of the specified event in the local context pattern', function () {
        var pubsub = PubSub.create()
          , localContext = pubsub.Context.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context) {
          context.publish('evented', null, 1);
        });

        localContext.subscribe('evented', a);
        localContext.subscribe('evented', b);
        localContext.unsubscribe('evented');

        function a(context) {
          actual.a += 1;
        }

        function b(context) {
          actual.a += 2;
        }

        pubsub.publish('event', localContext);
        assert.strictEqual(0, actual.a);
      });
    });

    describe('when bouth the event name and the subscriber are specified', function () {
      it('should canceled the applicable handler of the specified event', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', a);
        pubsub.subscribe('event', b);

        function a(context) {
          actual.a += 1;
        }

        function b(context) {
          actual.a += 2;
        }

        pubsub.unsubscribe('event', a);
        pubsub.publish('event', null);
        assert.strictEqual(2, actual.a);
      });

      it('should canceled the applicable handler of the specified event in the localContext pattern', function () {
        var pubsub = PubSub.create()
          , localContext = pubsub.Context.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context) {
          context.publish('evented', null, 1);
        });

        localContext.subscribe('evented', a);
        localContext.subscribe('evented', b);
        localContext.unsubscribe('evented', a);

        function a(context) {
          actual.a += 1;
        }

        function b(context) {
          actual.a += 2;
        }

        pubsub.publish('event', localContext);
        assert.strictEqual(2, actual.a);
      });

      it('should canceled the applicable handlers of the specified event', function () {
        var pubsub = PubSub.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', a);
        pubsub.subscribe('event', b);
        pubsub.subscribe('event', a);

        function a(context) {
          actual.a += 1;
        }

        function b(context) {
          actual.a += 5;
        }

        pubsub.unsubscribe('event', a);
        pubsub.publish('event', null);
        assert.strictEqual(5, actual.a);
      });

      it('should canceled the applicable handlers of the specified event in the localContext pattern', function () {
        var pubsub = PubSub.create()
          , localContext = pubsub.Context.create()
          , actual = {a: 0}
          ;

        pubsub.subscribe('event', function (context) {
          context.publish('evented', null, 1);
        });

        localContext.subscribe('evented', a);
        localContext.subscribe('evented', b);
        localContext.subscribe('evented', a);
        localContext.unsubscribe('evented', a);

        function a(context) {
          actual.a += 1;
        }

        function b(context) {
          actual.a += 5;
        }

        pubsub.publish('event', localContext);
        assert.strictEqual(5, actual.a);
      });

      describe('when applicable handler does not exist', function () {
        it('should nothing is done', function () {
          var pubsub = PubSub.create()
            , actual = {a: 0}
            ;

          pubsub.subscribe('event', a);

          function a(context) {
            actual.a += 1;
          }

          function b(context) {
            actual.a += 2;
          }

          pubsub.unsubscribe('event', b);
          pubsub.publish('event', null);
          assert.strictEqual(1, actual.a);
        });

        it('should nothing is done in the localContext pattern', function () {
          var pubsub = PubSub.create()
            , localContext = pubsub.Context.create()
            , actual = {a: 0}
            ;

          pubsub.subscribe('event', function (context) {
            context.publish('evented', null, 1);
          });

          localContext.subscribe('evented', a);
          localContext.unsubscribe('evented', b);

          function a(context) {
            actual.a += 1;
          }

          function b(context) {
            actual.a += 5;
          }

          pubsub.publish('event', localContext);
          assert.strictEqual(1, actual.a);
        });
      });
      describe('When the using jQuery.proxy wrapped Fn passed', function () {
        it('should canceled the applicable handler of the specified event', function () {
          var pubsub = PubSub.create()
            , actual = {a: 0}
            , obj
            ;

          obj = {
            a: function () {
              actual.a += 1;
            },
            b: function () {
              actual.a += 2;
            }
          };

          pubsub.subscribe('event', $.proxy(obj, 'a'));
          pubsub.subscribe('event', $.proxy(obj, 'b'));

          pubsub.unsubscribe('event', $.proxy(obj, 'a'));
          pubsub.publish('event', null);
          assert.strictEqual(2, actual.a);
        });
      });
    });
  });

  describe('#dump', function () {
    describe('when globalContext has any event and handlers', function () {
      describe('when `dump` doesnt give eventName', function () {
        it('should return all subscribers', function () {
          var pubsub = PubSub.create()
            , actual
            ;

          function a() {}
          function b() {}
          function c() {}

          pubsub.subscribe('event1', a);
          pubsub.subscribe('event1', b);
          pubsub.subscribe('event2', c);

          actual = pubsub.dump();
          assert.deepEqual(actual, {event1: [a, b], event2: [c]});
        });
      });

      describe('when `dump` give eventName', function () {
        it('should return all subscribers related eventName', function () {
          var pubsub = PubSub.create()
            , actual
            ;

          function a() {}
          function b() {}
          function c() {}

          pubsub.subscribe('event1', a);
          pubsub.subscribe('event1', b);
          pubsub.subscribe('event2', c);

          actual = pubsub.dump('event1');
          assert.deepEqual(actual, [a, b]);
        });
      });
    });
  });
});


text:
#import "BTDemosAppController.h"

@implementation BTDemosAppController

- (id) init
{
	if ( self = [super init] )
	{
		// change cwd to .app/Contents/Resources
		NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
		[[NSFileManager defaultManager] changeCurrentDirectoryPath:resourcePath];
	}

	return self;
}

- (void) awakeFromNib
{}

#pragma mark -
#pragma mark Public API

- (void) setFullscreen: (BOOL) fullscreen
{
	[_glView setFullscreen: fullscreen];
}

- (BOOL) fullscreen
{
	return [_glView fullscreen];
}

- (void) setShowParameters: (BOOL) showParameters
{
	_showParameters = showParameters;
}

- (BOOL) showParameters
{
	return _showParameters;
}

- (NSArray*) demos
{
	return [BTDemo demoNames];
}

- (void) setDemo: (NSString*) demoName
{
	[_currentDemo release];
	[_glView setDelegate: nil];

	_currentDemo = [[BTDemo demoWithName: demoName] retain];

	if ( _currentDemo )
	{
		// the demo is the rendering & input delegate for the gl view
		[_glView setDelegate: _currentDemo];

		[_currentDemo contextWillResize];
		[_currentDemo contextResized: [_glView bounds].size];
		[_currentDemo contextDidResize];
	}
}

- (NSString*) demo
{
	return _currentDemo ? [_currentDemo demoName] : nil;
}

#pragma mark -
#pragma mark IBActions

- (IBAction) nextDemo: (id) sender
{
	NSArray *demos = [self demos];
	unsigned index = [demos indexOfObject: [self demo]];
	if ( index != NSNotFound )
	{
		index = ( index + 1 ) % [demos count];
		[self setDemo: [demos objectAtIndex: index]];
	}
}

- (IBAction) previousDemo: (id) sender
{
	NSArray *demos = [self demos];
	unsigned index = [demos indexOfObject: [self demo]];
	if ( index != NSNotFound )
	{
		if ( index == 0 ) index = [demos count] - 1;
		else index--;

		[self setDemo: [demos objectAtIndex: index]];
	}
}

- (IBAction) toggleFullscreen: (id) sender
{
	[self setFullscreen: ![self fullscreen]];
}

- (IBAction) toggleParameters: (id) sender
{
	[self setShowParameters: ![self showParameters]];
}

- (IBAction) resetDemo: (id) sender
{
	[_currentDemo reset];
}

- (IBAction) nullMenuTarget: (id) sender
{
	// this handles a 10.4 bug. A menu bound to some property for toggling
	// will not invoke unless it has a target and selector set.
}

#pragma mark -
#pragma mark NSApplicationDelegate

- (void) applicationDidFinishLaunching: (NSNotification *)aNotification
{
	// note: We load the first demo here and not in -awakeFromNib as the
	// OpenGL view is instantiated, but not running yet at that point

	[self setDemo: [[self demos] objectAtIndex:0]];
}

- (BOOL) applicationShouldTerminateAfterLastWindowClosed: (NSApplication *)theApplication
{
	return YES;
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 15: 211 (1946)

#### Original name
Acrotheca harunganae Hansf.

### Remarks
null


text:
<?php

return [

    /**
     * Settings text strings
     * Contains all text strings used in the general settings sections of BookStack
     * including users and roles.
     */

    'settings' => 'Préférences',
    'settings_save' => 'Enregistrer les préférences',
    'settings_save_success' => 'Préférences enregistrées',

    /**
     * App settings
     */

    'app_settings' => 'Préférences de l\'application',
    'app_name' => 'Nom de l\'application',
    'app_name_desc' => 'Ce nom est affiché dans l\'en-tête et les e-mails.',
    'app_name_header' => 'Afficher le nom dans l\'en-tête ?',
    'app_public_viewing' => 'Accepter le visionnage public des pages ?',
    'app_secure_images' => 'Activer l\'ajout d\'image sécurisé ?',
    'app_secure_images_desc' => 'Pour des questions de performances, toutes les images sont publiques. Cette option ajoute une chaîne aléatoire difficile à deviner dans les URLs des images.',
    'app_editor' => 'Editeur des pages',
    'app_editor_desc' => 'Sélectionnez l\'éditeur qui sera utilisé pour modifier les pages.',
    'app_custom_html' => 'HTML personnalisé dans l\'en-tête',
    'app_custom_html_desc' => 'Le contenu inséré ici sera ajouté en bas de la balise  de toutes les pages. Vous pouvez l\'utiliser pour ajouter du CSS personnalisé ou un tracker analytique.',
    'app_logo' => 'Logo de l\'Application',
    'app_logo_desc' => 'Cette image doit faire 43px de hauteur.
Les images plus larges seront réduites.',
    'app_primary_color' => 'Couleur principale de l\'application',
    'app_primary_color_desc' => 'Cela devrait être une valeur hexadécimale.
Laisser vide pour rétablir la couleur par défaut.',

    /**
     * Registration settings
     */

    'reg_settings' => 'Préférence pour l\'inscription',
    'reg_allow' => 'Accepter l\'inscription ?',
    'reg_default_role' => 'Rôle par défaut lors de l\'inscription',
    'reg_confirm_email' => 'Obliger la confirmation par e-mail ?',
    'reg_confirm_email_desc' => 'Si la restriction de domaine est activée, la confirmation sera automatiquement obligatoire et cette valeur sera ignorée.',
    'reg_confirm_restrict_domain' => 'Restreindre l\'inscription à un domaine',
    'reg_confirm_restrict_domain_desc' => 'Entrez une liste de domaines acceptés lors de l\'inscription, séparés par une virgule. Les utilisateur recevront un e-mail de confirmation à cette adresse.
 Les utilisateurs pourront changer leur adresse après inscription s\'ils le souhaitent.',
    'reg_confirm_restrict_domain_placeholder' => 'Aucune restriction en place',

    /**
     * Role settings
     */

    'roles' => 'Rôles',
    'role_user_roles' => 'Rôles des utilisateurs',
    'role_create' => 'Créer un nouveau rôle',
    'role_create_success' => 'Rôle créé avec succès',
    'role_delete' => 'Supprimer le rôle',
    'role_delete_confirm' => 'Ceci va supprimer le rôle \':roleName\'.',
    'role_delete_users_assigned' => 'Ce rôle a :userCount utilisateurs assignés. Vous pouvez choisir un rôle de remplacement pour ces utilisateurs.',
    'role_delete_no_migration' => "Ne pas assigner de nouveau rôle",
    'role_delete_sure' => 'Êtes vous sûr(e) de vouloir supprimer ce rôle ?',
    'role_delete_success' => 'Le rôle a été supprimé avec succès',
    'role_edit' => 'Modifier le rôle',
    'role_details' => 'Détails du rôle',
    'role_name' => 'Nom du rôle',
    'role_desc' => 'Courte description du rôle',
    'role_system' => 'Permissions système',
    'role_manage_users' => 'Gérer les utilisateurs',
    'role_manage_roles' => 'Gérer les rôles et permissions',
    'role_manage_entity_permissions' => 'Gérer les permissions sur les livres, chapitres et pages',
    'role_manage_own_entity_permissions' => 'Gérer les permissions de ses propres livres, chapitres, et pages',
    'role_manage_settings' => 'Gérer les préférences de l\'application',
    'role_asset' => 'Asset Permissions',
    'role_asset_desc' => 'These permissions control default access to the assets within the system. Permissions on Books, Chapters and Pages will override these permissions.',
    'role_all' => 'Tous',
    'role_own' => 'Propres',
    'role_controlled_by_asset' => 'Controlled by the asset they are uploaded to',
    'role_save' => 'Enregistrer le rôle',
    'role_update_success' => 'Rôle mis à jour avec succès',
    'role_users' => 'Utilisateurs ayant ce rôle',
    'role_users_none' => 'Aucun utilisateur avec ce rôle actuellement',

    /**
     * Users
     */

    'users' => 'Utilisateurs',
    'user_profile' => 'Profil d\'utilisateur',
    'users_add_new' => 'Ajouter un nouvel utilisateur',
    'users_search' => 'Chercher les utilisateurs',
    'users_role' => 'Rôles des utilisateurs',
    'users_external_auth_id' => 'Identifiant d\'authentification externe',
    'users_password_warning' => 'Remplissez ce fomulaire uniquement si vous souhaitez changer de mot de passe:',
    'users_system_public' => 'Cet utilisateur représente les invités visitant votre instance. Il est assigné automatiquement aux invités.',
    'users_delete' => 'Supprimer un utilisateur',
    'users_delete_named' => 'Supprimer l\'utilisateur :userName',
    'users_delete_warning' => 'Ceci va supprimer \':userName\' du système.',
    'users_delete_confirm' => 'Êtes-vous sûr(e) de vouloir supprimer cet utilisateur ?',
    'users_delete_success' => 'Utilisateurs supprimés avec succès',
    'users_edit' => 'Modifier l\'utilisateur',
    'users_edit_profile' => 'Modifier le profil',
    'users_edit_success' => 'Utilisateur mis à jour avec succès',
    'users_avatar' => 'Avatar de l\'utilisateur',
    'users_avatar_desc' => 'Cette image doit être un carré d\'environ 256px.',
    'users_preferred_language' => 'Langue préférée',
    'users_social_accounts' => 'Comptes sociaux',
    'users_social_accounts_info' => 'Vous pouvez connecter des réseaux sociaux à votre compte pour vous connecter plus rapidement. Déconnecter un compte n\'enlèvera pas les accès autorisés précédemment sur votre compte de réseau social.',
    'users_social_connect' => 'Connecter le compte',
    'users_social_disconnect' => 'Déconnecter le compte',
    'users_social_connected' => 'Votre compte :socialAccount a été ajouté avec succès.',
    'users_social_disconnected' => 'Votre compte :socialAccount a été déconnecté avec succès',

];


text:
package com.android.slangify.repository.models;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by bettykin on 09/03/2017.
 */

public class PhraseModel implements Parcelable {
    private String text;
    private String extra;
    private int risky;
    private int score;
    private String translation;

    public PhraseModel() {

    }

    public PhraseModel(Parcel in) {

        // the order needs to be the same as in writeToParcel() method
        this.text = in.readString();
        this.extra = in.readString();
        this.score = in.readInt();
        this.risky = in.readInt();
        this.translation = in.readString();
    }

    public PhraseModel(String text, String extra, int score, int risky, String translation) {
        this.text = text;
        this.extra = extra;
        this.score = score;
        this.risky = risky;
        this.translation = translation;
    }

    public static final Creator<PhraseModel> CREATOR = new Creator<PhraseModel>() {
        @Override
        public PhraseModel createFromParcel(Parcel in) {
            return new PhraseModel(in);
        }

        @Override
        public PhraseModel[] newArray(int size) {
            return new PhraseModel[size];
        }
    };

    public String getText() {
        return text;
    }

    public String getExtra() {
        return extra;
    }

    public int getScore() {
        return score;
    }

    public String getTranslation() {
        return translation;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(text);
        dest.writeString(extra);
        dest.writeInt(score);
        dest.writeInt(risky);
        dest.writeString(translation);
    }
}


text:
layout: relation
title: 'auxpass'
shortdef: 'passive auxiliary'
---

A passive auxiliary of a clause is a form of the [auxiliary verb](cs-pos/AUX) _být_ "to be"
used to construct the periphrastic passive voice (in any tense or in the infinitive).

~~~ sdparse
Kennedy byl zabit . \n Kennedy was killed .
auxpass(zabit, byl)
auxpass(killed, was)
~~~

~~~ sdparse
Kennedy bude zabit . \n Kennedy will-be killed .
auxpass(zabit, bude)
auxpass(killed, will-be)
~~~

~~~ sdparse
Kennedy netušil , že jeho osudem je být zabit . \n Kennedy did-not-anticipate that his fate is to-be killed .
auxpass(zabit, být)
auxpass(killed, to-be)
~~~

Note that the passive participle may be also used as nominal predicate with [copula](cop).
Hence it may be difficult to distinguish a passive construction from a copula construction.
The former focuses on the process while the latter emphasizes the result.

- Passive:

~~~ sdparse
Smlouva byla podepsána v Bílém domě . \n Contract was signed in White House .
auxpass(podepsána, byla)
auxpass(signed, was)
~~~

- Copula:

~~~ sdparse
Smlouva byla podepsána červeným inkoustem . \n Contract was signed in-red ink .
cop(podepsána, byla)
cop(signed, was)
~~~


text:
'use strict';

module.exports = function every(fn) {
  return this.items.map(function (item, index) {
    return fn(item, index);
  }).indexOf(false) === -1;
};


text:
import random

def makeList( l ):
    if not l:
        return "nothing"
    if len( l ) == 1:
        return l[0]
    return ", ".join( l[:-1]) + " and " + l[-1]

def makeCountingList( d ):
    rv = []
    for thing, things in d.items():
        rv.append( thing.amount( len(things), informal = True ) )
    return makeList( rv )

def capitalizeFirst( s ):
    if not s:
        return ""
    return s[0].upper() + s[1:]

SmallNumbers = {
    0 : "zero",
    1 : "one",
    2 : "two",
    3 : "three",
    4 : "four",
    5 : "five",
    6 : "six",
    7 : "seven",
    8 : "eight",
    9 : "nine",
    10 : "ten",
    11 : "eleven",
    12 : "twelve",
    13 : "thirteen",
    14 : "fourteen",
    15 : "fifteen",
    16 : "sixteen",
    17 : "seventeen",
    18 : "eighteen",
    19 : "nineteen",
    20 : "twenty",
}

def NumberWord( n ):
    try:
        m = SmallNumbers[n]
    except KeyError:
        m = "%d" % n
    return m

class Verb:
    def __init__(self, person2, person3 = None): # plural or first-person is not really needed
        self.person2 = person2
        if not person3:
            person3 = person2 + "s"
        self.person3 = person3
    def second(self):
        return self.person2
    def third(self):
        return self.person3

class Noun:
    def __init__(self, article, singular, plural, gender = "neuter", the = True):
        self.article = article
        self.singular = singular
        self.plural = plural
        self.the = the
        self.gender = gender
    def absorb(self, that):
        self.article = that.article
        self.singular = that.singular
        self.plural = that.plural
        self.the = that.the
        self.gender = that.gender
    def pronounPossessive(self):
        if self.gender == "female":
            return "her"
        if self.gender == "male":
            return "his"
        return "its"
    def pronounReflexive(self):
        if self.gender == "female":
            return "herself"
        if self.gender == "male":
            return "himself"
        return "itself"
    def pronounObject(self):
        if self.gender == "female":
            return "her"
        if self.gender == "male":
            return "him"
        return "it"
    def pronounSubject(self):
        if self.gender == "female":
            return "she"
        if self.gender == "male":
            return "he"
        return "it"
    def indefiniteSingular(self):
        rv = [ self.singular ]
        if self.article:
            rv.insert( 0, self.article )
        return " ".join( rv )
    def amount(self, n, informal = False):
        m = NumberWord( n )
        if informal and n == 1 and self.article:
            m = self.article
        return " ".join( [ m, self.plural if n != 1 else self.singular ] )
    def definiteSingular(self):
        if self.the:
            return " ".join( [ "the", self.singular ] )
        return self.singular
    def __str__(self):
        return self.singular
    def __eq__(self, that):
        return self.singular == that.singular
    def __hash__(self):
        return self.singular.__hash__()
    def selectGender(self):
        if self.gender != 'random':
            return self
        import copy
        rv = copy.copy( self )
        rv.gender = 'male' if random.randint(0,1) else 'female'
        return rv

class ProperNoun ( Noun ):
    def __init__(self, name, gender ):
        Noun.__init__(self, None, name, "<no plural: %s>" % name, the = False, gender = gender )
    def amount(self, n, informal = False):
        if n == 1:
            return self.singular
        return Noun.amount(self, n, informal = informal)

if __name__ == '__main__':
    penguin = Noun( "a", "penguin", "penguins" )
    print penguin.indefiniteSingular()
    for i in range(40):
        print penguin.indefiniteAmount( i )
    print penguin.definiteSingular()
    percy = ProperNoun( "Percy" )
    print percy.indefiniteSingular()
    for i in range(2):
        print percy.indefiniteAmount( i )
    print percy.definiteSingular()


text:
actions :setup_iscsi, :setup_mediator_disk
default_action :setup_iscsi

attribute :name, :kind_of => String, :required => true, :name_attribute => true


text:
package org.hisp.dhis.organisationunit;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.MetadataObject;
import org.hisp.dhis.schema.annotation.PropertyRange;

/**
 * @author Lars Helge Overland
 */
@JacksonXmlRootElement( localName = "organisationUnitLevel", namespace = DxfNamespaces.DXF_2_0 )
public class OrganisationUnitLevel
    extends BaseIdentifiableObject implements MetadataObject
{
    private int level;

    private Integer offlineLevels;

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    public OrganisationUnitLevel()
    {
    }

    public OrganisationUnitLevel( int level, String name )
    {
        this.level = level;
        this.name = name;
    }

    public OrganisationUnitLevel( int level, String name, Integer offlineLevels )
    {
        this.level = level;
        this.name = name;
        this.offlineLevels = offlineLevels;
    }

    @Override
    public String toString()
    {
        return "[Name: " + name + ", level: " + level + "]";
    }

    // -------------------------------------------------------------------------
    // Getters and setters
    // -------------------------------------------------------------------------

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    @PropertyRange( min = 1, max = 999 )
    public int getLevel()
    {
        return level;
    }

    public void setLevel( int level )
    {
        this.level = level;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Integer getOfflineLevels()
    {
        return offlineLevels;
    }

    public void setOfflineLevels( Integer offlineLevels )
    {
        this.offlineLevels = offlineLevels;
    }
}


text:
<?php

namespace Orders;

return [
	'service_manager' => [
        'factories' => [
            'Orders/Listener/BindInvoiceAddressEntity' => 'Orders\Factory\Form\Listener\BindInvoiceAddressEntityFactory',
            'Orders/Listener/CreateJobOrder' => 'Orders\Factory\Listener\CreateJobOrderFactory',
            'Orders/Listener/AdminWidgetProvider' => 'Orders\Factory\Listener\AdminWidgetProviderFactory',
            'Orders/Entity/JobInvoiceAddress' => 'Orders\Factory\Entity\JobInvoiceAddressFactory',
        ],
    ],

    'controllers' => [
        'invokables' => [
            'Orders/List' => 'Orders\Controller\ListController',
        ],
        'factories' => [
            Controller\ViewController::class => Factory\Controller\ViewControllerFactory::class,
        ],
    ],

    'form_elements' => [
        'invokables' => [
            'Orders/InvoiceAddress' => 'Orders\Form\InvoiceAddress',
        ],
        'factories' => [
            'Orders/JobInvoiceAddress' => 'Orders\Factory\Form\JobInvoiceAddressFactory',
            Form\InvoiceAddressSettingsFieldset::class => \Settings\Form\Factory\SettingsFieldsetFactory::class,
            'Orders/InvoiceAddressFieldset' => Factory\Form\InvoiceAddressFieldsetFactory::class,
        ],
        'aliases' => [
            'Orders/InvoiceAddressSettingsFieldset' => Form\InvoiceAddressSettingsFieldset::class,
        ]
    ],

    'filters' => [
        'invokables' => [
            'PaginationQuery/Orders' => 'Orders\Repository\Filter\PaginationQuery',
        ],
    ],

    'view_helpers' => [
        'invokables' => [
            'formatInvoiceAddress' => 'Orders\View\Helper\FormatInvoiceAddress',
        ],
    ],
];


text:
package org.caleydo.data.importer.tcga;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.RecursiveTask;
import java.util.logging.Logger;

import org.caleydo.core.data.collection.table.Table;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.datadomain.DataDomainManager;
import org.caleydo.core.data.datadomain.IDataDomain;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.io.DataLoader;
import org.caleydo.core.serialize.ProjectManager;
import org.caleydo.core.serialize.ProjectMetaData;
import org.caleydo.data.importer.tcga.model.TCGADataSet;
import org.caleydo.data.importer.tcga.model.TCGADataSets;
import org.caleydo.view.tourguide.api.score.ISerializeableScore;
import org.caleydo.view.tourguide.api.score.Scores;
import org.eclipse.core.runtime.NullProgressMonitor;

import com.google.common.collect.Lists;
import com.google.gson.JsonElement;

public abstract class ATCGATask extends RecursiveTask<JsonElement> {
	private static final long serialVersionUID = 6349085075502142673L;
	private static final Logger log = Logger.getLogger(ATCGATask.class.getName());

	public static class AdditionalInfo {
		private AdditionalPerspectiveInfo gene;
		private AdditionalPerspectiveInfo sample;

		public AdditionalInfo(ATableBasedDataDomain d) {
			gene = new AdditionalPerspectiveInfo(d.getTable(), false);
			sample = new AdditionalPerspectiveInfo(d.getTable(), true);
		}

		/**
		 * @return the gene, see {@link #gene}
		 */
		public AdditionalPerspectiveInfo getGene() {
			return gene;
		}

		/**
		 * @return the sample, see {@link #sample}
		 */
		public AdditionalPerspectiveInfo getSample() {
			return sample;
		}
	}

	public static class AdditionalPerspectiveInfo {
		private int count;
		private List<String> groupings = new ArrayList<>();

		public AdditionalPerspectiveInfo(Table table, boolean record) {
			this.count = record ? table.depth() : table.size();
			Iterable<String> list = record ? table.getRecordPerspectiveIDs() : table.getDimensionPerspectiveIDs();

			for (String id : list) {
				Perspective p = record ? table.getRecordPerspective(id) : table.getDimensionPerspective(id);
				if (p.isPrivate())
					continue;
				if (p.equals(record ? table.getDefaultRecordPerspective(false) : table
						.getDefaultRecordPerspective(false)))
					continue;
				if (p.getLabel().equalsIgnoreCase("ungrouped"))
					continue;
				groupings.add(p.getLabel());
			}
		}

		/**
		 * @return the count, see {@link #count}
		 */
		public int getCount() {
			return count;
		}

		/**
		 * @return the groupings, see {@link #groupings}
		 */
		public List<String> getGroupings() {
			return groupings;
		}
	}

	protected static boolean saveProject(Collection<ATableBasedDataDomain> dataDomains, String projectOutputPath,
			ProjectMetaData metaData) {
		try {
			ProjectManager.save(projectOutputPath, true, dataDomains, metaData).run(new NullProgressMonitor());
			return true;
		} catch (InvocationTargetException | InterruptedException e) {
			e.printStackTrace();
			return false;
		}
	}

	protected static Collection<ATableBasedDataDomain> loadProject(TCGADataSets project) {
		Collection<ATableBasedDataDomain> dataDomains = new ArrayList<>();
		for (TCGADataSet desc : project) {
			try {
			ATableBasedDataDomain dataDomain = DataLoader.loadData(desc.getDescription(), new NullProgressMonitor());
			if (dataDomain == null)
				continue;
			dataDomains.add(dataDomain);
			desc.setDataDomain(dataDomain);
			} catch (Exception e) {
				continue;
			}
		}
		return dataDomains;
	}

	protected static void cleanUp(Collection<? extends IDataDomain> dataDomains) {
		log.info("cleanup " + dataDomains.size() + " data domains");
		for (IDataDomain dataDomain : dataDomains)
			DataDomainManager.get().unregister(dataDomain);
		// remove external scores
		final Scores scores = Scores.get();
		for (ISerializeableScore s : Lists.newArrayList(scores.getPersistentScores()))
			scores.removePersistentScore(s);
	}
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hapalophragmium nsukkaensis Eboh

### Remarks
null


text:
export interface Point {
    x: number;
    y: number;
}


text:
"""Generates system metadata for a file.

e.g.:

export OBJECT=/some/file
generate_sysmeta.py -f $OBJECT \
                    -i "Some_Identifier" \
                    -s "CN=Dave Vieglais T799,O=Google,C=US,DC=cilogon,DC=org" \
                    -t "some_format"

"""

import logging
import optparse
import os.path
import sys
import urllib.request

import d1_common.date_time
import d1_common.types.dataoneTypes

import d1_test.instance_generator.system_metadata

# import lxml

# flake8: noqa: F821

def getObjectFormatFromID(fmtid, default="application/octet-stream"):
    """Returns an ObjectFormat instance given a format id."""
    formatlistURL = (
        "https://repository.dataone.org/software/cicore/trunk/d1_common_java/src/"
        "main/resources/org/dataone/service/resources/config/v1/objectFormatList.xml"
    )
    doc = urllib.request.urlopen(formatlistURL).read().decode("utf-8")
    formats = d1_common.types.dataoneTypes.CreateFromDocument(doc)
    for format in formats.objectFormat:
        if format.formatId == fmtid:
            logging.debug("Found format for %s" % fmtid)
            return format
    for format in formats:
        if format.formatId == default:
            return format
    return None

def processDoc(fname, options={}):
    """Generate system metadata XML for file fname."""
    # add script arguments to a comment in the generated metadata
    tnow = d1_common.date_time.local_now_iso()
    comment = lxml.etree.Comment(
        "Warning: This file was generated by an automated process. Manual edits may "
        "be overwritten without further warning.\n"
        "timestamp:: %s\n"
        "created_with:: generate_sysmeta.py\n"
        "arguments:: %s\n"
        "command:: generate_sysmeta.py %s\n"
        % (tnow, repr(sys.argv[1:]), " ".join(sys.argv[1:]))
    )
    sysm = d1_test.instance_generator.system_metadata.generate_from_file_path(
        fname, options
    )
    root = lxml.etree.fromstring(sysm.toxml("utf-8"))
    root.insert(0, comment)
    pxml = lxml.etree.tostring(
        root, pretty_print=True, encoding="utf-8", xml_declaration=True
    )
    return pxml

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option(
        "-f",
        "--fname",
        action="store",
        type="string",
        help="File name of target object",
    )
    parser.add_option(
        "-i",
        "--id",
        dest="identifier",
        action="store",
        type="string",
        help="Identifier of target object",
    )
    parser.add_option(
        "-t",
        "--format",
        action="store",
        type="string",
        default="application/octet-stream",
        help="Object format ID of target object",
    )
    parser.add_option(
        "-s",
        "--submitter",
        action="store",
        type="string",
        default="dataone_integration_test_user",
        help="Subject of the submitter [default: %default].",
    )
    parser.add_option(
        "-r",
        "--rights",
        dest="rightsHolder",
        action="store",
        type="string",
        help="Subject of the object rights holder, defaults to submitter.",
    )
    parser.add_option(
        "-o",
        "--origin",
        dest="originMemberNode",
        action="store",
        type="string",
        default="test_documents",
        help="Origin member node identifier [default: %default].",
    )
    parser.add_option(
        "-n",
        "--replicas",
        dest="numberReplicas",
        type="int",
        default=3,
        help="Number of replicas requested.",
    )
    parser.add_option(
        "-l",
        "--loglevel",
        dest="llevel",
        default=20,
        type="int",
        help="Reporting level: 10=debug, 20=Info, 30=Warning, "
        "40=Error, 50=Fatal [default: %default]",
    )
    (options, args) = parser.parse_args(sys.argv)
    if options.llevel not in [10, 20, 30, 40, 50]:
        options.llevel = 20
    logging.basicConfig(level=int(options.llevel))
    if options.fname is None:
        print("File name for object is required.")
        parser.print_help()
        sys.exit()
    if options.identifier is None:
        print("Identifier for object is required.")
        parser.print_help()
        sys.exit()
    if not os.path.exists(options.fname):
        print("File %s not found" % options.fname)
        parser.print_help()
        sys.exit()

    oopts = {}
    oopts["fname"] = options.fname
    oopts["identifier"] = options.identifier
    objectFormat = getObjectFormatFromID(options.format)
    oopts["formatId"] = objectFormat.formatId
    oopts["submitter"] = options.submitter
    if options.rightsHolder is None:
        oopts["rightsHolder"] = options.submitter
    else:
        oopts["rightsHolder"] = options.rightsHolder
    oopts["originMemberNode"] = options.originMemberNode
    oopts["authoritativeMemberNode"] = options.originMemberNode

    defrepl = d1_common.types.dataoneTypes.ReplicationPolicy()
    if options.numberReplicas == 0:
        defrepl.replicationAllowed = False
    else:
        defrepl.replicationAllowed = True
        defrepl.numberReplicas = options.numberReplicas
    oopts["replicationPolicy"] = defrepl

    defap = d1_common.types.dataoneTypes.AccessPolicy()
    ar = d1_common.types.dataoneTypes.AccessRule()
    ar.permission = [d1_common.types.dataoneTypes.Permission.read]
    ar.subject = ["public"]
    defap.allow = [ar]
    ar = d1_common.types.dataoneTypes.AccessRule()
    ar.permission = [d1_common.types.dataoneTypes.Permission.write]
    ar.subject = [oopts["submitter"]]
    defap.allow.append(ar)
    oopts["accessPolicy"] = defap

    logging.debug(str(oopts))

    print(processDoc(oopts["fname"], oopts))
    sys.exit()


text:
using HueApi.Entertainment.Effects.BasEffects;
using HueApi.Entertainment.Extensions;
using HueApi.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HueApi.Entertainment.Models
{
  public class EntertainmentLayer : List<EntertainmentLight>
  {

    public bool IsBaseLayer { get; set; }

    /// <summary>
    /// List of effects applied to this streaminggroup
    /// </summary>
    public List<BaseEffect> Effects { get; set; } = new List<BaseEffect>();

    public EntertainmentLayer(bool isBaseLayer = false)
    {
      IsBaseLayer = isBaseLayer;
    }

    internal void ProcessTransitions()
    {
      ForEach(x => x.ProcessTransitions());
    }

    /// <summary>
    /// Adds an effect to the effect list
    /// </summary>
    /// <param name="baseEffect"></param>
    public void PlaceEffect(BaseEffect baseEffect)
    {
      Effects.Add(baseEffect);
    }

    /// <summary>
    /// Used to auto update and apply effects that are added to the Effects list of the StreamingGroup
    /// </summary>
    /// <param name="entGroup"></param>
    /// <param name="cancellationToken"></param>
    public void AutoCalculateEffectUpdate(CancellationToken cancellationToken)
    {
      Task.Run(async () =>
      {
        int waitTime = 50;

        while (!cancellationToken.IsCancellationRequested)
        {
          foreach (var light in this)
          {
            double? finalMultiplier = null;
            BaseEffect? finalEffect = null;

            //Only activate effect with strongest effect multiplier
            foreach (var effect in Effects.Where(x => x.State != null).ToList())
            {
              var effectMultiplier = effect.GetEffectStrengthMultiplier(light);
              if (effectMultiplier > finalMultiplier || !finalMultiplier.HasValue)
              {
                finalMultiplier = effectMultiplier;
                finalEffect = effect;
              }
            }

            if (finalMultiplier.HasValue)
            {
              light.SetState(cancellationToken, finalEffect?.State?.RGBColor, finalEffect?.State?.Brightness * finalMultiplier.Value);
            }
          }

          await Task.Delay(waitTime, cancellationToken).ConfigureAwait(false);
        }

      }, cancellationToken);
    }
  }

  /// <summary>
  /// Light that is included in a entertainment group
  /// </summary>
  public class EntertainmentLight
  {
    private readonly object transitionLock = new object();

    public HuePosition LightLocation { get; private set; }

    public byte Id { get; set; }

    public EntertainmentState State { get; set; } = new EntertainmentState();

    private Transition? _transition;
    public Transition? Transition
    {
      get
      {
        return _transition;
      }
      set
      {
        lock (transitionLock)
        {
          _transition = value;
        }
      }
    }

    public EntertainmentLight(byte id, HuePosition location)
    {
      Id = id;
      LightLocation = location;
    }

    /// <summary>
    /// Changes the state based on one or more transition
    /// </summary>
    internal void ProcessTransitions()
    {
      lock (transitionLock)
      {
        if (Transition == null)
          return;

        State.SetBrightness(Transition.TransitionState.Brightness);
        State.SetRGBColor(Transition.TransitionState.RGBColor);

        if (Transition.IsFinished)
          Transition = null;
      }
    }
  }
}


text:
		<title>Colibrio - Collaborative Tweet Chat</title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<link rel="stylesheet" href="http://visuel.tv/colibrio/main.css" type="text/css"/>

Colibrio - Collaborative Tweet Chat

Enter a username:

		<form id="setNick">
			<input size="35" id="nickname"></input>
			<input type="submit" value="Join Chat"></input>
		</form>

			<form id="send-message">
				Enter your tweet here:
				<textarea id="message" maxlength="140"></textarea>

				<input type="submit" value="Send"></input>
			</form>

Connected Users:

Tweet


text:
.. spelling::

    coretext

.. index:: system_library_finder ; coretext

.. _pkg.coretext:

coretext
========

.. note::

    This is a helper package. There is no corresponding package in Hunter to be included by ``hunter_add_package(...)``

.. code-block:: cmake

    find_package(coretext REQUIRED)
    target_link_libraries(... coretext::coretext)

Same as

.. code-block:: cmake

    target_link_libraries(... "-framework CoreText")

-  https://developer.apple.com/documentation/coretext?language=objc


text:
#include <net/if_arp.h>

/*
 * Ethernet address - 6 octets
 */
struct ether_addr {
	u_char	ether_addr_octet[6];
};

/*
 * Structure of a 10Mb/s Ethernet header.
 */
struct	ether_header {
	u_char	ether_dhost[6];
	u_char	ether_shost[6];
	u_short	ether_type;
};

#define	ETHERTYPE_PUP		0x0200	/* PUP protocol */
#define	ETHERTYPE_IP		0x0800	/* IP protocol */
#define	ETHERTYPE_IPV6		0x86dd	/* IPv6 protocol */
#define ETHERTYPE_ARP		0x0806	/* Addr. resolution protocol */
#define ETHERTYPE_REVARP	0x8035	/* reverse Addr. resolution protocol */

/*
 * The ETHERTYPE_NTRAILER packet types starting at ETHERTYPE_TRAIL have
 * (type-ETHERTYPE_TRAIL)*512 bytes of data followed
 * by an ETHER type (as given above) and then the (variable-length) header.
 */
#define	ETHERTYPE_TRAIL		0x1000		/* Trailer packet */
#define	ETHERTYPE_NTRAILER	16

#define	ETHERMTU	1500
#define	ETHERMIN	(60-14)

/*
 * Ethernet Address Resolution Protocol.
 *
 * See RFC 826 for protocol description.  Structure below is adapted
 * to resolving internet addresses.  Field names used correspond to
 * RFC 826.
 */
struct	ether_arp {
	struct	arphdr ea_hdr;	/* fixed-size header */
	u_char	arp_sha[6];	/* sender hardware address */
	u_char	arp_spa[4];	/* sender protocol address */
	u_char	arp_tha[6];	/* target hardware address */
	u_char	arp_tpa[4];	/* target protocol address */
};
#define	arp_hrd	ea_hdr.ar_hrd
#define	arp_pro	ea_hdr.ar_pro
#define	arp_hln	ea_hdr.ar_hln
#define	arp_pln	ea_hdr.ar_pln
#define	arp_op	ea_hdr.ar_op


text:
layout: post
title: "Mates y Football"
date: 2018-04-28 21:04:22
tags: [Deportes]
categories: [Quincenal, Argentina, Uruguay]
preview: https://ia601502.us.archive.org/5/items/500Ruta97ToniMateuArrom/300Logo_up-RicardoChocron.jpg
---

![Mates y Football](https://ia601502.us.archive.org/5/items/500Ruta97ToniMateuArrom/500Logo_up-RicardoChocron.jpg)

## Escucha su más reciente episodio

<audio id="audio" preload="auto" controls="" src="http://www.ivoox.com/mates-football-s01e13-analisis-vivo_mf_30020101_feed_1.mp3"></audio>

Te contamos todo acerca del mundo NFL con acento rioplatense.

_ _ _

Autor: **Agustín Espósito, Gonzalo Machín, Ricardo Chocron**
[Feed](http://www.ivoox.com/mates-football_fg_f1566742_filtro_1.xml)

**Contacta:**
Twitter: [@MatesyFootball](https://twitter.com/MatesyFootball)
Correo: [matesyfootball@gmail.com](mailto:matesyfootball@gmail.com)


text:
package org.usc.wechat.mp.sdk.vo.media;

import java.util.List;

import org.usc.wechat.mp.sdk.vo.AbstractToStringBuilder;

import com.alibaba.fastjson.annotation.JSONField;

/**
 *
 * @author Shunli
 */
public class NewsMedia extends AbstractToStringBuilder {
    @JSONField(name = "articles")
    private List<NewsMediaDetail> articles;

    public NewsMedia(List<NewsMediaDetail> articles) {
        this.articles = articles;
    }

    public List<NewsMediaDetail> getArticles() {
        return articles;
    }

    public void setArticles(List<NewsMediaDetail> articles) {
        this.articles = articles;
    }

}


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

HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, 'README.rst')) as f:
    README = f.read()
with open(os.path.join(HERE, 'CHANGELOG.rst')) as f:
    CHANGELOG = f.read()

REQUIRES = [
    'requests',
]

setup(name='rp_arsenal_ansible_inventory',
      version=1.0,
      description='Python script to generate ansbile inventory from an arsenal query.',
      long_description=README + '\n\n' + CHANGELOG,
      classifiers=[
          'Programming Language :: Python',
      ],
      author='Aaron Bandt',
      author_email='abandt@rubiconproject.com',
      url='',
      license='Apache',
      keywords='Arsenal devops',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires=REQUIRES,
      tests_require=REQUIRES,
      test_suite='rp_arsenal_ansible_inventory',
      scripts=['bin/arsenal_ansible_inventory.py']
     )