text:
Better-Than-tit-for-tat
=======================

A small piece of matlab code that aims at reproducing the results of Nowak and Sigmund's Nature 1993 paper [A strategy of win-stay, lose-shift that outperforms tit-for-tat in the Prisoner's Dilemma game](http://abel.math.harvard.edu/archive/153_fall_04/Additional_reading_material/A_strategy_of_winstay_loseshift_that_out_performs_titfortat_in_the_Prisoners_Dilemma_game.pdf.pdf).

The surprising result is that a simple strategy called Pavlov (due to the work of Ivan Pavlov on [classical conditioning](http://en.wikipedia.org/wiki/Classical_conditioning)), fares better population-wise than tit-for-tat, whose success in Axelrod's Tournaments received widespread attention.

The code reproduces the main figure of the paper, which shows Pavlov outperforming tit-for-tat in the long run:

![Prisoner's Dilemma with pop size of 100](http://jltmtz.github.io/assets/images/pop100.png)

## The Blog Post

I wrote a [blog post](http://jltmtz.github.io/game%20theory/2014/09/03/better-than-tit-for-that/) analyzing the paper.  Its 2 main contributions, which end up evolving a strategy that outperforms tit-for-tat reside in

* Noting that in the real world it is very hard to follow a deterministic strategy. Therefore, it makes more sense to represent strategies as probabilities
* Demonstrating that it is possible to efficiently simulate large populations and iterations of the Prisoner's Dilemma under these conditions

Of course, check the blog post to see the details.

redpajama_set_name: RedPajamaGithub


text:
package xyz.vopen.cartier.classpathscanner.matchprocessor;

import java.lang.reflect.Executable;

/**
 * The method to run when a class that has a method or constructor with a specified annotation is found on the
 * classpath.
 *
 * @param matchingClass
 *            the matching class.
 * @param matchingMethodOrConstructor
 *            the Method or Constructor that has the annotation. (Executable is the superclass of both Method and
 *            Constructor.)
 */
@FunctionalInterface
public interface MethodAnnotationMatchProcessor {
    public void processMatch(Class<?> matchingClass, Executable matchingMethodOrConstructor);
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_file_snprintf_12.c
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-12.tmpl.c
*/
/*
 * @description
 * CWE: 134 Uncontrolled Format String
 * BadSource: file Read input from a file
 * GoodSource: Copy a fixed string into data
 * Sinks: swprintf
 *    GoodSink: snwprintf with "%s" as the third argument and data as the fourth
 *    BadSink : snwprintf with data as the third argument
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif

#ifdef _WIN32
#define SNPRINTF _snwprintf
#else
#define SNPRINTF swprintf
#endif

#ifndef OMITBAD

void CWE134_Uncontrolled_Format_String__wchar_t_file_snprintf_12_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(globalReturnsTrueOrFalse())
    {
        {
            /* Read input from a file */
            size_t dataLen = wcslen(data);
            FILE * pFile;
            /* if there is room in data, attempt to read the input from a file */
            if (100-dataLen > 1)
            {
                pFile = fopen(FILENAME, "r");
                if (pFile != NULL)
                {
                    /* POTENTIAL FLAW: Read data from a file */
                    if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                    {
                        printLine("fgetws() failed");
                        /* Restore NUL terminator if fgetws fails */
                        data[dataLen] = L'\0';
                    }
                    fclose(pFile);
                }
            }
        }
    }
    else
    {
        /* FIX: Use a fixed string that does not contain a format specifier */
        wcscpy(data, L"fixedstringtest");
    }
    if(globalReturnsTrueOrFalse())
    {
        {
            wchar_t dest[100] = L"";
            /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
            SNPRINTF(dest, 100-1, data);
            printWLine(dest);
        }
    }
    else
    {
        {
            wchar_t dest[100] = L"";
            /* FIX: Specify the format disallowing a format string vulnerability */
            SNPRINTF(dest, 100-1, L"%s", data);
            printWLine(dest);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() - use badsource and goodsink by changing the first "if" so that
   both branches use the BadSource and the second "if" so that both branches
   use the GoodSink */
static void goodB2G()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(globalReturnsTrueOrFalse())
    {
        {
            /* Read input from a file */
            size_t dataLen = wcslen(data);
            FILE * pFile;
            /* if there is room in data, attempt to read the input from a file */
            if (100-dataLen > 1)
            {
                pFile = fopen(FILENAME, "r");
                if (pFile != NULL)
                {
                    /* POTENTIAL FLAW: Read data from a file */
                    if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                    {
                        printLine("fgetws() failed");
                        /* Restore NUL terminator if fgetws fails */
                        data[dataLen] = L'\0';
                    }
                    fclose(pFile);
                }
            }
        }
    }
    else
    {
        {
            /* Read input from a file */
            size_t dataLen = wcslen(data);
            FILE * pFile;
            /* if there is room in data, attempt to read the input from a file */
            if (100-dataLen > 1)
            {
                pFile = fopen(FILENAME, "r");
                if (pFile != NULL)
                {
                    /* POTENTIAL FLAW: Read data from a file */
                    if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                    {
                        printLine("fgetws() failed");
                        /* Restore NUL terminator if fgetws fails */
                        data[dataLen] = L'\0';
                    }
                    fclose(pFile);
                }
            }
        }
    }
    if(globalReturnsTrueOrFalse())
    {
        {
            wchar_t dest[100] = L"";
            /* FIX: Specify the format disallowing a format string vulnerability */
            SNPRINTF(dest, 100-1, L"%s", data);
            printWLine(dest);
        }
    }
    else
    {
        {
            wchar_t dest[100] = L"";
            /* FIX: Specify the format disallowing a format string vulnerability */
            SNPRINTF(dest, 100-1, L"%s", data);
            printWLine(dest);
        }
    }
}

/* goodG2B() - use goodsource and badsink by changing the first "if" so that
   both branches use the GoodSource and the second "if" so that both branches
   use the BadSink */
static void goodG2B()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: Use a fixed string that does not contain a format specifier */
        wcscpy(data, L"fixedstringtest");
    }
    else
    {
        /* FIX: Use a fixed string that does not contain a format specifier */
        wcscpy(data, L"fixedstringtest");
    }
    if(globalReturnsTrueOrFalse())
    {
        {
            wchar_t dest[100] = L"";
            /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
            SNPRINTF(dest, 100-1, data);
            printWLine(dest);
        }
    }
    else
    {
        {
            wchar_t dest[100] = L"";
            /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
            SNPRINTF(dest, 100-1, data);
            printWLine(dest);
        }
    }
}

void CWE134_Uncontrolled_Format_String__wchar_t_file_snprintf_12_good()
{
    goodB2G();
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE134_Uncontrolled_Format_String__wchar_t_file_snprintf_12_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE134_Uncontrolled_Format_String__wchar_t_file_snprintf_12_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
"""
******
Entity
******

The Entity class is the base class for all entities, including Project, Folder, File, and Link.

Entities are dictionary-like objects in which both object and dictionary notation (entity.foo or entity['foo']) can be
used interchangeably.

Imports::

    from synapseclient import Project, Folder, File, Link

.. autoclass:: synapseclient.entity.Entity

~~~~~~~
Project
~~~~~~~

.. autoclass:: synapseclient.entity.Project

~~~~~~
Folder
~~~~~~

.. autoclass:: synapseclient.entity.Folder

~~~~
File
~~~~

.. autoclass:: synapseclient.entity.File

Changing File Names
-------------------

A Synapse File Entity has a name separate from the name of the actual file it represents. When a file is uploaded to
Synapse, its filename is fixed, even though the name of the entity can be changed at any time. Synapse provides a way
to change this filename and the content-type of the file for future downloads by creating a new version of the file
with a modified copy of itself.  This can be done with the synapseutils.copy_functions.changeFileMetaData function.

>>> import synapseutils
>>> e = syn.get(synid)
>>> print(os.path.basename(e.path))  ## prints, e.g., "my_file.txt"
>>> e = synapseutils.changeFileMetaData(syn, e, "my_newname_file.txt")

Setting *fileNameOverride* will **not** change the name of a copy of the
file that's already downloaded into your local cache. Either rename the
local copy manually or remove it from the cache and re-download.:

>>> syn.cache.remove(e.dataFileHandleId)
>>> e = syn.get(e)
>>> print(os.path.basename(e.path))  ## prints "my_newname_file.txt"

~~~~
Link
~~~~

.. autoclass:: synapseclient.entity.Link

~~~~~~~~~~~~
Table Schema
~~~~~~~~~~~~

.. autoclass:: synapseclient.table.Schema

~~~~~~~~~~~~~~~~~~
Entity View Schema
~~~~~~~~~~~~~~~~~~

.. autoclass:: synapseclient.table.EntityViewSchema

~~~~~~~~~~~~~~~~
DockerRepository
~~~~~~~~~~~~~~~~

.. autoclass:: synapseclient.entity.DockerRepository

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Properties and annotations, implementation details
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In Synapse, entities have both properties and annotations. Properties are used by the system, whereas annotations are
completely user defined. In the Python client, we try to present this situation as a normal object, with one set of
properties.

Printing an entity will show the division between properties and annotations.::

    print(entity)

Under the covers, an Entity object has two dictionaries, one for properties and one for annotations. These two
namespaces are distinct, so there is a possibility of collisions. It is recommended to avoid defining annotations with
names that collide with properties, but this is not enforced.::

    ## don't do this!
    entity.properties['description'] = 'One thing'
    entity.annotations['description'] = 'A different thing'

In case of conflict, properties will take precedence.::

    print(entity.description)
    #> One thing

Some additional ambiguity is entailed in the use of dot notation. Entity objects have their own internal properties
which are not persisted to Synapse. As in all Python objects, these properties are held in object.__dict__. For
example, this dictionary holds the keys 'properties' and 'annotations' whose values are both dictionaries themselves.

The rule, for either getting or setting is: first look in the object then look in properties, then look in annotations.
If the key is not found in any of these three, a get results in a ``KeyError`` and a set results in a new annotation
being created. Thus, the following results in a new annotation that will be persisted in Synapse::

    entity.foo = 'bar'

To create an object member variable, which will *not* be persisted in Synapse, this unfortunate notation is required::

    entity.__dict__['foo'] = 'bar'

As mentioned previously, name collisions are entirely possible.
Keys in the three namespaces can be referred to unambiguously like so::

    entity.__dict__['key']

    entity.properties.key
    entity.properties['key']

    entity.annotations.key
    entity.annotations['key']

Most of the time, users should be able to ignore these distinctions and treat Entities like normal Python objects.
End users should never need to manipulate items in __dict__.

See also:

- :py:mod:`synapseclient.annotations`

"""

import collections.abc
import itertools
import io
import os
import inspect
import urllib.parse as urllib_parse

from synapseclient.core import utils
from synapseclient.core.exceptions import SynapseMalformedEntityError
from synapseclient.core.models.dict_object import DictObject
from synapseclient.core.utils import id_of, itersubclasses

class Versionable(object):
    """An entity for which Synapse will store a version history."""

    _synapse_entity_type = 'org.sagebionetworks.repo.model.Versionable'
    _property_keys = ['versionNumber', 'versionLabel', 'versionComment', 'versionUrl', 'versions']

# TODO: inherit from UserDict.DictMixin?
#       http://docs.python.org/2/library/userdict.html#UserDict.DictMixin

# Alternate implementations include:
# - a naming convention to tag object members
# - keeping a list of 'transient' variables (the object members)
# - giving up on the dot notation (implemented in Entity2.py in commit e441fcf5a6963118bcf2b5286c67fc66c004f2b5 in the
# entity_object branch)
# - giving up on hiding the difference between properties and annotations

class Entity(collections.abc.MutableMapping):
    """
    A Synapse entity is an object that has metadata, access control, and potentially a file. It can represent data,
    source code, or a folder that contains other entities.

    Entities should typically be created using the constructors for specific subclasses such as Project, Folder or File.
    """

    _synapse_entity_type = 'org.sagebionetworks.repo.model.Entity'
    _property_keys = ['id', 'name', 'description', 'parentId',
                      'entityType', 'concreteType',
                      'uri', 'etag', 'annotations', 'accessControlList',
                      'createdOn', 'createdBy', 'modifiedOn', 'modifiedBy']
    _local_keys = []

    @classmethod
    def create(cls, properties=None, annotations=None, local_state=None):
        """
        Create an Entity or a subclass given dictionaries of properties and annotations, as might be received from the
        Synapse Repository.

        :param properties:  A map of Synapse properties

            If 'concreteType' is defined in properties, we create the proper subclass of Entity. If not, give back the
            type whose constructor was called:

            If passed an Entity as input, create a new Entity using the input entity as a prototype.

        :param annotations: A map of user defined annotations
        :param local_state: Internal use only
        """

        # Create a new Entity using an existing Entity as a prototype
        if isinstance(properties, Entity):
            if annotations is None:
                annotations = {}
            if local_state is None:
                local_state = {}
            annotations.update(properties.annotations)
            local_state.update(properties.local_state())
            properties = properties.properties
            if 'id' in properties:
                del properties['id']

        if cls == Entity \
                and 'concreteType' in properties \
                and properties['concreteType'] in entity_type_to_class:
            cls = entity_type_to_class[properties['concreteType']]
        return cls(properties=properties, annotations=annotations, local_state=local_state)

    @classmethod
    def getURI(cls, id):
        return '/entity/%s' % id

    def __new__(cls, *args, **kwargs):
        obj = object.__new__(cls)

        # Make really sure that properties and annotations exist before
        # any object methods get invoked. This is important because the
        # dot operator magic methods have been overridden and depend on
        # properties and annotations existing.
        obj.__dict__['properties'] = DictObject()
        obj.__dict__['annotations'] = DictObject()
        return obj

    def __init__(self, properties=None, annotations=None, local_state=None, parent=None, **kwargs):

        if properties:
            if isinstance(properties, collections.abc.Mapping):
                if 'annotations' in properties and isinstance(properties['annotations'], collections.abc.Mapping):
                    annotations.update(properties['annotations'])
                    del properties['annotations']

                # Re-map `items` to `datasetItems` to avoid namespace conflicts
                # between Dataset schema and the items() builtin method.
                if 'items' in properties:
                    properties['datasetItems'] = properties['items']
                    del properties['items']
                self.__dict__['properties'].update(properties)
            else:
                raise SynapseMalformedEntityError(
                    'Unknown argument type: properties is a %s' % str(type(properties))
                )

        if annotations:
            if isinstance(annotations, collections.abc.Mapping):
                self.__dict__['annotations'].update(annotations)
            elif isinstance(annotations, str):
                self.properties['annotations'] = annotations
            else:
                raise SynapseMalformedEntityError(
                    'Unknown argument type: annotations is a %s' % str(type(annotations))
                )

        if local_state:
            if isinstance(local_state, collections.abc.Mapping):
                self.local_state(local_state)
            else:
                raise SynapseMalformedEntityError(
                    'Unknown argument type: local_state is a %s' % str(type(local_state))
                )

        for key in self.__class__._local_keys:
            if key not in self.__dict__:
                self.__dict__[key] = None

        # Extract parentId from parent
        if 'parentId' not in kwargs:
            if parent:
                try:
                    kwargs['parentId'] = id_of(parent)
                except Exception:
                    if isinstance(parent, Entity) and 'id' not in parent:
                        raise SynapseMalformedEntityError(
                            "Couldn't find 'id' of parent."
                            " Has it been stored in Synapse?"
                        )
                    else:
                        raise SynapseMalformedEntityError("Couldn't find 'id' of parent.")

        # Note: that this will work properly if derived classes declare their internal state variable *before* invoking
        # super(...).__init__(...)
        for key, value in kwargs.items():
            self.__setitem__(key, value)

        if 'concreteType' not in self:
            self['concreteType'] = self.__class__._synapse_entity_type

        # Only project can be top-level. All other entity types require parentId don't enforce this for generic Entity
        if 'parentId' not in self \
                and not isinstance(self, Project) \
                and not type(self) == Entity:
            raise SynapseMalformedEntityError("Entities of type %s must have a parentId." % type(self))

    def postURI(self):
        return '/entity'

    def putURI(self):
        return '/entity/%s' % self.id

    def deleteURI(self, versionNumber=None):
        if versionNumber:
            return '/entity/%s/version/%s' % (self.id, versionNumber)
        else:
            return '/entity/%s' % self.id

    def local_state(self, state=None):
        """
        Set or get the object's internal state, excluding properties, or annotations.

        :param state: A dictionary
        """
        if state:
            for key, value in state.items():
                if key not in ['annotations', 'properties']:
                    self.__dict__[key] = value
        result = {}
        for key, value in self.__dict__.items():
            if key not in ['annotations', 'properties'] and not key.startswith('__'):
                result[key] = value
        return result

    def __setattr__(self, key, value):
        return self.__setitem__(key, value)

    def __setitem__(self, key, value):
        if key in self.__dict__ or key in self.__class__._local_keys:
            # If we assign like so:
            #   entity.annotations = {'foo';123, 'bar':'bat'}
            # Wrap the dictionary in a DictObject so we can
            # later do:
            #   entity.annotations.foo = 'bar'
            if (key == 'annotations' or key == 'properties') and not isinstance(value, DictObject):
                value = DictObject(value)
            self.__dict__[key] = value
        elif key in self.__class__._property_keys:
            self.properties[key] = value
        else:
            self.annotations[key] = value

    # TODO: def __delattr__

    def __getattr__(self, key):
        # Note: that __getattr__ is only called after an attempt to
        # look the key up in the object's dictionary has failed.
        try:
            return self.__getitem__(key)
        except KeyError:
            # Note that hasattr in Python2 is more permissive than Python3
            # about what exceptions it catches. In Python3, hasattr catches
            # only AttributeError
            raise AttributeError(key)

    def __getitem__(self, key):
        if key in self.__dict__:
            return self.__dict__[key]
        elif key in self.properties:
            return self.properties[key]
        elif key in self.annotations:
            return self.annotations[key]
        else:
            raise KeyError(key)

    def __delitem__(self, key):
        if key in self.properties:
            del self.properties[key]
        elif key in self.annotations:
            del self.annotations[key]

    def __iter__(self):
        return iter(self.keys())

    def __len__(self):
        return len(self.keys())

    # TODO shouldn't these include local_state as well? -jcb
    def keys(self):
        """Returns a set of property and annotation keys"""
        return set(self.properties.keys()) | set(self.annotations.keys())

    def has_key(self, key):
        """Is the given key a property or annotation?"""

        return key in self.properties or key in self.annotations

    def _write_kvps(self, f, dictionary, key_filter=None, key_aliases=None):
        for key in sorted(dictionary.keys()):
            if (not key_filter) or key_filter(key):
                f.write('  ')
                f.write(str(key) if not key_aliases else key_aliases[key])
                f.write('=')
                f.write(str(dictionary[key]))
                f.write('\n')

    def __str__(self):
        f = io.StringIO()

        f.write('%s: %s (%s)\n' % (self.__class__.__name__, self.properties.get('name', 'None'),
                                   self['id'] if 'id' in self else '-',))

        self._str_localstate(f)

        f.write('properties:\n')
        self._write_kvps(f, self.properties)

        f.write('annotations:\n')
        self._write_kvps(f, self.annotations)

        return f.getvalue()

    def _str_localstate(self, f):  # type: (io.StringIO) -> None
        """
        Helper method for writing the string representation of the local state to a StringIO object
        :param f: a StringIO object to which the local state string will be written
        """
        self._write_kvps(f, self.__dict__,
                         lambda key: not (key in ['properties', 'annotations'] or key.startswith('__')))

    def __repr__(self):
        """Returns an eval-able representation of the Entity."""

        f = io.StringIO()
        f.write(self.__class__.__name__)
        f.write("(")
        f.write(", ".join(
            {"%s=%s" % (str(key), value.__repr__(),) for key, value in
                itertools.chain(
                    list([k_v for k_v in self.__dict__.items()
                          if not (k_v[0] in ['properties', 'annotations'] or k_v[0].startswith('__'))]),
                    self.properties.items(),
                    self.annotations.items())}))
        f.write(")")
        return f.getvalue()

class Project(Entity):
    """
    Represents a project in Synapse.

    Projects in Synapse must be uniquely named. Trying to create a project with a name that's already taken, say
    'My project', will result in an error

    :param name:            The name of the project
    :param properties:      A map of Synapse properties
    :param annotations:     A map of user defined annotations
    :param local_state:     Internal use only

    Example::

        project = Project('Foobarbat project')
        project = syn.store(project)
    """

    _synapse_entity_type = 'org.sagebionetworks.repo.model.Project'

    def __init__(self, name=None, properties=None, annotations=None, local_state=None, **kwargs):
        if name:
            kwargs['name'] = name
        super(Project, self).__init__(concreteType=Project._synapse_entity_type, properties=properties,
                                      annotations=annotations, local_state=local_state, **kwargs)

class Folder(Entity):
    """
    Represents a folder in Synapse.

    Folders must have a name and a parent and can optionally have annotations.

    :param name:            The name of the folder
    :param parent:          The parent project or folder
    :param properties:      A map of Synapse properties
    :param annotations:     A map of user defined annotations
    :param local_state:     Internal use only

    Example::

        folder = Folder('my data', parent=project)
        folder = syn.store(folder)
    """

    _synapse_entity_type = 'org.sagebionetworks.repo.model.Folder'

    def __init__(self, name=None, parent=None, properties=None, annotations=None, local_state=None, **kwargs):
        if name:
            kwargs['name'] = name
        super(Folder, self).__init__(concreteType=Folder._synapse_entity_type, properties=properties,
                                     annotations=annotations, local_state=local_state, parent=parent, **kwargs)

class Link(Entity):
    """
    Represents a link in Synapse.

    Links must have a target ID and a parent. When you do :py:func:`synapseclient.Synapse.get` on a Link object,
    the Link object is returned. If the target is desired, specify followLink=True in synapseclient.Synapse.get.

    :param targetId:        The ID of the entity to be linked
    :param targetVersion:   The version of the entity to be linked
    :param parent:          The parent project or folder
    :param properties:      A map of Synapse properties
    :param annotations:     A map of user defined annotations
    :param local_state:     Internal use only

    Example::

        link = Link('targetID', parent=folder)
        link = syn.store(link)
    """
    _property_keys = Entity._property_keys + ['linksTo', 'linksToClassName']
    _local_keys = Entity._local_keys
    _synapse_entity_type = 'org.sagebionetworks.repo.model.Link'

    def __init__(self, targetId=None, targetVersion=None, parent=None, properties=None, annotations=None,
                 local_state=None, **kwargs):
        if targetId is not None and targetVersion is not None:
            kwargs['linksTo'] = dict(targetId=utils.id_of(targetId), targetVersionNumber=targetVersion)
        elif targetId is not None and targetVersion is None:
            kwargs['linksTo'] = dict(targetId=utils.id_of(targetId))
        elif properties is not None and 'linksTo' in properties:
            pass
        else:
            raise SynapseMalformedEntityError("Must provide a target id")
        super(Link, self).__init__(concreteType=Link._synapse_entity_type, properties=properties,
                                   annotations=annotations, local_state=local_state, parent=parent, **kwargs)

class File(Entity, Versionable):
    """
    Represents a file in Synapse.

    When a File object is stored, the associated local file or its URL will be stored in Synapse. A File must have a
    path (or URL) and a parent.

    :param path:                Location to be represented by this File
    :param name:                Name of the file in Synapse, not to be confused with the name within the path
    :param parent:              Project or Folder where this File is stored
    :param synapseStore:        Whether the File should be uploaded or if only the path should be stored when
                                :py:func:`synapseclient.Synapse.store` is called on the File object.
                                Defaults to True (file should be uploaded)
    :param contentType:         Manually specify Content-type header, for example "application/png" or
                                "application/json; charset=UTF-8"
    :param dataFileHandleId:    Defining an existing dataFileHandleId will use the existing dataFileHandleId
                                The creator of the file must also be the owner of the dataFileHandleId to have
                                permission to store the file
    :param properties:          A map of Synapse properties
    :param annotations:         A map of user defined annotations
    :param local_state:         Internal use only

    Example::

        data = File('/path/to/file/data.xyz', parent=folder)
        data = syn.store(data)
    """
    # Note: externalURL technically should not be in the keys since it's only a field/member variable of
    # ExternalFileHandle, but for backwards compatibility it's included
    _file_handle_keys = ["createdOn", "id", "concreteType", "contentSize", "createdBy", "etag", "fileName",
                         "contentType", "contentMd5", "storageLocationId", 'externalURL']
    # Used for backwards compatability. The keys found below used to located in the entity's local_state
    # (i.e. __dict__).
    _file_handle_aliases = {'md5': 'contentMd5', 'externalURL': 'externalURL', 'fileSize': 'contentSize',
                            'contentType': 'contentType'}
    _file_handle_aliases_inverse = {v: k for k, v in _file_handle_aliases.items()}

    _property_keys = Entity._property_keys + Versionable._property_keys + ['dataFileHandleId']
    _local_keys = Entity._local_keys + ['path', 'cacheDir', 'files', 'synapseStore', '_file_handle']
    _synapse_entity_type = 'org.sagebionetworks.repo.model.FileEntity'

    # TODO: File(path="/path/to/file", synapseStore=True, parentId="syn101")
    def __init__(self, path=None, parent=None, synapseStore=True, properties=None,
                 annotations=None, local_state=None, **kwargs):
        if path and 'name' not in kwargs:
            kwargs['name'] = utils.guess_file_name(path)
        self.__dict__['path'] = path
        if path:
            cacheDir, basename = os.path.split(path)
            self.__dict__['cacheDir'] = cacheDir
            self.__dict__['files'] = [basename]
        else:
            self.__dict__['cacheDir'] = None
            self.__dict__['files'] = []
        self.__dict__['synapseStore'] = synapseStore

        # pop the _file_handle from local properties because it is handled differently from other local_state
        self._update_file_handle(local_state.pop('_file_handle', None) if (local_state is not None) else None)

        super(File, self).__init__(concreteType=File._synapse_entity_type, properties=properties,
                                   annotations=annotations, local_state=local_state, parent=parent, **kwargs)

    def _update_file_handle(self, file_handle_update_dict=None):
        """
        Sets the file handle

        Should not need to be called by users
        """

        # replace the file handle dict
        fh_dict = DictObject(file_handle_update_dict) if file_handle_update_dict is not None else DictObject()
        self.__dict__['_file_handle'] = fh_dict

        if file_handle_update_dict is not None \
                and file_handle_update_dict.get('concreteType') ==\
                "org.sagebionetworks.repo.model.file.ExternalFileHandle"\
                and urllib_parse.urlparse(file_handle_update_dict.get('externalURL')).scheme != 'sftp':
            self.__dict__['synapseStore'] = False

        # initialize all nonexistent keys to have value of None
        for key in self.__class__._file_handle_keys:
            if key not in fh_dict:
                fh_dict[key] = None

    def __setitem__(self, key, value):
        if key == '_file_handle':
            self._update_file_handle(value)
        elif key in self.__class__._file_handle_aliases:
            self._file_handle[self.__class__._file_handle_aliases[key]] = value
        else:
            def expand_and_convert_to_URL(path): return utils.as_url(os.path.expandvars(os.path.expanduser(path)))
            # hacky solution to allowing immediate switching into a ExternalFileHandle pointing to the current path
            # yes, there is boolean zen but I feel like it is easier to read/understand this way
            if key == 'synapseStore' and value is False and self['synapseStore'] is True \
                    and utils.caller_module_name(inspect.currentframe()) != 'client':
                self['externalURL'] = expand_and_convert_to_URL(self['path'])

            # hacky solution because we historically allowed modifying 'path' to indicate wanting to change to a new
            # ExternalFileHandle
            # don't change exernalURL if it's just the synapseclient setting metadata after a function call such as
            # syn.get()
            if key == 'path' and not self['synapseStore'] \
                    and utils.caller_module_name(inspect.currentframe()) != 'client':
                self['externalURL'] = expand_and_convert_to_URL(value)
                self['contentMd5'] = None
                self['contentSize'] = None
            super(File, self).__setitem__(key, value)

    def __getitem__(self, item):
        if item in self.__class__._file_handle_aliases:
            return self._file_handle[self.__class__._file_handle_aliases[item]]
        else:
            return super(File, self).__getitem__(item)

    def _str_localstate(self, f):
        self._write_kvps(f, self._file_handle, lambda key: key in ['externalURL', 'contentMd5', 'contentSize',
                                                                   'contentType'], self._file_handle_aliases_inverse)
        self._write_kvps(f, self.__dict__, lambda key: not (key in ['properties', 'annotations', '_file_handle']
                                                            or key.startswith('__')))

class DockerRepository(Entity):
    """
    A Docker repository is a lightweight virtual machine image.

    NOTE: store()-ing a DockerRepository created in the Python client will always result in it being treated as a
    reference to an external Docker repository that is not managed by synapse.
    To upload a docker image that is managed by Synapse please use the official Docker client and read
     http://docs.synapse.org/articles/docker.html for instructions on uploading a Docker Image to Synapse

    :param repositoryName: the name of the Docker Repository. Usually in the format: [host[:port]/]path.
     If host is not set, it will default to that of DockerHub. port can only be specified if the host is also specified.
    :param parent: the parent project for the Docker repository
    :param properties:      A map of Synapse properties
    :param annotations:     A map of user defined annotations
    :param local_state:     Internal use only

    :return:  an object of type :py:class:`synapseclient.entity.DockerRepository`
    """
    _synapse_entity_type = 'org.sagebionetworks.repo.model.docker.DockerRepository'

    _property_keys = Entity._property_keys + ['repositoryName']

    def __init__(self, repositoryName=None, parent=None, properties=None, annotations=None, local_state=None, **kwargs):
        if repositoryName:
            kwargs['repositoryName'] = repositoryName
        super(DockerRepository, self).__init__(properties=properties, annotations=annotations, local_state=local_state,
                                               parent=parent, **kwargs)
        if 'repositoryName' not in self:
            raise SynapseMalformedEntityError("DockerRepository must have a repositoryName.")

# Create a mapping from Synapse class (as a string) to the equivalent Python class.
entity_type_to_class = {}
for cls in itersubclasses(Entity):
    entity_type_to_class[cls._synapse_entity_type] = cls

_entity_types = ["folder", "file", "table", "link", "entityview", "dockerrepo",
                 "submissionview", "dataset", "materializedview"]

def split_entity_namespaces(entity):
    """
    Given a plain dictionary or an Entity object, splits the object into properties, annotations and local state.
    A dictionary will be processed as a specific type of Entity if it has a valid 'concreteType' field, otherwise it is
    treated as a generic Entity.

    :returns: a 3-tuple (properties, annotations, local_state).
    """
    if isinstance(entity, Entity):
        # Defensive programming: return copies
        return entity.properties.copy(), entity.annotations.copy(), entity.local_state()

    if not isinstance(entity, collections.abc.Mapping):
        raise SynapseMalformedEntityError("Can't split a %s object." % entity.__class__.__name__)

    if 'concreteType' in entity and entity['concreteType'] in entity_type_to_class:
        entity_class = entity_type_to_class[entity['concreteType']]
    else:
        entity_class = Entity

    properties = DictObject()
    annotations = DictObject()
    local_state = DictObject()

    property_keys = entity_class._property_keys
    local_keys = entity_class._local_keys
    for key, value in entity.items():
        if key in property_keys:
            properties[key] = value
        elif key in local_keys:
            local_state[key] = value
        else:
            annotations[key] = value

    return properties, annotations, local_state

ENTITY_TYPES = [
    'org.sagebionetworks.repo.model.FileEntity',
    'org.sagebionetworks.repo.model.Folder',
    'org.sagebionetworks.repo.model.Link',
    'org.sagebionetworks.repo.model.Project',
    'org.sagebionetworks.repo.model.table.TableEntity',
    'org.sagebionetworks.repo.model.table.Dataset'
]

def is_synapse_entity(entity):
    if isinstance(entity, Entity):
        return True
    if isinstance(entity, collections.abc.Mapping):
        return entity.get('concreteType', None) in ENTITY_TYPES
    return False

def is_versionable(entity):
    """Return True if the given entity's concreteType is one that is Versionable."""

    if isinstance(entity, Versionable):
        return True

    try:
        entity_class = entity_type_to_class[entity['concreteType']]
        return issubclass(entity_class, Versionable)
    except (KeyError, TypeError):
        # the dict input is not an entity
        raise ValueError("Input is not an entity.")

def is_container(entity):
    """Test if an entity is a container (ie, a Project or a Folder)"""
    if 'concreteType' in entity:
        concreteType = entity['concreteType']
    elif 'type' in entity:
        concreteType = entity['type']
    elif isinstance(entity, collections.abc.Mapping):
        prefix = utils.extract_prefix(entity.keys())
        if prefix+'concreteType' in entity:
            concreteType = entity[prefix+'concreteType'][0]
        elif prefix+'nodeType' in entity:
            return entity[prefix+'nodeType'] in ['project', 'folder']
        else:
            return False
    else:
        return False
    return concreteType in (Project._synapse_entity_type, Folder._synapse_entity_type)


text:
<?php

namespace Magento\Search\Test\Unit\Controller\Adminhtml\Term;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
use Magento\Framework\Controller\ResultFactory;

class MassDeleteTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Magento\Framework\Message\ManagerInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $messageManager;

    /** @var  \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $objectManager;

    /** @var \Magento\Search\Controller\Adminhtml\Term\MassDelete */
    private $controller;

    /** @var ObjectManagerHelper */
    private $objectManagerHelper;

    /** @var \Magento\Backend\App\Action\Context|\PHPUnit_Framework_MockObject_MockObject */
    private $context;

    /** @var \Magento\Framework\View\Result\PageFactory|\PHPUnit_Framework_MockObject_MockObject */
    private $pageFactory;

    /** @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $request;

    /**
     * @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    private $resultFactoryMock;

    /**
     * @var \Magento\Backend\Model\View\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject
     */
    private $resultRedirectMock;

    protected function setUp()
    {
        $this->request = $this->getMockBuilder('\Magento\Framework\App\RequestInterface')
            ->disableOriginalConstructor()
            ->setMethods([])
            ->getMockForAbstractClass();
        $this->objectManager = $this->getMockBuilder('\Magento\Framework\ObjectManagerInterface')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMockForAbstractClass();
        $this->messageManager = $this->getMockBuilder('\Magento\Framework\Message\ManagerInterface')
            ->disableOriginalConstructor()
            ->setMethods(['addSuccess', 'addError'])
            ->getMockForAbstractClass();
        $this->pageFactory = $this->getMockBuilder('Magento\Framework\View\Result\PageFactory')
            ->setMethods([])
            ->disableOriginalConstructor()
            ->getMock();
        $this->resultRedirectMock = $this->getMockBuilder('Magento\Backend\Model\View\Result\Redirect')
            ->disableOriginalConstructor()
            ->getMock();
        $this->resultFactoryMock = $this->getMockBuilder('Magento\Framework\Controller\ResultFactory')
            ->disableOriginalConstructor()
            ->getMock();
        $this->resultFactoryMock->expects($this->any())
            ->method('create')
            ->with(ResultFactory::TYPE_REDIRECT, [])
            ->willReturn($this->resultRedirectMock);
        $this->context = $this->getMockBuilder('Magento\Backend\App\Action\Context')
            ->disableOriginalConstructor()
            ->getMock();
        $this->context->expects($this->atLeastOnce())
            ->method('getRequest')
            ->willReturn($this->request);
        $this->context->expects($this->any())
            ->method('getObjectManager')
            ->willReturn($this->objectManager);
        $this->context->expects($this->any())
            ->method('getMessageManager')
            ->willReturn($this->messageManager);
        $this->context->expects($this->any())
            ->method('getResultFactory')
            ->willReturn($this->resultFactoryMock);

        $this->objectManagerHelper = new ObjectManagerHelper($this);
        $this->controller = $this->objectManagerHelper->getObject(
            'Magento\Search\Controller\Adminhtml\Term\MassDelete',
            [
                'context' => $this->context,
                'resultPageFactory' => $this->pageFactory,
            ]
        );
    }

    public function testExecute()
    {
        $ids = [1, 2];
        $this->request->expects($this->once())
            ->method('getParam')
            ->with('search')
            ->will($this->returnValue($ids));

        $this->createQuery(0, 1);
        $this->createQuery(1, 2);
        $this->messageManager->expects($this->once())
            ->method('addSuccess')
            ->will($this->returnSelf());
        $this->resultRedirectMock->expects($this->once())
            ->method('setPath')
            ->with('search/*/')
            ->willReturnSelf();

        $this->assertSame($this->resultRedirectMock, $this->controller->execute());
    }

    /**
     * @param $index
     * @param $id
     * @return \Magento\Search\Model\Query|\PHPUnit_Framework_MockObject_MockObject
     */
    private function createQuery($index, $id)
    {
        $query = $this->getMockBuilder('Magento\Search\Model\Query')
            ->disableOriginalConstructor()
            ->setMethods(['load', 'delete'])
            ->getMock();
        $query->expects($this->at(0))
            ->method('delete')
            ->will($this->returnSelf());
        $query->expects($this->at(0))
            ->method('load')
            ->with($id)
            ->will($this->returnSelf());
        $this->objectManager->expects($this->at($index))
            ->method('create')
            ->with('Magento\Search\Model\Query')
            ->will($this->returnValue($query));
        return $query;
    }
}


text:
/*globals define*/
define(function(){
    "use strict";
    var whatever = function(){
        return 'whatever return value';
    };

    return {
        whatever: whatever
    };
});


text:
/* eslint-env mocha */

import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { assert } from 'meteor/practicalmeteor:chai';

import { Activities } from './activities.js';

if (Meteor.isServer) {
  describe('Activities', () => {
    describe('methods', () => {
      const userId = Random.id();
      let taskId;

      beforeEach(() => {
        Activities.remove({});
        taskId = Activities.insert({
          text: 'test task',
          createdAt: new Date(),
          owner: userId,
          username: 'tmeasday',
        });
      });

      it('can delete owned task', () => {
        // Find the internal implementation of the task method so we can
        // test it in isolation
        const deleteTask = Meteor.server.method_handlers['activities.remove'];

        // Set up a fake method invocation that looks like what the method expects
        const invocation = { userId };

        // Run the method with `this` set to the fake invocation
        deleteTask.apply(invocation, [taskId]);

        // Verify that the method does what we expected
        assert.equal(Activities.find().count(), 0);
      });
    });
  });
}


text:
/**
 * Created by maglo on 08/09/2016.
 */
Ext.define("JS.article.View", {
    //extend: "JS.panel.Form",
    extend: "Xfr.Component",
    config: {
        dynamicTpl: false,

        panelData: {
            formUrl: Routing.generate("get_manuscrit_step", {stepId: "new", _format: 'html'})
        },
        listeners: {
            "loadtpl": {
                fn: "onLoadTpl"
            },
            //"afterrendertpl": {
            //    fn: "afterRenderTpl"
            //},
            "render": {
                fn: "onShow"
            }
        },
        eventBound:false,
        action:"",
        article:null,
        title: 'View',
        subtitle: '',
        jsApp:null,
        author: false,
        reviewer: false,
        editor:true,
        showToolBar:true
    },
    initialize: function () {
        var me = this;
        console.log("Initialising View class");

        var templateHelpers= {
            isArticleEditable: function(article){
                console.log("IsArticleEditable called");
                console.log(article);
                return article.statut=="SOUMISSION_RETOURNE_A_L_AUTEUR" ||
                    article.statut=="SOUMISSION_INCOMPLETE"||
                    article.statut=="SOUMISSION_EN_ATTENTE_DE_VALIDATION"||
                    article.statut=="REVISION_RENVOYE_A_L_AUTEUR"||
                    article.statut=="REVISION_INCOMPLETE"||
                    article.statut=="REVISION_EN_ATTENTE_DE_VALIDATION";
            }

        };

        me.callParent(arguments);

        me.binder.set("helpers", templateHelpers);
    },

    onLoadTpl: function () {
        var me = this;
        console.log("View tpl form loaded");
        me.callParent(arguments);

    },
    afterRenderTpl: function () {
        var me = this;
        me.callParent(arguments);

        //On set les données du template

        var data={
            article: me.getArticle(),
            baseUrl: baseUrl,
            getColor: function(index) {
                // validate hex strisng
                console.log("Generating random color");
                var letters = '012345'.split('');
                var color = '#';
                if(index>5){
                    index=Math.round(Math.random() * 5);
                }
                color += index; //letters[Math.round(Math.random() * 5)];
                letters = '0123456789ABCDEF'.split('');
                for (var i = 0; i < 5; i++) {
                    color += letters[Math.round(Math.random() * 15)];
                }
                return color;
            },
            getFontSize: function(index) {
                // validate hex strisng
                console.log("Generating random font size");

                var fontSize = '%';

                index=Math.round(Math.random() * 60);

                index=index+80;

                fontSize=index+fontSize;

                return fontSize;
            }
        };
        me.setData(data);

        $('.box-body.article-view-box').slimScroll({
            height: '225px'
        });

        console.log("binding events on buttons");

        me.binder.on('assing-editor-view', function (e) {
            console.log("Assign editor button clicked");
            me.showDialogEditor();
        });

        me.binder.on('propose-reviewer-view', function (e) {

            console.log("Propose reviewer button clicked");
            me.showDialogReviewers();
        });

        me.binder.on('sent-back-to-author-view', function (e) {

            console.log("Sent back to author button clicked");
            me.sentBackToAuthor();
        });

        me.binder.on('js-cancel-view', function (e) {

            console.log("Cancel button clicked");
            me.rejectArticle();
        });

        me.binder.on('js-validate-view', function (e) {

            console.log("Cancel button clicked");
            me.acceptArticle();
        });

        me.binder.on('validate-manuscript-view', function (e) {

            console.log("Validate manuscript clicked");
            me.validateManuscript();
            //me.showDialogAdd();
        });

        me.binder.on('show-edit', function(e){
            me.editManuscript();
        });

        me.binder.on('start-revision', function(e){
            me.createRevision();
        });

        console.log("End event binding on button");

    },
    editManuscript: function(){
        var me=this;
        var article=me.getArticle();
        me.getJsApp().showPanel("JS.article.ManuscritForm",{
            title: article.titre_court,
            article: article
        });
    },
    createRevision: function(){
        var me=this;
        var article=me.getArticle();
        var id=-1;

        Xfr.Mask.show("Creating Revision...", null, me.$this);

        if(article!=null){
            id=article.id;
        }
        $.ajax({
            url: Routing.generate('get_article_revision', {
                _format: 'json',
                id: id
            }),
            cache: false,
            contentType: false,
            processData: false,
            type: "GET",
            data: null,
            dataType: "json",
            success: function (response, textStatus, jqXHR) {
                console.log("ajax success");
                console.log(response);
                Xfr.Mask.hide();
                if(response && response.success){
                    var article=response.data;
                    me.getJsApp().showPanel("JS.article.ManuscritForm",{
                        title: article.titre_court,
                        article: article
                    });
                }
                else{
                    Xfr.Msg.show({
                        message: "An error occured durring revision creation. Please retry in few minutes.",
                        title: "Error",
                        icon: Xfr.Msg.ERROR.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            Xfr.Mask.hide();
                        }

                    });

                }
                //$("li.current").toggleClass('current');

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("Error: "+ errorThrown);
                Xfr.Mask.hide();

            }
        });
    },
    validateManuscript: function(){
        var me=this;
        var article=me.getArticle();
        var id=-1;

        Xfr.Mask.show("Validating...", null, me.$this);

        if(article!=null){
            id=article.id;
        }
        $.ajax({
            url: Routing.generate('put_manuscript_validate', {
                _format: 'json',
                id: id
            }),
            cache: false,
            contentType: false,
            processData: false,
            type: "PUT",
            data: null,
            dataType: "json",
            success: function (response, textStatus, jqXHR) {
                console.log("ajax success");
                console.log(response);
                Xfr.Mask.hide();
                if(response && response.success){

                    Xfr.Msg.show({
                        message: "Your manuscript has been submitted successfully!",
                        title: "Success",
                        icon: Xfr.Msg.INFO.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            me.getJsApp().back();
                            Xfr.Mask.hide();
                        }

                    });
                }
                else{
                    Xfr.Msg.show({
                        message: "An error occured durring submission. Please retry in few minutes.",
                        title: "Error",
                        icon: Xfr.Msg.ERROR.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            Xfr.Mask.hide();
                        }

                    });

                }
                //$("li.current").toggleClass('current');

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("Error: "+ errorThrown);
                Xfr.Mask.hide();

            }
        });
    },
    showDialogEditor: function(){
        var me=this;
        var dialog=Ext.create("Xfr.panel.Window", {
            size: 'medium',
            title:  "Assigning editor",
            renderTo: document.body,
            items: [{
                className: "JS.article.EditorForm",
                height: "100%",
                position: '[xfr-window-content]',
                reviewer: null,
                selectedArticles : [me.getArticle()],
                parentCmp : me,
                jsApp: me.getJsApp(),
                listeners: {
                    "onCancel": function(){
                        console.log("Cancel event fired");
                        dialog.hide();
                        me.getGrid().reload();
                    }
                }
            }]
        });
        dialog.show();
    },
    showDialogReviewers: function(){
        var me=this;
        var dialog=Ext.create("Xfr.panel.Window", {
            size: 'medium',
            title:  "Proposing reviewers",
            renderTo: document.body,
            items: [{
                className: "JS.article.ReviewRequestForm",
                height: "100%",
                position: '[xfr-window-content]',
                reviewer: null,
                selectedArticles : [me.getArticle()],
                parentCmp : me,
                jsApp: me.getJsApp(),
                listeners: {
                    "onCancel": function(){
                        console.log("Cancel event fired");
                        dialog.hide();
                        me.getGrid().reload();
                    }
                }
            }]
        });
        dialog.show();
    },
    acceptArticle:function(){
        var me=this;

        var id=-1;

        Xfr.Mask.show("Saving...",null);
        //SAve current step

        var selectedArticles=[me.getArticle()];
        var articleIds='';
        if(selectedArticles!=null && selectedArticles.length>0){
            articleIds=selectedArticles[0].id;
            for(var i=1; i<selectedArticles.length; i++){
                articleIds=articleIds+','+selectedArticles[i].id;
            }
        }

        $.ajax({
            url: Routing.generate('post_validate', {
                _format: 'json',
                id: id,
                articleIds: articleIds
            }),
            cache: false,
            contentType: false,
            processData: false,
            type: "POST",
            data: null,
            dataType: "json",
            success: function (response, textStatus, jqXHR) {
                console.log("ajax success");
                console.log(response);
                if(response && response.success){
                    Xfr.Msg.show({
                        message: "Selected articles accepted successfully",
                        title: "Success",
                        icon: Xfr.Msg.INFO.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            Xfr.Mask.hide();
                        }

                    });
                }
                else{
                    console.log("Success False");

                    Xfr.Msg.show({
                        message: response.message,
                        title: "Error",
                        icon: Xfr.Msg.ERROR.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            Xfr.Mask.hide();
                        }
                    });

                }
                //$("li.current").toggleClass('current');

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("Error: "+ errorThrown);

            }
        });
    },
    sentBackToAuthor: function(){
        var me=this;

        var id=-1;

        Xfr.Mask.show("Saving...",null);
        //SAve current step

        var selectedArticles=[me.getArticle()];
        var articleIds='';
        if(selectedArticles!=null && selectedArticles.length>0){
            articleIds=selectedArticles[0].id;
            for(var i=1; i<selectedArticles.length; i++){
                articleIds=articleIds+','+selectedArticles[i].id;
            }
        }

        $.ajax({
            url: Routing.generate('post_sentbacktouser', {
                _format: 'json',
                id: id,
                articleIds: articleIds
            }),
            cache: false,
            contentType: false,
            processData: false,
            type: "POST",
            data: null,
            dataType: "json",
            success: function (response, textStatus, jqXHR) {
                console.log("ajax success");
                console.log(response);
                if(response && response.success){
                    Xfr.Msg.show({
                        message: "Selected articles sent back to author successfully",
                        title: "Success",
                        icon: Xfr.Msg.INFO.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            Xfr.Mask.hide();
                            //me.fireEvent('onCancel', me);
                        }
                    });
                }
                else{
                    console.log("Success False");

                    Xfr.Msg.show({
                        message: response.message,
                        title: "Error",
                        icon: Xfr.Msg.ERROR.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            Xfr.Mask.hide();
                        }
                    });

                }

                //$("li.current").toggleClass('current');

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("Error: "+ errorThrown);

            }
        });
    },
    rejectArticle:function(){
        var me=this;

        var id=-1;

        Xfr.Mask.show("Saving...",null);
        //SAve current step

        var selectedArticles=[me.getArticle()];
        var articleIds='';
        if(selectedArticles!=null && selectedArticles.length>0){
            articleIds=selectedArticles[0].id;
            for(var i=1; i<selectedArticles.length; i++){
                articleIds=articleIds+','+selectedArticles[i].id;
            }
        }

        $.ajax({
            url: Routing.generate('post_reject', {
                _format: 'json',
                id: id,
                articleIds: articleIds
            }),
            cache: false,
            contentType: false,
            processData: false,
            type: "POST",
            data: null,
            dataType: "json",
            success: function (response, textStatus, jqXHR) {
                console.log("ajax success");
                console.log(response);
                if(response && response.success){
                    Xfr.Msg.show({
                        message: "Selected articles rejected successfully",
                        title: "Success",
                        icon: Xfr.Msg.INFO.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            Xfr.Mask.hide();
                        }
                    });
                }
                else{
                    console.log("Success False");

                    Xfr.Msg.show({
                        message: response.message,
                        title: "Error",
                        icon: Xfr.Msg.ERROR.iconClass,
                        btn: [
                            {text: Xfr.Msg.OK.text, type: 'btn'}
                        ],
                        action:function(btn){
                            //me.fireEvent('onCancel', me);
                            Xfr.Mask.hide();
                        }
                    });

                }
                //$("li.current").toggleClass('current');

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("Error: "+ errorThrown);

            }
        });
    },
    onShow: function () {
        var me = this;
        Xfr.log("View form rendered or shown");
        me.callParent(arguments);

    },

    statics: {

    }
});


