text:
.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        Click :ref:`here <sphx_glr_download_auto_examples_example_02_categorical.py>`     to download the full example code
    .. rst-class:: sphx-glr-example-title

    .. _sphx_glr_auto_examples_example_02_categorical.py:

2. Categorical Predictors
=========================

The syntax for handling categorical predictors is **different** between standard regression models/two-stage-models (i.e. :code:`Lm` and :code:`Lm2`) and multi-level models (:code:`Lmer`) in :code:`pymer4`. This is because formula parsing is passed to R for :code:`Lmer` models, but handled by Python for other models.

Lm and Lm2 Models
-----------------
:code:`Lm` and :code:`Lm2` models use `patsy  <https://patsy.readthedocs.io/en/latest/>`_ to parse model formulae. Patsy is very powerful and has built-in support for handling categorical coding schemes by wrapping a predictor in then :code:`C()` *within* the module formula. Patsy can also perform some pre-processing such as scaling and standardization using special functions like :code:`center()`. Here are some examples.

.. code-block:: default

    # import basic libraries and sample data
    import os
    import pandas as pd
    from pymer4.utils import get_resource_path
    from pymer4.models import Lm

    # IV3 is a categorical predictors with 3 levels in the sample data
    df = pd.read_csv(os.path.join(get_resource_path(), "sample_data.csv"))

Dummy-coded/Treatment contrasts
+++++++++++++++++++++++++++++++

.. code-block:: default

    # Estimate a model using Treatment contrasts (dummy-coding)
    # with '1.0' as the reference level
    # This is the default of the C() function
    model = Lm("DV ~ C(IV3, levels=[1.0, 0.5, 1.5])", data=df)
    print(model.fit())

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    Formula: DV~C(IV3,levels=[1.0,0.5,1.5])

    Family: gaussian         Estimator: OLS

    Std-errors: non-robust  CIs: standard 95%       Inference: parametric

    Number of observations: 564      R^2: 0.004      R^2_adj: 0.001

    Log-likelihood: -2728.620        AIC: 5463.241   BIC: 5476.246

    Fixed effects:

                                           Estimate  2.5_ci  97.5_ci     SE   DF  T-stat  P-val  Sig
    Intercept                                42.721  38.334   47.108  2.233  561  19.129  0.000  ***
    C(IV3, levels=[1.0, 0.5, 1.5])[T.0.5]     1.463  -4.741    7.667  3.158  561   0.463  0.643
    C(IV3, levels=[1.0, 0.5, 1.5])[T.1.5]    -3.419  -9.622    2.785  3.158  561  -1.082  0.280

Orthogonal Polynomial Contrasts
+++++++++++++++++++++++++++++++

.. code-block:: default

    # Patsy can do this using the Poly argument to the
    # C() function
    model = Lm("DV ~ C(IV3, Poly)", data=df)
    print(model.fit())

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    Formula: DV~C(IV3,Poly)

    Family: gaussian         Estimator: OLS

    Std-errors: non-robust  CIs: standard 95%       Inference: parametric

    Number of observations: 564      R^2: 0.004      R^2_adj: 0.001

    Log-likelihood: -2728.620        AIC: 5463.241   BIC: 5476.246

    Fixed effects:

                            Estimate  2.5_ci  97.5_ci     SE   DF  T-stat  P-val  Sig
    Intercept                 42.069  39.537   44.602  1.289  561  32.627  0.000  ***
    C(IV3, Poly).Linear       -3.452  -7.838    0.935  2.233  561  -1.546  0.123
    C(IV3, Poly).Quadratic    -0.798  -5.185    3.588  2.233  561  -0.357  0.721

Sum-to-zero contrasts
+++++++++++++++++++++

.. code-block:: default

    # Similar to before but with the Sum argument
    model = Lm("DV ~ C(IV3, Sum)", data=df)
    print(model.fit())

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    Formula: DV~C(IV3,Sum)

    Family: gaussian         Estimator: OLS

    Std-errors: non-robust  CIs: standard 95%       Inference: parametric

    Number of observations: 564      R^2: 0.004      R^2_adj: 0.001

    Log-likelihood: -2728.620        AIC: 5463.241   BIC: 5476.246

    Fixed effects:

                        Estimate  2.5_ci  97.5_ci     SE   DF  T-stat  P-val  Sig
    Intercept             42.069  39.537   44.602  1.289  561  32.627  0.000  ***
    C(IV3, Sum)[S.0.5]     2.115  -1.467    5.697  1.823  561   1.160  0.247
    C(IV3, Sum)[S.1.0]     0.652  -2.930    4.234  1.823  561   0.357  0.721

Scaling/Centering
+++++++++++++++++

.. code-block:: default

    # Moderation with IV2, but centering IV2 first
    model = Lm("DV ~ center(IV2) * C(IV3, Sum)", data=df)
    print(model.fit())

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    Formula: DV~center(IV2)*C(IV3,Sum)

    Family: gaussian         Estimator: OLS

    Std-errors: non-robust  CIs: standard 95%       Inference: parametric

    Number of observations: 564      R^2: 0.511      R^2_adj: 0.507

    Log-likelihood: -2528.051        AIC: 5068.102   BIC: 5094.113

    Fixed effects:

                                    Estimate  2.5_ci  97.5_ci     SE   DF  T-stat  P-val  Sig
    Intercept                         42.051  40.268   43.833  0.908  558  46.329  0.000  ***
    C(IV3, Sum)[S.0.5]                 0.580  -1.942    3.102  1.284  558   0.452  0.652
    C(IV3, Sum)[S.1.0]                 0.383  -2.136    2.903  1.282  558   0.299  0.765
    center(IV2)                        0.746   0.685    0.807  0.031  558  24.012  0.000  ***
    center(IV2):C(IV3, Sum)[S.0.5]     0.050  -0.037    0.137  0.044  558   1.132  0.258
    center(IV2):C(IV3, Sum)[S.1.0]    -0.057  -0.144    0.029  0.044  558  -1.306  0.192

Please refer to the `patsy documentation <https://patsy.readthedocs.io/en/latest/categorical-coding.html>`_ for more details when working categorical predictors in :code:`Lm` or :code:`Lm2` models.

Lmer Models
-----------
:code:`Lmer()` models currently have support for handling categorical predictors in one of three ways based on how R's :code:`factor()` works (see the note at the end of this tutorial):

- Dummy-coded factor levels (treatment contrasts) in which each model term is the difference between a factor level and a selected reference level
- Orthogonal polynomial contrasts in which each model term is a polynomial contrast across factor levels (e.g. linear, quadratic, cubic, etc)
- Custom contrasts for each level of a factor, which should be provided in the manner expected by R.

To make re-parameterizing models easier, factor codings are passed as a dictionary to the :code:`factors` argument of a model's :code:`.fit()`. This obviates the need for adjusting data-frame properties as in R. Note that this is **different** from :code:`Lm` and :code:`Lm2` models above which expect factor codings in their formulae (because patsy does).

Each of these ways also enables you to easily compute post-hoc comparisons between factor levels, as well as interactions between continuous predictors and each factor level. See tutorial 3 for more on post-hoc tests.

.. code-block:: default

    from pymer4.models import Lmer

    # We're going to fit a multi-level logistic regression using the
    # dichotomous DV_l variable and the same categorical predictor (IV3)
    # as before
    model = Lmer("DV_l ~ IV3 + (IV3|Group)", data=df, family="binomial")

Dummy-coding factors
++++++++++++++++++++
First we'll use dummy-coding/treatment contrasts with 1.0 as the reference level. This will compute two coefficients: 0.5 > 1.0 and 1.5 > 1.0.

.. code-block:: default

    print(model.fit(factors={"IV3": ["1.0", "0.5", "1.5"]}))

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    boundary (singular) fit: see ?isSingular

    Formula: DV_l~IV3+(IV3|Group)

    Family: binomial         Inference: parametric

    Number of observations: 564      Groups: {'Group': 47.0}

    Log-likelihood: -389.003         AIC: 796.006

    Random effects:

                  Name    Var    Std
    Group  (Intercept)  0.022  0.148
    Group       IV30.5  0.060  0.246
    Group       IV31.5  0.038  0.196

                   IV1     IV2  Corr
    Group  (Intercept)  IV30.5  -1.0
    Group  (Intercept)  IV31.5  -1.0
    Group       IV30.5  IV31.5   1.0

    Fixed effects:

                 Estimate  2.5_ci  97.5_ci     SE     OR  ...  Prob_2.5_ci  Prob_97.5_ci  Z-stat  P-val  Sig
    (Intercept)    -0.129  -0.419    0.162  0.148  0.879  ...        0.397         0.540  -0.867  0.386
    IV31            0.129  -0.283    0.540  0.210  1.137  ...        0.430         0.632   0.612  0.541
    IV32           -0.128  -0.539    0.283  0.210  0.880  ...        0.368         0.570  -0.612  0.541

    [3 rows x 13 columns]

Polynomial contrast coding
++++++++++++++++++++++++++
Second we'll use orthogonal polynomial contrasts. This is accomplished using the :code:`ordered=True` argument and specifying the order of the *linear* contrast in increasing order. R will automatically compute higher order polynomial contrats that are orthogonal to this linear contrast. In this example, since there are 3 factor levels this will result in two polynomial terms: a linear contrast we specify below corresponding to 0.5 < 1.0 < 1.5 and an orthogonal quadratic contrast automatically determined by R, corresponding to 0.5 > 1 < 1.5

.. code-block:: default

    print(model.fit(factors={"IV3": ["0.5", "1.0", "1.5"]}, ordered=True))

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    boundary (singular) fit: see ?isSingular

    boundary (singular) fit: see ?isSingular

    Formula: DV_l~IV3+(IV3|Group)

    Family: binomial         Inference: parametric

    Number of observations: 564      Groups: {'Group': 47.0}

    Log-likelihood: -389.003         AIC: 796.006

    Random effects:

                  Name    Var    Std
    Group  (Intercept)  0.010  0.098
    Group       IV31.0  0.060  0.246
    Group       IV31.5  0.003  0.050

                   IV1     IV2  Corr
    Group  (Intercept)  IV31.0  -1.0
    Group  (Intercept)  IV31.5  -1.0
    Group       IV31.0  IV31.5   1.0

    Fixed effects:

                 Estimate  2.5_ci  97.5_ci     SE     OR  ...  Prob_2.5_ci  Prob_97.5_ci  Z-stat  P-val  Sig
    (Intercept)    -0.128  -0.294    0.037  0.085  0.879  ...        0.427         0.509  -1.518  0.129
    IV31           -0.182  -0.469    0.106  0.147  0.834  ...        0.385         0.526  -1.238  0.216
    IV32            0.000  -0.292    0.292  0.149  1.000  ...        0.428         0.572   0.001  1.000

    [3 rows x 13 columns]

Custom contrasts
++++++++++++++++
:code:`Lmer` models can also take custom factor contrasts based on how they are expected by R (see the note at the end of this tutorial for how contrasts work in R). Remember that there can be at most k-1 model terms representing any k level factor without over-parameterizing a model. If you specify a custom contrast, R will generate set of orthogonal contrasts for the rest of your model terms.

