text:
.. _whatsnew_0110:

v0.11.0 (April 22, 2013)
------------------------

{{ header }}

This is a major release from 0.10.1 and includes many new features and
enhancements along with a large number of bug fixes. The methods of Selecting
Data have had quite a number of additions, and Dtype support is now full-fledged.
There are also a number of important API changes that long-time pandas users should
pay close attention to.

There is a new section in the documentation, :ref:`10 Minutes to Pandas <10min>`,
primarily geared to new users.

There is a new section in the documentation, :ref:`Cookbook <cookbook>`, a collection
of useful recipes in pandas (and that we want contributions!).

There are several libraries that are now :ref:`Recommended Dependencies <install.recommended_dependencies>`

Selection Choices
~~~~~~~~~~~~~~~~~

Starting in 0.11.0, object selection has had a number of user-requested additions in
order to support more explicit location based indexing. Pandas now supports
three types of multi-axis indexing.

- ``.loc`` is strictly label based, will raise ``KeyError`` when the items are not found, allowed inputs are:

  - A single label, e.g. ``5`` or ``'a'``, (note that ``5`` is interpreted as a *label* of the index. This use is **not** an integer position along the index)
  - A list or array of labels ``['a', 'b', 'c']``
  - A slice object with labels ``'a':'f'``, (note that contrary to usual python slices, **both** the start and the stop are included!)
  - A boolean array

  See more at :ref:`Selection by Label <indexing.label>`

- ``.iloc`` is strictly integer position based (from ``0`` to ``length-1`` of the axis), will raise ``IndexError`` when the requested indices are out of bounds. Allowed inputs are:

  - An integer e.g. ``5``
  - A list or array of integers ``[4, 3, 0]``
  - A slice object with ints ``1:7``
  - A boolean array

  See more at :ref:`Selection by Position <indexing.integer>`

- ``.ix`` supports mixed integer and label based access. It is primarily label based, but will fallback to integer positional access. ``.ix`` is the most general and will support
  any of the inputs to ``.loc`` and ``.iloc``, as well as support for floating point label schemes. ``.ix`` is especially useful when dealing with mixed positional and label
  based hierarchical indexes.

  As using integer slices with ``.ix`` have different behavior depending on whether the slice
  is interpreted as position based or label based, it's usually better to be
  explicit and use ``.iloc`` or ``.loc``.

  See more at :ref:`Advanced Indexing <advanced>` and :ref:`Advanced Hierarchical <advanced.advanced_hierarchical>`.

Selection Deprecations
~~~~~~~~~~~~~~~~~~~~~~

Starting in version 0.11.0, these methods *may* be deprecated in future versions.

- ``irow``
- ``icol``
- ``iget_value``

See the section :ref:`Selection by Position <indexing.integer>` for substitutes.

Dtypes
~~~~~~