text:
class boss : public deft {
public:
    boss(play *p, std::vector<ob*> *g, std::vector<ob*> *b, std::vector<anima*> *e);

    const QPointF* sub_draw() const;
    bool request_shot();
    ob* shoot();
};

#endif // BOSS_H


text:
title: 'Hubungi Kami'
visible: false
form:
    name: my-nice-form
    fields:
        -
            name: name
            label: Name
            placeholder: 'Enter your name'
            autofocus: 'on'
            autocomplete: 'on'
            type: text
            validate:
                required: true
        -
            name: email
            label: Email
            placeholder: 'Enter your email address'
            type: email
            validate:
                required: true
    buttons:
        -
            type: submit
            value: Submit
        -
            type: reset
            value: Reset
    process:
        -
            email:
                from: '{{ config.plugins.email.from }}'
                to: ['{{ config.plugins.email.from }}', '{{ form.value.email }}']
                subject: '[Feedback] {{ form.value.name|e }}'
                body: '{% include ''forms/data.html.twig'' %}'
        -
            save:
                fileprefix: feedback-
                dateformat: Ymd-His-u
                extension: txt
                body: '{% include ''forms/data.txt.twig'' %}'
        -
            message: 'Thank you for your feedback!'
        -
            display: thankyou
---

# My Form
##Thanks You!