.. code-block:: default

    # Compare level '1.0' to the mean of levels '0.5' and '1.5'
    # and let R determine the second contrast orthogonal to it

    print(model.fit(factors={"IV3": {"1.0": 1, "0.5": -0.5, "1.5": -0.5}}))

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    boundary (singular) fit: see ?isSingular

    boundary (singular) fit: see ?isSingular

    boundary (singular) fit: see ?isSingular

    Formula: DV_l~IV3+(IV3|Group)

    Family: binomial         Inference: parametric

    Number of observations: 564      Groups: {'Group': 47.0}

    Log-likelihood: -389.003         AIC: 796.006

    Random effects:

                  Name    Var    Std
    Group  (Intercept)  0.022  0.148
    Group       IV30.5  0.060  0.246
    Group       IV31.5  0.038  0.196

                   IV1     IV2  Corr
    Group  (Intercept)  IV30.5  -1.0
    Group  (Intercept)  IV31.5  -1.0
    Group       IV30.5  IV31.5   1.0

    Fixed effects:

                 Estimate  2.5_ci  97.5_ci     SE     OR  ...  Prob_2.5_ci  Prob_97.5_ci  Z-stat  P-val  Sig
    (Intercept)    -0.128  -0.294    0.037  0.085  0.879  ...        0.427         0.509  -1.518  0.129
    IV31           -0.000  -0.358    0.357  0.182  1.000  ...        0.412         0.588  -0.001  1.000
    IV32           -0.182  -0.469    0.106  0.147  0.834  ...        0.385         0.526  -1.238  0.216

    [3 rows x 13 columns]

User-created contrasts (without R)
++++++++++++++++++++++++++++++++++
Another option available to you is fitting a model with *only* your desired contrast(s) rather than a full set of k-1 contrasts. Contrary to how statistics is usually taught, you don't ever *have to* include a full set of k-1 contrasts for a k level factor! The upside to doing this is that you won't need to rely on R to compute anything for you (aside from the model fit), and you will have a model with exactly the number of terms as contrasts you desire, giving you complete control. The downside is that post-hoc tests will no longer be available (see tutorial 3 for more information on post-hoc tests), but it's unlikely you're doing post-hoc tests if you are computing a subset of specific contrasts anyway. This is also a useful approach if you don't want to use patsy's formula syntax with :code:`Lm` and :code:`Lm2` as noted above.

This can be accomplished by creating new columns in your dataframe to test specific hypotheses and is trivial to do with pandas `map <https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.Series.map.html/>`_ and `assign <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html/>`_ methods. For example, here we manually compute a linear contrast by creating a new column in our dataframe and treating it as a continuous variable.

.. code-block:: default

    # Create a new column in the dataframe with a custom (linear) contrast
    df = df.assign(IV3_custom_lin=df["IV3"].map({0.5: -1, 1.0: 0, 1.5: 1}))
    print(df.head())

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

       Group   IV1  DV_l         DV       IV2  IV3  IV3_custom_lin
    0      1  20.0     0   7.936508  4.563492  0.5              -1
    1      1  20.0     0  15.277778  0.000000  1.0               0
    2      1  20.0     1   0.000000  0.000000  1.5               1
    3      1  20.0     1   9.523810  0.000000  0.5              -1
    4      1  12.5     0   0.000000  0.000000  1.0               0

Now we can use this variable as a continuous predictor without the need for the :code:`factors` argument. Notice how the z-stat and p-value of the estimate are the same as the linear polynomial contrast estimated above. The coefficients differ in scale only because R uses [~-0.707, ~0, ~0.707] for its polynomial contrasts rather than [-1, 0, 1] like we did.

.. code-block:: default

    # Estimate model
    model = Lmer(
        "DV_l ~ IV3_custom_lin + (IV3_custom_lin|Group)", data=df, family="binomial"
    )
    print(model.fit())

.. rst-class:: sphx-glr-script-out

 Out:

 .. code-block:: none

    boundary (singular) fit: see ?isSingular

    Formula: DV_l~IV3_custom_lin+(IV3_custom_lin|Group)

    Family: binomial         Inference: parametric

    Number of observations: 564      Groups: {'Group': 47.0}

    Log-likelihood: -389.016         AIC: 788.031

    Random effects:

                     Name  Var  Std
    Group     (Intercept)  0.0  0.0
    Group  IV3_custom_lin  0.0  0.0

                   IV1             IV2  Corr
    Group  (Intercept)  IV3_custom_lin   NaN

    Fixed effects:

                    Estimate  2.5_ci  97.5_ci     SE    OR  ...  Prob_2.5_ci  Prob_97.5_ci  Z-stat  P-val  Sig
    (Intercept)       -0.128  -0.294    0.037  0.085  0.88  ...        0.427         0.509  -1.517  0.129
    IV3_custom_lin    -0.128  -0.331    0.075  0.104  0.88  ...        0.418         0.519  -1.239  0.215

    [2 rows x 13 columns]

A note on how contrasts in R work
---------------------------------
.. note::
  This is just for folks curious about how contrasts in R work

Specifying multiple custom contrasts in R has always been a point of confusion amongst users. This because the :code:`contrasts()` command in R doesn't actually expect contrast weights (i.e. a design matrix) as one would intuit. Rather, it is made for generating contrast coding schemes which are the inverse of the contrast weight matrix. For a longer explanation with examples see `this reference <https://rstudio-pubs-static.s3.amazonaws.com/65059_586f394d8eb84f84b1baaf56ffb6b47f.html>`_ and `this reference <https://github.com/ejolly/R/blob/master/Guides/Contrasts_in_R.md>`_. For these situations pymer4 offers a few utility functions to convert between these matrix types if desired in :code:`pymer4.utils`: :code:`R2con()` and :code:`con2R()`.

.. _sphx_glr_download_auto_examples_example_02_categorical.py:

.. only :: html

 .. container:: sphx-glr-footer
    :class: sphx-glr-footer-example

  .. container:: sphx-glr-download sphx-glr-download-python

     :download:`Download Python source code: example_02_categorical.py <example_02_categorical.py>`

  .. container:: sphx-glr-download sphx-glr-download-jupyter

     :download:`Download Jupyter notebook: example_02_categorical.ipynb <example_02_categorical.ipynb>`

.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_


text:
<!doctype html>

        <title>Murphy-Beach</title>
        <link rel="stylesheet" href="mystyle.css">

August Murphy-Beach

Straight 'Outta Kansas

About

Projects

Coursework

Resume

Past and Current Projects:

This Website

                         An ongoing adventure into web design, I'm constantly tweaking it to keep my HTML and CSS form in check. It is, of course, written in HTML/CSS.

TrashTalkr

                        Part of a group project for CPSC 224, Trashtalkr allows anonymous peer-to-peer communication between users, given a host node IP. Written in Java 8 / Swing.

HillClimbr

                        Independent-Project-turned-Final, Hillclimbr calculates a Users speed up a hill, racing various cycling benchmarks. Written in Netlogo.

redpajama_set_name: RedPajamaGithub


text:
def date_handler(obj):
    return obj.isoformat() if hasattr(obj, 'isoformat') else obj


text:
package org.wso2.siddhi.core.query.processor.stream.window;

import org.apache.log4j.Logger;
import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.MetaComplexEvent;
import org.wso2.siddhi.core.event.stream.StreamEvent;
import org.wso2.siddhi.core.event.stream.StreamEventCloner;
import org.wso2.siddhi.core.executor.ConstantExpressionExecutor;
import org.wso2.siddhi.core.executor.ExpressionExecutor;
import org.wso2.siddhi.core.executor.VariableExpressionExecutor;
import org.wso2.siddhi.core.query.processor.Processor;
import org.wso2.siddhi.core.table.EventTable;
import org.wso2.siddhi.core.util.collection.operator.Finder;
import org.wso2.siddhi.core.util.parser.CollectionOperatorParser;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.expression.Expression;

import java.util.List;
import java.util.Map;

public class ExternalTimeWindowProcessor extends WindowProcessor implements FindableProcessor {
    static final Logger log = Logger.getLogger(ExternalTimeWindowProcessor.class);
    private long timeToKeep;
    private ComplexEventChunk<StreamEvent> expiredEventChunk;
    private VariableExpressionExecutor timeStampVariableExpressionExecutor;

    @Override
    protected void init(ExpressionExecutor[] attributeExpressionExecutors, ExecutionPlanContext executionPlanContext) {
        this.expiredEventChunk = new ComplexEventChunk<StreamEvent>();
        if (attributeExpressionExecutors[1].getReturnType() == Attribute.Type.INT) {
            timeToKeep = Integer.parseInt(String.valueOf(((ConstantExpressionExecutor) attributeExpressionExecutors[1]).getValue()));
        } else {
            timeToKeep = Long.parseLong(String.valueOf(((ConstantExpressionExecutor) attributeExpressionExecutors[1]).getValue()));
        }
        timeStampVariableExpressionExecutor = ((VariableExpressionExecutor) attributeExpressionExecutors[0]);
    }

    @Override
    protected synchronized void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) {
        while (streamEventChunk.hasNext()) {

            StreamEvent streamEvent = streamEventChunk.next();
            long currentTime = (Long) streamEvent.getAttribute(timeStampVariableExpressionExecutor.getPosition());

            StreamEvent clonedEvent = null;
            if (streamEvent.getType() == StreamEvent.Type.CURRENT) {
                clonedEvent = streamEventCloner.copyStreamEvent(streamEvent);
                clonedEvent.setType(StreamEvent.Type.EXPIRED);
                clonedEvent.setTimestamp(currentTime + timeToKeep);
            }

            while (expiredEventChunk.hasNext()) {
                StreamEvent expiredEvent = expiredEventChunk.next();
                long timeDiff = expiredEvent.getTimestamp() - currentTime;
                if (timeDiff <= 0) {
                    expiredEventChunk.remove();
                    streamEventChunk.insertBeforeCurrent(expiredEvent);
                } else {
                    expiredEventChunk.reset();
                    break;
                }
            }

            if (streamEvent.getType() == StreamEvent.Type.CURRENT) {
                this.expiredEventChunk.add(clonedEvent);
            }
            expiredEventChunk.reset();
        }
        nextProcessor.process(streamEventChunk);
    }

    @Override
    public void start() {
        //Do nothing
    }

    @Override
    public void stop() {
        //Do nothing
    }

    @Override
    public Object[] currentState() {
        return new Object[]{expiredEventChunk};
    }

    @Override
    public void restoreState(Object[] state) {
        expiredEventChunk = (ComplexEventChunk<StreamEvent>) state[0];
    }

    @Override
    public synchronized StreamEvent find(ComplexEvent matchingEvent, Finder finder) {
        return finder.find(matchingEvent, expiredEventChunk,streamEventCloner);
    }

    @Override
    public Finder constructFinder(Expression expression, MetaComplexEvent metaComplexEvent, ExecutionPlanContext executionPlanContext, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, EventTable> eventTableMap, int matchingStreamIndex, long withinTime) {
        return CollectionOperatorParser.parse( expression, metaComplexEvent, executionPlanContext, variableExpressionExecutors, eventTableMap, matchingStreamIndex, inputDefinition, withinTime);
    }
}