Numeric dtypes will propagate and can coexist in DataFrames. If a dtype is passed (either directly via the ``dtype`` keyword, a passed ``ndarray``, or a passed ``Series``, then it will be preserved in DataFrame operations. Furthermore, different numeric dtypes will **NOT** be combined. The following example will give you a taste.

.. ipython:: python

   df1 = pd.DataFrame(np.random.randn(8, 1), columns=['A'], dtype='float32')
   df1
   df1.dtypes
   df2 = pd.DataFrame({'A': pd.Series(np.random.randn(8), dtype='float16'),
                       'B': pd.Series(np.random.randn(8)),
                       'C': pd.Series(range(8), dtype='uint8')})
   df2
   df2.dtypes

   # here you get some upcasting
   df3 = df1.reindex_like(df2).fillna(value=0.0) + df2
   df3
   df3.dtypes

Dtype Conversion
~~~~~~~~~~~~~~~~

This is lower-common-denominator upcasting, meaning you get the dtype which can accommodate all of the types

.. ipython:: python

   df3.values.dtype

Conversion

.. ipython:: python

   df3.astype('float32').dtypes

Mixed Conversion

.. ipython:: python
   :okwarning:

   df3['D'] = '1.'
   df3['E'] = '1'
   df3.convert_objects(convert_numeric=True).dtypes

   # same, but specific dtype conversion
   df3['D'] = df3['D'].astype('float16')
   df3['E'] = df3['E'].astype('int32')
   df3.dtypes

Forcing Date coercion (and setting ``NaT`` when not datelike)

.. ipython:: python
   :okwarning:

   import datetime
   s = pd.Series([datetime.datetime(2001, 1, 1, 0, 0), 'foo', 1.0, 1,
                  pd.Timestamp('20010104'), '20010105'], dtype='O')
   s.convert_objects(convert_dates='coerce')

Dtype Gotchas
~~~~~~~~~~~~~

**Platform Gotchas**

Starting in 0.11.0, construction of DataFrame/Series will use default dtypes of ``int64`` and ``float64``,
*regardless of platform*. This is not an apparent change from earlier versions of pandas. If you specify
dtypes, they *WILL* be respected, however (:issue:`2837`)

The following will all result in ``int64`` dtypes

.. ipython:: python

    pd.DataFrame([1, 2], columns=['a']).dtypes
    pd.DataFrame({'a': [1, 2]}).dtypes
    pd.DataFrame({'a': 1}, index=range(2)).dtypes

Keep in mind that ``DataFrame(np.array([1,2]))`` **WILL** result in ``int32`` on 32-bit platforms!

**Upcasting Gotchas**

Performing indexing operations on integer type data can easily upcast the data.
The dtype of the input data will be preserved in cases where ``nans`` are not introduced.

.. ipython:: python

   dfi = df3.astype('int32')
   dfi['D'] = dfi['D'].astype('int64')
   dfi
   dfi.dtypes

   casted = dfi[dfi > 0]
   casted
   casted.dtypes

While float dtypes are unchanged.

.. ipython:: python

   df4 = df3.copy()
   df4['A'] = df4['A'].astype('float32')
   df4.dtypes

   casted = df4[df4 > 0]
   casted
   casted.dtypes

Datetimes Conversion
~~~~~~~~~~~~~~~~~~~~

Datetime64[ns] columns in a DataFrame (or a Series) allow the use of ``np.nan`` to indicate a nan value,
in addition to the traditional ``NaT``, or not-a-time. This allows convenient nan setting in a generic way.
Furthermore ``datetime64[ns]`` columns are created by default, when passed datetimelike objects (*this change was introduced in 0.10.1*)
(:issue:`2809`, :issue:`2810`)

.. ipython:: python

   df = pd.DataFrame(np.random.randn(6, 2), pd.date_range('20010102', periods=6),
                     columns=['A', ' B'])
   df['timestamp'] = pd.Timestamp('20010103')
   df

   # datetime64[ns] out of the box
   df.get_dtype_counts()

   # use the traditional nan, which is mapped to NaT internally
   df.loc[df.index[2:4], ['A', 'timestamp']] = np.nan
   df

Astype conversion on ``datetime64[ns]`` to ``object``, implicitly converts ``NaT`` to ``np.nan``

.. ipython:: python

   s = pd.Series([datetime.datetime(2001, 1, 2, 0, 0) for i in range(3)])
   s.dtype
   s[1] = np.nan
   s
   s.dtype
   s = s.astype('O')
   s
   s.dtype

API changes
~~~~~~~~~~~

  - Added to_series() method to indices, to facilitate the creation of indexers
    (:issue:`3275`)

  - ``HDFStore``

    - added the method ``select_column`` to select a single column from a table as a Series.
    - deprecated the ``unique`` method, can be replicated by ``select_column(key,column).unique()``
    - ``min_itemsize`` parameter to ``append`` will now automatically create data_columns for passed keys

Enhancements
~~~~~~~~~~~~

  - Improved performance of df.to_csv() by up to 10x in some cases. (:issue:`3059`)

  - Numexpr is now a :ref:`Recommended Dependencies <install.recommended_dependencies>`, to accelerate certain
    types of numerical and boolean operations

  - Bottleneck is now a :ref:`Recommended Dependencies <install.recommended_dependencies>`, to accelerate certain
    types of ``nan`` operations

  - ``HDFStore``

    - support ``read_hdf/to_hdf`` API similar to ``read_csv/to_csv``

      .. ipython:: python
          :suppress:

          from pandas.compat import lrange

      .. ipython:: python

          df = pd.DataFrame({'A': lrange(5), 'B': lrange(5)})
          df.to_hdf('store.h5', 'table', append=True)
          pd.read_hdf('store.h5', 'table', where=['index > 2'])

      .. ipython:: python
          :suppress:
          :okexcept:

          import os

          os.remove('store.h5')

    - provide dotted attribute access to ``get`` from stores, e.g. ``store.df == store['df']``

    - new keywords ``iterator=boolean``, and ``chunksize=number_in_a_chunk`` are
      provided to support iteration on ``select`` and ``select_as_multiple`` (:issue:`3076`)

  - You can now select timestamps from an *unordered* timeseries similarly to an *ordered* timeseries (:issue:`2437`)

  - You can now select with a string from a DataFrame with a datelike index, in a similar way to a Series (:issue:`3070`)

    .. ipython:: python

        idx = pd.date_range("2001-10-1", periods=5, freq='M')
        ts = pd.Series(np.random.rand(len(idx)), index=idx)
        ts['2001']

        df = pd.DataFrame({'A': ts})
        df['2001']

  - ``Squeeze`` to possibly remove length 1 dimensions from an object.

    .. ipython:: python

       p = pd.Panel(np.random.randn(3, 4, 4), items=['ItemA', 'ItemB', 'ItemC'],
                    major_axis=pd.date_range('20010102', periods=4),
                    minor_axis=['A', 'B', 'C', 'D'])
       p
       p.reindex(items=['ItemA']).squeeze()
       p.reindex(items=['ItemA'], minor=['B']).squeeze()

  - In ``pd.io.data.Options``,

    + Fix bug when trying to fetch data for the current month when already
      past expiry.
    + Now using lxml to scrape html instead of BeautifulSoup (lxml was faster).
    + New instance variables for calls and puts are automatically created
      when a method that creates them is called. This works for current month
      where the instance variables are simply ``calls`` and ``puts``. Also
      works for future expiry months and save the instance variable as
      ``callsMMYY`` or ``putsMMYY``, where ``MMYY`` are, respectively, the
      month and year of the option's expiry.
    + ``Options.get_near_stock_price`` now allows the user to specify the
      month for which to get relevant options data.
    + ``Options.get_forward_data`` now has optional kwargs ``near`` and
      ``above_below``. This allows the user to specify if they would like to
      only return forward looking data for options near the current stock
      price. This just obtains the data from Options.get_near_stock_price
      instead of Options.get_xxx_data() (:issue:`2758`).

  - Cursor coordinate information is now displayed in time-series plots.

  - added option `display.max_seq_items` to control the number of
    elements printed per sequence pprinting it.  (:issue:`2979`)

  - added option `display.chop_threshold` to control display of small numerical
    values. (:issue:`2739`)

  - added option `display.max_info_rows` to prevent verbose_info from being
    calculated for frames above 1M rows (configurable). (:issue:`2807`, :issue:`2918`)

  - value_counts() now accepts a "normalize" argument, for normalized
    histograms. (:issue:`2710`).

  - DataFrame.from_records now accepts not only dicts but any instance of
    the collections.Mapping ABC.

  - added option `display.mpl_style` providing a sleeker visual style
    for plots. Based on https://gist.github.com/huyng/816622 (:issue:`3075`).

  - Treat boolean values as integers (values 1 and 0) for numeric
    operations. (:issue:`2641`)

  - to_html() now accepts an optional "escape" argument to control reserved
    HTML character escaping (enabled by default) and escapes ``&``, in addition
    to ``<`` and ``>``.  (:issue:`2919`)

See the :ref:`full release notes
<release>` or issue tracker
on GitHub for a complete list.

.. _whatsnew_0.11.0.contributors:

Contributors
~~~~~~~~~~~~

.. contributors:: v0.10.1..v0.11.0


text:
/*
* Requirements mandating inclusion:
*
* 3.2.1.6.3.2 User can create Game Rules by selecting Game Events and adding a Game Action to that event.
* 3.2.1.3.7.2 User can view Event actions and rules.
* 3.2.1.3.7.3 User can edit Event actions and rules.
* 3.2.2.5.3.1 Rule Interpreter will interpret and execute Game Rules for a Card Game.
* */
package model.GameEvents;

import model.*;
import view.Gameplay.GameplayViewUpdater;

public class OnTurnStartEvent extends GameEvent {

    public OnTurnStartEvent() {
        this.className = "OnTurnStartEvent";
        this.description = "The player's turn is starting.";
    }

    @Override
    public void run() {
        GameState.getInstance().setCurrentRule(this);
        if (RuleInterpreter.gameCompleted()) {return;}

        Player currentPlayer = GameState.getInstance().getCurrentPlayer();
        if (currentPlayer == null) { // This means that RoundStart was just run. It sets activePlayer to null.
            currentPlayer = GameCreation.getInstance().getPlayers().get(0); // Get the first player.
            GameState.getInstance().setCurrentPlayer(currentPlayer);
        }

        if (currentPlayer.isInactive()) {
            GameplayViewUpdater.postGameplayMessage(GameplayMessageType.INFO, "Player '"
                    + GameState.getInstance().getCurrentPlayer().getName() + "' has been set to inactive. Skipping turn.");
            RuleInterpreter.launchTurnEndEvent();
            return;
        }

        GameplayViewUpdater.postGameplayMessage(GameplayMessageType.EVENT, RuleInterpreter.defaultGameplayMessage() + " -- Starting " + currentPlayer.getName() + "'s turn.");
        GameplayViewUpdater.updateSelectedPile(currentPlayer.getHand());
        GameState.getInstance().setSelectedPile(currentPlayer.getHand());

        RuleInterpreter.launchPostRules(this);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<query xmlns="http://labkey.org/data/xml/query">
    <metadata>
        <tables xmlns="http://labkey.org/data/xml">
            <table tableName="miscChargesFeeRates" tableDbType="NOT_IN_DB">
                <tableTitle>Misc. Charges</tableTitle>
                <columns>
                    <column columnName="unitCost">
                        <columnTitle>Unit Cost</columnTitle>
                        <formatString>$###,##0.00</formatString>
                    </column>
                    <column columnName="groupName">
                        <columnTitle>Group</columnTitle>
                    </column>
                    <column columnName="totalCost">
                        <columnTitle>Total Cost</columnTitle>
                        <formatString>$###,##0.00</formatString>
                    </column>
                    <column columnName="createdby">
                        <columnTitle>Entered By</columnTitle>
                        <fk>
                            <fkTable>Users</fkTable>
                            <fkDbSchema>core</fkDbSchema>
                            <fkColumnName>UserId</fkColumnName>
                        </fk>
                    </column>
                </columns>
            </table>
        </tables>
    </metadata>
</query>


text:
import sys
if sys.platform == 'win32':
    from tzlocal.win32 import get_localzone, reload_localzone
elif 'darwin' in sys.platform:
    from tzlocal.darwin import get_localzone, reload_localzone
else:
    from tzlocal.unix import get_localzone, reload_localzone


text:
package mireka;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

import mireka.util.StreamCopier;

public class ByteArrayMailData implements MailData {
    public final byte[] bytes;

    public ByteArrayMailData(byte[] bytes) {
        this.bytes = bytes;
    }

    @Override
    public ByteArrayInputStream getInputStream() {
        return new ByteArrayInputStream(bytes);
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        StreamCopier.writeMailDataInputStreamIntoOutputStream(this, out);
    }

    @Override
    public void dispose() {
        // nothing to do
    }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

// Array 'old_class_name' => 'new\class_name'.
$renamedclasses = array(

    // Changed in Moodle 2.8.
    'quiz_question_bank_view'                 => 'mod_quiz\question\bank\custom_view',
    'question_bank_add_to_quiz_action_column' => 'mod_quiz\question\bank\add_action_column',
    'question_bank_question_name_text_column' => 'mod_quiz\question\bank\question_name_text_column',
);


text:
package com.obdobion.funnel.publisher;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.ParseException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.obdobion.funnel.parameters.FunnelContext;

/**
 *

 * FixedLengthFilePublisher class.
 *

 *
 * @author Chris DeGreef fedupforone@gmail.com
 */
public class FixedLengthFilePublisher extends FixedLengthPublisher
{
    static final private Logger logger = LoggerFactory.getLogger(FixedLengthFilePublisher.class);

    File                        sortedTempFile;

    /**
     *

     * Constructor for FixedLengthFilePublisher.
     *

     *
     * @param _context a {@link com.obdobion.funnel.parameters.FunnelContext}
     *            object.
     * @throws java.text.ParseException if any.
     * @throws java.io.IOException if any.
     */
    public FixedLengthFilePublisher(final FunnelContext _context) throws ParseException, IOException
    {
        super(_context);
        logger.debug("fixed length file publisher activated");
    }

    /** {@inheritDoc} */
    @Override
    public void close() throws Exception
    {
        super.close();

        ((RandomAccessFile) writer).close();

        if (context.getOutputFile().delete())
            logger.debug("deleted {}", context.getOutputFile().getAbsolutePath());

        if (!sortedTempFile.renameTo(context.getOutputFile()))
            throw new IOException("failed to rename "
                    + sortedTempFile.getAbsolutePath()
                    + " to "
                    + context.getOutputFile().getAbsolutePath());

        logger.debug("renamed {} to {}", sortedTempFile.getAbsolutePath(), context.getOutputFile().getAbsolutePath());
    }

    /**
     * @param context2
     */
    @Override
    void openOutput(final FunnelContext context2) throws IOException
    {
        sortedTempFile = File
                .createTempFile("Sorted.", ".tmp", context.getOutputFile().getAbsoluteFile().getParentFile());
        sortedTempFile.deleteOnExit();
        writer = new RandomAccessFile(sortedTempFile, "rw");

        logger.debug("writing {}", sortedTempFile.getAbsolutePath());
    }
}


text:
package com.google.api.generator.gapic.composer.utils;

import static org.junit.Assert.assertEquals;

import com.google.api.generator.testutils.LineFormatter;
import org.junit.Test;

public class CommentFormatterTest {
  private static final String SERVICE_DESCRIPTION_HEADER_PATTERN = "Service Description: %s";

  @Test
  public void parseCommentWithItemizedList_paragraphContainsList() {
    String protobufComment =
        LineFormatter.lines(
            "Service Name\n\n",
            "One line initial description. Here is a list of items:\n",
            " * This is item one\n",
            " * This is item two");
    String result = CommentFormatter.formatAsJavaDocComment(protobufComment, null);
    String expectedJavaDocComment =
        LineFormatter.lines(
            "
 Service Name\n",
            "
 One line initial description. Here is a list of items:\n",
            "
\n",
            "
  This is item one\n",
            "
  This is item two\n",
            "
");
    assertEquals(expectedJavaDocComment, result);
  }

  @Test
  public void parseCommentWithItemizedList_paragraphStartsWithList() {
    String protobufComment =
        LineFormatter.lines(
            "Paragraphs starting with list items should still be parsed as list:\n\n",
            " * This is item one\n",
            " * This is item two");
    String result = CommentFormatter.formatAsJavaDocComment(protobufComment, null);
    String expectedJavaDocComment =
        LineFormatter.lines(
            "
 Paragraphs starting with list items should still be parsed as list:\n",
            "
\n",
            "
  This is item one\n",
            "
  This is item two\n",
            "
");
    assertEquals(expectedJavaDocComment, result);
  }

  @Test
  public void parseCommentWithPrefixPattern_addIfStartsWithParagraph() {
    String protobufComment =
        LineFormatter.lines(
            "Service Name\n\n",
            "Here is a list of items:\n",
            " * This is item one\n",
            " * This is item two");
    String result =
        CommentFormatter.formatAsJavaDocComment(
            protobufComment, SERVICE_DESCRIPTION_HEADER_PATTERN);
    String expectedJavaDocComment =
        LineFormatter.lines(
            "
 Service Description: Service Name\n",
            "
 Here is a list of items:\n",
            "
\n",
            "
  This is item one\n",
            "
  This is item two\n",
            "
");
    assertEquals(expectedJavaDocComment, result);
  }

  @Test
  public void parseCommentWithPrefixPattern_ignoreIfStartsWithList() {
    String protobufComment = LineFormatter.lines(" * This is item one\n", " * This is item two");
    String result =
        CommentFormatter.formatAsJavaDocComment(
            protobufComment, SERVICE_DESCRIPTION_HEADER_PATTERN);
    String expectedJavaDocComment =
        LineFormatter.lines(
            "
\n", "
  This is item one\n", "
  This is item two\n", "
");
    assertEquals(expectedJavaDocComment, result);
  }
}


text:
pz_chainsaw_mod
===============

Project Zomboid chainsaw item mod

I want to chop down trees with a chainsaw. I've currently got a working
chainsaw with silly sounds that can chop down trees and kill zombies.
I'm currently (as of this commit date) working on getting fuel amounts
and fuel filling menus working.

Warning:

BACK UP YOUR SAVE!

I've mangled a bunch of saves so please back up any saves before using
this.

Setup:

Note that I'm developing this on Linux.

I'm currently linking the pz_chainsaw_mod/chainsaw/ directory into the
media/lua/client/ directory in the steam PZ dir.
(~/.steam/steam/SteamApps/common/ProjectZomboid/projectzomboid/media/lua/client/)

I'm also linking scripts/chainsaw.txt into <steam dir>/media/scripts/

e.g.
ln -s ~/dev/pz_chainsaw_mod/chainsaw/
    ~/.steam/steam/SteamApps/common/ProjectZomboid/projectzomboid/media/lua/client/chainsaw/

ln -s ~/dev/pz_chainsaw_mod/scripts/chainsaw.txt
    ~/.steam/steam/SteamApps/common/ProjectZomboid/projectzomboid/media/scripts/chainsaw.txt

Mod Loader:

I've got a simple mod picture and info but the mod loader doesn't seem
to be working for me and I'm not super interested in distribution at
this point.

Ideas:
- chop logs on the ground into planks on the ground
- chainsaw will require gas
- chainsaw will be fairly loud, but not quite gunshot loud
- chainsaw will be a handy zombie weapon


text:
package org.camunda.spin.xml;

import java.io.Writer;
import java.util.Collection;
import java.util.List;

import org.camunda.spin.SpinList;

/**
 * An element in a tree-oriented XML data format.
 *
 * @author Sebastian Menski
 * @author Daniel Meyer
 *
 */
public abstract class SpinXmlElement extends SpinXmlNode<SpinXmlElement> {

  /**
   * Checks whether this element has a attribute with an empty namespace and the given name.
   *
   * @param attributeName the name of the attribute
   * @return true if the element has an attribute with this name under the local namespace, false otherwise
   * @throws IllegalArgumentException if the attributeName is null
   */
  public abstract boolean hasAttr(String attributeName);

  /**
   * Returns the wrapped attribute for an empty namespace and the given name.
   *
   * @param attributeName the name of the attribute
   * @return the wrapped {@link SpinXmlAttribute attribute}
   * @throws IllegalArgumentException if the attributeName is null
   * @throws SpinXmlAttributeException if the attribute is not found
   */
  public abstract SpinXmlAttribute attr(String attributeName);

  /**
   * Sets the attribute value in the local namespace of this element.
   *
   * @param attributeName the name of the attribute
   * @param value the value to set
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the attributeName or value is null
   */
  public abstract SpinXmlElement attr(String attributeName, String value);

  /**
   * Removes the attribute with an empty namespace.
   *
   * @param attributeName the name of the attribute
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the attributeName is null
   */
  public abstract SpinXmlElement removeAttr(String attributeName);

  /**
   * Checks whether this element has a attribute with the given namespace and name.
   *
   * @param namespace the namespace of the attribute
   * @param attributeName the name of the attribute
   * @return true if the element has an attribute with this name under given namespace, false otherwise
   * @throws IllegalArgumentException if the attributeName is null
   */
  public abstract boolean hasAttrNs(String namespace, String attributeName);

  /**
   * Returns the wrapped attribute for the given namespace and name.
   *
   * @param namespace the namespace of the attribute
   * @param attributeName the name of the attribute
   * @return the wrapped {@link SpinXmlAttribute attribute}
   * @throws IllegalArgumentException if attributeName or value is null
   * @throws SpinXmlElementImplementationException if the attribute cannot be set in the underlying implementation
   */
  public abstract SpinXmlAttribute attrNs(String namespace, String attributeName);

  /**
   * Sets the attribute value in the given namespace.
   *
   * @param namespace the namespace of the attribute
   * @param attributeName the name of the attribute
   * @param value the value to set
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if attributeName or value is null
   * @throws SpinXmlElementImplementationException if the attribute cannot be set in the underlying implementation
   */
  public abstract SpinXmlElement attrNs(String namespace, String attributeName, String value);

  /**
   * Removes the attribute under the given namespace.
   *
   * @param namespace the namespace of the attribute
   * @param attributeName the name of the attribute
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the attributeName is null
   */
  public abstract SpinXmlElement removeAttrNs(String namespace, String attributeName);

  /**
   * Returns all wrapped attributes of this element.
   *
   * @return the wrapped attributes or an empty list of no attributes are found
   */
  public abstract SpinList<SpinXmlAttribute> attrs();

  /**
   * Returns all wrapped attributes for the given namespace.
   *
   * @param namespace the namespace of the attributes
   * @return the wrapped attributes or an empty list of no attributes are found
   */
  public abstract SpinList<SpinXmlAttribute> attrs(String namespace);

  /**
   * Returns all names of the attributes of this element.
   *
   * @return the names of the attributes
   */
  public abstract List<String> attrNames();

  /**
   * Returns all names of the attributes in the given namespace.
   *
   * @return the names of the attributes
   */
  public abstract List<String> attrNames(String namespace);

  /**
   * Returns the text content of an element.
   *
   * @return the text content or an empty string if non exists
   */
  public abstract String textContent();

  /**
   * Sets the text content of an element.
   * @param textContent the text content to set
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the textContent is null
   */
  public abstract SpinXmlElement textContent(String textContent);

  /**
   * Returns a single wrapped child element for the given name
   * in the local namespace of this element.
   *
   * @param elementName the element name
   * @return the wrapped child {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the elementName is null
   * @throws SpinXmlElementException if none or more than one child element is found
   */
  public abstract SpinXmlElement childElement(String elementName);

  /**
   * Returns a single wrapped child {@link SpinXmlElement element} for the given namespace
   * and name.
   *
   * @param namespace the namespace of the element
   * @param elementName the element name
   * @return the wrapped child {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the elementName is null
   * @throws SpinXmlElementException if none or more than one child element is found
   */
  public abstract SpinXmlElement childElement(String namespace, String elementName);

  /**
   * Returns all child elements of this {@link SpinXmlElement elements}.
   *
   * @return list of wrapped child {@link SpinXmlElement elements}
   */
  public abstract SpinList<SpinXmlElement> childElements();

  /**
   * Returns all child {@link SpinXmlElement elements} with a given name in the local namespace
   * of this element.
   *
   * @param elementName the element name
   * @return a collection of wrapped {@link SpinXmlElement elements}
   * @throws IllegalArgumentException if the element name is null
   * @throws SpinXmlElementException if no child element was found
   */
  public abstract SpinList<SpinXmlElement> childElements(String elementName);

  /**
   * Returns all child {@link SpinXmlElement elements} with a given namespace and name.
   *
   * @param namespace the namespace of the element
   * @param elementName the element name
   * @return a collection of wrapped {@link SpinXmlElement elements}
   * @throws IllegalArgumentException if the element name is null
   * @throws SpinXmlElementException if no child element was found
   */
  public abstract SpinList<SpinXmlElement> childElements(String namespace, String elementName);

  /**
   * Appends child elements to this {@link SpinXmlElement element}.
   *
   * @param childElements the child elements to append
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the childElements is null or one of them
   * @throws SpinXmlElementImplementationException if a child element cannot be appended in the underlying implementation
   */
  public abstract SpinXmlElement append(SpinXmlElement... childElements);

  /**
   * Appends child elements to this {@link SpinXmlElement element}.
   *
   * @param childElements the child elements to append
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the childElements is null or one of them
   * @throws SpinXmlElementImplementationException if a child element cannot be appended in the underlying implementation
   */
  public abstract SpinXmlElement append(Collection<SpinXmlElement> childElements);

  /**
   * Appends a child element to this element before the existing child element.
   *
   * @param childElement the child element to append
   * @param existingChildElement the child element to append before
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the child element or existing child element is null
   * @throws SpinXmlElementException if the existing child element is not a child of this element
   * @throws SpinXmlElementImplementationException if the new child element cannot be inserted in the underlying implementation
   */
  public abstract SpinXmlElement appendBefore(SpinXmlElement childElement, SpinXmlElement existingChildElement);

  /**
   * Appends a child element to this {@link SpinXmlElement element} after the existing child {@link SpinXmlElement element}.
   *
   * @param childElement the child element to append
   * @param existingChildElement the child element to append after
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the child element or existing child element is null
   * @throws SpinXmlElementException if the existing child element is not a child of this element
   * @throws SpinXmlElementImplementationException if the new child element cannot be inserted in the underlying implementation
   */
  public abstract SpinXmlElement appendAfter(SpinXmlElement childElement, SpinXmlElement existingChildElement);

  /**
   * Removes all child elements from this element.
   *
   * @param childElements the child elements to remove
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if child elements is null or any of them
   * @throws SpinXmlElementException if one of the child elements does not exist
   * @throws SpinXmlElementImplementationException if the child element cannot be removed in the underlying implementation
   */
  public abstract SpinXmlElement remove(SpinXmlElement... childElements);

  /**
   * Removes all child elements from this element.
   *
   * @param childElements the child elements to remove
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if child elements is null or any of them
   * @throws SpinXmlElementException if one of the child elements does not exist
   * @throws SpinXmlElementImplementationException if the child element cannot be removed in the underlying implementation
   */
  public abstract SpinXmlElement remove(Collection<SpinXmlElement> childElements);

  /**
   * Replaces this element by an new one.
   *
   * @param newChildElement the new element
   * @return the new wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if the new element is null or has the wrong type
   * @throws SpinXmlElementException if this element has no parent element
   * @throws SpinXmlElementImplementationException if the element cannot be replaced in the underlying implementation
   */
  public abstract SpinXmlElement replace(SpinXmlElement newChildElement);

  /**
   * Replaces an existing child element with a new one.
   *
   * @param existingChildElement the existing child element to replace
   * @param newChildElement the new child element
   * @return the wrapped {@link SpinXmlElement element}
   * @throws IllegalArgumentException if any of the child elements is null
   * @throws SpinXmlElementException if the existing element is not a child element of this
   * @throws SpinXmlElementImplementationException if the child cannot be replaced in the underlying implementation
   */
  public abstract SpinXmlElement replaceChild(SpinXmlElement existingChildElement, SpinXmlElement newChildElement);

  /**
   * Creates a XPath query on this element.
   *
   * @param expression the XPath expression
   * @return the XPath query
   */
  public abstract SpinXPathQuery xPath(String expression);

  /**
   * Returns the wrapped XML element as string representation.
   *
   * @return the string representation
   * @throws SpinXmlElementException if the element cannot be transformed or no new transformer can be created
   */
  public abstract String toString();

  /**
   * Writes the wrapped XML element to a existing writer.
   *
   * @param writer the writer to write to
   * @throws SpinXmlElementException if the element cannot be transformed or no new transformer can be created
   */
  public abstract void writeToWriter(Writer writer);
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { YourProfileComponent } from './your-profile.component';

describe('YourProfileComponent', () => {
  let component: YourProfileComponent;
  let fixture: ComponentFixture<YourProfileComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ YourProfileComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(YourProfileComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
package controllers

import (
	"net/http"
	"encoding/json"
	"github.com/vonji/vonji-api/models"
	"github.com/vonji/vonji-api/utils"
	"github.com/vonji/vonji-api/services"
	"github.com/gorilla/mux"
)

type ResponseController struct {
	APIBaseController
}

func (ctrl ResponseController) GetAll() (interface{}, *utils.HttpError) {
	return services.Response.GetAll(), nil
}

func (ctrl ResponseController) GetOne(id uint) (interface{}, *utils.HttpError) {
	return services.Response.GetOne(id), nil
}

func (ctrl ResponseController) GetOneWhere(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	response := models.Response{}

	if err := json.Unmarshal([]byte(mux.Vars(r)["condition"]), &response); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	return *services.Response.GetOneWhere(&response), nil
}

func (ctrl ResponseController) GetAllWhere(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	response := models.Response{}

	if err := json.Unmarshal([]byte(mux.Vars(r)["condition"]), &response); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	return services.Response.GetAllWhere(&response), nil
}

func (ctrl ResponseController) Create(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	response := models.Response{}

	if err := json.NewDecoder(r.Body).Decode(&response); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	return services.Response.Create(&response), nil
}

func (ctrl ResponseController) Update(w http.ResponseWriter, r *http.Request) *utils.HttpError{
	response := models.Response{}

	if err := json.NewDecoder(r.Body).Decode(&response); err != nil {
		return utils.BadRequest(err.Error())
	}

	services.Response.Update(&response)

	return nil
}

func (ctrl ResponseController) Delete(id uint) *utils.HttpError {
	services.Response.Delete(id)
	return nil
}


text:
package com.finder.reorgnaize_data.encapsulate_filed;

/**
 * Created by longhuai.hlh on 2016/11/24.
 */
public class IntRange {
    private int low;
    private int high;

    public IntRange(int low, int high) {
        this.low = low;
        this.high = high;
    }

    public boolean includes(int arg){
        return arg >= this.getLow() && arg <= this.getHigh();
    }

    public void grow(int factor){
        this.setHigh(this.getHigh() * factor);
    }

    public int getLow() {
        return low;
    }

    public void setLow(int low) {
        this.low = low;
    }

    public int getHigh() {
        return high;
    }

    public void setHigh(int high) {
        this.high = high;
    }
}


text:
namespace llvm {
  class PassRegistry;
}

using namespace llvm;
using namespace llvm::objcarc;

/// \brief A handy option to enable/disable all ARC Optimizations.
bool llvm::objcarc::EnableARCOpts;
static cl::opt<bool, true>
EnableARCOptimizations("enable-objc-arc-opts",
                       cl::desc("enable/disable all ARC Optimizations"),
                       cl::location(EnableARCOpts),
                       cl::init(true));

/// initializeObjCARCOptsPasses - Initialize all passes linked into the
/// ObjCARCOpts library.
void llvm::initializeObjCARCOpts(PassRegistry &Registry) {
  initializeObjCARCAliasAnalysisPass(Registry);
  initializeObjCARCAPElimPass(Registry);
  initializeObjCARCExpandPass(Registry);
  initializeObjCARCContractPass(Registry);
  initializeObjCARCOptPass(Registry);
}

void LLVMInitializeObjCARCOpts(LLVMPassRegistryRef R) {
  initializeObjCARCOpts(*unwrap(R));
}


text:
package org.syphr.mythtv.control;

import java.io.IOException;
import java.net.URL;

import junit.framework.Assert;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.syphr.mythtv.commons.exception.CommandException;
import org.syphr.mythtv.commons.exception.ProtocolException;
import org.syphr.mythtv.commons.exception.ProtocolException.Direction;
import org.syphr.mythtv.control.test.Utils;
import org.syphr.mythtv.test.Settings;
import org.syphr.mythtv.types.FrontendLocation;
import org.syphr.prom.PropertiesManager;

public class ControlPlayMusicIT
{
    public static final Logger LOGGER = LoggerFactory.getLogger(ControlPlayMusicIT.class);

    private static PropertiesManager<Settings> settings;
    private static Control control;

    @BeforeClass
    public static void setUpBeforeClass() throws IOException
    {
        settings = Settings.createSettings();
        control = Utils.connect(settings);

        control.jump(FrontendLocation.PLAY_MUSIC);
        org.syphr.mythtv.test.Utils.waitSeconds(10, "start music player");

        if (!FrontendLocation.PLAY_MUSIC.equals(control.queryLocation()))
        {
            Assert.fail("Frontend failed to start music player");
            return;
        }

        control.playMusicPlay();
    }

    @AfterClass
    public static void tearDownAfterClass() throws IOException, CommandException
    {
        control.playMusicStop();
        org.syphr.mythtv.test.Utils.waitSeconds(5, "stop playing music");

        control.jump(FrontendLocation.MAIN_MENU);
        control.exit();
    }

    @Test
    public void testPlayMusicPause() throws IOException, CommandException
    {
        control.playMusicPause();
        org.syphr.mythtv.test.Utils.waitSeconds(2, "pause music");
    }

    @Test
    public void testPlayMusicPlay() throws IOException, CommandException
    {
        control.playMusicPlay();
        org.syphr.mythtv.test.Utils.waitSeconds(5, "play music");
    }

    @Test
    public void testPlayMusicSetVolume() throws IOException, CommandException
    {
        control.playMusicSetVolume(50);
        org.syphr.mythtv.test.Utils.waitSeconds(2, "set music volume to 50%");
    }

    @Test(expected = ProtocolException.class)
    public void testPlayVolumeTooLow() throws IOException, CommandException
    {
        if (isVersionBefore(ControlVersion._0_25))
        {
            throw new ProtocolException("Inject protocol exception for unsupported functionality test",
                                        Direction.SEND);
        }

        control.playMusicSetVolume(-1);
        org.syphr.mythtv.test.Utils.waitSeconds(2, "set music volume to -1%");
    }

    @Test(expected = ProtocolException.class)
    public void testPlayVolumeTooHigh() throws IOException, CommandException
    {
        if (isVersionBefore(ControlVersion._0_25))
        {
            throw new ProtocolException("Inject protocol exception for unsupported functionality test",
                                        Direction.SEND);
        }

        control.playMusicSetVolume(101);
        org.syphr.mythtv.test.Utils.waitSeconds(2, "set music volume to 101%");
    }

    @Test
    public void testPlayMusicGetVolume() throws IOException, CommandException
    {
        LOGGER.debug("Volume: {}", control.playMusicGetVolume());
    }

    @Test
    public void testPlayMusicGetMeta() throws IOException, CommandException
    {
        LOGGER.debug("Metadata: {}", control.playMusicGetMeta());
    }

    @Test
    public void testPlayMusicFile() throws IOException, CommandException
    {
        control.playMusicFile("/var/lib/mythtv/music/test with spaces.mp3");
        org.syphr.mythtv.test.Utils.waitSeconds(5, "play music file");
    }

    @Test
    public void testPlayMusicTrack() throws IOException, CommandException
    {
        control.playMusicTrack(1);
        org.syphr.mythtv.test.Utils.waitSeconds(5, "play music track");
    }

    @Test
    public void testPlayMusicUrl() throws IOException, CommandException
    {
        control.playMusicUrl(new URL("http://scfire-mtc-aa05.stream.aol.com:80/stream/1010"));
        org.syphr.mythtv.test.Utils.waitSeconds(5, "play music url");
    }

    private boolean isVersionBefore(ControlVersion version)
    {
        return settings.getEnumProperty(Settings.FRONTEND_CONTROL_VERSION,
                                        ControlVersion.class).compareTo(version) < 0;
    }
}


text:
    <meta content="HTML Tidy for HTML5 for Linux version 5.2.0" name="generator"/>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
    <meta content="FreeRTOS is a completely free professional grade, portable, open source, mini Real Time kernel for use in small embedded systems. This page describes the xTimerIsTimerActive() FreeRTOS API function which is part of the FreeRTOS software timer functionality." name="description"/>
    <meta content="timers, software timers, FreeRTOS API, RTOS API, FreeRTOS timer, RTOS timer, timer API, xTimerIsTimerActive, ARM7, ARM9, Cortex-M3, RX600, RX62N, 8051, 8052, Free RTOS, royalty free, RTOS, free, RTOS free, open source, real time, embedded, FreeRTOS, source code, AVR, GNU, PIC, PIC18, development tools" name="keywords"/>
    <title>FreeRTOS - Quality, small footprint, open source software
      for microcontrollers - FreeRTOS xTimerIsTimerActive() API
      function description</title>

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

    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>

    <link href="code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

Quality RTOS & Embedded
                                      Software

                          Hint: Use the tree menu
                            to navigate groups of related pages

xTimerIsTimerActive

                      [Timer API]

                    timers.h

 BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer );

Queries a software timer to see if it is active or
                      dormant.

A timer will be dormant if:

It has been created but not started, or

It is an expired one-shot timer that has not
                        been restarted.

Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions
                      can all be used to transition a timer into the
                      active state.

Parameters:

                              xTimer

                              The timer being
                                queried.

Returns:

pdFALSE will be returned if the timer is
                        dormant. A value other than pdFALSE will be
                        returned if the timer is active.

                    Example usage:

 /* This function assumes xTimer has already
 been created. */
 void vAFunction( TimerHandle_t xTimer )
 {
     /* or more simply and equivalently
     "if( xTimerIsTimerActive( xTimer ) )" */
     if( xTimerIsTimerActive( xTimer ) != pdFALSE )
     {
         /* xTimer is active, do something. */
     }
     else
     {
         /* xTimer is not active, do something else. */
     }
 }

[
                      Back to the top ]    [ About FreeRTOS
                      ]    [ Sitemap
                      ]    [

                      Report an error on this page (with anti-spam) ]

Copyright (C) 2004-2010 Richard Barry. Copyright
                      (C) 2010-2016 Real Time Engineers Ltd.

                      Any and all data, files, source code, html
                      content and documentation included in the
                      FreeRTOSTM
                      distribution or available on this site are the
                      exclusive property of Real Time Engineers Ltd..
                      See the files license.txt (included in the
                      distribution) and this copyright notice for more information.
                      FreeRTOSTM and FreeRTOS.orgTM are trade marks of Real Time Engineers
                      Ltd.


text:
Exercise 37: Symbol Review¶

It's time to review the symbols and Ruby words you know, and to try to
pick up a few more for the next few lessons. What I've done here is
written out all the Ruby symbols and keywords that are important to
know.

In this lesson take each keyword, and first try to write out what it
does from memory. Next, search online for it and see what it really
does. It may be hard because some of these are going to be impossible to
search for, but keep trying.

If you get one of these wrong from memory, write up an index card with
the correct definition and try to "correct" your memory. If you just
didn't know about it, write it down, and save it for later.

Finally, use each of these in a small Ruby program, or as many as you
can get done. The key here is to find out what the symbol does, make
sure you got it right, correct it if you do not, then use it to lock it
in.

Keywords¶

<tt class="docutils literal">alias</tt>

<tt class="docutils literal">and</tt>

<tt class="docutils literal">BEGIN</tt>

<tt class="docutils literal">begin</tt>

<tt class="docutils literal">break</tt>

<tt class="docutils literal">case</tt>

<tt class="docutils literal">class</tt>

<tt class="docutils literal">def</tt>

<tt class="docutils literal">defined?</tt>

<tt class="docutils literal">do</tt>

<tt class="docutils literal">else</tt>

<tt class="docutils literal">elsif</tt>

<tt class="docutils literal">END</tt>

<tt class="docutils literal">end</tt>

<tt class="docutils literal">ensure</tt>

<tt class="docutils literal">false</tt>

<tt class="docutils literal">for</tt>

<tt class="docutils literal">if</tt>

<tt class="docutils literal">in</tt>

<tt class="docutils literal">module</tt>

<tt class="docutils literal">next</tt>

<tt class="docutils literal">nil</tt>

<tt class="docutils literal">not</tt>

<tt class="docutils literal">or</tt>

<tt class="docutils literal">redo</tt>

<tt class="docutils literal">rescue</tt>

<tt class="docutils literal">retry</tt>

<tt class="docutils literal">return</tt>

<tt class="docutils literal">self</tt>

<tt class="docutils literal">super</tt>

<tt class="docutils literal">then</tt>

<tt class="docutils literal">true</tt>

<tt class="docutils literal">undef</tt>

<tt class="docutils literal">unless</tt>

<tt class="docutils literal">until</tt>

<tt class="docutils literal">when</tt>

<tt class="docutils literal">while</tt>

<tt class="docutils literal">yield</tt>

Data Types¶

For data types, write out what makes up each one. For example, with
strings write out how you create a string. For numbers write out a few
numbers.

true

false

nil

<tt class="docutils literal">constants</tt>

<tt class="docutils literal">strings</tt>

<tt class="docutils literal">numbers</tt>

<tt class="docutils literal">ranges</tt>

<tt class="docutils literal">arrays</tt>

<tt class="docutils literal">hashes</tt>

String Escapes Sequences For string escape sequences, use them in
strings to make sure they do what you think they do.

<tt class="docutils literal">\\</tt>

<tt class="docutils literal">\'</tt>

<tt class="docutils literal">\"</tt>

<tt class="docutils literal">\a</tt>

<tt class="docutils literal">\b</tt>

<tt class="docutils literal">\f</tt>

<tt class="docutils literal">\n</tt>

<tt class="docutils literal">\r</tt>

<tt class="docutils literal">\t</tt>

<tt class="docutils literal">\v</tt>

Operators Some of these may be unfamiliar to you, but look them up
anyway. Find out what they do, and if you still can't figure it out,
save it for later.

<tt class="docutils literal">::</tt>

<tt class="docutils literal">[]</tt>

<tt class="docutils literal">**</tt>

<tt class="docutils literal">-(unary)</tt>

<tt class="docutils literal">+(unary)</tt>

<tt class="docutils literal">!</tt>

<tt class="docutils literal">~</tt>

<tt class="docutils literal">*</tt>

<tt class="docutils literal">/</tt>

<tt class="docutils literal">%</tt>

<tt class="docutils literal">+</tt>

<tt class="docutils literal">-</tt>

<tt class="docutils literal"><<</tt>

<tt class="docutils literal">>></tt>

<tt class="docutils literal">&</tt>

<tt class="docutils literal">|</tt>

<tt class="docutils literal">></tt>

<tt class="docutils literal">>=</tt>

<tt class="docutils literal"><</tt>

<tt class="docutils literal"><=</tt>

<tt class="docutils literal"><=></tt>

<tt class="docutils literal">==</tt>

<tt class="docutils literal">===</tt>

<tt class="docutils literal">!=</tt>

<tt class="docutils literal">=~</tt>

<tt class="docutils literal">!~</tt>

<tt class="docutils literal">&&</tt>

<tt class="docutils literal">||</tt>

<tt class="docutils literal">..</tt>

<tt class="docutils literal">...</tt>

Spend about a week on this, but if you finish faster that's great. The
point is to try to get coverage on all these symbols and make sure they
are locked in your head. What's also important is to find out what you
do not know so you can fix it later.


text:
package flowless;

/**
 * Supplied by Flow to the Listener, which is responsible for calling onComplete().
 */
public interface TraversalCallback {
    /**
     * Must be called exactly once to indicate that the corresponding transition has completed.
     *
     * If not called, the history will not be updated and further calls to Flow will not execute.
     * Calling more than once will result in an exception.
     */
    void onTraversalCompleted();
}


text:
package org.jboss.resteasy.plugins.providers;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class FileRangeException extends WebApplicationException
{
   public FileRangeException(MediaType mediaType, File file, long begin, long end)
   {
      super(Response.status(206).entity(new FileRange(file, begin, end)).type(mediaType).build());
   }
}


text:
{{ title('Sign in') }}
{{ lib.alert(true, "Please click the link in your e-mail to sign in.") }}


text:
void SimpleCreateCanvas(char* data);
void SimpleKillCanvas(void);

void SimpleUpdateSize(cdCanvas* cnv);
void SimpleFlush(void);

int SimplePlayClipboard(void);
int SimplePlayCGMBin(void);
int SimplePlayCGMText(void);
int SimplePlayMetafile(void);
int SimplePlayWMF(void);
int SimplePlayEMF(void);

int SimpleDrawDebug(void);
int SimpleDrawWindow(void);
int SimpleDrawCGMText(void);
int SimpleDrawCGMBin(void);
int SimpleDrawDXF(void);
int SimpleDrawDGN(void);
int SimpleDrawEMF(void);
int SimpleDrawMetafile(void);
int SimpleDrawPDF(void);
int SimpleDrawPS(void);
int SimpleDrawEPS(void);
int SimpleDrawSVG(void);
int SimpleDrawWMF(void);
int SimpleDrawPrint(void);
int SimpleDrawPrintDialog(void);
int SimpleDrawClipboardBitmap(void);
int SimpleDrawClipboardMetafile(void);
int SimpleDrawClipboardEMF(void);
int SimpleDrawImage(void);
int SimpleDrawImageRGB(void);
int SimpleDrawSimulate(void);
int SimpleDrawGL(void);

int SimpleNotXor(void);
int SimpleXor(void);
int SimpleReplace(void);
int SimpleClippingOff(void);
int SimpleClippingArea(void);
int SimpleClippingPolygon(void);
int SimpleClippingRegion(void);

int SimpleTransform(void);
int SimpleContextPlus(void);
int SimpleAll(void);
int SimpleTextAlign(void);
int SimpleTextFonts(void);
int SimpleTest(void);
int SimpleRepaint(void);

#endif


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Orleans.CodeGeneration;
using UnitTests.GrainInterfaces;

#if !EXCLUDE_ASSEMBLYINFO // TODO remove after source tree merge

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TestGrainInterfaces")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("15F8D1EB-6A01-408B-81B0-6CF5FD0D190A")]

#endif

[assembly: InternalsVisibleTo("TesterInternal")]
[assembly: InternalsVisibleTo("DefaultCluster.Tests")]
[assembly: InternalsVisibleTo("NonSilo.Tests")]
[assembly: GenerateSerializer(typeof(SomeTypeDerivedFromTypeUsedInGrainInterface))]


text:
namespace live2d
{
	class IBaseData ;

	class IBaseContext : public live2d::LDObject
	{
	public:
		IBaseContext(IBaseData* src) ;
		virtual ~IBaseContext(){}

		void* getSrcPtr(){ return this->srcPtr ; }

		void setPartsIndex( int p ){ this->partsIndex = p ; }
		int getPartsIndex() { return this->partsIndex ; }

		bool isOutsideParam() {	return this->outsideParam;	}
		void setOutsideParam( bool outsideParam ) {	this->outsideParam = outsideParam ;	}

		bool isAvailable()
		{
			return available && ! outsideParam ;
		}

		void setAvailable(bool available)
		{
			this->available = available;
		}

		float getTotalScale()
		{
			return totalScale ;
		}

		void setTotalScale_notForClient(float totalScale)
		{
			this->totalScale = totalScale ;
		}

		float getInterpolatedOpacity(){	return interpolatedOpacity ;}

		void setInterpolatedOpacity(float interpolatedOpacity){this->interpolatedOpacity = interpolatedOpacity ;}

		float getTotalOpacity(){return totalOpacity ;}

		void setTotalOpacity(float totalOpacity){this->totalOpacity = totalOpacity ;}

	private:
		IBaseData* srcPtr ;
		int partsIndex ;

		bool outsideParam ;
		bool available ;

	protected:

		float		totalScale;

		float		interpolatedOpacity;
		float		totalOpacity;

	};
}
//------------ LIVE2D NAMESPACE ------------

#endif // __SKIP_DOC__

#endif // __IBASE_CONTEXT__


text:
namespace gtfo
{
    namespace _tt
    {
        /// defines static member constant value of type bool
        /// which is true if and only if
        /// Function is a type of function or function object
        /// lvalue of which can be invoked without any arguments
        template<typename Function>
        struct is_invokable_fun0
        {
            template<typename Fun>
            static yes_type test(typename remove_reference
                                 <
                                     decltype( declval<Fun &>()() )
                                 >::type *);

            template<typename Fun>
            static no_type test(...);

            static constexpr bool value = sizeof(test<Function>(nullptr)) == sizeof(yes_type);
        };
    }
}

#endif // GTFO_FILE_INCLUDED_TYPE_TRAITS_IS_INVOKABLE_FUN0_HPP


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace LightBDD.Formatting.Helpers
{
    /// <summary>
    /// Extension methods for formatting TimeSpan values.
    /// </summary>
    [DebuggerStepThrough]
    public static class TimeFormatter
    {
        private static readonly Tuple<string, int, Func<TimeSpan, int>>[] _formatters = {
            new Tuple<string, int, Func<TimeSpan, int>>("d", 1, ts => ts.Days),
            new Tuple<string, int, Func<TimeSpan, int>>("h", 2, ts => ts.Hours),
            new Tuple<string, int, Func<TimeSpan, int>>("m", 2, ts => ts.Minutes),
            new Tuple<string, int, Func<TimeSpan, int>>("s", 2, ts => ts.Seconds),
            new Tuple<string, int, Func<TimeSpan, int>>("ms", 3, ts => ts.Milliseconds)
        };
        /// <summary>
        /// Formats given value if provided or returns empty string.
        ///
        /// This method returns up to 2 most meaningful time components of given time, to make it most readable.
        /// Maximal supported time component is 'day', while the minimal is 'millisecond'.
        /// TimeSpan value being less than 1ms but larger than 0 would be presented as <1ms.
        ///
        /// Example values:
        /// <list type="bullet">
        /// <item><description>1d 12h</description></item>
        /// <item><description>5h</description></item>
        /// <item><description>5m 02s</description></item>
        /// <item><description>2s 527ms</description></item>
        /// <item><description><1ms</description></item>
        /// <item><description>0ms</description></item>
        /// </list>
        /// </summary>
        public static string FormatPretty(this TimeSpan? ts)
        {
            return ts.HasValue ? ts.Value.FormatPretty() : string.Empty;
        }
        /// <summary>
        /// This method returns up to 2 most meaningful time components of given time, to make it most readable.
        /// Maximal supported time component is 'day', while the minimal is 'millisecond'.
        /// TimeSpan value being less than 1ms but larger than 0 would be presented as <1ms.
        ///
        /// Example values:
        /// <list type="bullet">
        /// <item><description>1d 12h</description></item>
        /// <item><description>5h</description></item>
        /// <item><description>5m 02s</description></item>
        /// <item><description>2s 527ms</description></item>
        /// <item><description><1ms</description></item>
        /// <item><description>0ms</description></item>
        /// </list>
        /// </summary>
        public static string FormatPretty(this TimeSpan ts)
        {
            if (ts.Ticks == 0)
                return "0ms";

            var sb = new StringBuilder();
            var position = FindFirst(ts);

            foreach (var fmt in _formatters.Skip(position).Take(2).Where(f => f.Item3(ts) > 0))
                FormatPretty(sb, ts, fmt);

            if (sb.Length == 0)
                sb.Append("<1ms");

            return sb.ToString();
        }

        private static int FindFirst(TimeSpan ts)
        {
            int i;
            for (i = 0; i < _formatters.Length; i++)
            {
                if (_formatters[i].Item3(ts) > 0)
                    break;
            }
            return i;
        }

        private static void FormatPretty(StringBuilder sb, TimeSpan ts, Tuple<string, int, Func<TimeSpan, int>> formatter)
        {
            var padding = formatter.Item2;
            if (sb.Length == 0)
                padding = 1;
            else
                sb.Append(" ");
            sb.Append(formatter.Item3(ts).ToString("D" + padding)).Append(formatter.Item1);
        }
    }
}


text:
// Copyright (c) 2004, Open Cloud Limited.

package com.amazon.redshift.core.v3;

import com.amazon.redshift.core.Field;
import com.amazon.redshift.core.NativeQuery;
import com.amazon.redshift.core.Oid;
import com.amazon.redshift.core.ParameterList;
import com.amazon.redshift.core.Query;
import com.amazon.redshift.core.SqlCommand;
import com.amazon.redshift.core.Utils;
import com.amazon.redshift.jdbc.RedshiftResultSet;
import com.amazon.redshift.logger.LogLevel;
import com.amazon.redshift.logger.RedshiftLogger;

import java.lang.ref.PhantomReference;
import java.util.BitSet;
import java.util.Map;

/**
 * V3 Query implementation for a single-statement query. This also holds the state of any associated
 * server-side named statement. We use a PhantomReference managed by the QueryExecutor to handle
 * statement cleanup.
 *
 * @author Oliver Jowett (oliver@opencloud.com)
 */
class SimpleQuery implements Query {
  protected RedshiftLogger logger;

  SimpleQuery(SimpleQuery src, RedshiftLogger logger) {
    this(src.nativeQuery, src.transferModeRegistry, src.sanitiserDisabled, logger);
  }

  SimpleQuery(NativeQuery query, TypeTransferModeRegistry transferModeRegistry,
      boolean sanitiserDisabled, RedshiftLogger logger) {
  	this.logger = logger;
    this.nativeQuery = query;
    this.transferModeRegistry = transferModeRegistry;
    this.sanitiserDisabled = sanitiserDisabled;
  }

  public ParameterList createParameterList() {
    if (nativeQuery.bindPositions.length == 0) {
      return NO_PARAMETERS;
    }

    return new SimpleParameterList(getBindCount(), transferModeRegistry, nativeQuery.redshiftParamMarkers);
  }

  public String toString(ParameterList parameters) {
    return nativeQuery.toString(parameters);
  }

  public String toString() {
    return toString(null);
  }

  public void close() {
    unprepare();
  }

  public SimpleQuery[] getSubqueries() {
    return null;
  }

  /**
   *
Return maximum size in bytes that each result row from this query may return. Mainly used for
   * batches that return results.

   *
   *
Results are cached until/unless the query is re-described.

   *
   * @return Max size of result data in bytes according to returned fields, 0 if no results, -1 if
   *         result is unbounded.
   * @throws IllegalStateException if the query is not described
   */
  public int getMaxResultRowSize() {
    if (cachedMaxResultRowSize != null) {
      return cachedMaxResultRowSize;
    }
    if (!this.statementDescribed) {
      throw new IllegalStateException(
          "Cannot estimate result row size on a statement that is not described");
    }
    int maxResultRowSize = 0;
    if (fields != null) {
      for (Field f : fields) {
        final int fieldLength = f.getLength();
        if (fieldLength < 1 || fieldLength >= 65535) {
          /*
           * Field length unknown or large; we can't make any safe estimates about the result size,
           * so we have to fall back to sending queries individually.
           */
          maxResultRowSize = -1;
          break;
        }
        maxResultRowSize += fieldLength;
      }
    }
    cachedMaxResultRowSize = maxResultRowSize;
    return maxResultRowSize;
  }

  //
  // Implementation guts
  //

  public String getNativeSql() {
    return nativeQuery.nativeSql;
  }

  void setStatementName(String statementName, short deallocateEpoch) {
    assert statementName != null : "statement name should not be null";
    this.statementName = statementName;
    this.encodedStatementName = Utils.encodeUTF8(statementName);
    this.deallocateEpoch = deallocateEpoch;
  }

  void setPrepareTypes(int[] paramTypes) {
    // Remember which parameters were unspecified since the parameters will be overridden later by
    // ParameterDescription message
    for (int i = 0; i < paramTypes.length; i++) {
      int paramType = paramTypes[i];
      if (paramType == Oid.UNSPECIFIED) {
        if (this.unspecifiedParams == null) {
          this.unspecifiedParams = new BitSet();
        }
        this.unspecifiedParams.set(i);
      }
    }

    // paramTypes is changed by "describe statement" response, so we clone the array
    // However, we can reuse array if there is one
    if (this.preparedTypes == null) {
      this.preparedTypes = paramTypes.clone();
      return;
    }
    System.arraycopy(paramTypes, 0, this.preparedTypes, 0, paramTypes.length);
  }

  int[] getPrepareTypes() {
    return preparedTypes;
  }

  String getStatementName() {
    return statementName;
  }

  boolean isPreparedFor(int[] paramTypes, short deallocateEpoch) {
    if (statementName == null || preparedTypes == null) {
      return false; // Not prepared.
    }
    if (this.deallocateEpoch != deallocateEpoch) {
      return false;
    }

    assert paramTypes.length == preparedTypes.length
        : String.format("paramTypes:%1$d preparedTypes:%2$d", paramTypes.length,
        preparedTypes.length);
    // Check for compatible types.
    BitSet unspecified = this.unspecifiedParams;
    for (int i = 0; i < paramTypes.length; ++i) {
      int paramType = paramTypes[i];
      // Either paramType should match prepared type
      // Or paramType==UNSPECIFIED and the prepare type was UNSPECIFIED

      // Note: preparedTypes can be updated by "statement describe"
      // 1) parse(name="S_01", sql="select ?::timestamp", types={UNSPECIFIED})
      // 2) statement describe: bind 1 type is TIMESTAMP
      // 3) SimpleQuery.preparedTypes is updated to TIMESTAMP
      // ...
      // 4.1) bind(name="S_01", ..., types={TIMESTAMP}) -> OK (since preparedTypes is equal to TIMESTAMP)
      // 4.2) bind(name="S_01", ..., types={UNSPECIFIED}) -> OK (since the query was initially parsed with UNSPECIFIED)
      // 4.3) bind(name="S_01", ..., types={DATE}) -> KO, unprepare and parse required

      int preparedType = preparedTypes[i];
      if (paramType != preparedType
          && (paramType != Oid.UNSPECIFIED
          || unspecified == null
          || !unspecified.get(i))) {
        if (RedshiftLogger.isEnable()) {
          logger.log(LogLevel.DEBUG,
              "Statement {0} does not match new parameter types. Will have to un-prepare it and parse once again."
                  + " To avoid performance issues, use the same data type for the same bind position. Bind index (1-based) is {1},"
                  + " preparedType was {2} (after describe {3}), current bind type is {4}",
              new Object[]{statementName, i + 1,
                  Oid.toString(unspecified != null && unspecified.get(i) ? 0 : preparedType),
                  Oid.toString(preparedType), Oid.toString(paramType)});
        }
        return false;
      }
    }

    return true;
  }

  boolean hasUnresolvedTypes() {
    if (preparedTypes == null) {
      return true;
    }

    return this.unspecifiedParams != null && !this.unspecifiedParams.isEmpty();
  }

  byte[] getEncodedStatementName() {
    return encodedStatementName;
  }

  /**
   * Sets the fields that this query will return.
   *
   * @param fields The fields that this query will return.
   */
  void setFields(Field[] fields) {
    this.fields = fields;
    this.resultSetColumnNameIndexMap = null;
    this.cachedMaxResultRowSize = null;
    this.needUpdateFieldFormats = fields != null;
    this.hasBinaryFields = false; // just in case
  }

  /**
   * Returns the fields that this query will return. If the result set fields are not known returns
   * null.
   *
   * @return the fields that this query will return.
   */
  Field[] getFields() {
    return fields;
  }

  /**
   * Returns true if current query needs field formats be adjusted as per connection configuration.
   * Subsequent invocations would return {@code false}. The idea is to perform adjustments only
   * once, not for each
   * {@link QueryExecutorImpl#sendBind(SimpleQuery, SimpleParameterList, Portal, boolean)}.
   *
   * @return true if current query needs field formats be adjusted as per connection configuration
   */
  boolean needUpdateFieldFormats() {
    if (needUpdateFieldFormats) {
      needUpdateFieldFormats = false;
      return true;
    }
    return false;
  }

  public void resetNeedUpdateFieldFormats() {
    needUpdateFieldFormats = fields != null;
  }

  public boolean hasBinaryFields() {
    return hasBinaryFields;
  }

  public void setHasBinaryFields(boolean hasBinaryFields) {
    this.hasBinaryFields = hasBinaryFields;
  }

  // Have we sent a Describe Portal message for this query yet?
  boolean isPortalDescribed() {
    return portalDescribed;
  }

  void setPortalDescribed(boolean portalDescribed) {
    this.portalDescribed = portalDescribed;
    this.cachedMaxResultRowSize = null;
  }

  // Have we sent a Describe Statement message for this query yet?
  // Note that we might not have need to, so this may always be false.
  public boolean isStatementDescribed() {
    return statementDescribed;
  }

  void setStatementDescribed(boolean statementDescribed) {
    this.statementDescribed = statementDescribed;
    this.cachedMaxResultRowSize = null;
  }

  public boolean isEmpty() {
    return getNativeSql().isEmpty();
  }

  void setCleanupRef(PhantomReference<?> cleanupRef) {
    if (this.cleanupRef != null) {
      this.cleanupRef.clear();
      this.cleanupRef.enqueue();
    }
    this.cleanupRef = cleanupRef;
  }

  void unprepare() {
    if (cleanupRef != null) {
      cleanupRef.clear();
      cleanupRef.enqueue();
      cleanupRef = null;
    }
    if (this.unspecifiedParams != null) {
      this.unspecifiedParams.clear();
    }

    statementName = null;
    encodedStatementName = null;
    fields = null;
    this.resultSetColumnNameIndexMap = null;
    portalDescribed = false;
    statementDescribed = false;
    cachedMaxResultRowSize = null;
  }

  public int getBatchSize() {
    return 1;
  }

  NativeQuery getNativeQuery() {
    return nativeQuery;
  }

  public final int getBindCount() {
    return nativeQuery.bindPositions.length * getBatchSize();
  }

  private Map<String, Integer> resultSetColumnNameIndexMap;

  @Override
  public Map<String, Integer> getResultSetColumnNameIndexMap() {
    Map<String, Integer> columnPositions = this.resultSetColumnNameIndexMap;
    if (columnPositions == null && fields != null) {
      columnPositions =
          RedshiftResultSet.createColumnNameIndexMap(fields, sanitiserDisabled);
      if (statementName != null) {
        // Cache column positions for server-prepared statements only
        this.resultSetColumnNameIndexMap = columnPositions;
      }
    }
    return columnPositions;
  }

  @Override
  public SqlCommand getSqlCommand() {
    return nativeQuery.getCommand();
  }

  private final NativeQuery nativeQuery;

  private final TypeTransferModeRegistry transferModeRegistry;
  private String statementName;
  private byte[] encodedStatementName;
  /**
   * The stored fields from previous execution or describe of a prepared statement. Always null for
   * non-prepared statements.
   */
  private Field[] fields;
  private boolean needUpdateFieldFormats;
  private boolean hasBinaryFields;
  private boolean portalDescribed;
  private boolean statementDescribed;
  private final boolean sanitiserDisabled;
  private PhantomReference<?> cleanupRef;
  private int[] preparedTypes;
  private BitSet unspecifiedParams;
  private short deallocateEpoch;

  private Integer cachedMaxResultRowSize;

  static final SimpleParameterList NO_PARAMETERS = new SimpleParameterList(0, null);
}


text:
package squid
package anf

import ir._
import squid.anf.analysis.ControlFlowBase
import squid.anf.analysis.BinOpBase
import squid.anf.analysis.BlockHelpers
import squid.anf.transfo.LogicNormalizer
import squid.anf.transfo.StandardNormalizer
import squid.anf.transfo.LogicFlowNormalizer
import squid.ir.BottomUpTransformer
import squid.ir.FixPointRuleBasedTransformer
import squid.ir.StandardEffects
import squid.ir.TopDownTransformer
import squid.ir.FixPointTransformer
import utils._

class BooleanFlowTests extends MyFunSuite(SimpleANFTests.DSLWithEffects) {
  import DSL.Predef._
  import DSL.Quasicodes._

  object Opt extends DSL.SelfTransformer with StandardNormalizer with LogicNormalizer with TopDownTransformer with FixPointTransformer {
    override val MAX_TRANSFORM_ITERATIONS = 16
  }

  object Flow extends DSL.SelfTransformer with LogicFlowNormalizer

  test("Options Stuff") {

    val a = code{Option(42) orElse Option(666) orElse Some(0) orElse Some(1)} //and println

    val b = a transformWith Opt

    b eqt code[Option[Int]]{ // Notice that if type param is ommitted, we get a difft result type for the ITE, which makes the code not equivalent!!
      if ((42).==(null).&&((42).==(null).&&((666).==(null).`unary_!`).`unary_!`))
        scala.Some.apply[scala.Int](0)
      else
        if ((42).==(null))
          if ((666).==(null))
            scala.None
          else
            scala.Some.apply[scala.Int](666)
        else
          if ((42).==(null))
            scala.None
          else
            scala.Some.apply[scala.Int](42)
    }

    val c = b transformWith Flow

    val d = c transformWith Opt

    d eqt code[Option[Int]]{
      if ((42).==(null).&&((666).==(null)))
        scala.Some.apply[scala.Int](0) : Option[Int] // also needed, otherwise this ITE is inferred of type Some[Int]...
      else
        if ((42).==(null))
          scala.Some.apply[scala.Int](666) : Option[Int]
        else
          scala.Some.apply[scala.Int](42)
    }

  }

}


text:
namespace Miruken.Http
{
    using System;

    public class ExceptionData
    {
        public ExceptionData()
        {
        }

        public ExceptionData(Exception exception)
        {
            if (exception == null)
                throw new ArgumentNullException(nameof(exception));

            ExceptionType = exception.GetType().AssemblyQualifiedName;
            HelpLink      = exception.HelpLink;
            Message       = exception.Message;
            Source        = exception.Source;
        }

        public string ExceptionType { get; set; }
        public string HelpLink      { get; set; }
        public string Message       { get; set; }
        public string Source        { get; set; }
    }
}


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

<TITLE>
W-Index
</TITLE>

<META NAME="date" CONTENT="2013-05-31">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

W

waiting -
Static variable in class net.floodlightcontroller.flowcache.PortDownReconciliation

waitingTask -
Variable in class net.floodlightcontroller.core.util.SingletonTask.SingletonTaskContext

WebService - Class in datastore.workloads.logger

wildcard(OFMatch, IOFSwitch, Integer) -
Method in class net.floodlightcontroller.routing.ForwardingBase

wildcard(Wildcards.Flag) -
Method in class org.openflow.protocol.Wildcards

return a Wildcards object that has the given flags set

wildcard(Wildcards.Flag, Wildcards.Flag) -
Method in class org.openflow.protocol.Wildcards

return a Wildcards object that has the given flags set

wildcard(Wildcards.Flag...) -
Method in class org.openflow.protocol.Wildcards

return a Wildcards object that has the given flags wildcarded

wildcard_dl_dst -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_dl_src -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_dl_type -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_dpid -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_in_port -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_nw_dst -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_nw_proto -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_nw_src -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_tp_dst -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcard_tp_src -
Variable in class net.floodlightcontroller.firewall.FirewallRule

wildcards -
Variable in class net.floodlightcontroller.firewall.RuleWildcardsPair

wildcards -
Variable in class net.floodlightcontroller.routing.RoutingDecision

wildcards -
Variable in class org.openflow.protocol.OFMatch

wildcards -
Variable in class org.openflow.protocol.statistics.OFTableStatistics

Wildcards - Class in org.openflow.protocol
a more user friendly representation of the wildcards bits in an OpenFlow
 match.
Wildcards.Flag - Enum in org.openflow.protocol
enum type for the binary flags that can be set in the wildcards field of
 an OFMatch.
WildcardsPair - Class in net.floodlightcontroller.firewall

WildcardsPair() -
Constructor for class net.floodlightcontroller.firewall.WildcardsPair

windowSize -
Variable in class net.floodlightcontroller.packet.TCP

withNwDstMask(int) -
Method in class org.openflow.protocol.Wildcards

return a Wildcard object that has the given nwDstCidrMask set.

withNwSrcMask(int) -
Method in class org.openflow.protocol.Wildcards

return a Wildcard object that has the given nwSrcCidrMask set.

workerThread -
Variable in class net.floodlightcontroller.core.internal.RoleChanger

workerThreads -
Variable in class net.floodlightcontroller.core.internal.Controller

WorkLoadResults - Class in datastore.workloads

WorkLoadResults(String) -
Constructor for class datastore.workloads.WorkLoadResults

WorkLoadResults(List<RequestLogEntry>, List<ActivityEvent>) -
Constructor for class datastore.workloads.WorkLoadResults

WorkLoadResults.ContainsType - Class in datastore.workloads
Help class to define predicates filtering RequesLogEntries based on their types.
WorkLoadResults.ContainsType(RequestType) -
Constructor for class datastore.workloads.WorkLoadResults.ContainsType

WorkLoadResults.ContainsType(SuperType) -
Constructor for class datastore.workloads.WorkLoadResults.ContainsType

write() -
Method in class datastore.workloads.ReportGenerator.Formats.ExcelWriter

write(OFMessage, FloodlightContext) -
Method in interface net.floodlightcontroller.core.IOFSwitch

Writes to the OFMessage to the output stream.

write(List<OFMessage>, FloodlightContext) -
Method in interface net.floodlightcontroller.core.IOFSwitch

Writes the list of messages to the output stream
 The message will be handed to the floodlightProvider for possible filtering
 and processing by message listeners.

write(OFMessage, FloodlightContext) -
Method in class net.floodlightcontroller.core.OFSwitchBase

write(List<OFMessage>, FloodlightContext) -
Method in class net.floodlightcontroller.core.OFSwitchBase

write(IOFSwitch, OFMessage, FloodlightContext) -
Method in class net.floodlightcontroller.util.OFMessageDamper

write the messag to the switch according to our dampening settings

write(IOFSwitch, OFMessage, FloodlightContext, boolean) -
Method in class net.floodlightcontroller.util.OFMessageDamper

write the messag to the switch according to our dampening settings

WRITE_OP -
Static variable in interface datastore.bench.flowsimulations.FlowSimulation

writeChartToPDF(JFreeChart, int, int, String) -
Static method in class datastore.workloads.ReportGenerator.Formats.PDFExporter

writeLinkToStorage(Link, LinkInfo) -
Method in class net.floodlightcontroller.linkdiscovery.internal.LinkDiscoveryManager

Writes a LinkTuple and corresponding LinkInfo to storage

writeRequestSize(WorkLoadResults) -
Static method in class datastore.workloads.ReportGenerator.StatsCreator

writeResponseSize(WorkLoadResults) -
Static method in class datastore.workloads.ReportGenerator.StatsCreator

writeString(String, ByteBuffer, int) -
Method in class net.floodlightcontroller.packet.DHCP

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFAction

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionDataLayer

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionEnqueue

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionNetworkLayerAddress

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionNetworkTypeOfService

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionOutput

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionStripVirtualLan

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionTransportLayer

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionVendor

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionVendorGeneric

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionVirtualLanIdentifier

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.action.OFActionVirtualLanPriorityCodePoint

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFEchoRequest

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFError

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFFeaturesReply

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFFlowMod

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFFlowRemoved

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFMatch

Write this message's binary format to the specified ByteBuffer

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFMessage

Write this message's binary format to the specified ByteBuffer

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFPacketIn

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFPacketOut

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFPacketQueue

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFPhysicalPort

Write this message's binary format to the specified ByteBuffer

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFPortMod

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFPortStatus

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFQueueGetConfigReply

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFQueueGetConfigRequest

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFQueueProp

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFStatisticsMessageBase

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFSwitchConfig

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.OFVendor

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFAggregateStatisticsReply

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFAggregateStatisticsRequest

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFDescriptionStatistics

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFFlowStatisticsReply

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFFlowStatisticsRequest

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFPortStatisticsReply

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFPortStatisticsRequest

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFQueueStatisticsReply

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFQueueStatisticsRequest

writeTo(ChannelBuffer) -
Method in interface org.openflow.protocol.statistics.OFStatistics

Write this message's binary format to the specified ByteBuffer

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFTableStatistics

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.statistics.OFVendorStatistics

writeTo(ChannelBuffer) -
Method in class org.openflow.protocol.vendor.OFByteArrayVendorData

Write the vendor data bytes to the ChannelBuffer

writeTo(ChannelBuffer) -
Method in interface org.openflow.protocol.vendor.OFVendorData

Write the vendor data to the specified ChannelBuffer

writeTo(ChannelBuffer, int, String) -
Static method in class org.openflow.util.StringByteSerializer

writeTo(ChannelBuffer) -
Method in class org.openflow.vendor.nicira.OFNiciraVendorData

Write the vendor data to the ChannelBuffer

writeTo(ChannelBuffer) -
Method in class org.openflow.vendor.nicira.OFRoleVendorData

Write the role vendor data to the ChannelBuffer

writeTo(ChannelBuffer) -
Method in class org.openflow.vendor.openflow.OFOpenFlowVendorData

Write the vendor data to the ChannelBuffer

writeTo(ChannelBuffer) -
Method in class org.openflow.vendor.openflow.OFQueueVendorData

Write the queue message data to the ChannelBuffer

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _


text:
#ifndef _SYS_IMGACT_H_
#define	_SYS_IMGACT_H_

struct image_params {
	struct proc *proc;	/* our process struct */
	struct execve_args *uap; /* syscall arguments */
	struct vnode *vp;	/* pointer to vnode of file to exec */
	struct vattr *attr;	/* attributes of file */
	const char *image_header; /* head of file to exec */
	char *stringbase;	/* base address of tmp string storage */
	char *stringp;		/* current 'end' pointer of tmp strings */
	char *endargs;		/* end of argv vector */
	int stringspace;	/* space left in tmp string storage area */
	int argc, envc;		/* count of argument and environment strings */
	char *argv0;		/* Replacement for argv[0] when interpreting */
	unsigned long entry_addr; /* entry address of target executable */
	char vmspace_destroyed;	/* flag - we've blown away original vm space */
	char interpreted;	/* flag - this executable is interpreted */
	char interpreter_name[64]; /* name of the interpreter */
	void *auxargs;		/* ELF Auxinfo structure pointer */
	struct vm_page *firstpage;	/* first page that we mapped */
	char *fname;            /* pointer to filename of executable (user space) */
	unsigned long ps_strings; /* PS_STRINGS for BSD/OS binaries */
};

#ifdef _KERNEL
int	exec_check_permissions __P((struct image_params *));
int	exec_extract_strings __P((struct image_params *));
int	exec_new_vmspace __P((struct image_params *));
#endif

#endif /* !_SYS_IMGACT_H_ */


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CommonLanguageServerProtocol.Framework;
using Microsoft.VisualStudio.Text.Adornments;
using Newtonsoft.Json.Linq;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;

namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
    /// <summary>
    /// Handle a completion resolve request to add description.
    ///
    /// TODO - This must be moved to the MS.CA.LanguageServer.Protocol project once the
    /// references to VS icon types and classified text runs are removed.
    /// See https://github.com/dotnet/roslyn/issues/55142
    /// </summary>
    /// <remarks>
    /// This isn't a <see cref="ILspServiceDocumentRequestHandler{TRequest, TResponse}" /> because it could return null.
    /// </remarks>
    [Method(LSP.Methods.TextDocumentCompletionResolveName)]
    internal sealed class CompletionResolveHandler : ILspServiceRequestHandler<LSP.CompletionItem, LSP.CompletionItem>, ITextDocumentIdentifierHandler<LSP.CompletionItem, LSP.TextDocumentIdentifier?>
    {
        private readonly CompletionListCache _completionListCache;
        private readonly IGlobalOptionService _globalOptions;

        public bool MutatesSolutionState => false;
        public bool RequiresLSPSolution => true;

        public CompletionResolveHandler(IGlobalOptionService globalOptions, CompletionListCache completionListCache)
        {
            _globalOptions = globalOptions;
            _completionListCache = completionListCache;
        }

        public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionItem request)
            => GetCompletionListCacheEntry(request)?.TextDocument;

        public async Task<LSP.CompletionItem> HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken)
        {
            var document = context.GetRequiredDocument();
            var clientCapabilities = context.GetRequiredClientCapabilities();

            var completionService = document.Project.Services.GetRequiredService<CompletionService>();

            var cacheEntry = GetCompletionListCacheEntry(completionItem);
            if (cacheEntry == null)
            {
                // Don't have a cache associated with this completion item, cannot resolve.
                context.TraceInformation("No cache entry found for the provided completion item at resolve time.");
                return completionItem;
            }

            var list = cacheEntry.CompletionList;

            // Find the matching completion item in the completion list
            var selectedItem = list.ItemsList.FirstOrDefault(cachedCompletionItem => MatchesLSPCompletionItem(completionItem, cachedCompletionItem));
            if (selectedItem == null)
            {
                return completionItem;
            }

            var completionOptions = _globalOptions.GetCompletionOptions(document.Project.Language);
            var displayOptions = _globalOptions.GetSymbolDescriptionOptions(document.Project.Language);
            var description = await completionService.GetDescriptionAsync(document, selectedItem, completionOptions, displayOptions, cancellationToken).ConfigureAwait(false)!;
            if (description != null)
            {
                var supportsVSExtensions = clientCapabilities.HasVisualStudioLspCapability();
                if (supportsVSExtensions)
                {
                    var vsCompletionItem = (LSP.VSInternalCompletionItem)completionItem;
                    vsCompletionItem.Description = new ClassifiedTextElement(description.TaggedParts
                        .Select(tp => new ClassifiedTextRun(tp.Tag.ToClassificationTypeName(), tp.Text)));
                }
                else
                {
                    var clientSupportsMarkdown = clientCapabilities.TextDocument?.Completion?.CompletionItem?.DocumentationFormat.Contains(LSP.MarkupKind.Markdown) == true;
                    completionItem.Documentation = ProtocolConversions.GetDocumentationMarkupContent(description.TaggedParts, document, clientSupportsMarkdown);
                }
            }

            // We compute the TextEdit resolves for complex text edits (e.g. override and partial
            // method completions) here. Lazily resolving TextEdits is technically a violation of
            // the LSP spec, but is currently supported by the VS client anyway. Once the VS client
            // adheres to the spec, this logic will need to change and VS will need to provide
            // official support for TextEdit resolution in some form.
            if (selectedItem.IsComplexTextEdit)
            {
                Contract.ThrowIfTrue(completionItem.InsertText != null);
                Contract.ThrowIfTrue(completionItem.TextEdit != null);

                var snippetsSupported = clientCapabilities?.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false;

                completionItem.TextEdit = await GenerateTextEditAsync(
                    document, completionService, selectedItem, snippetsSupported, cancellationToken).ConfigureAwait(false);
            }

            return completionItem;
        }

        private static bool MatchesLSPCompletionItem(LSP.CompletionItem lspCompletionItem, CompletionItem completionItem)
        {
            if (!lspCompletionItem.Label.StartsWith(completionItem.DisplayTextPrefix, StringComparison.Ordinal))
            {
                return false;
            }

            // The prefix matches, consume the matching prefix from the lsp completion item label.
            var displayTextWithSuffix = lspCompletionItem.Label[completionItem.DisplayTextPrefix.Length..];
            if (!displayTextWithSuffix.EndsWith(completionItem.DisplayTextSuffix, StringComparison.Ordinal))
            {
                return false;
            }

            // The suffix matches, consume the matching suffix from the lsp completion item label.
            var originalDisplayText = displayTextWithSuffix[..^completionItem.DisplayTextSuffix.Length];

            // Now we're left with what should be the original display text for the lsp completion item.
            // Check to make sure it matches the cached completion item label.
            return string.Equals(originalDisplayText, completionItem.DisplayText);
        }

        // Internal for testing
        internal static async Task<LSP.TextEdit> GenerateTextEditAsync(
            Document document,
            CompletionService completionService,
            CompletionItem selectedItem,
            bool snippetsSupported,
            CancellationToken cancellationToken)
        {
            var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            var completionChange = await completionService.GetChangeAsync(
                document, selectedItem, cancellationToken: cancellationToken).ConfigureAwait(false);
            var completionChangeSpan = completionChange.TextChange.Span;
            var newText = completionChange.TextChange.NewText;
            Contract.ThrowIfNull(newText);

            // If snippets are supported, that means we can move the caret (represented by $0) to
            // a new location.
            if (snippetsSupported)
            {
                var caretPosition = completionChange.NewPosition;
                if (caretPosition.HasValue)
                {
                    // caretPosition is the absolute position of the caret in the document.
                    // We want the position relative to the start of the snippet.
                    var relativeCaretPosition = caretPosition.Value - completionChangeSpan.Start;

                    // The caret could technically be placed outside the bounds of the text
                    // being inserted. This situation is currently unsupported in LSP, so in
                    // these cases we won't move the caret.
                    if (relativeCaretPosition >= 0 && relativeCaretPosition <= newText.Length)
                    {
                        newText = newText.Insert(relativeCaretPosition, "$0");
                    }
                }
            }

            var textEdit = new LSP.TextEdit()
            {
                NewText = newText,
                Range = ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText),
            };

            return textEdit;
        }

        private CompletionListCache.CacheEntry? GetCompletionListCacheEntry(LSP.CompletionItem request)
        {
            Contract.ThrowIfNull(request.Data);
            var resolveData = ((JToken)request.Data).ToObject<CompletionResolveData>();
            if (resolveData?.ResultId == null)
            {
                Contract.Fail("Result id should always be provided when resolving a completion item we returned.");
                return null;
            }

            var cacheEntry = _completionListCache.GetCachedCompletionList(resolveData.ResultId.Value);
            if (cacheEntry == null)
            {
                // No cache for associated completion item. Log some telemetry so we can understand how frequently this actually happens.
                Logger.Log(FunctionId.LSP_CompletionListCacheMiss, KeyValueLogMessage.NoProperty);
            }

            return cacheEntry;
        }
    }
}