text:
package org.apache.arrow.vector;

import static org.apache.arrow.vector.NullCheckingForGet.NULL_CHECKING_ENABLED;

import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.vector.complex.impl.TimeSecReaderImpl;
import org.apache.arrow.vector.complex.reader.FieldReader;
import org.apache.arrow.vector.holders.NullableTimeSecHolder;
import org.apache.arrow.vector.holders.TimeSecHolder;
import org.apache.arrow.vector.types.Types.MinorType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.util.TransferPair;

import io.netty.buffer.ArrowBuf;

/**
 * TimeSecVector implements a fixed width (4 bytes) vector of
 * time (seconds resolution) values which could be null. A validity buffer (bit vector) is
 * maintained to track which elements in the vector are null.
 */
public final class TimeSecVector extends BaseFixedWidthVector {
  private static final byte TYPE_WIDTH = 4;
  private final FieldReader reader;

  /**
   * Instantiate a TimeSecVector. This doesn't allocate any memory for
   * the data in vector.
   *
   * @param name name of the vector
   * @param allocator allocator for memory management.
   */
  public TimeSecVector(String name, BufferAllocator allocator) {
    this(name, FieldType.nullable(MinorType.TIMESEC.getType()), allocator);
  }

  /**
   * Instantiate a TimeSecVector. This doesn't allocate any memory for
   * the data in vector.
   *
   * @param name name of the vector
   * @param fieldType type of Field materialized by this vector
   * @param allocator allocator for memory management.
   */
  public TimeSecVector(String name, FieldType fieldType, BufferAllocator allocator) {
    this(new Field(name, fieldType, null), allocator);
  }