text:
<?php

namespace Travis;

class XML
{
    /**
     * Core array of data.
     *
     * @var     array
     */
    public $array;

    /**
     * Build object from string.
     *
     * @param   string  $string
     * @return  object
     */
    public static function fromString($string)
    {
        $class = __CLASS__;
        $object = new $class;
        $object->convert($string);
        return $object;
    }

    /**
     * Build object from path.
     *
     * @param   string  $path
     * @return  object
     */
    public static function fromFile($path)
    {
        // open file
        $string = file_get_contents($path);

        // return
        return static::fromString($string);
    }

    /**
     * Build object from URL (string).
     *
     * @param   string  $url
     * @return  object
     */
    public static function fromURL($url)
    {
        return static::fromFile($url);
    }

    /**
     * Build object from array.
     *
     * @param   array   $array
     * @return  object
     */
    public static function fromArray($array)
    {
        if (!is_array($array)) trigger_error('Must be array.');

        $class = __CLASS__;
        $object = new $class;
        $object->array = $array;
        return $object;
    }

    /**
     * Convert string to array.
     *
     * @param   string  $string
     * @return  void
     */
    protected function convert($string)
    {
        // The following is a function I've had for a long time,
        // and I have no idea where I got it.  It takes an XML string,
        // parses it, and converts it to an array.  We'll store that
        // array in the object and use it as we need.

        /////////////////////////////////////////////////

        if (!function_exists('xml_parser_create')) return false;
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $string, $dataml_values);
        xml_parser_free($parser);
        if (!$dataml_values) return;
        $dataml_array = array();
        $parents = array();
        $opened_tags = array();
        $arr = array();
        $current = &$dataml_array;
        foreach($dataml_values as $data)
        {
            unset($attributes,$value);
            extract($data);
            $result = '';
            $result = array();
            if (isset($value)) $result['value'] = $value;
            if (isset($attributes))
            {
                foreach($attributes as $attr => $val)
                {
                    $result['attr'][$attr] = $val;
                }
            }
            if ($type == 'open')
            {
                $parent[$level-1] = &$current;
                if (!is_array($current) or (!in_array($tag, array_keys($current))))
                {
                    $current[$tag] = $result;
                    $current = &$current[$tag];
                }
                else
                {
                    if (isset($current[$tag][0]))
                    {
                        array_push($current[$tag], $result);
                    }
                    else
                    {
                        $current[$tag] = array($current[$tag],$result);
                    }
                    $last = count($current[$tag]) - 1;
                    $current = &$current[$tag][$last];
                }
            }
            elseif ($type == 'complete')
            {
                if (!isset($current[$tag]))
                {
                    $current[$tag] = $result;
                }
                else
                {
                    if (is_array($current[$tag]) or (isset($current[$tag][0]) and is_array($current[$tag][0])))
                    {
                        array_push($current[$tag],$result);
                    }
                    else
                    {
                        $current[$tag] = array($current[$tag],$result);
                    }
                }
            }
            elseif ($type == 'close')
            {
                $current = &$parent[$level-1];
            }
        }

        /////////////////////////////////////////////////

        // save object array
        $this->array = $dataml_array;
    }

    /**
     * Get specific value from object array.
     *
     * @param   string  $dots
     * @param   string  $default
     * @return  mixed
     */
    public function get($dots, $default = null)
    {
        return ex($this->array, $dots, $default);
    }

    /**
     * Return object array.
     *
     * @return  array
     */
    public function toArray()
    {
        return $this->array;
    }

    /**
     * Return XML as string.
     *
     * @param   string  $root_node_name
     * @return  boolean
     */
    public function toString($root_node_name = 'root')
    {
        // build
        $xml = \Array2XML::createXML($root_node_name, $this->array);

        // convert
        return $xml->saveXML();
    }

    /**
     * Save object array as file.
     *
     * @param   string  $path
     * @param   string  $root_node_name
     * @return  boolean
     */
    public function toFile($path, $root_node_name = 'root')
    {
        // save
        return file_put_contents($path, $this->toString($root_node_name));
    }
}


text:
#ifndef _CARTO_TILEDOWNLOADLISTENER_H_
#define _CARTO_TILEDOWNLOADLISTENER_H_

#include "core/MapTile.h"

#include <memory>

namespace carto {

    /**
     * Listener for tile downloader.
     */
    class TileDownloadListener {
    public:
        virtual ~TileDownloadListener() { }

        /**
         * Listener method that is called before download has actually started to report the total tile count.
         * @param tileCount The number of tiles that will be downloaded (if not already in the cache).
         */
        virtual void onDownloadStarting(int tileCount) { }
        /**
         * Listener method that is called to report about download progress.
         * @param progress The progress of the download, from 0 to 100.
         */
        virtual void onDownloadProgress(float progress) { }
        /**
         * Listener method that is called when downloading has finished.
         */
        virtual void onDownloadCompleted() { }
        /**
         * Listener method that is called when a tile download fails.
         * @param tile The tile that could not be downloaded.
         */
        virtual void onDownloadFailed(const MapTile& tile) { }
    };

}

#endif


text:
using System.IO;
using SharpDX.Toolkit.Content;

namespace SharpDX.Toolkit.Graphics
{
    /// <summary>
    /// Content reader for <see cref="EffectData"/>.
    /// </summary>
    class EffectDataContentReader : IContentReader
    {
        public object ReadContent(IContentManager readerManager, string assetName, Stream stream, out bool keepStreamOpen, object options)
        {
            keepStreamOpen = false;
            return EffectData.Load(stream);
        }
    }
}


text:
=begin
Copyright 2010-2012 Tasos Laskos <tasos.laskos@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end

###
#
# Network port option.
#
###
class Arachni::Component::Options::Port < Arachni::Component::Options::Base
    def type
        'port'
    end

    def valid?( value )
        return false if empty_required_value?( value )

        if value && !value.to_s.empty? &&
            ((!value.to_s.match( /^\d+$/ ) || value.to_i <= 0 || value.to_i > 65535))
            return false
        end

        super
    end
end


text:
<?php

use G4\Tasker\Tasker2\RetryAfterResolver;

class RetryAfterResolverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array
     */
    private $delayForRetries;

    /**
     * @var RetryAfterResolver
     */
    private $resolverDelay;

    /**
     * @var RetryAfterResolver
     */
    private $resolverDelayEmptyArray;

    /**
     * @var RetryAfterResolver
     */
    private $resolverDelayNotSet;

    /**
     * Set up method
     */
    protected function setUp()
    {
        $this->delayForRetries = [
            10,
            10,
            20,
            60,
            120,
            600,
            1800,
            86400
        ];

        $this->resolverDelay = new RetryAfterResolver($this->delayForRetries);
        $this->resolverDelayEmptyArray = new RetryAfterResolver([]);
        $this->resolverDelayNotSet = new RetryAfterResolver();
    }

    /**
     * Tear down method
     */
    protected function tearDown()
    {
        $this->delayForRetries = null;
        $this->resolverDelay = null;
        $this->resolverDelayNotSet = null;
        $this->resolverDelayEmptyArray = null;
    }

    /**
     * @dataProvider resolverDataProvider
     */
    public function testResolve($startedCount, $retryAfter)
    {
        $resolver = new RetryAfterResolver();

        $this->assertSame($retryAfter, $resolver->resolve($startedCount));
    }

    public function resolverDataProvider()
    {
        return [
            [1, 60],
            [2, 300],
            [3, 1000]
        ];
    }

    /**
     * @dataProvider resolverDelayForRetriesDataProvider
     */
    public function testResolveDelayForRetries($startedCount, $retryAfter)
    {
        $this->assertSame($retryAfter, $this->resolverDelay->resolve($startedCount));
    }

    public function testGetMaxRetryAttempts()
    {
        $this->assertEquals(count($this->delayForRetries), $this->resolverDelay->getMaxRetryAttempts());
    }

    public function testGetDelayForRetries()
    {
        $testArray = [
            1 => 10,
            2 => 10,
            3 => 20,
            4 => 60,
            5 => 120,
            6 => 600,
            7 => 1800,
            8 => 86400
        ];
        $this->assertSame($testArray, $this->resolverDelay->getDelayForRetries());
    }

    public function testDelayForRetriesNotSet()
    {
        $testArray = [
            1 => 60,
            2 => 300,
            3 => 1000
        ];

        $this->assertSame($testArray, $this->resolverDelayNotSet->getDelayForRetries());
    }

    public function testMaxCountDelayForRetriesNotSet()
    {
        $this->assertEquals(count(RetryAfterResolver::DEFAULT_DELAY), $this->resolverDelayNotSet->getMaxRetryAttempts());
    }

    public function testDelayForRetriesEmptyArray()
    {
        $testArray = [
            1 => 60,
            2 => 300,
            3 => 1000
        ];

        $this->assertSame($testArray, $this->resolverDelayEmptyArray->getDelayForRetries());
    }

    public function testMaxCountDelayForRetriesEmptyArray()
    {
        $this->assertEquals(count(RetryAfterResolver::DEFAULT_DELAY), $this->resolverDelayEmptyArray->getMaxRetryAttempts());
    }

    public function resolverDelayForRetriesDataProvider()
    {
        return [
            [1, 10],
            [2, 10],
            [3, 20],
            [4, 60],
            [5, 120],
            [6, 600],
            [7, 1800],
            [8, 86400]
        ];
    }
}


text:
django-unfriendly
=================

The unfriendliest urls in town! ``django-unfriendly`` is a Django app that obfuscates urls and allows your application to natively execute the original view.

.. image:: https://travis-ci.org/tomatohater/django-unfriendly.png?branch=master
    :target: https://travis-ci.org/tomatohater/django-unfriendly

.. image:: https://coveralls.io/repos/tomatohater/django-unfriendly/badge.png?branch=master
	:target: https://coveralls.io/r/tomatohater/django-unfriendly?branch=master

.. image:: https://badge.fury.io/py/django-unfriendly.png
    :target: http://badge.fury.io/py/django-unfriendly

There is lots of talk about SEO friendly urls. The trend is towards more and more human readable information in your urls and Django makes it easy to create urls like::

    http://yoursite.com/music/awesome/the-melvins/

But sometimes urls can give too much away. This is where ``django-unfriendly`` comes in.

``django-unfriendly`` provides a template filter that obfuscates urls in your templates, and a url handler/view that deobfuscates and executes the original view (e.g. no redirection).

Read the docs
*************

https://django-unfriendly.readthedocs.org/en/latest/

Version compatibility
*********************

- v0.6
    - Python 2.7, 3.5
    - Django 1.8, 1.9, 1.10
- v0.5.0
    - Python 2.7
    - Django 1.8, 1.9, 1.10