  /**
   * Instantiate a TimeSecVector. This doesn't allocate any memory for
   * the data in vector.
   *
   * @param field Field materialized by this vector
   * @param allocator allocator for memory management.
   */
  public TimeSecVector(Field field, BufferAllocator allocator) {
    super(field, allocator, TYPE_WIDTH);
    reader = new TimeSecReaderImpl(TimeSecVector.this);
  }

  /**
   * Get a reader that supports reading values from this vector.
   *
   * @return Field Reader for this vector
   */
  @Override
  public FieldReader getReader() {
    return reader;
  }

  /**
   * Get minor type for this vector. The vector holds values belonging
   * to a particular type.
   *
   * @return {@link org.apache.arrow.vector.types.Types.MinorType}
   */
  @Override
  public MinorType getMinorType() {
    return MinorType.TIMESEC;
  }

  /*----------------------------------------------------------------*
   |                                                                |
   |          vector value retrieval methods                        |
   |                                                                |
   *----------------------------------------------------------------*/

  /**
   * Get the element at the given index from the vector.
   *
   * @param index   position of element
   * @return element at given index
   */
  public int get(int index) throws IllegalStateException {
    if (NULL_CHECKING_ENABLED && isSet(index) == 0) {
      throw new IllegalStateException("Value at index is null");
    }
    return valueBuffer.getInt(index * TYPE_WIDTH);
  }

  /**
   * Get the element at the given index from the vector and
   * sets the state in holder. If element at given index
   * is null, holder.isSet will be zero.
   *
   * @param index   position of element
   */
  public void get(int index, NullableTimeSecHolder holder) {
    if (isSet(index) == 0) {
      holder.isSet = 0;
      return;
    }
    holder.isSet = 1;
    holder.value = valueBuffer.getInt(index * TYPE_WIDTH);
  }

  /**
   * Same as {@link #get(int)}.
   *
   * @param index   position of element
   * @return element at given index
   */
  public Integer getObject(int index) {
    if (isSet(index) == 0) {
      return null;
    } else {
      return valueBuffer.getInt(index * TYPE_WIDTH);
    }
  }

  /*----------------------------------------------------------------*
   |                                                                |
   |          vector value setter methods                           |
   |                                                                |
   *----------------------------------------------------------------*/

  private void setValue(int index, int value) {
    valueBuffer.setInt(index * TYPE_WIDTH, value);
  }

  /**
   * Set the element at the given index to the given value.
   *
   * @param index   position of element
   * @param value   value of element
   */
  public void set(int index, int value) {
    BitVectorHelper.setValidityBitToOne(validityBuffer, index);
    setValue(index, value);
  }

  /**
   * Set the element at the given index to the value set in data holder.
   * If the value in holder is not indicated as set, element in the
   * at the given index will be null.
   *
   * @param index   position of element
   * @param holder  nullable data holder for value of element
   */
  public void set(int index, NullableTimeSecHolder holder) throws IllegalArgumentException {
    if (holder.isSet < 0) {
      throw new IllegalArgumentException();
    } else if (holder.isSet > 0) {
      BitVectorHelper.setValidityBitToOne(validityBuffer, index);
      setValue(index, holder.value);
    } else {
      BitVectorHelper.setValidityBit(validityBuffer, index, 0);
    }
  }