- v0.4.1
    - Python 2.6 and 2.7
    - Django 1.0 - 1.8


text:
<?php
	class RegistrationConfirmListener implements EventSubscriberInterface
	{
	    private $router;

	    public function __construct(UrlGeneratorInterface $router)
	    {
	        $this->router = $router;
	    }

	    /**
	     * {@inheritDoc}
	     */
	    public static function getSubscribedEvents()
	    {
	        return array(
	                FOSUserEvents::REGISTRATION_CONFIRM => 'onRegistrationConfirm'
	        );
	    }

	    public function onRegistrationConfirm(GetResponseUserEvent $event)
	    {
	        $url = $this->router->generate('wall_profile');

	        $event->setResponse(new RedirectResponse($url));
	    }
	}
?>


text:
Listener::Listener(QObject *parent) : QObject(parent)
{

}

Listener::~Listener(){
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/header" />

    <!--<android.support.v4.widget.SwipeRefreshLayout-->
        <!--android:id="@+id/contact_refresh"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent">-->

        <com.test.myqq.view.ContactView
            android:id="@+id/contactView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    <!--</android.support.v4.widget.SwipeRefreshLayout>-->
</LinearLayout>


text:
class EditorComponent;

class PaintToolWindow : public wi::gui::Window
{
	float rot = 0;
	float stroke_dist = 0;
	bool history_needs_recording_start = false;
	bool history_needs_recording_end = false;
	size_t history_redo_jump_position = 0;
	size_t history_textureIndex = 0;
	struct TextureSlot
	{
		wi::graphics::Texture texture;
		int srgb_subresource = -1;
	};
	wi::vector<TextureSlot> history_textures;
	TextureSlot GetEditTextureSlot(const wi::scene::MaterialComponent& material, int* uvset = nullptr);
	void ReplaceEditTextureSlot(wi::scene::MaterialComponent& material, const TextureSlot& textureslot);

	struct SculptingIndex
	{
		size_t ind;
		float affection;
	};
	wi::vector<SculptingIndex> sculpting_indices;
	XMFLOAT3 sculpting_normal = XMFLOAT3(0, 0, 0);

	wi::Resource brushTex;
	wi::Resource revealTex;

	struct Stroke
	{
		XMFLOAT2 position;
		float pressure;
	};
	std::deque<Stroke> strokes;

public:
	void Create(EditorComponent* editor);

	EditorComponent* editor = nullptr;

	wi::gui::ComboBox modeComboBox;
	wi::gui::Label infoLabel;
	wi::gui::Slider radiusSlider;
	wi::gui::Slider amountSlider;
	wi::gui::Slider smoothnessSlider;
	wi::gui::Slider spacingSlider;
	wi::gui::Slider rotationSlider;
	wi::gui::Slider stabilizerSlider;
	wi::gui::CheckBox backfaceCheckBox;
	wi::gui::CheckBox wireCheckBox;
	wi::gui::CheckBox pressureCheckBox;
	wi::gui::ColorPicker colorPicker;
	wi::gui::ComboBox textureSlotComboBox;
	wi::gui::ComboBox brushShapeComboBox;
	wi::gui::Button saveTextureButton;
	wi::gui::Button brushTextureButton;
	wi::gui::Button revealTextureButton;
	wi::gui::ComboBox axisCombo;

	void Update(float dt);
	void DrawBrush(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const;

	XMFLOAT2 pos = XMFLOAT2(0, 0);

	enum MODE
	{
		MODE_DISABLED,
		MODE_TEXTURE,
		MODE_VERTEXCOLOR,
		MODE_SCULPTING_ADD,
		MODE_SCULPTING_SUBTRACT,
		MODE_SOFTBODY_PINNING,
		MODE_SOFTBODY_PHYSICS,
		MODE_HAIRPARTICLE_ADD_TRIANGLE,
		MODE_HAIRPARTICLE_REMOVE_TRIANGLE,
		MODE_HAIRPARTICLE_LENGTH,
		MODE_WIND,
	};
	MODE GetMode() const;

	enum class AxisLock
	{
		Disabled,
		X,
		Y,
		Z
	};

	wi::Archive* currentHistory = nullptr;
	void RecordHistory(bool start, wi::graphics::CommandList cmd = wi::graphics::CommandList());
	void ConsumeHistoryOperation(wi::Archive& archive, bool undo);

	void ResizeLayout() override;
};


text:
package org.broadinstitute.hellbender.engine;

import org.broadinstitute.hellbender.engine.filters.ReadFilterLibrary;
import org.broadinstitute.hellbender.engine.filters.ReadNameReadFilter;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.broadinstitute.hellbender.utils.Utils;
import org.broadinstitute.hellbender.utils.read.GATKRead;
import org.broadinstitute.hellbender.utils.io.IOUtils;
import org.broadinstitute.hellbender.GATKBaseTest;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public final class ReadsContextUnitTest extends GATKBaseTest {

    @DataProvider(name = "EmptyReadsContextDataProvider")
    public Object[][] getEmptyReadsContextData() {
        // Default-constructed ReadsContexts and ReadsContexts constructed from null ReadsDataSources/intervals
        // should behave as empty context objects.
        return new Object[][] {
                { new ReadsContext() },
                { new ReadsContext(null, null, null) },
                { new ReadsContext(null, new SimpleInterval("1", 1, 1), null ) },
                { new ReadsContext(new ReadsPathDataSource(IOUtils.getPath(publicTestDir + "org/broadinstitute/hellbender/engine/reads_data_source_test1.bam")), null) }
        };
    }

    @Test(dataProvider = "EmptyReadsContextDataProvider")
    public void testEmptyReadsContext( final ReadsContext readsContext ) {
        Assert.assertFalse(readsContext.hasBackingDataSource() && readsContext.getInterval() != null,
                           "Empty ReadsContext reports having both a backing data source and an interval");
        Assert.assertFalse(readsContext.iterator().hasNext(), "Empty ReadsContext should have returned an empty iterator from iterator()");
    }

    @DataProvider(name = "ReadsContextFilteringDataProvider")
    public Object[][] getValidReadsContextData() {
        // Default-constructed ReadsContexts and ReadsContexts constructed from null ReadsDataSources/intervals
        // should behave as empty context objects.
        ReadNameReadFilter readNameFilter = new ReadNameReadFilter();
        readNameFilter.readName = "d";
        return new Object[][]{
                {new ReadsContext(
                        new ReadsPathDataSource(IOUtils.getPath(publicTestDir + "org/broadinstitute/hellbender/engine/reads_data_source_test1.bam")),
                        new SimpleInterval("1", 200, 210), // query over small interval, with no read filter
                        ReadFilterLibrary.ALLOW_ALL_READS), new String[] { "a", "b", "c" },
                },
                {new ReadsContext(
                        new ReadsPathDataSource(IOUtils.getPath(publicTestDir + "org/broadinstitute/hellbender/engine/reads_data_source_test1.bam")),
                        new SimpleInterval("1", 200, 1000), // query over larger interval with readNameFilter on "d"
                        readNameFilter), new String[] { "d" }
                }
        };
    }

    @Test(dataProvider = "ReadsContextFilteringDataProvider")
    public void testReadsContextFiltering(final ReadsContext readsContext, String[] expectedReads ) {
        Assert.assertTrue(readsContext.hasBackingDataSource() && readsContext.getInterval() != null,
                "Valid ReadsContext reports having no backing data source or interval");
        Iterator<GATKRead> it = readsContext.iterator();
        while (it.hasNext()) {
            Assert.assertTrue(Arrays.asList(expectedReads).contains(it.next().getName()));
        }
    }

    @Test
    public void testIteratorOverDifferentInterval() {
        final ReadsDataSource readsDataSource = new ReadsPathDataSource(IOUtils.getPath(publicTestDir + "org/broadinstitute/hellbender/engine/reads_data_source_test1.bam"));
        final SimpleInterval originalInterval = new SimpleInterval("1", 200, 210);
        final ReadsContext readsContext = new ReadsContext(readsDataSource, originalInterval, ReadFilterLibrary.ALLOW_ALL_READS);
        final SimpleInterval otherInterval = new SimpleInterval("1", 276, 300);
        final List<String> readNames = Utils.stream(readsContext.iterator(otherInterval)).map(GATKRead::getName).collect(Collectors.toList());
        Assert.assertEquals(readNames, Arrays.asList("b", "c"));
    }

}


text:
package com.example.ruolan.cainiaogo.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

/**
 * Created by ruolan on 2015/11/14.
 */
public class JSONUtil {

    private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public static  Gson getGson(){
        return  gson;
    }

    public static <T> T fromJson(String json,Class<T> clz){

        return  gson.fromJson(json,clz);
    }

    public static <T> T fromJson(String json,Type type){

        return  gson.fromJson(json,type);
    }

    public static String toJSON(Object object){

        return gson.toJson(object);
    }

}


text:
package com.github.msoliter.iroh.tests;

/**
 * Exception while initializing com.github.msoliter.iroh.container.aspects.AutowiringAspect:
 *  com.github.msoliter.iroh.container.exceptions.DependencyCycleException:
 *      A dependency cycle was detected:
 *          class com.github.msoliter.iroh.tests.DependencyCycleTest$A =>
 *          class com.github.msoliter.iroh.tests.DependencyCycleTest$B =>
 *          class com.github.msoliter.iroh.tests.DependencyCycleTest$A.
 */
//public class DependencyCycleTest {
//
//    @Component
//    public static class A {
//
//        @Autowired
//        private B b;
//    }
//
//    @Component
//    public static class B {
//
//        @Autowired
//        private A a;
//    }
//
//    @Test
//    public void test() { }
//}


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

     Copyright 2005-2016 Red Hat, Inc.

     Red Hat licenses this file to you under the Apache License, version
     2.0 (the "License"); you may not use this file except in compliance
     with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
     implied.  See the License for the specific language governing
     permissions and limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>components</artifactId>
        <groupId>io.fabric8</groupId>
        <version>2.3-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gerrit-api</artifactId>
    <name>Fabric8 :: Gerrit :: API</name>

    <properties>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.fabric8</groupId>
            <artifactId>cxf-utils</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-jaxb-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
        </dependency>

        <dependency>
            <groupId>io.fabric8</groupId>
            <artifactId>gitrepo-api</artifactId>
        </dependency>
        <dependency>
            <groupId>io.fabric8</groupId>
            <artifactId>kubernetes-api</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

</project>


text:
The `mount` commands allow managing mounted substores. This is one of the
distinctive core features of `gopass` and we aim making working with substores
as seamless as possible.

Instead of support for encrypting different parts of a store for different
recipients we instead encourage users to mount different stores - each
encrypted to a uniform set of recipients - into a semless virtual tree structure.

This feature is modeled after standard POSIX mount semantics.

## Synopsis

```
$ gopass mounts
$ gopass mounts add mount/point /path/to/store
$ gopass mounts remove mount/point
```

## Modes of operation

* Add a new mount
* List existing mounts
* Remove an existing mount

## Creating new mounts

You can also create new mounts using `init` even if your store is already initialized:

```
gopass init --store mynewsubstore pgpkeyidentitfier
```

(You can also specify a specific local path using `--path`, just make sure to keep your PGP key identifier, e.g. its email or fingerprint, as the last argument.)


text:
/* global window, define, Uint8Array: false */
define(['./Stopwatch', './uuid'], function(Stopwatch, generateUUID) {

    'use strict';

    function firstDefined() {
        var args = [].slice.call(arguments),
            result = args.shift();
        while (args.length && result === undefined) {
            result = args.shift();
        }
        return result;
    }

    function getValue(params) {

        var args = [].slice.call(arguments),
            def = args.pop(),
            names = args.slice(1);

        return names.reduce(function (prev, name) {
            return firstDefined((params.data || {})[name], params[name], prev);
        }, def);

    }

    function clone(obj) {
        return Object.keys(obj).reduce(function copy(result, key) {
            return result[key] = obj[key], result;
        }, {});
    }

    /**
     * Encapsulates the tracking information provided by all
     * tracking sources into a single consistent schema for
     * consumption by collectors.
     * @class TrackingInfo
     * @param {Object} params An object whose properties will
     *  be examined to set properties on the TrackingInfo
     *  instance.
     * @example
     * var info = new TrackingInfo({
     *   type: 'event',
     *   action: 'click',
     *   label: 'custom label'
     * });
     */
    return function TrackingInfo(params) {

        if (!(this instanceof TrackingInfo)) {
            return new TrackingInfo(params);
        }

        /**
         * @member {Object} [TrackingInfo#data] Any optional data
         *  associated with the current instance.
         */
        this.data = clone(params.data || {});

        /**
         * @member {Array} [TrackingInfo#tags] Any optional strings
         *  to associate with the current instance.
         */
        this.tags = getValue(params, 'tags', []);

        /**
         * @member {Number} [TrackingInfo#count=1] Typically used to
         *  indicate the number of times an event,
         *  mark, or measure has been collected.
         */
        this.count = getValue(params, 'count', 1);

        /**
         * @member {String} [TrackingInfo#type="unknown"] The type
         *  of this instance. Built-in types include
         *  'event', 'timer', 'mark', 'measure',
         *  'network', 'context', 'metric', and
         *  'dimension'
         */
        this.type = getValue(params, 'type', 'unknown');

        /**
         * @member {String} [TrackingInfo#id] The unique id to associate
         *  with this instance. If not provided, a universally
         *  unique identifier will be generated automatically.
         */
        this.id = getValue(params, 'id', undefined) || generateUUID();

        /**
         * @member {Number} [TrackingInfo#start] The number of milliseconds since
         *  1/1/1970 before this instance was started. If not
         *  provided, defaults to the current date and time.
         */
        this.start = getValue(params, 'start', 'startTime', Stopwatch.now());

        /**
         * @member {Number} [TrackingInfo#stop] The number of milliseconds since
         *  1/1/1970 before this instance was stopped. If not
         *  provided, defaults to the start time.
         */
        this.stop = getValue(params, 'stop', 'stopTime', 'end', 'endTime', this.start);

        /**
         * @member {Number} [TrackingInfo#duration] The number of milliseconds
         *  between this instance's stop time and start time.
         */
        this.duration = this.stop - this.start;

        /**
         * @member {String} [TrackingInfo#label] The label to associate with
         *  this instance.
         */
        this.label = getValue(params, 'label', 'description', undefined);

        /**
         * @member {String} [TrackingInfo#action] The action to associate with
         *  this instance.
         */
        this.action = getValue(params, 'action', undefined);

        /**
         * @member {String} [TrackingInfo#category] The category to associate
         *  with this instance.
         */
        this.category = getValue(params, 'category', undefined);

        /**
         * @member {*} [TrackingInfo#variable] Some custom value to associate
         *  with this instance. Typically used in conjunction with
         *  data events to register some conditional state of the
         *  application (such as the number of options available
         *  to the user at a given decision point).
         */
        this.variable = getValue(params, 'variable', undefined);

        /**
         * @member {Array} [TrackingInfo#children] Contains any nested TrackingInfo
         *  instances. Timers and measures can both have children, but
         *  technically any custom data object with a `children` array
         *  will be attempted to be converted into TrackingInfo instances.
         */
        this.children = getValue(params, 'children', []).map(TrackingInfo);

        Object.keys(this).forEach(function(key) {
            delete this.data[key];
        }.bind(this));

        this.toString = function toString() {
            return 'TrackingInfo: ' + JSON.stringify(this, null, 2);
        };

        Object.freeze(this);

    };

});


text:
$.fn.Menu = function(options) {

    // Specify the default options for the menu plugin.
    var options = $.extend({
        Animate: true,
        AnimateDirection: "up",
        AnimateDirectionSubMenu: "left",
        DelayTime: 500,
        TransitionTime: 100
    }, options );

    // Get the object on which this is called.
    var object = $(this);

    Initialize();

    // Section: Functions.

        // Initialize the menu. This is done by placing classes on the various elements that together form the menu.
        // This is done to keep the HTML less cluthered.
        function Initialize() {
            $(".menucontents UL").addClass("OfficeUI_nowrap OfficeUI_nopadding OfficeUI_nomargin");
            $(".menu").addClass("OfficeUI_absolute");
        }

    // End of section: Functions.

    // Section: Event Handlers

        var waitHandle; // An object that is used to specify a delay.

        // Executed when you click on a menu entry.
        $("LI.menuEntry:not(.OfficeUI_disabled)").on("click", function(e) {
            e.stopPropagation();

            // Make sure to clear the timeout on the waithandle, otherwise, the menuitem might be showed twice.
            clearTimeout(waitHandle);

            // Check if the menuitem holds a submenu.
            if ($(".subMenuHolder", this).length > 0) {
                var element = $(this);

                transitionDirection = options.AnimateDirectionSubMenu;

                // Hide all the other open submenus.
                $(".menu", $(element).parent()).each(function() {
                    $(this).hide().parent().Deactivate();
                });

                // When the menu should be animated (specified in the options, animate it, otherwise just show it.)
                if (options.Animate) { $(".menu", element).first().show("slide", { direction: transitionDirection }, options.TransitionTime).Activate();
                } else { $(".menu", element).first().show(); }
            }
        });

        // Shows the submenu of a menuitem that's not disabled when hovering over it.
        $("LI.menuEntry:not(.OfficeUI_disabled)").on("mouseenter", function(e) {
            // Prevents the page from further execution.
            e.stopPropagation();

            // Sets the current transition direction. This variable is needed because it changes depending if it's a submenu or not.
            var transitionDirection = options.AnimateDirection;

            // Check if the menuitem holds a submenu.
            if ($(".subMenuHolder", this).length > 0) {
                var element = $(this);

                // Sets the direction of the transition.
                transitionDirection = options.AnimateDirectionSubMenu;

                // Specifies the function that should occur after the delay time has been passed.
                waitHandle = setTimeout(function() {

                    // Hide all the other open submenus.
                    $(".menu", $(element).parent()).each(function() {
                        $(this).hide().parent().Deactivate();
                    });

                    // When the menu should be animated (specified in the options, animate it, otherwise just show it.)
                    if (options.Animate) { $(".menu", element).first().show("slide", { direction: transitionDirection }, options.TransitionTime).Activate();
                    } else { $(".menu", element).first().show(); }

                }, options.DelayTime);
            } else {
                // The menuitem does not hold a submenu, which means that we can close all the other submenu items.
                $(".menu", $(this).parent()).each(function() {
                    $(this).hide().parent().Deactivate();
                });
            }
        });

        // When the cursor moves away from the menuitem, make sure to clear the timeout, otherwise, the menu on which your cursor was placed will still open.
        $("LI.menuEntry").on("mouseout", function(e) {
            clearTimeout(waitHandle);
        });

        // When you click anywhere on the document, make sure that all the menu's are hidden.
        $(document).on("click", function (e) {
            $(".menu").each(function() {
                $(this).hide().parent().Deactivate();
                $(this).data("state", 0);
            });
        });

    // End of section: Event Handlers.

    // Section: API Creation.

        // Create an API and return that one.
        return CreateMenuAPI();

        // Creates the ribbon API.
        function CreateMenuAPI() {
            return {
                Show: Show,
                Hide: Hide,
                OpenContextMenu : OpenContextMenu
            }
        }

        // Shows the menu entry on which it it called.
        function Show() {
            if (options.Animate) { object.show("slide", { direction: options.AnimateDirection }, options.TransitionTime).Activate(); } // Always shows the menu. Never hide it on a hover.
            else { object.show(); }
        }

        // Hides the menu on which it is called.
        function Hide() {
            object.hide();
        }

        // Open a context menu.
        // Parameters:
        //      e:      The page event.
        function OpenContextMenu(e) {
            // Prevent the page from further execution.
            e.preventDefault();

            //getting height and width of the message box
            var height = $(".contextMenuInArea").height();
            var width = $(".contextMenuInArea").width();

            //calculating offset for displaying popup message
            leftVal = e.pageX - (width / 2) + "px";
            topVal = e.pageY - (height / 2) + "px";

            //show the popup message and hide with fading effect
            if (options.Animate) { object.css({left:leftVal,top:topVal}).show("slide", { direction: options.AnimateDirection }, options.TransitionTime).Activate(); } // Always shows the menu. Never hide it on a hover.
            else { object.css({left:leftVal,top:topVal}).show(); }

            return false;
        }

    // End of section: API Creation.
}


text:
from swgpy.object import *

def create(kernel):
	result = Cell()

	result.template = "object/cell/shared_cell.iff"
	result.attribute_template_id = -1
	result.stfName("","")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
mergeInto(LibraryManager.library, {
  $PATH__deps: ['$FS'],
  $PATH: {
    // split a filename into [root, dir, basename, ext], unix version
    // 'root' is just a slash, or nothing.
    splitPath: function(filename) {
      var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
      return splitPathRe.exec(filename).slice(1);
    },
    normalizeArray: function(parts, allowAboveRoot) {
      // if the path tries to go above the root, `up` ends up > 0
      var up = 0;
      for (var i = parts.length - 1; i >= 0; i--) {
        var last = parts[i];
        if (last === '.') {
          parts.splice(i, 1);
        } else if (last === '..') {
          parts.splice(i, 1);
          up++;
        } else if (up) {
          parts.splice(i, 1);
          up--;
        }
      }
      // if the path is allowed to go above the root, restore leading ..s
      if (allowAboveRoot) {
        for (; up--; up) {
          parts.unshift('..');
        }
      }
      return parts;
    },
    normalize: function(path) {
      var isAbsolute = path.charAt(0) === '/',
          trailingSlash = path.substr(-1) === '/';
      // Normalize the path
      path = PATH.normalizeArray(path.split('/').filter(function(p) {
        return !!p;
      }), !isAbsolute).join('/');
      if (!path && !isAbsolute) {
        path = '.';
      }
      if (path && trailingSlash) {
        path += '/';
      }
      return (isAbsolute ? '/' : '') + path;
    },
    dirname: function(path) {
      var result = PATH.splitPath(path),
          root = result[0],
          dir = result[1];
      if (!root && !dir) {
        // No dirname whatsoever
        return '.';
      }
      if (dir) {
        // It has a dirname, strip trailing slash
        dir = dir.substr(0, dir.length - 1);
      }
      return root + dir;
    },
    basename: function(path) {
      // EMSCRIPTEN return '/'' for '/', not an empty string
      if (path === '/') return '/';
      var lastSlash = path.lastIndexOf('/');
      if (lastSlash === -1) return path;
      return path.substr(lastSlash+1);
    },
    extname: function(path) {
      return PATH.splitPath(path)[3];
    },
    join: function() {
      var paths = Array.prototype.slice.call(arguments, 0);
      return PATH.normalize(paths.join('/'));
    },
    join2: function(l, r) {
      return PATH.normalize(l + '/' + r);
    },
    resolve: function() {
      var resolvedPath = '',
        resolvedAbsolute = false;
      for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
        var path = (i >= 0) ? arguments[i] : FS.cwd();
        // Skip empty and invalid entries
        if (typeof path !== 'string') {
          throw new TypeError('Arguments to path.resolve must be strings');
        } else if (!path) {
          return ''; // an invalid portion invalidates the whole thing
        }
        resolvedPath = path + '/' + resolvedPath;
        resolvedAbsolute = path.charAt(0) === '/';
      }
      // At this point the path should be resolved to a full absolute path, but
      // handle relative paths to be safe (might happen when process.cwd() fails)
      resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
        return !!p;
      }), !resolvedAbsolute).join('/');
      return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
    },
    relative: function(from, to) {
      from = PATH.resolve(from).substr(1);
      to = PATH.resolve(to).substr(1);
      function trim(arr) {
        var start = 0;
        for (; start < arr.length; start++) {
          if (arr[start] !== '') break;
        }
        var end = arr.length - 1;
        for (; end >= 0; end--) {
          if (arr[end] !== '') break;
        }
        if (start > end) return [];
        return arr.slice(start, end - start + 1);
      }
      var fromParts = trim(from.split('/'));
      var toParts = trim(to.split('/'));
      var length = Math.min(fromParts.length, toParts.length);
      var samePartsLength = length;
      for (var i = 0; i < length; i++) {
        if (fromParts[i] !== toParts[i]) {
          samePartsLength = i;
          break;
        }
      }
      var outputParts = [];
      for (var i = samePartsLength; i < fromParts.length; i++) {
        outputParts.push('..');
      }
      outputParts = outputParts.concat(toParts.slice(samePartsLength));
      return outputParts.join('/');
    }
  }
});