  /**
   * Set the element at the given index to the value set in data holder.
   *
   * @param index   position of element
   * @param holder  data holder for value of element
   */
  public void set(int index, TimeSecHolder holder) {
    BitVectorHelper.setValidityBitToOne(validityBuffer, index);
    setValue(index, holder.value);
  }

  /**
   * Same as {@link #set(int, int)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param value   value of element
   */
  public void setSafe(int index, int value) {
    handleSafe(index);
    set(index, value);
  }

  /**
   * Same as {@link #set(int, NullableTimeSecHolder)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param holder  nullable data holder for value of element
   */
  public void setSafe(int index, NullableTimeSecHolder holder) throws IllegalArgumentException {
    handleSafe(index);
    set(index, holder);
  }

  /**
   * Same as {@link #set(int, TimeSecHolder)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param holder  data holder for value of element
   */
  public void setSafe(int index, TimeSecHolder holder) {
    handleSafe(index);
    set(index, holder);
  }

  /**
   * Store the given value at a particular position in the vector. isSet indicates
   * whether the value is NULL or not.
   *
   * @param index position of the new value
   * @param isSet 0 for NULL value, 1 otherwise
   * @param value element value
   */
  public void set(int index, int isSet, int value) {
    if (isSet > 0) {
      set(index, value);
    } else {
      BitVectorHelper.setValidityBit(validityBuffer, index, 0);
    }
  }

  /**
   * Same as {@link #set(int, int, int)} except that it handles the case
   * when index is greater than or equal to current value capacity of the
   * vector.
   *
   * @param index position of the new value
   * @param isSet 0 for NULL value, 1 otherwise
   * @param value element value
   */
  public void setSafe(int index, int isSet, int value) {
    handleSafe(index);
    set(index, isSet, value);
  }

  /**
   * Given a data buffer, get the value stored at a particular position
   * in the vector.
   *
   * <p>This method should not be used externally.
   *
   * @param buffer data buffer
   * @param index position of the element.
   * @return value stored at the index.
   */
  public static int get(final ArrowBuf buffer, final int index) {
    return buffer.getInt(index * TYPE_WIDTH);
  }

  /*----------------------------------------------------------------*
   |                                                                |
   |                      vector transfer                           |
   |                                                                |
   *----------------------------------------------------------------*/

  /**
   * Construct a TransferPair comprising of this and and a target vector of
   * the same type.
   *
   * @param ref name of the target vector
   * @param allocator allocator for the target vector
   * @return {@link TransferPair}
   */
  @Override
  public TransferPair getTransferPair(String ref, BufferAllocator allocator) {
    return new TransferImpl(ref, allocator);
  }

  /**
   * Construct a TransferPair with a desired target vector of the same type.
   *
   * @param to target vector
   * @return {@link TransferPair}
   */
  @Override
  public TransferPair makeTransferPair(ValueVector to) {
    return new TransferImpl((TimeSecVector) to);
  }

  private class TransferImpl implements TransferPair {
    TimeSecVector to;

    public TransferImpl(String ref, BufferAllocator allocator) {
      to = new TimeSecVector(ref, field.getFieldType(), allocator);
    }

    public TransferImpl(TimeSecVector to) {
      this.to = to;
    }

    @Override
    public TimeSecVector getTo() {
      return to;
    }

    @Override
    public void transfer() {
      transferTo(to);
    }

    @Override
    public void splitAndTransfer(int startIndex, int length) {
      splitAndTransferTo(startIndex, length, to);
    }

    @Override
    public void copyValueSafe(int fromIndex, int toIndex) {
      to.copyFromSafe(fromIndex, toIndex, TimeSecVector.this);
    }
  }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Globalization;
using System.Waf.UnitTesting;
using Waf.BookLibrary.Library.Domain;
using Waf.BookLibrary.Library.Domain.Properties;

namespace Test.BookLibrary.Library.Domain;

[TestClass]
public class BookTest
{
    [TestMethod]
    public void GeneralBookTest()
    {
        var book = new Book();
        Assert.IsNotNull(book.Id);

        book.Title = "Star Wars - Heir to the Empire";
        book.Author = "Timothy Zahn";
        book.Publisher = "Spectra";
        book.PublishDate = new DateTime(1992, 5, 1);
        book.Isbn = "0553296124";
        book.Language = Language.English;
        book.Pages = 416;

        Assert.IsTrue(book.Validate());

        Assert.AreEqual("Star Wars - Heir to the Empire by Timothy Zahn", book.ToString(null, CultureInfo.InvariantCulture));
    }

    [TestMethod]
    public void BookLanguagePropertyChangedTest()
    {
        var book = new Book() { Language = Language.English };
        AssertHelper.PropertyChangedEvent(book, x => x.Language, () => book.Language = Language.German);
        Assert.AreEqual(Language.German, book.Language);
    }

    [TestMethod]
    public void BookLendToPropertyChangedTest()
    {
        var book = new Book();
        Assert.IsNull(book.LendTo);

        var person = new Person();
        AssertHelper.PropertyChangedEvent(book, x => x.LendTo, () => book.LendTo = person);
        Assert.AreEqual(person, book.LendTo);
    }

    [TestMethod]
    public void BookTitleValidationTest()
    {
        var book = new Book();
        book.Validate();

        Assert.AreEqual("", book.Title);
        Assert.AreEqual(Resources.TitleMandatory, book.GetErrors(nameof(book.Title)).Single().ErrorMessage);

        book.Title = new string('A', 101);
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.TitleMaxLength, "Title", 100), book.GetErrors(nameof(book.Title)).Single().ErrorMessage);

        book.Title = new string('A', 100);
        Assert.IsFalse(book.GetErrors(nameof(book.Title)).Any());
    }

    [TestMethod]
    public void BookAuthorValidationTest()
    {
        var book = new Book();
        book.Validate();

        Assert.AreEqual("", book.Author);
        Assert.AreEqual(Resources.AuthorMandatory, book.GetErrors(nameof(book.Author)).Single().ErrorMessage);

        book.Author = new string('A', 101);
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.AuthorMaxLength, "Author", 100), book.GetErrors(nameof(book.Author)).Single().ErrorMessage);

        book.Author = new string('A', 100);
        Assert.IsFalse(book.GetErrors(nameof(book.Author)).Any());
    }

    [TestMethod]
    public void BookPublisherValidationTest()
    {
        var book = new Book();
        book.Validate();

        Assert.IsNull(book.Publisher);
        Assert.IsFalse(book.GetErrors(nameof(book.Publisher)).Any());

        book.Publisher = new string('A', 101);
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.PublisherMaxLength, "Publisher", 100), book.GetErrors(nameof(book.Publisher)).Single().ErrorMessage);

        book.Publisher = new string('A', 100);
        Assert.IsFalse(book.GetErrors(nameof(book.Publisher)).Any());
    }

    [TestMethod]
    public void BookPublishDateValidationTest()
    {
        var book = new Book();
        book.Validate();

        Assert.IsFalse(book.GetErrors(nameof(book.PublishDate)).Any());

        book.PublishDate = new DateTime(1752, 1, 1);
        Assert.IsTrue(book.GetErrors(nameof(book.PublishDate)).Any());

        book.PublishDate = new DateTime(2000, 1, 1);
        Assert.IsFalse(book.GetErrors(nameof(book.PublishDate)).Any());

        book.PublishDate = new DateTime(1000, 1, 1);
        Assert.IsTrue(book.GetErrors(nameof(book.PublishDate)).Any());
    }

    [TestMethod]
    public void BookIsbnValidationTest()
    {
        var book = new Book();
        book.Validate();

        Assert.IsNull(book.Isbn);
        Assert.IsFalse(book.GetErrors(nameof(book.Isbn)).Any());

        book.Isbn = new string('A', 15);
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.IsbnMaxLength, "Isbn", 14), book.GetErrors(nameof(book.Isbn)).Single().ErrorMessage);

        book.Isbn = new string('A', 14);
        Assert.IsFalse(book.GetErrors(nameof(book.Isbn)).Any());
    }

    [TestMethod]
    public void BookPagesValidationTest()
    {
        var book = new Book();
        book.Validate();

        Assert.AreEqual(0, book.Pages);
        Assert.IsFalse(book.GetErrors(nameof(book.Pages)).Any());

        book.Pages = -1;
        Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, Resources.PagesEqualOrLarger, "Pages", 0), book.GetErrors(nameof(book.Pages)).Single().ErrorMessage);

        book.Pages = 400;
        Assert.IsFalse(book.GetErrors(nameof(book.Pages)).Any());
    }
}


text:
namespace MyMarket.Data.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    using Common.Models;

    public class Flag : IAuditInfo
    {
        [Key]
        public int Id { get; set; }

        public DateTime CreatedOn { get; set; }

        public DateTime? ModifiedOn { get; set; }

        [Required]
        public int AdId { get; set; }

        [ForeignKey("AdId")]
        public virtual Ad Ad { get; set; }

        [Required]
        public string UserId { get; set; }

        [ForeignKey("UserId")]
        public virtual User User { get; set; }
    }
}


text:
namespace java.security.cert
{
    public abstract partial class Certificate : global::java.lang.Object, global::java.io.Serializable
    {
        protected partial class CertificateRep : global::java.lang.Object, global::java.io.Serializable
        {
            public CertificateRep(global::java.lang.String prm1, byte[] prm2){}
            protected virtual global::System.Object readResolve(){return default(global::System.Object);}
        }
        public override bool equals(global::System.Object prm1){return default(bool);}
        public override int hashCode(){return default(int);}
        public Certificate(global::java.lang.String prm1){}
        public override global::java.lang.String toString(){return default(global::java.lang.String);}
        public virtual void verify(PublicKey prm1, global::java.lang.String prm2){}
        public virtual void verify(PublicKey prm1){}
        protected virtual global::System.Object writeReplace(){return default(global::System.Object);}
        public byte[]  Encoded { get; private set;}
        public PublicKey  PublicKey { get; private set;}
        public global::java.lang.String  Type { get; private set;}
    }
}


text:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.algaworks.pedidovenda.model.Grupo;
import com.algaworks.pedidovenda.model.Usuario;

public class TestesUsuarioGrupoCRUD {

	public static void main(String[] args) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("PedidoPU");
		EntityManager manager = factory.createEntityManager();

		EntityTransaction trx = manager.getTransaction();
		trx.begin();

		Usuario usuario = new Usuario();
		usuario.setNome("Maria");
		usuario.setEmail("maria@abadia.com");
		usuario.setSenha("123");

		Grupo grupo = new Grupo();
		grupo.setNome("Vendedores");
		grupo.setDescricao("Vendedores da empresa");

		//usuario.getGrupos().add(grupo);

		manager.persist(usuario);

		trx.commit();
	}

}


text:
-- --------------------------------------------------------
-- Хост:                         127.0.0.1
-- Версия на сървъра:            10.1.26-MariaDB - mariadb.org binary distribution
-- ОС на сървъра:                Win32
-- HeidiSQL Версия:              9.4.0.5125
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