text:
id: 174-Form-Decorators-Tutorial-posted
author: matthew
title: 'Form Decorators Tutorial posted'
draft: false
public: true
created: '2008-05-05T10:25:00-04:00'
updated: '2008-05-05T10:25:00-04:00'
tags:
    0: php
    2: 'zend framework'
---
As a continuing part of my MVC series, I've posted a new article on
[Form Decorators](http://devzone.zend.com/article/3450-Decorators-with-Zend_Form)
up on the DevZone.

I'm hoping this will be the definitive guide to using form decorators. I cover
the design decisions behind them, basics of operation, how to customize output
by mixing and matching standard decorators, and how to create your own custom
decorators. Among the examples are how to create a table-based layout for your
forms (instead of the dynamic list layout used by default), and how to use a
View Script as your form decorator in order to have full control over your form
layout.

So, if you've been playing with `Zend_Form` and having trouble wrapping your
head around decorators, [give it a read](http://devzone.zend.com/article/3450-Decorators-with-Zend_Form)!


text:
require 'test/unit'

require 'rubygems'
require 'active_support'
require 'action_controller'
# require 'action_controller/test_process'
require 'action_view'
require 'action_view/helpers'
require 'action_view/helpers/tag_helper'
require 'i18n'
require 'formtastic'

require 'localized_language_select'

class LocalizedLanguageSelectTest < Test::Unit::TestCase

  include ActionView::Helpers::FormOptionsHelper
  include ActionView::Helpers::TagHelper

  def test_action_view_should_include_helper_for_object
    assert ActionView::Helpers::FormBuilder.instance_methods.include?(:localized_language_select)
    assert ActionView::Helpers::FormOptionsHelper.instance_methods.include?(:localized_language_select)
  end

  def test_action_view_should_include_helper_tag
    assert ActionView::Helpers::FormOptionsHelper.instance_methods.include?(:localized_language_select_tag)
  end

  def test_should_return_select_tag_with_proper_name_for_object
    assert localized_language_select(:user, :language) =~
              Regexp.new(Regexp.escape('<select id="user_language" name="user[language]">')),
              "Should have proper name for object"
  end

  def test_should_return_select_tag_with_proper_name
    assert localized_language_select_tag( "competition_submission[data][language]", nil) =~
              Regexp.new(
              Regexp.escape('<select id="competition_submission[data][language]" name="competition_submission[data][language]">') ),
              "Should have proper name"
  end

  def test_should_return_option_tags
    assert localized_language_select(:user, :language) =~ Regexp.new(Regexp.escape('<option value="es">Spanish</option>'))
  end

  def test_should_return_localized_option_tags
    I18n.locale = 'fr'
    assert localized_language_select(:user, :language) =~ Regexp.new(Regexp.escape('<option value="es">espagnol</option>'))
  end

  def test_should_return_localized_country_option_tags
    I18n.locale = 'fr'
    assert localized_language_select(:user, :language) =~ Regexp.new(Regexp.escape('<option value="es-ES">espagnol ibérique</option>'))
  end

  def test_should_return_priority_languages_first
    # Once with symbols, and once with strings
    [ [ :es, :fr, :"nl-BE" ], [ "es", "fr", "nl-BE" ] ].each do |langs|
      assert localized_language_options_for_select(nil, langs) =~ Regexp.new(
        Regexp.escape("<option value=\"es\">Spanish</option>\n<option value=\"fr\">French</option>\n<option value=\"nl-BE\">Flemish</option><option value=\"\" disabled=\"disabled\">-------------</option>\n<option value=\"ab\">Abkhazian</option>\n"))
    end
  end

  def test_i18n_should_know_about_languages
    assert_equal 'Spanish', I18n.t('es', :scope => 'languages')
    I18n.locale = 'fr'
    assert_equal 'espagnol', I18n.t('es', :scope => 'languages')
  end

  def test_localized_languages_array_returns_correctly
    assert_nothing_raised { LocalizedLanguageSelect::localized_languages_array() }
    I18n.locale = 'en'
    assert_equal 504, LocalizedLanguageSelect::localized_languages_array.size
    assert_equal 'Abkhazian', LocalizedLanguageSelect::localized_languages_array.first[0]
    I18n.locale = 'fr'
    assert_equal 503, LocalizedLanguageSelect::localized_languages_array.size
    assert_equal 'abkhaze', LocalizedLanguageSelect::localized_languages_array.first[0]
  end

  def test_priority_languages_returns_correctly_and_in_correct_order
    assert_nothing_raised { LocalizedLanguageSelect::priority_languages_array([:nl, :fr]) }
    I18n.locale = 'en'
    assert_equal [ ['Dutch', 'nl'], ['French', 'fr'] ], LocalizedLanguageSelect::priority_languages_array([:nl, :fr])
  end

  def test_include_country_rejects_on_except_option
    assert !LocalizedLanguageSelect::include_language?('af', :except => ['af'])
    assert LocalizedLanguageSelect::include_language?('ad', :except => ['af'])
  end

  def test_include_country_accept_on_only_option
    assert LocalizedLanguageSelect::include_language?('af', :only => ['af'])
    assert !LocalizedLanguageSelect::include_language?('af', :only => ['ad'])
  end

  def test_localized_countries_array_rejects_on_except_option
    list = LocalizedLanguageSelect::localized_languages_array(:except => ['af'])
    assert !list.include?(['Afrikaans', 'af'])
  end

  def test_formtastic_input_is_defined
    assert Formtastic::Inputs.constants.include?(:LanguageInput)
  end

  # private

  def setup
    ['fr', 'en'].each do |locale|
      # I18n.load_translations( File.join(File.dirname(__FILE__), '..', 'locale', "#{locale}.rb")  )  # <-- Old style! :)
      I18n.load_path += Dir[ File.join(File.dirname(__FILE__), '..', 'locale', "#{locale}.{rb,yml}") ]
    end
    I18n.locale = 'en'
  end

end


text:
package net.bytebuddy.instrumentation.method.bytecode.stack.member;

import net.bytebuddy.instrumentation.Instrumentation;
import net.bytebuddy.instrumentation.field.FieldDescription;
import net.bytebuddy.instrumentation.method.bytecode.stack.StackManipulation;
import net.bytebuddy.instrumentation.method.bytecode.stack.StackSize;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * An access representation to a given field.
 */
public enum FieldAccess {

    /**
     * The representation of field access to a static field.
     */
    STATIC(Opcodes.PUTSTATIC, Opcodes.GETSTATIC, StackSize.ZERO),

    /**
     * The representation of field access to an instance field.
     */
    INSTANCE(Opcodes.PUTFIELD, Opcodes.GETFIELD, StackSize.SINGLE);

    /**
     * The opcode for setting a field value.
     */
    private final int putterOpcode;

    /**
     * The opcode for getting a field value.
     */
    private final int getterOpcode;

    /**
     * The amount of operand slots this field access operation consumes when it is applied before eventually
     * adding new values onto the operand stack.
     */
    private final int targetSizeChange;

    /**
     * Creates a new field access.
     *
     * @param putterOpcode     The opcode for setting a field value.
     * @param getterOpcode     The opcode for getting a field value.
     * @param targetSizeChange The amount of operand slots this field access operation consumes when it is applied
     *                         before eventually adding new values onto the operand stack.
     */
    FieldAccess(int putterOpcode, int getterOpcode, StackSize targetSizeChange) {
        this.putterOpcode = putterOpcode;
        this.getterOpcode = getterOpcode;
        this.targetSizeChange = targetSizeChange.getSize();
    }

    /**
     * Creates a field access representation for a given field.
     *
     * @param fieldDescription The field to be accessed.
     * @return A field access definition for the given field.
     */
    public static Defined forField(FieldDescription fieldDescription) {
        if (fieldDescription.isStatic()) {
            return STATIC.new AccessDispatcher(fieldDescription);
        } else {
            return INSTANCE.new AccessDispatcher(fieldDescription);
        }
    }

    @Override
    public String toString() {
        return "FieldAccess." + name();
    }

    /**
     * Representation of a field access for which a getter and a putter can be created.
     */
    public interface Defined {

        /**
         * Creates a getter representation for a given field.
         *
         * @return A stack manipulation representing the retrieval of a field value.
         */
        StackManipulation getter();

        /**
         * Creates a putter representation for a given field.
         *
         * @return A stack manipulation representing the setting of a field value.
         */
        StackManipulation putter();

        /**
         * Returns the field for which this field access is defined for.
         *
         * @return The field for which this field access was defined for.
         */
        FieldDescription getDefinedField();
    }

    /**
     * A dispatcher for implementing a read or write access on a field.
     */
    protected class AccessDispatcher implements Defined {

        /**
         * A description of the accessed field.
         */
        private final FieldDescription fieldDescription;

        /**
         * Creates a new access dispatcher.
         *
         * @param fieldDescription A description of the accessed field.
         */
        protected AccessDispatcher(FieldDescription fieldDescription) {
            this.fieldDescription = fieldDescription;
        }

        @Override
        public StackManipulation getter() {
            return new FieldGetInstruction();
        }

        @Override
        public StackManipulation putter() {
            return new FieldPutInstruction();
        }

        @Override
        public FieldDescription getDefinedField() {
            return fieldDescription;
        }

        @Override
        public boolean equals(Object other) {
            return this == other || !(other == null || getClass() != other.getClass())
                    && FieldAccess.this.equals(((AccessDispatcher) other).getFieldAccess())
                    && fieldDescription.equals(((AccessDispatcher) other).fieldDescription);
        }

        @Override
        public int hashCode() {
            return fieldDescription.hashCode() + 31 * FieldAccess.this.hashCode();
        }

        @Override
        public String toString() {
            return "FieldAccess.AccessDispatcher{" +
                    "fieldAccess=" + FieldAccess.this +
                    ", fieldDescription=" + fieldDescription +
                    '}';
        }

        /**
         * Returns the outer instance.
         *
         * @return The outer instance.
         */
        private FieldAccess getFieldAccess() {
            return FieldAccess.this;
        }

        /**
         * An abstract base implementation for accessing a field value.
         */
        private abstract class AbstractFieldInstruction implements StackManipulation {

            @Override
            public boolean isValid() {
                return true;
            }

            @Override
            public Size apply(MethodVisitor methodVisitor, Instrumentation.Context instrumentationContext) {
                methodVisitor.visitFieldInsn(getOpcode(),
                        fieldDescription.getDeclaringType().getInternalName(),
                        fieldDescription.getInternalName(),
                        fieldDescription.getDescriptor());
                return resolveSize(fieldDescription.getFieldType().getStackSize());
            }

            /**
             * Returns the opcode for implementing the field access.
             *
             * @return The opcode for implementing the field access.
             */
            protected abstract int getOpcode();

            /**
             * Resolves the actual size of this field access operation.
             *
             * @param fieldSize The size of the accessed field.
             * @return The size of the field access operation based on the field's size.
             */
            protected abstract Size resolveSize(StackSize fieldSize);
        }

        /**
         * A reading field access operation.
         */
        protected class FieldGetInstruction extends AbstractFieldInstruction {

            @Override
            protected int getOpcode() {
                return getterOpcode;
            }

            @Override
            protected Size resolveSize(StackSize fieldSize) {
                int sizeChange = fieldSize.getSize() - targetSizeChange;
                return new Size(sizeChange, sizeChange);
            }

            @Override
            public boolean equals(Object other) {
                return this == other || !(other == null || getClass() != other.getClass())
                        && getAccessDispatcher().equals(((FieldGetInstruction) other).getAccessDispatcher());
            }

            @Override
            public int hashCode() {
                return getAccessDispatcher().hashCode() + 7;
            }

            @Override
            public String toString() {
                return "FieldAccess.AccessDispatcher.FieldGetInstruction{fieldDescription=" + fieldDescription + '}';
            }

            /**
             * Returns the outer instance.
             *
             * @return The outer instance.
             */
            private AccessDispatcher getAccessDispatcher() {
                return AccessDispatcher.this;
            }
        }

        /**
         * A writing field access operation.
         */
        protected class FieldPutInstruction extends AbstractFieldInstruction {

            @Override
            protected int getOpcode() {
                return putterOpcode;
            }

            @Override
            protected Size resolveSize(StackSize fieldSize) {
                return new Size(-1 * (fieldSize.getSize() + targetSizeChange), 0);
            }

            @Override
            public boolean equals(Object other) {
                return this == other || !(other == null || getClass() != other.getClass())
                        && getAccessDispatcher().equals(((FieldPutInstruction) other).getAccessDispatcher());
            }

            @Override
            public int hashCode() {
                return getAccessDispatcher().hashCode() + 14;
            }

            @Override
            public String toString() {
                return "FieldAccess.AccessDispatcher.FieldPutInstruction{fieldDescription=" + fieldDescription + '}';
            }

            /**
             * Returns the outer instance.
             *
             * @return The outer instance.
             */
            private AccessDispatcher getAccessDispatcher() {
                return AccessDispatcher.this;
            }
        }
    }
}


text:
goog.provide('p3rf.perfkit.explorer.models.perfkit_simple_builder.PicklistModel');

goog.scope(function() {
const explorer = p3rf.perfkit.explorer;

/**
 * @constructor
 */
explorer.models.perfkit_simple_builder.PicklistModel =
    function() {
  /** @type {Array.<string>} */
  this.items = [];
};
const PicklistModel = explorer.models.perfkit_simple_builder.PicklistModel;

});  // goog.scope


text:
\documentclass[11pt,letterpaper,en-US]{article}

\usepackage{basicstyle}

\title{CS6378 Advanced Operating System Project 2 \\Design Document}

\author{Hanlin He (hxh160630)}

\begin{document}
\maketitle

\section{Introduction}
This document describes the development process of the project.
It generally consists of six parts:
requirement analysis,
use cases,
domain model,
class diagram,
communication protocol design
and program output.

\section{Requirement}
\begin{enumerate}
    \item The system should consists of 7 data servers
        and 5 clients.
    \item Clients should be able to store content on servers,
        and each content should have 3 replica on 3 different servers.
        Each content should have a distinct ID.
    \item The system should provide a hash function so that
        a content with certain ID will always be store on 3
        specific servers.
    \item A client should be able to randomly choose any of the
        three replicas of an object when it wishes to read the
        value of the object.
        If a client tries to read an object that is not present,
        the operation should return with an error code.
    \item When a client wishes to update/insert an object into
        the data repository, it should be able to successfully
        perform the operation on at least two, and if possible
        all the three servers that are required to store the object.
    \item If a client is unable to access at least two out of the
        three servers that are required to store an object, then
        the client does not perform updates to any replica of
        that object.
    \item If two or more clients try to concurrently write to
        the same object and at least two replicas are available,
        the writes must be performed in the same order at all
        the replicas of the object.
\end{enumerate}

\section{Use Cases}
\subsection{Use Case Diagram}
First, consider the system as a black box,
in user's perspective, there are only two scenarios: read and write in the system.
The use case diagram is shown in \cref{ucdori}
\begin{figure}[!htb]
    \caption{Use Case Diagram Consider the System as Black Box}
    \label{ucdori}
    \centering
    \includegraphics[width = 0.6\textwidth]{usecaseori}
\end{figure}

Furthermore, if we divide the system into server and client,
the client is the representative of the system in user's view, i.e.
the black box in previous diagram.
Now consider the server as a black box and client as the user.
The scenarios remain the same.

\subsection{Use Case Text}
\subsubsection{Use Case: Write Object}
\begin{tabularx}{\textwidth}{>{\bfseries}lX}
    Use Case Name: & Write Content\\
    Scope: & Distributed Storage System\\
    Level: & User Goal\\
    Actors: & User\\
    Stakeholders: & User - Specify content ID,\\
                  & System - Correctly store the content. \\
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
    \textbf{Main Flow (Success)}
    \begin{enumerate}[label={\arabic*.}]
        \item The system indicates that it's ready to accept command.
        \item The user enters the write command, specifying the target
            server, the content id and the value to be written.
        \item The system displays the write success message.
        \item Repeat 2-3 until the user terminate the program.
        \item The use case ends successfully.
    \end{enumerate}
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
    \textbf{Extensions}
    \begin{itemize}
        \item[*a.] At any time, user exit the system.
            \begin{enumerate}[label={\arabic*.}]
                \item The system goes back to the process, waiting for user to operate.
            \end{enumerate}
    \end{itemize}
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
    \textbf{Alternate Flow - More than one server unavailable, write operation fail.}
    \begin{itemize}
        \item[3a.] The system display a write error message and wait for user next command.
    \end{itemize}
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
\textbf{Post Conditions (Success Guarantee)}\\
\textbf{Successful Completion} \\
\qquad The system correctly store the content on at least two server.\\
\textbf{Failure Condition} \\
\qquad The system store the content on only one server, or the values of three replicas on each normal server is different.\\
\end{tabularx}

\subsubsection{Use Case: Read Object}
\begin{tabularx}{\textwidth}{>{\bfseries}lX}
    Use Case Name: & Read Content\\
    Scope: & Distributed Storage System\\
    Level: & User Goal\\
    Actors: & User\\
    Stakeholders: & User - Specify content ID
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
    \textbf{Main Flow (Success)}
    \begin{enumerate}[label={\arabic*.}]
        \item The system indicates that it's ready to accept command.
        \item The user enters the read command, specifying the target server,
            and the content ID.
        \item The system displays the value of the content.
        \item Repeat 2-3 until the user terminate the program.
        \item The use case ends successfully.
    \end{enumerate}
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
    \textbf{Extensions}
    \begin{itemize}
        \item[*a.] At any time, user exit the system.
            \begin{enumerate}[label={\arabic*.}]
                \item The system goes back to the process, waiting for user to operate.
            \end{enumerate}
    \end{itemize}
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
    \textbf{Alternate Flow - The selected server is not working.}
    \begin{itemize}
        \item[3a.] The system display a read error message and wait for user next command.
    \end{itemize}
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
    \textbf{Alternate Flow - The selected content does not exist on server.}
    \begin{itemize}
        \item[3a.] The system display a read error message and wait for user next command.
    \end{itemize}
\end{tabularx}\\
\begin{tabularx}{\textwidth}{X}
\textbf{Post Conditions (Success Guarantee)}\\
\textbf{Successful Completion} \\
\qquad The system correctly retrieve the content on server.\\
\textbf{Failure Condition} \\
\qquad The system fail to retrieve the value of specifies content.
\end{tabularx}

\section{Domain Model}
Based on use cases, we can identify the following concept.
\begin{itemize}
    \item Host.
    \item Client.
    \item Server.
    \item VectorTime.
    \item Message.
    \item Content.
\end{itemize}
The corresponding domain model is shown if \cref{domainm}.

\begin{figure}[h]
    \caption{Domain Model}\label{domainm}
    \centering
    \includegraphics[width=.6\textwidth]{domainmodel}
\end{figure}

The system sequence diagram is basically the same as use case text, so the document will not cover it.

\section{Class Diagram and Specification}
Furthermore analyze the domain model, I derived the class diagram for the system as shown in \cref{classdia}.

\begin{figure}[!hb]
    \caption{Class Diagram}\label{classdia}
    \centering
    \includegraphics[width=\textwidth]{classdiagram}
\end{figure}

\subsubsection*{Some Specification about the Class Diagram}
\begin{itemize}
    \item \emph{HostConfiguration} class is the configuration read from the file,
        indicating which host with specific acting as client or server,
        and its corresponding working mode.
    \item \emph{Client} the \emph{Server} are basically the specialization of class \emph{Host},
        inheriting the identity variable \emph{id} and configuration \emph{hostConfiguration}.
    \item \emph{VectorTime} is to implement vector clock. It helped to implement the
        ordering of concurrently writing operation.
    \item \emph{StoredContent} is used to represent the object in storage. It uses an
        integer value as key and another integer as value.
    \item \emph{Message} object is data being transfer among the network. Its type reflects
        the operation of the sender. If a message was sent from a client, it would not
        carry the vector timestamp since client does not have that. On the other hand,
        when the message is from a server, it carries the vector timestamp so that the
        other servers may know the causal relation of each message.
\end{itemize}

More detailed information about different message types will be talked about in next chapter.

\section{Inter-Server and Communication Protocol}
\subsection{Inter-Server Sychronization}
There are two choices for selecting the coordinator of the write operation in the system:
\begin{itemize}
    \item The client directly informs three server about the write operation.
        The three server is the quorum for a client.
    \item The client only informs one server about the write operation,
        and let the servers themselves to synchronize.
\end{itemize}
Based on Amazon's Dynamo\cite{amazon1}, the second approach is adopted in this project,
since it guarantee the concurrent write operations of the same content on all servers.

\subsection{Communication Protocol}
The core component of this project is a well-defined communication protocol\cite{liang1}.
The messge type used in this project is list in \cref{mtype}:

\begin{table}[H]
    \caption{Message Type}\label{mtype}
    \centering
    \begin{tabularx}{\textwidth}{>{\ttfamily}lllX}\hline
        \textnormal{Message Type} & From & To & Specification \\\hline
        \detokenize{client_put} & Client & Server & Client specifies the content and its value to update/insert. \\\hline
        \detokenize{client_put_ack} & Server & Client & Server acknowledge the success of write operation. \\\hline
        \detokenize{client_put_fail} & Server & Client & Server informs the client about the failure of write operation. \\\hline
        \detokenize{client_get} & Client & Server & Client specify the content value to be retrieved. \\\hline
        \detokenize{client_get_ack} & Server & Client & Server send the acknowledgment together with the wanted content value. \\\hline
        \detokenize{server_put} & Server & Server & Server informs other servers to commit changes. \\\hline
        \detokenize{server_put_ack} & Server & Server &  Server acknowledge the success of commit operation to the source server. \\\hline
        \detokenize{server_put_req} & Server & Server & Server requests other servers to write a content. \\\hline
        \detokenize{server_put_req_ack} & Server & Server & Server acknowledge that it is ready to write the specific content. \\\hline
        \detokenize{server_put_fai}l & Server & Server & Server informs the source server about the failure of write operation. \\\hline
        \detokenize{server_put_end} & Server & Server & Server informs the target server to close the socket connection. \\\hline
        \detokenize{server_unavailable} & Server & Client & Server informs the client that it is unavailable. \\\hline
    \end{tabularx}
\end{table}

\section{Program Output}
To test the program, I furthermore implemented an automated client to automatically
generate write operation of random content ID ranging from 0 to 9 and value ranging from 0 to 999.

To start the program run the following command on the specific server.

\begin{alltt}
    java Main <Host ID>
\end{alltt}

Upon start, the program would read the configuration file ``all\_nodes.cfg'' in the local directory.
I used the following configuration file:
\begin{alltt}
    7 5
    0 127.0.0.1 20000 0
    1 127.0.0.1 20100 0
    2 127.0.0.1 20200 0
    3 127.0.0.1 20300 0
    4 127.0.0.1 20400 0
    5 127.0.0.1 20500 0
    6 127.0.0.1 20600 0
    7 127.0.0.1 20700 1
    8 127.0.0.1 20800 2
    9 127.0.0.1 20900 2
    10 127.0.0.1 20100 2
    11 127.0.0.1 20110 2
\end{alltt}

The first line indicates the number of server/client in the system (7 servers \& 5 clients).
The following lines indicate the configuration for each host as
\begin{alltt}
    <Host ID> <Host IP> <Host Port as server> <Host Mode>
\end{alltt}
Note that, Host Mode \textbf{0} indicated the host would act as server,
Host Mode \textbf{1} indicated the host would act as normal client,
and Host Mode \textbf{2} indicated the host would act as automated client.

In normal client mode, the command is as follow:
\begin{alltt}
    <Server Choice> <Operation> <Content ID> [New Content Value]
\end{alltt}

The \texttt{Server Choice} could be \emph{a,b,c}, client can choose whichever it want.

The \texttt{Operation} could be \emph{put/get}, if the operation is get, the last parameter
\texttt{New Content Value} is optional.

Based on the configuration, the host 7 is the normal client, so I take the following screen script from host 7.

In the third \texttt{b get 1} command, I typed ``offline'' at server 2, thus the result of \texttt{b get 1} is ``Server Unavailable'',
and the result of \texttt{c put 1 20} is ``Set content 1 as 20 . Result: Success'', since there are still two server available.
And after I set both server 1 and 2 ``offline'', the last \texttt{c put 1 30} command ``Fail'', as there is less than two available server.

\begin{alltt}
> java Main 7
Client start.
Establishing connection to
    Server 0:127.0.0.1:20000... Done.
    Server 1:127.0.0.1:20100... Done.
    Server 2:127.0.0.1:20200... Done.
    Server 3:127.0.0.1:20300... Done.
    Server 4:127.0.0.1:20400... Done.
    Server 5:127.0.0.1:20500... Done.
    Server 6:127.0.0.1:20600... Done.
> a get 1
Content Not exist.
> a put 1 10
Set content 1 as 10 . Result: Success
> b get 1
10
> c put 1 20
Set content 1 as 20 . Result: Success
> b get 1
20
## entering ``offline'' at server 2
> b get 1
Server Unavailable.
> c put 1 20
Set content 1 as 20 . Result: Success
## entering ``offline'' at server 1 and 2
> c put 1 30
Set content 1 as 30 . Result: Fail
\end{alltt}

The server would record a log file at home directory as follow:
\begin{footnotesize}
\begin{alltt}
Content 6 was modified from null    to 320      by node 0   at 2017-03-30 23:07:59.450
Content 1 was modified from null    to 576      by node 2   at 2017-03-30 23:08:00.071
Content 1 was modified from 576     to 10       by node 7   at 2017-03-30 23:08:02.073
\end{alltt}
\end{footnotesize}

\pagebreak
\begin{thebibliography}{2}
\bibitem{amazon1}
  Giuseppe DeCandia, Deniz Hastorun, Madan Jampani, Gunavardhan Kakulapati, Avinash Lakshman, Alex Pilchin, Swaminathan Sivasubramanian, Peter Vosshall and Werner Vogels,
  \emph{Dynamo: Amazon's Highly Available Key-value Store}
  Amazon.com.
\bibitem{liang1}
  Jun Liang(https://github.com/JunLiang), Xue Ning,
  \emph{Design},
  Github, 2014.
\end{thebibliography}
\end{document}


text:
class Tweet < ActiveRecord::Base
	belongs_to :trend
	belongs_to :country
	before_create :set_country

	def analyze_sentiment
		results = AlchemyAPI.search(:sentiment_analysis, :text => self.text.delete("#").delete("&")) || { type: "neutral", score: 0.0 }
		self.update_attributes(sentiment: results["type"] || "neutral",
													 sentiment_score: results["score"] || 0.0)
	end

	private

	def set_country
		self.country = Country.find_or_create_by(country_code: self.country_code)
	end
end


text:
<?php
namespace Mouf\Utils\Common;

/**
 * This interface is implemented by any object that represent dataset that can be paginated.
 * An object implementing this interface will expose a "paginate($limit, $offset)" method.
 *
 * @author David Négrier
 */
interface PaginableInterface {

	/**
	 * Paginates the result set.
	 *
	 * @param int $limit
	 * @param int $offset
	 */
	public function paginate($limit, $offset = 0);
}


text:
<bill session="110" type="h" number="1271" updated="2009-01-08T19:29:42-05:00">
	<status><introduced date="1172725200" datetime="2007-03-01"/></status>

	<introduced date="1172725200" datetime="2007-03-01"/>
	<titles>
		<title type="official" as="introduced">To amend title 5, United States Code, to make creditable for civil service retirement purposes certain periods of service performed with Air America, Incorporated, Air Asia Company Limited, or the Pacific Division of Southern Air Transport, Incorporated, while those entities were owned or controlled by the Government of the United States and operated or managed by the Central Intelligence Agency.</title>
	</titles>
	<sponsor id="400024"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1172725200" datetime="2007-03-01"><text>Referred to the House Committee on Oversight and Government Reform.</text></action>
		<action date="1174968000" datetime="2007-03-27"><text>Referred to the Subcommittee on Federal Workforce, Post Office, and the District of Columbia.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	3/1/2007--Introduced.
Makes creditable for civil service retirement purposes pre-1977 service performed by a U.S. citizen with Air America, Incorporated, Air Asia Company Limited, or the Pacific Division of Southern Air Transport, Incorporated, while those entities were owned or controlled by the U.S. Government and operated or managed by the Central Intelligence Agency (CIA).

</bill>


text:
module Spree
  module ControllerHacks
    def get(action, parameters = nil, session = nil, flash = nil)
      process_spree_action(action, parameters, session, flash, "GET")
    end

    # Executes a request simulating POST HTTP method and set/volley the response
    def post(action, parameters = nil, session = nil, flash = nil)
      process_spree_action(action, parameters, session, flash, "POST")
    end

    # Executes a request simulating PUT HTTP method and set/volley the response
    def put(action, parameters = nil, session = nil, flash = nil)
      process_spree_action(action, parameters, session, flash, "PUT")
    end

    # Executes a request simulating DELETE HTTP method and set/volley the response
    def delete(action, parameters = nil, session = nil, flash = nil)
      process_spree_action(action, parameters, session, flash, "DELETE")
    end

    private

    def process_spree_action(action, parameters = nil, session = nil, flash = nil, method = "GET")
      parameters ||= {}
      process(action, parameters.merge!(:use_route => :spree), session, flash, method)
    end
  end
end

RSpec.configure do |c|
  c.include Spree::ControllerHacks, :type => :controller
end


text:
#ifndef __CONFIG_H
#define __CONFIG_H

#include <linux/sizes.h>
#include <configs/rk3036_common.h>

#ifndef CONFIG_SPL_BUILD

/* Store env in emmc */
#define CONFIG_SYS_MMC_ENV_DEV		0 /* emmc */
#define CONFIG_SYS_MMC_ENV_PART		0 /* user area */

#endif

#endif


text:
<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="description" content="Simple HTML and Javascript Editor.">
      <meta name="keywords" content="HTML,Javascript,editor">
      <meta name="author" content="Omar El Sayyed">
      <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

      <title>Simple HTML and Javascript Editor</title>

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