-- Дъмп структура за таблица tasks.categories
CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- Data exporting was unselected.
-- Дъмп структура за таблица tasks.tasks
CREATE TABLE IF NOT EXISTS `tasks` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(50) NOT NULL,
  `description` text,
  `location` varchar(100) DEFAULT NULL,
  `author_id` int(10) unsigned NOT NULL,
  `category_id` int(10) unsigned NOT NULL,
  `started_on` datetime DEFAULT NULL,
  `due_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_tasks_users` (`author_id`),
  KEY `FK_tasks_categories` (`category_id`),
  CONSTRAINT `FK_tasks_categories` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`),
  CONSTRAINT `FK_tasks_users` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

-- Data exporting was unselected.
-- Дъмп структура за таблица tasks.users
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- Data exporting was unselected.
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


text:
require 'test_helper'

class Aviator::Test

  describe 'aviator/openstack/volume/v2/public/delete_snapshot' do

    def create_snapshot
      response = session.volume_service.request :create_volume, api_version: :v1 do |params|
        params[:display_name]         = 'Volume for Delete Snapshot'
        params[:display_description]  = 'Volume for Delete Snapshot Description'
        params[:size]                 = '1'
      end
      @volume = response.body[:volume]

      response = session.volume_service.request(:create_snapshot, api_version: :v2) do |params|
        params[:name]         = 'Snapshot for Delete Test'
        params[:description]  = 'Snapshot for Delete Test Description'
        params[:volume_id]    =  @volume[:id]
        params[:force]        =  true
      end

      # sleep 5
      @snapshot = response.body[:snapshot]
    end

    def get_session_data
      session.send :auth_info
    end

    def helper
      Aviator::Test::RequestHelper
    end

    def klass
      @klass ||= helper.load_request('openstack', 'volume', 'v2', 'public', 'delete_snapshot.rb')
    end

    def session
      unless @session
        @session = Aviator::Session.new(
                     config_file: Environment.path,
                     environment: 'openstack_member'
                   )
        @session.authenticate
      end

      @session
    end

    validate_attr :anonymous? do
      klass.anonymous?.must_equal false
    end

    validate_attr :api_version do
      klass.api_version.must_equal :v2
    end

    validate_response 'parameters are provided' do
      snapshot = create_snapshot

      snapshot.wont_be_empty

      #delete snapshot
      response = session.volume_service.request(:delete_snapshot, api_version: :v2) do |params|
        params[:snapshot_id] = snapshot[:id]
      end

      response.status.must_equal 202

      # sleep 5

      list = session.volume_service.request(:list_snapshots, api_version: :v2)
      list.body[:snapshots].collect{ |s| s[:id] }.include?(snapshot[:id]).must_equal false

      # sleep 5
      #delete volume
      response = session.volume_service.request(:delete_volume, api_version: :v1) do |params|
        params[:id] = @volume[:id]
      end
    end

  end

end


text:
import UserStory                      from "../../../project/user_story";
import UserStoryCollection            from "../../../project/user_story/collection";

class StandardUserStoryCollection implements UserStoryCollection
{
  private userStories: Array<UserStory>;

  constructor()
  {
    this.userStories = new Array<UserStory>();
  }

  addUserStory(userStory: UserStory): void
  {
    this.userStories.push(userStory);
  }

  contains(userStory: UserStory): boolean
  {
    return this.userStories.includes(userStory);
  }
}

export default StandardUserStoryCollection;


text:
package com.google.android.finsky.utils;

import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Paint;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.view.ViewGroup;
import com.google.android.finsky.FinskyApp;
import com.google.android.finsky.api.model.Document;
import com.google.android.finsky.experiments.FinskyExperiments;
import com.google.android.finsky.layout.DecoratedTextView;
import com.google.android.finsky.protos.AlbumDetails;
import com.google.android.finsky.protos.Badge;
import com.google.android.finsky.protos.Common.Image;
import com.google.android.finsky.protos.DocDetails.DocumentDetails;
import com.google.android.finsky.protos.DocV2;
import com.google.android.finsky.protos.MusicDetails;
import com.google.android.finsky.protos.TvEpisodeDetails;
import com.google.android.finsky.utils.image.ThumbnailUtils;
import com.google.android.play.image.BitmapLoader;
import com.google.android.play.image.FifeImageView;
import com.google.android.play.layout.PlayTextView;
import com.google.android.play.layout.StarRatingBar;
import java.text.NumberFormat;
import java.text.ParseException;

public final class BadgeUtils
{
  private static Boolean sHideEmptyStarsInReviews;
  private static NumberFormat sRatingFormatter;
  private static Boolean sUseCompactStarRating;

  static
  {
    NumberFormat localNumberFormat = NumberFormat.getNumberInstance();
    sRatingFormatter = localNumberFormat;
    localNumberFormat.setMinimumFractionDigits(1);
    sRatingFormatter.setMaximumFractionDigits(1);
  }

  public static void configureBadge(Badge paramBadge, BitmapLoader paramBitmapLoader, DecoratedTextView paramDecoratedTextView)
  {
    CharSequence localCharSequence = paramDecoratedTextView.getText();
    if (paramBadge != null)
    {
      int i = (int)paramDecoratedTextView.getTextSize();
      Common.Image localImage = getImage$7bb5454b(paramBadge);
      if (localImage != null)
      {
        paramDecoratedTextView.loadDecoration(paramBitmapLoader, localImage, i);
        Resources localResources = paramDecoratedTextView.getResources();
        Object[] arrayOfObject = new Object[2];
        arrayOfObject[0] = localCharSequence;
        arrayOfObject[1] = paramBadge.title;
        paramDecoratedTextView.setContentDescription(localResources.getString(2131361991, arrayOfObject));
        return;
      }
      paramDecoratedTextView.setContentDescription(localCharSequence);
      return;
    }
    paramDecoratedTextView.setCompoundDrawables(null, null, null, null);
    paramDecoratedTextView.setContentDescription(localCharSequence);
  }

  public static void configureContentRatingBadge(Document paramDocument, BitmapLoader paramBitmapLoader, ViewGroup paramViewGroup)
  {
    if ((paramDocument.mDocument.docType != 1) && (paramDocument.mDocument.docType != 6))
    {
      paramViewGroup.setVisibility(8);
      return;
    }
    Badge localBadge = paramDocument.getBadgeForContentRating();
    if (localBadge == null)
    {
      paramViewGroup.setVisibility(8);
      return;
    }
    DecoratedTextView localDecoratedTextView = (DecoratedTextView)paramViewGroup.findViewById(2131755400);
    if (localBadge.hasTextInTitleSection)
    {
      localDecoratedTextView.setText(localBadge.textInTitleSection);
      localDecoratedTextView.setVisibility(0);
    }
    FifeImageView localFifeImageView;
    for (;;)
    {
      localFifeImageView = (FifeImageView)paramViewGroup.findViewById(2131755399);
      if ((localBadge.image != null) && (localBadge.image.length != 0)) {
        break;
      }
      localFifeImageView.setVisibility(8);
      return;
      localDecoratedTextView.setVisibility(8);
    }
    ThumbnailUtils.adjustWidthFromImageMetadata(localFifeImageView, localBadge.image[0]);
    localFifeImageView.setImage(localBadge.image[0].imageUrl, true, paramBitmapLoader);
    localFifeImageView.setVisibility(0);
  }

  public static void configureCreatorBadge(Document paramDocument, BitmapLoader paramBitmapLoader, DecoratedTextView paramDecoratedTextView)
  {
    if (paramDocument.hasCreatorBadges()) {}
    for (Badge localBadge = paramDocument.getFirstCreatorBadge();; localBadge = null)
    {
      configureBadge(localBadge, paramBitmapLoader, paramDecoratedTextView);
      return;
    }
  }

  public static void configureRatingItemSection(Document paramDocument, StarRatingBar paramStarRatingBar, DecoratedTextView paramDecoratedTextView)
  {
    if (paramDecoratedTextView != null) {
      paramDecoratedTextView.setVisibility(8);
    }
    if ((paramDecoratedTextView != null) && (paramDocument.hasItemBadges()))
    {
      paramDecoratedTextView.setVisibility(0);
      Badge localBadge = paramDocument.mDocument.annotations.badgeForDoc[0];
      int j = (int)paramDecoratedTextView.getTextSize();
      Common.Image localImage = getImage$7bb5454b(localBadge);
      if (localImage != null) {
        paramDecoratedTextView.loadDecoration(FinskyApp.get().mBitmapLoader, localImage, j);
      }
      paramDecoratedTextView.setText(localBadge.title.toUpperCase());
      ColorStateList localColorStateList = paramDecoratedTextView.getResources().getColorStateList(2131689798);
      paramDecoratedTextView.setTextColor(localColorStateList);
      paramDecoratedTextView.mDrawBorder = false;
      if (paramDecoratedTextView.mDrawBorder) {
        paramDecoratedTextView.mBorderPaint.setColor(localColorStateList.getDefaultColor());
      }
      paramDecoratedTextView.invalidate();
      ViewCompat.setPaddingRelative(paramDecoratedTextView, 0, paramDecoratedTextView.getPaddingTop(), 0, paramDecoratedTextView.getPaddingBottom());
    }
    do
    {
      return;
      if ((paramDecoratedTextView != null) && ((paramDocument.hasCensoring()) || (paramDocument.hasReleaseType())))
      {
        configureTipperSticker(paramDocument, paramDecoratedTextView);
        int i = paramDecoratedTextView.getResources().getDimensionPixelSize(2131493473);
        ViewCompat.setPaddingRelative(paramDecoratedTextView, i, paramDecoratedTextView.getPaddingTop(), i, paramDecoratedTextView.getPaddingBottom());
        return;
      }
      if ((paramDecoratedTextView != null) && (paramDocument.mDocument.docType == 20))
      {
        if ((paramDocument.getTvEpisodeDetails() != null) && (!TextUtils.isEmpty(paramDocument.getTvEpisodeDetails().releaseDate)))
        {
          paramDecoratedTextView.setVisibility(0);
          paramDecoratedTextView.setContentColorId(2131689551, false);
          paramDecoratedTextView.setText(paramDocument.getTvEpisodeDetails().releaseDate);
          paramDecoratedTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
        ViewCompat.setPaddingRelative(paramDecoratedTextView, 0, paramDecoratedTextView.getPaddingTop(), 0, paramDecoratedTextView.getPaddingBottom());
        return;
      }
    } while (paramStarRatingBar == null);
    paramStarRatingBar.setCompactMode(shouldUseCompactStarRating());
    if ((paramDocument.hasRating()) && (paramDocument.getRatingCount() > 0L))
    {
      paramStarRatingBar.setRating(paramDocument.getStarRating());
      paramStarRatingBar.setVisibility(0);
      return;
    }
    paramStarRatingBar.setVisibility(4);
  }

  public static void configureTipperSticker(Document paramDocument, PlayTextView paramPlayTextView)
  {
    int i = -1;
    int j = 2131689738;
    if (paramDocument.hasCensoring()) {}
    switch (paramDocument.mDocument.details.albumDetails.details.censoring)
    {
    default:
      if ((i == -1) && (paramDocument.hasReleaseType())) {
        switch (paramDocument.mDocument.details.albumDetails.details.releaseType[0])
        {
        }
      }
      break;
    }
    for (;;)
    {
      if (i < 0) {
        break label186;
      }
      paramPlayTextView.setVisibility(0);
      paramPlayTextView.setText(paramPlayTextView.getResources().getString(i).toUpperCase());
      paramPlayTextView.setContentColorId(j, true);
      paramPlayTextView.setCompoundDrawables(null, null, null, null);
      return;
      i = 2131362790;
      j = 2131689739;
      break;
      i = 2131362789;
      break;
      i = 2131362788;
      continue;
      i = 2131362791;
      continue;
      i = 2131362792;
    }
    label186:
    paramPlayTextView.setVisibility(8);
  }

  public static String formatRating(float paramFloat)
  {
    return sRatingFormatter.format(paramFloat);
  }

  public static Common.Image getImage$7bb5454b(Badge paramBadge)
  {
    for (Common.Image localImage : paramBadge.image) {
      if (localImage.imageType == 6) {
        return localImage;
      }
    }
    return null;
  }

  public static float roundRating(float paramFloat)
  {
    String str = formatRating(paramFloat);
    try
    {
      float f = sRatingFormatter.parse(str).floatValue();
      return f;
    }
    catch (ParseException localParseException)
    {
      FinskyLog.wtf("Cannot parse %s. Exception %s", new Object[] { str, localParseException });
    }
    return paramFloat;
  }

  public static boolean shouldHideEmptyStarsInReviews()
  {
    if (sHideEmptyStarsInReviews == null) {
      sHideEmptyStarsInReviews = Boolean.valueOf(FinskyApp.get().getExperiments().isEnabled(12603097L));
    }
    return sHideEmptyStarsInReviews.booleanValue();
  }

  public static boolean shouldUseCompactStarRating()
  {
    if (sUseCompactStarRating == null) {
      sUseCompactStarRating = Boolean.valueOf(FinskyApp.get().getExperiments().isEnabled(12602623L));
    }
    return sUseCompactStarRating.booleanValue();
  }
}

/* Location:           F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar

 * Qualified Name:     com.google.android.finsky.utils.BadgeUtils

 * JD-Core Version:    0.7.0.1

 */