text:
import time

from django.shortcuts import get_object_or_404
from django.conf import settings

from canvas import (models, experiments, session_utils, search, bgwork, economy, last_sticker, fact, util,
                    stickers, browse, knobs)
from canvas.api_decorators import api_decorator
from canvas.exceptions import ServiceError, InsufficientPrivileges
from canvas.forms import validate_and_clean_comment
from canvas.models import Metrics, Comment, UserInfo
from canvas.notifications.actions import Actions
from canvas.redis_models import RateLimit, redis
from canvas.view_guards import require_user

urlpatterns = []
api = api_decorator(urlpatterns)

@api('validate_post')
def validate_comment(request, parent_comment=None, replied_comment=None,
                     reply_content=None, category=None):
    """ Return {"success": True} if valid. """
    validate_and_clean_comment(
        request.user,
        parent_comment=parent_comment,
        replied_comment=replied_comment,
        reply_content=reply_content,
        category=category,
    )

@api('post')
@require_user
def post_comment(request, anonymous=False, parent_comment=None, replied_comment=None,
                 reply_content=None, category=None, fact_metadata={},
                 title=None, tags=[]):
    anonymous = bool(anonymous)

    # Remember the user's preference for anonymous posting.
    request.user.userinfo.post_anonymously = anonymous
    request.user.userinfo.save()

    replied_comment, parent_comment, reply_content, category, title = validate_and_clean_comment(
        request.user,
        parent_comment=parent_comment,
        replied_comment=replied_comment,
        reply_content=reply_content,
        category=category,
        title=title,
    )

    comment = models.Comment.create_and_post(
        request,
        request.user,
        anonymous,
        category,
        reply_content,
        parent_comment=parent_comment,
        replied_comment=replied_comment,
        fact_metadata=fact_metadata,
        title=title,
        tags=tags,
    )

    if parent_comment is None:
        key = 'posted_unvisited_threads'
        val = request.session.get(key, set())
        val.add(comment.id)
        request.session[key] = val

    @bgwork.defer
    def create_footer():
        if comment.footer.should_exist():
            comment.footer.call_update_in_new_process()

    @bgwork.defer
    def credit_original_author():
        if (not comment.reply_content
                or not comment.reply_content.is_remix()
                or not comment.reply_content.remix_of.first_caption):
            return
        original_author = comment.reply_content.remix_of.first_caption.author
        if original_author != comment.author:
            economy.credit_received_remix(original_author)

    @bgwork.defer
    def do_notify():
        Actions.replied(request.user, comment)

    return {'comment': comment.details()}

@api('replies')
def get_replies(request, comment_id=0, replies_after_timestamp=0.):
    from apps.features import feature_flags as features

    op_id = int(comment_id)
    # Fudge the timestamp a bit to err on the side of too many replies which we'll dedupe, instead of clicking the
    # button and having nothing happening.
    fudge = 5
    replies_after_timestamp = float(replies_after_timestamp) - fudge

    op = get_object_or_404(models.Comment, id=op_id)
    replies = [r.details() for r in op.replies.filter(models.Visibility.q_visible).filter(timestamp__gt=replies_after_timestamp).order_by('timestamp')]

    Metrics.get_new_replies.record(request, op=op_id, replies_after_timestamp=replies_after_timestamp)

    if features.thread_new(request):
        from apps.threads.jinja_tags import thread_new_comment
        html = u''.join(thread_new_comment({'request': request}, reply, ignore_lazy_load=True)
                        for reply in replies)
        return {'replies': replies, 'html': html}

    return {'replies': replies}

@api('mute')
def mute_thread(request, comment_id):
    """
    Mutes the op of a given comment, so that the user never receives any notifications pertaining to that thread.
    """
    comment = get_object_or_404(models.Comment, pk=comment_id)
    request.user.redis.mute_thread(comment)

@api('pin')
@require_user
def pin_comment(request, comment_id):
    """ Pin the thread this comment is a part of. """
    comment = get_object_or_404(models.Comment, pk=comment_id)
    pin = comment.add_pin(request.user)
    if pin is not None:
        # If a reply was pinned, this will be the OP.
        pinned_comment = pin.comment
        request.user.redis.pinned_bump_buffer.bump(pinned_comment.id, time.time())
        Metrics.pin.record(request, comment=pinned_comment.id)

@api('unpin')
@require_user
def unpin_comment(request, comment_id):
    comment = get_object_or_404(models.Comment, pk=comment_id)
    comment.remove_pin(request.user)
    fact.record("unpin", request, {'comment': comment.id})

@api('flag')
@require_user
def flag_comment(request, comment_id=None, quest_id=None):
    comment_id = comment_id or quest_id

    comment = get_object_or_404(models.Comment, pk=comment_id)

    # If the user hits the flag rate limit, silently ignore it.
    prefix = 'user:%s:flag_limit:' % request.user.id

    def allowed(key, val):
        if request.user.is_staff:
            return True
        freq, timespan = val
        return RateLimit(prefix+key, freq, timespan).allowed()

    if not all(allowed(key, val) for key,val in knobs.FLAG_RATE_LIMITS.iteritems()):
        Metrics.flag_ratelimit.record(request, comment=comment.id)
        raise ServiceError('Flag rate limit exceeded.')
    else:
        flag = comment.add_flag(request.user, ip=request.META['REMOTE_ADDR'])

        if flag is not None:
            if settings.PROJECT == 'canvas':
                request.user.redis.hidden_comments.hide_comment(comment)

            Metrics.flag.record(request, comment=comment.id)

            if comment.anonymous:
                Metrics.flag_anonymous_post.record(request, comment=comment.id)

    try:
        flag_count = comment.details().flag_counts[0]
    except KeyError:
        flag_count = 0

    auto_moderated = False

    if knobs.AUTO_DISABLE_FLAGGED_COMMENTS_THRESHOLD is not None:
        if (not comment.judged
                and flag_count == knobs.AUTO_DISABLE_FLAGGED_COMMENTS_THRESHOLD[comment.author.userinfo.trusted]):
            comment.visibility = models.Visibility.DISABLED
            comment.save()
            comment.visibility_changed()
            auto_moderated = True

    if (not auto_moderated
            and flag_count >= knobs.AUTO_CURATE_FLAGGED_COMMENTS_THRESHOLD[comment.author.userinfo.trusted]
            and not comment.judged):
        comment.visibility = models.Visibility.CURATED
        comment.save()
        comment.visibility_changed()
        auto_moderated = True

    if request.user.is_staff:
        comment.judged = False
        comment.save()

    return {'flag_counts': comment.details().flag_counts, 'flag_id': getattr(flag, 'id', None)}

@api('unflag')
@require_user
def unflag_comment(request, flag_id):
    flag = get_object_or_404(models.CommentFlag, id=flag_id)
    comment = flag.comment

    if flag.user != request.user:
        raise InsufficientPrivileges()

    flag.undone = True
    flag.save()
    comment.details.force()

    fact.record("unflag", request, {'comment': comment.id})

    return {'flag_counts': comment.details().flag_counts, 'flag_id': flag.id}

@api('delete')
@require_user
def delete_comment(request, comment_id):
    comment = models.Comment.all_objects.get(id=comment_id)

    if not comment.author == request.user:
        raise ServiceError("Not comment author")

    comment.moderate_and_save(models.Visibility.UNPUBLISHED, request.user, undoing=True)

    Metrics.delete_post.record(request, comment=comment.id)

@api('get_user_sticker')
@require_user
def get_user_sticker(request, comment_id):
    """
    Returns whether or not a user has stickered a post.
    """
    comment = get_object_or_404(models.Comment, pk=comment_id)
    sticker = bool(comment.get_user_sticker(request.user))
    return {
        "sticker": sticker,
    }

@api('moderate')
@require_user
def moderate_comment(request, comment_id, visibility, undoing=False):
    comment = get_object_or_404(models.Comment.all_objects, pk=comment_id)
    #TODO don't get attribs from user input without whitelisting or something first.
    visibility = getattr(models.Visibility, str(visibility.upper()))
    can_moderate = request.user.can_moderate_visibility

    if comment.visibility not in can_moderate or visibility not in can_moderate:
        raise InsufficientPrivileges()

    comment.moderate_and_save(visibility, request.user, undoing)

    return {'info': comment.admin_info}

@api('mark_offtopic')
@require_user
def mark_offtopic_comment(request, comment_id, ot_hidden=False):
    comment = get_object_or_404(models.Comment.all_objects, pk=comment_id)
    comment.mark_offtopic(request.user, offtopic=ot_hidden)


text:
interface Options {
    remoteUrl?: string;
    origin?: string;
    branch?: string;
    cacheDir?: string;
    push?: boolean;
    message?: string;
}

declare function ghPages(opts?: Options): NodeJS.ReadWriteStream;

declare namespace ghPages { }

export = ghPages;

redpajama_set_name: RedPajamaGithub


text:
Model
=====

The ``Model`` is the base ORM class that represents your database schema. SQLAlchemy provides a very basic default ORM model class when one calls ``sqlalchemy.ext.declarative.declarative_base``. SQLService extends the basic ORM class to provide a few extra to handle some basic use cases.

The general approach when using ``sqlservice.ModelBase`` is to use it as the base class for your own custom ``Model`` class that extends/overrides ``ModelBase`` to fit your specific needs.

.. code-block:: python

    # in models/base.py
    from sqlalchemy import MetaData
    from sqlservice import ModelBase, as_declarative, declarative_base

    metadata = MetaData()

    @as_declarative(metadata=metadata)
    class Model(ModelBase):
        pass

    # Or using the declarative_base function...
    # Model = declarative_base(ModelBase, metadata=metadata)

.. note::

    All keyword arguments to ``sqlservice.as_declarative`` and ``sqlservice.declarative_base`` will be passed to ``sqlalchemy.ext.declarative.declarative_base``.

From here you can use ``Model`` as the base class for your ORM models.

.. code-block:: python

    # in models/user.py
    from sqlalchemy import Column, types

    from .base import Model

    class User(Model):
        __tablename__ = "user"

        id = Column(types.Integer(), primary_key=True)
        name = Column(types.String(100))
        email = Column(types.String(100))

        about = orm.relation("UserAbout", uselist=False)
        devices = orm.relation("UserDevice")

    class UserAbout(Model):
        __tablename__ = "user_about"

        user_id = Column(types.Integer(), ForeignKey("user.id"), primary_key=True)
        nickname = Column(types.String(100))
        hometown = Column(types.String(100))

    class UserDevice(Model):
        __tablename__ = "user_device"

        id = Column(types.Integer(), primary_key=True)
        user_id = Column(types.Integer(), ForeignKey("user.id"), nullable=False)
        name = Column(types.String(100))

        keys = orm.relation("UserDeviceKey")

    class UserDeviceKey(Model):
        __tablename__ = "user_device_key"

        id = Column(types.Integer(), primary_key=True)
        device_id = Column(types.Integer(), ForeignKey("user_device.id"), nullable=False)
        key = Column(types.String(100))

Instantiation and Updating
--------------------------

What does ``ModelBase`` provide for you? Out of the box, you'll be able to do things like:

Create a new instance from keyword arguments:

.. code-block:: python

    user = User(name="Bob", email="bob@example.com")

.. note::

    Under the hood ``ModelBase.__init__`` calls ``ModelBase.set()`` so anything ``set()`` does, ``__init__`` does too.

Update an instance using keyword arguments:

.. code-block:: python

    user.set(name="Bob Smith")

Set relationship and nested relationships:

.. code-block:: python

    user = User(
        name="Bob Smith",
        email="bobsmith@example.com",
        about=UserAbout(nickname="Bobby", hometown="Example City"),
        devices=[
            UserDevice(name="device1", keys=[UserDeviceKey(key="key1a"), UserDeviceKey(key="key1b")]),
            UserDevice(name="device2", keys=[UserDeviceKey(key="key2a"), UserDeviceKey(key="key2b")]),
        ]
    )

    user
    # User(id=None, name='Bob Smith', email='bobsmith@example.com')

    user.about
    # UserAbout(user_id=None, nickname='Bobby', hometown='Example City')

    user.devices
    # [UserDevice(id=None, user_id=None, name='device1'),
    #  UserDevice(id=None, user_id=None, name='device2')]

    user.devices[0].keys
    # [UserDeviceKey(id=None, device_id=None, key='key1a'),
    #  UserDeviceKey(id=None, device_id=None, key='key1b')]

    user.devices[1].keys
    # [UserDeviceKey(id=None, device_id=None, key='key2a'),
    #  UserDeviceKey(id=None, device_id=None, key='key2b')]

.. warning::

    Depending on whether you've set up relationship cascades, calling ``ModelBase.set()`` on relationships can result in integrity errors since SQLAlchemy will nullify orphaned relationship models when they are replaced.

    .. code-block:: python

        user.set(devices=[UserDevice(name="device3")])

        with db.begin() as session:
            session.save(user)

        # sqlalchemy.exc.IntegrityError: (raised as a result of Query-invoked autoflush;
        # consider using a session.no_autoflush block if this flush is occurring
        # prematurely) (sqlite3.IntegrityError) NOT NULL constraint failed:
        # user_device.user_id [SQL: 'UPDATE user_device SET user_id=? WHERE
        # user_device.id = ?'] [parameters: ((None, 1), (None, 2))]

Dictionary Serialization
------------------------

Want to serialize your models to ``dict`` objects?

.. code-block:: python

    # Using to_dict() method.
    user.to_dict()

    # Or using dict() builtin.
    dict(user)

    # {
    #     "id": 1,
    #     "name": "Bob Smith",
    #     "email": "bobsmith@example.com",
    #     "about": {"nickname": "Bo", "hometown": "Example City"},
    #     "devices": [
    #         {"id": 1, "name": "device1", "user_id": 1},
    #         {"id": 2, "name": "device2", "user_id": 1},
    #     ],
    # }

As you can see, relationships are serialized too.

But how does this handle lazy loaded models? When serializing, the only data that is serialized is what is already loaded from that database and set on the model instance. This is done to avoid triggering a large number of individual queries on lazily loaded attributes. Essentially, ``Model.to_dict()`` by default only looks at what's already loaded in the object's state and never touches any attributes directly (which could lead to additional database queries). So it's up to you to ensure that your model is loaded with the data you want to be serialized before calling ``to_dict()``. However, as a convenience, if the potential performance impact of lazyloading data is not a concern, then ``Model.to_dict(lazyload=True)`` can be used serialize all columns and relationships regardless of their loaded state. To exclude relationships even if they are loaded, use ``Model.to_dict(exclude_relationships=True)``.

Need to serialize things with more fine-grained control? Then it's recommended to use a separate serialization library like one of the following:

- `marshmallow <https://marshmallow.readthedocs.io>`_ with or without `marshmallow-sqlalchemy <https://marshmallow-sqlalchemy.readthedocs.io>`_
- `pydantic <https://pydantic-docs.helpmanual.io/>`_ with or without `pydantic-sqlalchemy <https://github.com/tiangolo/pydantic-sqlalchemy>`_

Object Identity
---------------

You can get the primary key identity of any model object:

.. code-block:: python

    user.pk()
    # 1

.. note::

    If the model has multiple primary keys, a tuple is returned.

Core-style Querying
-------------------

As an alternative to using ``sqlalchemy.select(User)``, ``sqlalchemy.insert(User)``, ``sqlalchemy.update(User)``, and ``sqlalchemy.delete(User)`` to build a query, the class methods ``Model.select()``, ``Model.insert()``, ``Model.update()``, and ``Model.delete()`` can be used as shorthand instead.

.. code-block:: python

    import sqlalchemy as sa

    with db.session() as session:
        # Instead of this...
        result = session.execute(sa.select(User).join(UserAbout))
        session.execute(sa.insert(User).values(...))
        session.execute(sa.update(User).values(...))
        session.execute(sa.delete(User))

        # You can do this...
        result = session.execute(User.select().join(UserAbout))
        session.execute(User.insert().values(...))
        session.execute(User.update().values(...))
        session.execute(User.delete())


text:
Run the twice example, both by loading the file with the -l option and with dofile
]]

function twice(x)
  return 2 * x
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index of new symbols in 2.8</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="index.html" title="GTK+ Reference Manual">
<link rel="up" href="index.html" title="GTK+ Reference Manual">
<link rel="prev" href="api-index-2-6.html" title="Index of new symbols in 2.6">
<link rel="next" href="api-index-2-10.html" title="Index of new symbols in 2.10">
<meta name="generator" content="GTK-Doc V1.15 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GTK+ Reference Manual

A
                      |
                   C
                      |
                   D
                      |
                   E
                      |
                   F
                      |
                   I
                      |
                   M
                      |
                   R
                      |
                   S
                      |
                   T
                      |
                   W

Index of new symbols in 2.8

A

GtkAboutDialog:wrap-license, object property in GtkAboutDialog

gtk_about_dialog_get_wrap_license, function in GtkAboutDialog

gtk_about_dialog_set_wrap_license, function in GtkAboutDialog

gtk_action_get_accel_closure, function in GtkAction

C

GtkCellRendererPixbuf:follow-state, object property in GtkCellRendererPixbuf

GtkCellRendererPixbuf:icon-name, object property in GtkCellRendererPixbuf

GtkCellRendererText:wrap-mode, object property in GtkCellRendererText

GtkCellRendererText:wrap-width, object property in GtkCellRendererText

D

gtk_dialog_get_response_for_widget, function in GtkDialog

gtk_drag_set_icon_name, function in Drag and Drop

gtk_drag_source_set_icon_name, function in Drag and Drop

E

GtkEntryCompletion:popup-set-width, object property in GtkEntryCompletion

GtkEntryCompletion:popup-single-match, object property in GtkEntryCompletion

gtk_entry_completion_get_popup_set_width, function in GtkEntryCompletion

gtk_entry_completion_get_popup_single_match, function in GtkEntryCompletion

gtk_entry_completion_set_popup_set_width, function in GtkEntryCompletion

gtk_entry_completion_set_popup_single_match, function in GtkEntryCompletion

F

GtkFileChooser::confirm-overwrite, object signal in GtkFileChooser

GtkFileChooser:do-overwrite-confirmation, object property in GtkFileChooser

GtkFileChooserConfirmation, enum in GtkFileChooser

gtk_file_chooser_get_do_overwrite_confirmation, function in GtkFileChooser

gtk_file_chooser_set_do_overwrite_confirmation, function in GtkFileChooser

I

GtkIconView:reorderable, object property in GtkIconView

gtk_icon_view_create_drag_icon, function in GtkIconView

gtk_icon_view_enable_model_drag_dest, function in GtkIconView

gtk_icon_view_enable_model_drag_source, function in GtkIconView

gtk_icon_view_get_cursor, function in GtkIconView

gtk_icon_view_get_dest_item_at_pos, function in GtkIconView

gtk_icon_view_get_drag_dest_item, function in GtkIconView

gtk_icon_view_get_item_at_pos, function in GtkIconView

gtk_icon_view_get_reorderable, function in GtkIconView

gtk_icon_view_get_visible_range, function in GtkIconView

gtk_icon_view_scroll_to_path, function in GtkIconView

gtk_icon_view_set_cursor, function in GtkIconView

gtk_icon_view_set_drag_dest_item, function in GtkIconView

gtk_icon_view_set_reorderable, function in GtkIconView

gtk_icon_view_unset_model_drag_dest, function in GtkIconView

gtk_icon_view_unset_model_drag_source, function in GtkIconView

gtk_image_clear, function in GtkImage

M

GtkMenuBar:child-pack-direction, object property in GtkMenuBar

GtkMenuBar:pack-direction, object property in GtkMenuBar

GtkMenuShell:take-focus, object property in GtkMenuShell

gtk_menu_bar_get_child_pack_direction, function in GtkMenuBar

gtk_menu_bar_get_pack_direction, function in GtkMenuBar

gtk_menu_bar_set_child_pack_direction, function in GtkMenuBar

gtk_menu_bar_set_pack_direction, function in GtkMenuBar

gtk_menu_shell_get_take_focus, function in GtkMenuShell

gtk_menu_shell_set_take_focus, function in GtkMenuShell

R

GtkRadioMenuItem:group, object property in GtkRadioMenuItem

GtkRuler:metric, object property in GtkRuler

S

gtk_scrolled_window_get_hscrollbar, function in GtkScrolledWindow

gtk_scrolled_window_get_vscrollbar, function in GtkScrolledWindow

GtkSizeGroup:ignore-hidden, object property in GtkSizeGroup

gtk_size_group_get_ignore_hidden, function in GtkSizeGroup

gtk_size_group_set_ignore_hidden, function in GtkSizeGroup

GTK_STOCK_FULLSCREEN, macro in Stock Items

GTK_STOCK_INFO, macro in Stock Items

GTK_STOCK_LEAVE_FULLSCREEN, macro in Stock Items

gtk_stock_set_translate_func, function in Stock Items

T

GtkTextBuffer:text, object property in GtkTextBuffer

GtkTextTag:invisible, object property in GtkTextTag

GtkTextTag:paragraph-background, object property in GtkTextTag

GtkTextTag:paragraph-background-gdk, object property in GtkTextTag

gtk_text_iter_backward_visible_line, function in GtkTextIter

gtk_text_iter_backward_visible_lines, function in GtkTextIter

gtk_text_iter_forward_visible_line, function in GtkTextIter

gtk_text_iter_forward_visible_lines, function in GtkTextIter

GtkToggleToolButton:active, object property in GtkToggleToolButton

GtkToolbar:tooltips, object property in GtkToolbar

GtkToolButton:icon-name, object property in GtkToolButton

gtk_tool_button_get_icon_name, function in GtkToolButton

gtk_tool_button_set_icon_name, function in GtkToolButton

gtk_tree_row_reference_get_model, function in GtkTreeModel

gtk_tree_view_column_queue_resize, function in GtkTreeViewColumn

gtk_tree_view_get_visible_range, function in GtkTreeView

W

GtkWidget::grab-broken-event, object signal in GtkWidget

GtkWidget:draw-border, object property in GtkWidget

gtk_window_get_urgency_hint, function in GtkWindow

gtk_window_present_with_time, function in GtkWindow

gtk_window_set_urgency_hint, function in GtkWindow

          Generated by GTK-Doc V1.15


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class ListTicketCollaborators(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the ListTicketCollaborators Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(ListTicketCollaborators, self).__init__(temboo_session, '/Library/Zendesk/Tickets/ListTicketCollaborators')

    def new_input_set(self):
        return ListTicketCollaboratorsInputSet()

    def _make_result_set(self, result, path):
        return ListTicketCollaboratorsResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return ListTicketCollaboratorsChoreographyExecution(session, exec_id, path)

class ListTicketCollaboratorsInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the ListTicketCollaborators
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_Email(self, value):
        """
        Set the value of the Email input for this Choreo. ((required, string) The email address you use to login to your Zendesk account.)
        """
        super(ListTicketCollaboratorsInputSet, self)._set_input('Email', value)
    def set_ID(self, value):
        """
        Set the value of the ID input for this Choreo. ((required, integer) The ID number of a ticket.)
        """
        super(ListTicketCollaboratorsInputSet, self)._set_input('ID', value)
    def set_Page(self, value):
        """
        Set the value of the Page input for this Choreo. ((optional, integer) The page number of the results to be returned. Used together with the PerPage parameter to paginate a large set of results.)
        """
        super(ListTicketCollaboratorsInputSet, self)._set_input('Page', value)
    def set_Password(self, value):
        """
        Set the value of the Password input for this Choreo. ((required, password) Your Zendesk password.)
        """
        super(ListTicketCollaboratorsInputSet, self)._set_input('Password', value)
    def set_PerPage(self, value):
        """
        Set the value of the PerPage input for this Choreo. ((optional, integer) The number of results to return per page. Maximum is 100 and default is 100.)
        """
        super(ListTicketCollaboratorsInputSet, self)._set_input('PerPage', value)
    def set_Server(self, value):
        """
        Set the value of the Server input for this Choreo. ((required, string) Your Zendesk domain and subdomain (e.g., temboocare.zendesk.com).)
        """
        super(ListTicketCollaboratorsInputSet, self)._set_input('Server', value)

class ListTicketCollaboratorsResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the ListTicketCollaborators Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Zendesk.)
        """
        return self._output.get('Response', None)
    def get_NextPage(self):
        """
        Retrieve the value for the "NextPage" output from this Choreo execution. ((integer) The index for the next page of results.)
        """
        return self._output.get('NextPage', None)
    def get_PreviousPage(self):
        """
        Retrieve the value for the "PreviousPage" output from this Choreo execution. ((integer) The index for the previous page of results.)
        """
        return self._output.get('PreviousPage', None)

class ListTicketCollaboratorsChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return ListTicketCollaboratorsResultSet(response, path)


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

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/username"
        android:inputType="textEmailAddress" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:fontFamily="sans-serif"
        android:hint="@string/password"
        android:inputType="textPassword" />

</LinearLayout>


text:
package org.diirt.graphene.profile.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Handles reading from the .CSV file.
 *
 * @author asbarber
 */
public class CSVReader {

    /**
     * Quote delimiter for a .CSV formatted output file.
     */
    public static final String QUOTE = "\"";

    /**
     * Comma delimiter for a .CSV formatted output file.
     */
    public static final String DELIM = ",";

    /**
     * Prevents instantiation.
     */
    private CSVReader() {}

    //Parsing CSV File
    //--------------------------------------------------------------------------

    /**
     * Parse the entries from the row that are delimited by a comma.
     * @param row the string to be parsed
     * @return a List containing every entry from the row
     */
    private static List<String>          parseRow(String row){
        if (row == null){
            throw new IllegalArgumentException("Requires non-null row data.");
        }

        return Arrays.asList(row.split(DELIM));
    }

    /**
     * Reads an entry for each entry in the .CSV file.
     * @param csvFile .CSV file to read from
     * @return a List containing every row represented as a List of entries
     */
    private static List<List<String>>    parseRows(List<String> rows){
        if (rows == null){
            throw new IllegalArgumentException("Requires non-null list of rows.");
        }

        List<List<String>> parsed = new ArrayList<>();

        for (String row: rows){
            if (row == null){
                throw new IllegalArgumentException("Requires non-null row data.");
            }

            parsed.add( CSVReader.parseRow(row) );
        }

        return parsed;
    }

    /**
     * Reads a string for each row in the .CSV file and validates the file
     * as a valid .CSV file.
     * @param csvFile .CSV file to read from
     * @return a List with each row as a string
     */
    public static List<String>           readRows(File csvFile){
        CSVFinder.validateCSV(csvFile);

        List<String> rows = new ArrayList<>();
        String row;
        FileReader fr = null;
        BufferedReader reader;

        try{
            fr = new FileReader(csvFile);
            reader = new BufferedReader(fr);

            while ( (row = reader.readLine()) != null ){
                rows.add(row);
            }

            reader.close();
        }
        catch(FileNotFoundException ex){
            throw new IllegalArgumentException("The file " + csvFile.getPath() + " does not exist");
        }
        catch (IOException ex){
            System.err.println("Could not close BufferedReader stream.");
        }
        finally{
            try {
                if (fr != null){
                    fr.close();
                }
            }
            catch (IOException ex){
                System.err.println("Could not close FileReader stream.");
            }
        }

        return rows;
    }

    /**
     * Reads an entry for each entry in the .CSV file and validates the file
     * as a valid .CSV file.
     * @param csvFile .CSV file to read from
     * @return a List container every row represented as a List of entries
     */
    public static List<List<String>>     parseCSV(File csvFile){
        CSVFinder.validateCSV(csvFile);

        return parseRows(readRows(csvFile));
    }

    //--------------------------------------------------------------------------

    //Validating CSV File
    //--------------------------------------------------------------------------

    /**
     * Ensures that each file name contains three components as delimited
     * by the "-" character.
     * The first component represents a date, the second represents
     * the graph type, and the third type represents Table2D.
     *

     * Throws an illegal argument exception if the graph type and component
     * sizes are incorrect.
     *
     * @param csvA file A corresponding to one Table2D output file
     * @param csvB file B corresponding to one Table2D output file
     */
    public static void validate2DTablesNames(File csvA, File csvB){
        CSVFinder.validateCSV(csvA);
        CSVFinder.validateCSV(csvB);

        //{Date, Graph Type, Table.csv}
        String[] compA = csvA.getName().split("-");
        String[] compB = csvB.getName().split("-");

        if (compA.length != 3){
            throw new IllegalArgumentException("File A is name incorrectly");
        }
        if (compB.length != 3){
            throw new IllegalArgumentException("File B is name incorrectly");
        }

        if (!compA[1].equals(compB[1])){
            throw new IllegalArgumentException("The files are not the same graph type.");
        }
    }

    /**
     * Ensures that the data is non-null, the data has the same size,
     * and each inner list has the same size in both datasets.
     *

     * Throws an illegal argument exception if these conditions are not met.
     *
     * @param dataA one set of CSV entries
     * @param dataB another set of CSV entries
     */
    public static void validate2DTables(List<List<String>> dataA, List<List<String>> dataB){
        if (dataA == null){
            throw new IllegalArgumentException("Data must not be null.");
        }
        if (dataB == null){
            throw new IllegalArgumentException("Data must not be null.");
        }

        if (dataA.size() != dataB.size()){
            throw new IllegalArgumentException("Must have same number of rows.");
        }

        int rows = dataA.size();

        for (int i = 0; i < rows; ++i){
            if (dataA.get(i) == null){
                throw new IllegalArgumentException("Row " + i  + " of dataset 1 is null.");
            }

            if (dataB.get(i) == null){
                throw new IllegalArgumentException("Row " + i  + " of dataset 2 is null.");
            }

            if (dataA.get(i).size() != dataB.get(i).size()){
                throw new IllegalArgumentException("Row " + i  + " of dataset 1 and dataset2 must have the same number of columns.");
            }
        }
    }

    //--------------------------------------------------------------------------
}


text: <!DOCTYPE html>


text:
var http=require('http');
var assert=require('assert');

var opts={
    host:'localhost',
    port:8000,
    path:'/send',
    method:'POST',
    headers:{'content-type':'application/x-www-form-urlencoded'}
};

var req=http.request(opts,function(res){
    res.setEncoding('utf8');

    var data='';
    res.on('data',function(d){
        data+=d;
    });

    res.on('end',function(){
        assert.strictEqual(data,'{"status":"ok","message":"Tweet received"}');
        console.log('success');
    });
});
req.write("tweet=test");
req.end();


text:
module Ecm::Videos
  class Category < ActiveRecord::Base
    # markup support
    include Models::MarkupConcern
    markup :description

    # acts as published
    include ActsAsPublished::ActiveRecord
    acts_as_published

    has_many :videos, -> { order(position: :asc) }

    validates :locale, :name, :markup_language, presence: true

    after_initialize :set_defaults, if: :new_record?

    def preview_image
      videos.first.try(:preview_image)
    end

    def published_preview_image_url(style)
      return unless video = videos.published.first
      video.clip.url(style)
    end

    def videos_count
      videos.count
    end

    private

    def set_defaults
      self.markup_language = Configuration.default_markup_language
    end
  end
end


text:
We implemented a memebot for slack, built on the [serverless framework](https://serverless.com/) to use as a demonstration for the [Disruptors in Tech meetup](https://www.meetup.com/en-AU/Disruptors-in-Tech/).  [See slides](https://slid.es/em0ney/sls).  It was implemented by [GorillaStack](www.gorillastack.com) to serve as a boilerplate for similar serverless projects.

The key purpose of the talk was to demonstrate how to work with frameworks and minimise risks around framework changes and provider lock-in.

## Usage

### Development environment

It is possible to run this slackbot in your slack rooms without deploying to AWS!

#### Local environment variables

The serverless framework will be loading environment variables from the file `bot/.env`.  For security reasons, we ignore this file from the repository.  There is an example file you can copy.

```
cp bot/.env.example bot/.env
```

Then, it is important to get `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET` and the `SLACK_VERIFICATION_TOKEN` from `Settings` > `Basic Information` within the configuration of the Slack App.

Terminal1:

```shell
#!/bin/bash

## First install npm dependencies for the project
npm install

## Now install npm dependencies that will be packaged up with our slackbot and deployed
pushd bot && npm install && popd

## Now run babel in watch mode to listen for changes to our code
npm run compile:dev
```

Terminal2:

```shell
#!/bin/bash

## Move into the bot/ directory
cd bot

## Run the offline plugin for the serverless framework to emulate API gateway and invoke our lambda functions
## We should now be listening on localhost:3000
sls offline
```

Terminal3:

```shell
#!/bin/bash

## Use ngrok to expose our localhost:3000 to a public https endpoint
ngrok http 3000
```

While contributing, or working on your fork, run `npm test` to run tests, `npm run cover` to run tests and check code coverage and `npm run lint` to check our code styling.  To see an HTML report of our code coverage, go to `/path/to/project/coverage/lcov-report/index.html` in your web browser.

### Slack configuration

To integrate your development, production or any other environment with slack, you will need to set up a slack app.

1. Go to https://api.slack.com/apps
1. Click the "Create New App" button
1. Enter your app's name and a development slack team and click "Create App" ![create app](https://s3-ap-southeast-2.amazonaws.com/gorillastack-random/create_app.png)
1. Under "Add features and functionality", click "Slash Commands" ![add features and functionality](https://s3-ap-southeast-2.amazonaws.com/gorillastack-random/add_functionality.png)
1. Click "Create New Command"
1. Enter the command details and press save ![slash command details](https://s3-ap-southeast-2.amazonaws.com/gorillastack-random/create_new_command.png)
1. Select OAuth & Permissions from the sidebar
1. Click "Install App to Team" to finish :)

### Deploy to production


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="Users" transaction-type="RESOURCE_LOCAL">

		<class>no.haktho.cossmic.forest.model.User</class>
		<class>no.haktho.cossmic.forest.model.Node</class>
		<properties>
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
			<property name="javax.persistence.jdbc.user" value="root"/>
			<property name="javax.persistence.jdbc.password" value="cossmic123"/>
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
			<property name="javax.persistence.schema-generation.database.action" value="create"/>
		</properties>
	</persistence-unit>
</persistence>


text:
gitconfig
==========

[![Build Status][bd_travis_shield_url]][bd_travis_url]
[![Code Climate][bd_codeclimate_shield_url]][bd_codeclimate_url]
[![Code Coverage][bd_codeclimate_coverage_shield_url]][bd_codeclimate_url]
[![npm Version][bd_npm_shield_url]][bd_npm_url]
[![JS Standard][bd_standard_shield_url]][bd_standard_url]

[bd_repo_url]: https://github.com/okunishinishi/node-gitconfig
[bd_travis_url]: http://travis-ci.org/okunishinishi/node-gitconfig
[bd_travis_shield_url]: http://img.shields.io/travis/okunishinishi/node-gitconfig.svg?style=flat
[bd_travis_com_url]: http://travis-ci.com/okunishinishi/node-gitconfig
[bd_travis_com_shield_url]: https://api.travis-ci.com/okunishinishi/node-gitconfig.svg?token=
[bd_license_url]: https://github.com/okunishinishi/node-gitconfig/blob/master/LICENSE
[bd_codeclimate_url]: http://codeclimate.com/github/okunishinishi/node-gitconfig
[bd_codeclimate_shield_url]: http://img.shields.io/codeclimate/github/okunishinishi/node-gitconfig.svg?style=flat
[bd_codeclimate_coverage_shield_url]: http://img.shields.io/codeclimate/coverage/github/okunishinishi/node-gitconfig.svg?style=flat
[bd_gemnasium_url]: https://gemnasium.com/okunishinishi/node-gitconfig
[bd_gemnasium_shield_url]: https://gemnasium.com/okunishinishi/node-gitconfig.svg
[bd_npm_url]: http://www.npmjs.org/package/gitconfig
[bd_npm_shield_url]: http://img.shields.io/npm/v/gitconfig.svg?style=flat
[bd_standard_url]: http://standardjs.com/
[bd_standard_shield_url]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg

Run git config command

Installation
-----

```bash
npm install gitconfig --save
```

Usage
---------

```javascript
'use strict'

const gitconfig = require('gitconfig')

// Set git config values.
gitconfig.set({
  'user.mail': 'foo@example.com'
}, {
  location: 'local'
}).then(() => {
  /* ... */
})

// Unset git config values.
gitconfig.unset([ 'user.mail' ], {
  location: 'local'
}).then(() => {
  /* ... */
})

// Git all config values.
gitconfig.get({
  location: 'global'
}).then((config) => {
  /* ... */
})
```

API
---

| Signature | Description |
| --------- | ----------- |
| gitconfig.get(options, callback) | Get all git config. |
| gitconfig.get(key, options, callback) | Get config with key. |
| gitconfig.set(key, val, options, callback) | Set a config value. |
| gitconfig.set(values, options, callback) | Set mutliple config values. |
| gitconfig.unset(keys, options, callback) | Un set config value(s). |

Options
-------

| Name | Description |
| ---- | ----- |
| location | Config file location. (global, system, or local) |

License
-------
This software is released under the [MIT License](https://github.com/okunishinishi/node-gitconfig/blob/master/LICENSE).

Links
------

+ [git-config][git_config_url]

[git_config_url]: https://git-scm.com/docs/git-config


text:
#import "MDCTabBar.h"

#import "MDCTabBarIndicatorTemplate.h"
#import "MDCTabBarUnderlineIndicatorTemplate.h"
#import "MaterialInk.h"
#import "MaterialTypography.h"
#import "private/MDCItemBar.h"
#import "private/MDCItemBarAlignment.h"
#import "private/MDCItemBarStyle.h"

static NSString *const MDCTabBarItemsKey = @"MDCTabBarItemsKey";
static NSString *const MDCTabBarSelectedItemKey = @"MDCTabBarSelectedItemKey";
static NSString *const MDCTabBarDelegateKey = @"MDCTabBarDelegateKey";
static NSString *const MDCTabBarTintColorKey = @"MDCTabBarTintColorKey";
static NSString *const MDCTabBarSelectedItemTintColorKey = @"MDCTabBarSelectedItemTintColorKey";
static NSString *const MDCTabBarUnselectedItemTintColorKey = @"MDCTabBarUnselectedItemTintColorKey";
static NSString *const MDCTabBarInkColorKey = @"MDCTabBarInkColorKey";
static NSString *const MDCTabBarSelectedItemTitleFontKey = @"MDCTabBarSelectedItemTitleFontKey";
static NSString *const MDCTabBarUnselectedItemTitleFontKey = @"MDCTabBarUnselectedItemTitleFontKey";
static NSString *const MDCTabBarBarTintColorKey = @"MDCTabBarBarTintColorKey";
static NSString *const MDCTabBarAlignmentKey = @"MDCTabBarAlignmentKey";
static NSString *const MDCTabBarItemApperanceKey = @"MDCTabBarItemApperanceKey";
static NSString *const MDCTabBarDisplaysUppercaseTitlesKey = @"MDCTabBarDisplaysUppercaseTitlesKey";
static NSString *const MDCTabBarTitleTextTransformKey = @"MDCTabBarTitleTextTransformKey";
static NSString *const MDCTabBarSelectionIndicatorTemplateKey = @"MDCTabBarSelectionIndicatorTemplateKey";

/// Padding between image and title in points, according to the spec.
static const CGFloat kImageTitleSpecPadding = 10;

/// Adjustment added to spec measurements to compensate for internal paddings.
static const CGFloat kImageTitlePaddingAdjustment = -3;

// Heights based on the spec: https://material.io/guidelines/components/tabs.html

/// Height for image-only tab bars, in points.
static const CGFloat kImageOnlyBarHeight = 48;

/// Height for image-only tab bars, in points.
static const CGFloat kTitleOnlyBarHeight = 48;

/// Height for image-and-title tab bars, in points.
static const CGFloat kTitledImageBarHeight = 72;

/// Height for bottom navigation bars, in points.
static const CGFloat kBottomNavigationBarHeight = 56;

/// Maximum width for individual items in bottom navigation bars, in points.
static const CGFloat kBottomNavigationMaximumItemWidth = 168;

/// Title-image padding for bottom navigation bars, in points.
static const CGFloat kBottomNavigationTitleImagePadding = 3;

static MDCItemBarAlignment MDCItemBarAlignmentForTabBarAlignment(MDCTabBarAlignment alignment) {
  switch (alignment) {
    case MDCTabBarAlignmentCenter:
      return MDCItemBarAlignmentCenter;

    case MDCTabBarAlignmentLeading:
      return MDCItemBarAlignmentLeading;

    case MDCTabBarAlignmentJustified:
      return MDCItemBarAlignmentJustified;

    case MDCTabBarAlignmentCenterSelected:
      return MDCItemBarAlignmentCenterSelected;
  }

  NSCAssert(0, @"Invalid alignment value %ld", (long)alignment);
  return MDCItemBarAlignmentLeading;
}

@interface MDCTabBar () <MDCItemBarDelegate>
@end

@implementation MDCTabBar {
  /// Item bar responsible for displaying the actual tab bar content.
  MDCItemBar *_itemBar;

  // Flags tracking if properties are unset and using default values.
  BOOL _hasDefaultAlignment;
  BOOL _hasDefaultItemAppearance;

  // For properties which have been set, these store the new fixed values.
  MDCTabBarAlignment _alignmentOverride;
  MDCTabBarItemAppearance _itemAppearanceOverride;
}
// Inherit UIView's tintColor logic.
@dynamic tintColor;
@synthesize alignment = _alignment;
@synthesize barPosition = _barPosition;
@synthesize itemAppearance = _itemAppearance;

#pragma mark - Initialization

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  self = [super initWithCoder:aDecoder];
  if (self) {
    [self commonMDCTabBarInit];

    // Use self. when setter needs to be called
    if ([aDecoder containsValueForKey:MDCTabBarItemsKey]) {
      self.items = [aDecoder decodeObjectOfClass:[NSArray class] forKey:MDCTabBarItemsKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarSelectedItemKey]) {
      self.selectedItem = [aDecoder decodeObjectOfClass:[UIBarButtonItem class]
                                                 forKey:MDCTabBarSelectedItemKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarDelegateKey]) {
      self.delegate = [aDecoder decodeObjectForKey:MDCTabBarDelegateKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarTintColorKey]) {
      self.tintColor = [aDecoder decodeObjectOfClass:[UIColor class]
                                              forKey:MDCTabBarTintColorKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarSelectedItemTintColorKey]) {
      _selectedItemTintColor = [aDecoder decodeObjectOfClass:[UIColor class]
                                                      forKey:MDCTabBarSelectedItemTintColorKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarUnselectedItemTintColorKey]) {
      _unselectedItemTintColor =
          [aDecoder decodeObjectOfClass:[UIColor class] forKey:MDCTabBarUnselectedItemTintColorKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarInkColorKey]) {
      _inkColor = [aDecoder decodeObjectOfClass:[UIColor class] forKey:MDCTabBarInkColorKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarSelectedItemTitleFontKey]) {
      _selectedItemTitleFont = [aDecoder decodeObjectOfClass:[UIFont class]
                                                      forKey:MDCTabBarSelectedItemTitleFontKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarUnselectedItemTitleFontKey]) {
      _unselectedItemTitleFont =
          [aDecoder decodeObjectOfClass:[UIFont class] forKey:MDCTabBarUnselectedItemTitleFontKey];
    }

    if ([aDecoder containsValueForKey:MDCTabBarBarTintColorKey]) {
      self.barTintColor = [aDecoder decodeObjectOfClass:[UIColor class]
                                                 forKey:MDCTabBarBarTintColorKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarAlignmentKey]) {
      self.alignment = [aDecoder decodeIntegerForKey:MDCTabBarAlignmentKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarItemApperanceKey]) {
      self.itemAppearance = [aDecoder decodeIntegerForKey:MDCTabBarItemApperanceKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarDisplaysUppercaseTitlesKey]) {
      self.displaysUppercaseTitles = [aDecoder decodeBoolForKey:MDCTabBarDisplaysUppercaseTitlesKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarTitleTextTransformKey]) {
      _titleTextTransform = [aDecoder decodeIntegerForKey:MDCTabBarTitleTextTransformKey];
    }
    if ([aDecoder containsValueForKey:MDCTabBarSelectionIndicatorTemplateKey]) {
      _selectionIndicatorTemplate =
          [aDecoder decodeObjectOfClass:[NSObject class]
                                 forKey:MDCTabBarSelectionIndicatorTemplateKey];
    }
    [self updateItemBarStyle];
  }
  return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self commonMDCTabBarInit];
  }
  return self;
}

- (void)commonMDCTabBarInit {
  _selectedItemTintColor = [UIColor whiteColor];
  _unselectedItemTintColor = [UIColor colorWithWhite:1.0f alpha:0.7f];
  _inkColor = [UIColor colorWithWhite:1.0f alpha:0.7f];

  self.clipsToBounds = YES;
  _barPosition = UIBarPositionAny;
  _hasDefaultItemAppearance = YES;
  _hasDefaultAlignment = YES;

  // Set default values
  _alignment = [self computedAlignment];
  _titleTextTransform = MDCTabBarTextTransformAutomatic;
  _itemAppearance = [self computedItemAppearance];
  _selectionIndicatorTemplate = [MDCTabBar defaultSelectionIndicatorTemplate];
  _selectedItemTitleFont = [MDCTypography buttonFont];
  _unselectedItemTitleFont = [MDCTypography buttonFont];

  // Create item bar.
  _itemBar = [[MDCItemBar alloc] initWithFrame:self.bounds];
  _itemBar.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
  _itemBar.delegate = self;
  _itemBar.alignment = MDCItemBarAlignmentForTabBarAlignment(_alignment);
  [self addSubview:_itemBar];

  [self updateItemBarStyle];
}

- (void)layoutSubviews {
  [super layoutSubviews];

  CGSize sizeThatFits = [_itemBar sizeThatFits:self.bounds.size];
  _itemBar.frame = CGRectMake(0, 0, sizeThatFits.width, sizeThatFits.height);
}

-(void)encodeWithCoder:(NSCoder *)aCoder {
  [super encodeWithCoder:aCoder];
  [aCoder encodeObject:self.items forKey:MDCTabBarItemsKey];
  [aCoder encodeObject:self.selectedItem forKey:MDCTabBarSelectedItemKey];
  [aCoder encodeConditionalObject:self.delegate forKey:MDCTabBarDelegateKey];
  [aCoder encodeObject:self.tintColor forKey:MDCTabBarTintColorKey];
  [aCoder encodeObject:_selectedItemTintColor forKey:MDCTabBarSelectedItemTintColorKey];
  [aCoder encodeObject:_unselectedItemTintColor forKey:MDCTabBarUnselectedItemTintColorKey];
  [aCoder encodeObject:_inkColor forKey:MDCTabBarInkColorKey];
  [aCoder encodeObject:_selectedItemTitleFont forKey:MDCTabBarSelectedItemTitleFontKey];
  [aCoder encodeObject:_unselectedItemTitleFont forKey:MDCTabBarUnselectedItemTitleFontKey];
  [aCoder encodeObject:_barTintColor forKey:MDCTabBarBarTintColorKey];
  [aCoder encodeInteger:_alignment forKey:MDCTabBarAlignmentKey];
  [aCoder encodeInteger:_itemAppearance forKey:MDCTabBarItemApperanceKey];
  [aCoder encodeBool:self.displaysUppercaseTitles forKey:MDCTabBarDisplaysUppercaseTitlesKey];
  [aCoder encodeInteger:_titleTextTransform forKey:MDCTabBarTitleTextTransformKey];
  if ([_selectionIndicatorTemplate conformsToProtocol:@protocol(NSCoding)]) {
    [aCoder encodeObject:_selectionIndicatorTemplate
                  forKey:MDCTabBarSelectionIndicatorTemplateKey];
  }
}

#pragma mark - Public

+ (CGFloat)defaultHeightForBarPosition:(UIBarPosition)position
                        itemAppearance:(MDCTabBarItemAppearance)appearance {
  if ([self isTopTabsForPosition:position]) {
    switch (appearance) {
      case MDCTabBarItemAppearanceTitledImages:
        return kTitledImageBarHeight;

      case MDCTabBarItemAppearanceTitles:
        return kTitleOnlyBarHeight;

      case MDCTabBarItemAppearanceImages:
        return kImageOnlyBarHeight;
    }
  } else {
    // Bottom navigation has a fixed height.
    return kBottomNavigationBarHeight;
  }
}

+ (CGFloat)defaultHeightForItemAppearance:(MDCTabBarItemAppearance)appearance {
  return [self defaultHeightForBarPosition:UIBarPositionAny itemAppearance:appearance];
}

- (void)setDelegate:(id<MDCTabBarDelegate>)delegate {
  if (delegate != _delegate) {
    _delegate = delegate;

    // Delegate determines the position - update immediately.
    [self updateItemBarPosition];
  }
}

- (NSArray<UITabBarItem *> *)items {
  return _itemBar.items;
}

- (void)setItems:(NSArray<UITabBarItem *> *)items {
  _itemBar.items = items;
}

- (UITabBarItem *)selectedItem {
  return _itemBar.selectedItem;
}

- (void)setSelectedItem:(UITabBarItem *)selectedItem {
  _itemBar.selectedItem = selectedItem;
}

- (void)setSelectedItem:(UITabBarItem *)selectedItem animated:(BOOL)animated {
  [_itemBar setSelectedItem:selectedItem animated:animated];
}

- (void)setBarTintColor:(UIColor *)barTintColor {
  if (_barTintColor != barTintColor && ![_barTintColor isEqual:barTintColor]) {
    _barTintColor = barTintColor;

    // Update background color.
    self.backgroundColor = barTintColor;
  }
}

- (void)setInkColor:(UIColor *)inkColor {
  if (_inkColor != inkColor && ![_inkColor isEqual:inkColor]) {
    _inkColor = inkColor;

    [self updateItemBarStyle];
  }
}

- (void)setUnselectedItemTitleFont:(UIFont *)unselectedItemTitleFont {
  if ((unselectedItemTitleFont != _unselectedItemTitleFont) &&
      ![unselectedItemTitleFont isEqual:_unselectedItemTitleFont]) {
    _unselectedItemTitleFont = unselectedItemTitleFont;
    [self updateItemBarStyle];
  }
}

- (void)setSelectedItemTitleFont:(UIFont *)selectedItemTitleFont {
  if ((selectedItemTitleFont != _selectedItemTitleFont) &&
      ![selectedItemTitleFont isEqual:_selectedItemTitleFont]) {
    _selectedItemTitleFont = selectedItemTitleFont;
    [self updateItemBarStyle];
  }
}

- (void)setAlignment:(MDCTabBarAlignment)alignment {
  [self setAlignment:alignment animated:NO];
}

- (void)setAlignment:(MDCTabBarAlignment)alignment animated:(BOOL)animated {
  _hasDefaultAlignment = NO;
  _alignmentOverride = alignment;
  [self internalSetAlignment:[self computedAlignment] animated:animated];
}

- (void)setItemAppearance:(MDCTabBarItemAppearance)itemAppearance {
  _hasDefaultItemAppearance = NO;
  _itemAppearanceOverride = itemAppearance;
  [self internalSetItemAppearance:[self computedItemAppearance]];
}

- (void)setSelectedItemTintColor:(UIColor *)selectedItemTintColor {
  if (_selectedItemTintColor != selectedItemTintColor &&
      ![_selectedItemTintColor isEqual:selectedItemTintColor]) {
    _selectedItemTintColor = selectedItemTintColor;

    [self updateItemBarStyle];
  }
}

- (void)setUnselectedItemTintColor:(UIColor *)unselectedItemTintColor {
  if (_unselectedItemTintColor != unselectedItemTintColor &&
      ![_unselectedItemTintColor isEqual:unselectedItemTintColor]) {
    _unselectedItemTintColor = unselectedItemTintColor;

    [self updateItemBarStyle];
  }
}

- (BOOL)displaysUppercaseTitles {
  switch (self.titleTextTransform) {
    case MDCTabBarTextTransformAutomatic:
      return [MDCTabBar displaysUppercaseTitlesByDefaultForPosition:_barPosition];

    case MDCTabBarTextTransformNone:
      return NO;

    case MDCTabBarTextTransformUppercase:
      return YES;
  }
}

- (void)setDisplaysUppercaseTitles:(BOOL)displaysUppercaseTitles {
  self.titleTextTransform =
      displaysUppercaseTitles ? MDCTabBarTextTransformUppercase : MDCTabBarTextTransformNone;
}

- (void)setTitleTextTransform:(MDCTabBarTextTransform)titleTextTransform {
  if (titleTextTransform != _titleTextTransform) {
    _titleTextTransform = titleTextTransform;
    [self updateItemBarStyle];
  }
}

- (void)setSelectionIndicatorTemplate:(id<MDCTabBarIndicatorTemplate>)selectionIndicatorTemplate {
  id<MDCTabBarIndicatorTemplate> template = selectionIndicatorTemplate;
  if (!template) {
    template = [MDCTabBar defaultSelectionIndicatorTemplate];
  }
  _selectionIndicatorTemplate = template;
  [self updateItemBarStyle];
}

#pragma mark - MDCAccessibility

- (id)accessibilityElementForItem:(UITabBarItem *)item {
  return [_itemBar accessibilityElementForItem:item];
}

#pragma mark - MDCItemBarDelegate

- (void)itemBar:(__unused MDCItemBar *)itemBar didSelectItem:(UITabBarItem *)item {
  id<MDCTabBarDelegate> delegate = self.delegate;
  if ([delegate respondsToSelector:@selector(tabBar:didSelectItem:)]) {
    [delegate tabBar:self didSelectItem:item];
  }
}

- (BOOL)itemBar:(__unused MDCItemBar *)itemBar shouldSelectItem:(UITabBarItem *)item {
  id<MDCTabBarDelegate> delegate = self.delegate;
  BOOL shouldSelect = YES;
  if ([delegate respondsToSelector:@selector(tabBar:shouldSelectItem:)]) {
    shouldSelect = [delegate tabBar:self shouldSelectItem:item];
  }
  if (shouldSelect && [delegate respondsToSelector:@selector(tabBar:willSelectItem:)]) {
    [delegate tabBar:self willSelectItem:item];
  }
  return shouldSelect;
}

#pragma mark - UIView

- (void)tintColorDidChange {
  [super tintColorDidChange];

  [self updateItemBarStyle];
}

- (CGSize)intrinsicContentSize {
  return _itemBar.intrinsicContentSize;
}

- (CGSize)sizeThatFits:(CGSize)size {
  return [_itemBar sizeThatFits:size];
}

- (void)didMoveToWindow {
  [super didMoveToWindow];

  // Ensure the bar position is up to date before moving to a window.
  [self updateItemBarPosition];
}

#pragma mark - Private

+ (MDCItemBarStyle *)defaultStyleForPosition:(UIBarPosition)position
                              itemAppearance:(MDCTabBarItemAppearance)appearance {
  MDCItemBarStyle *style = [[MDCItemBarStyle alloc] init];

  // Set base style using position.
  if ([self isTopTabsForPosition:position]) {
    // Top tabs
    style.shouldDisplaySelectionIndicator = YES;
    style.shouldGrowOnSelection = NO;
    style.inkStyle = MDCInkStyleBounded;
    style.titleImagePadding = (kImageTitleSpecPadding + kImageTitlePaddingAdjustment);
    style.textOnlyNumberOfLines = 2;
  } else {
    // Bottom navigation
    style.shouldDisplaySelectionIndicator = NO;
    style.shouldGrowOnSelection = YES;
    style.maximumItemWidth = kBottomNavigationMaximumItemWidth;
    style.inkStyle = MDCInkStyleUnbounded;
    style.titleImagePadding = kBottomNavigationTitleImagePadding;
    style.textOnlyNumberOfLines = 1;
  }

  // Update appearance-dependent style properties.
  BOOL displayImage = NO;
  BOOL displayTitle = NO;
  switch (appearance) {
    case MDCTabBarItemAppearanceImages:
      displayImage = YES;
      break;

    case MDCTabBarItemAppearanceTitles:
      displayTitle = YES;
      break;

    case MDCTabBarItemAppearanceTitledImages:
      displayImage = YES;
      displayTitle = YES;
      break;

    default:
      NSAssert(0, @"Invalid appearance value %ld", (long)appearance);
      displayTitle = YES;
      break;
  }
  style.shouldDisplayImage = displayImage;
  style.shouldDisplayTitle = displayTitle;

  // Update default height
  CGFloat defaultHeight = [self defaultHeightForBarPosition:position itemAppearance:appearance];
  if (defaultHeight == 0) {
    NSAssert(0, @"Missing default height for %ld", (long)appearance);
    defaultHeight = kTitleOnlyBarHeight;
  }
  style.defaultHeight = defaultHeight;

  // Only show badge with images.
  style.shouldDisplayBadge = displayImage;

  return style;
}

+ (BOOL)isTopTabsForPosition:(UIBarPosition)position {
  switch (position) {
    case UIBarPositionAny:
    case UIBarPositionTop:
      return YES;

    case UIBarPositionBottom:
      return NO;

    case UIBarPositionTopAttached:
      NSAssert(NO, @"MDCTabBar does not support UIBarPositionTopAttached");
      return NO;
  }
}

+ (BOOL)displaysUppercaseTitlesByDefaultForPosition:(UIBarPosition)position {
  switch (position) {
    case UIBarPositionAny:
    case UIBarPositionTop:
      return YES;

    case UIBarPositionBottom:
      return NO;

    case UIBarPositionTopAttached:
      NSAssert(NO, @"MDCTabBar does not support UIBarPositionTopAttached");
      return YES;
  }
}

+ (MDCTabBarAlignment)defaultAlignmentForPosition:(UIBarPosition)position {
  switch (position) {
    case UIBarPositionAny:
    case UIBarPositionTop:
      return MDCTabBarAlignmentLeading;

    case UIBarPositionBottom:
      return MDCTabBarAlignmentJustified;

    case UIBarPositionTopAttached:
      NSAssert(NO, @"MDCTabBar does not support UIBarPositionTopAttached");
      return MDCTabBarAlignmentLeading;
  }
}

+ (MDCTabBarItemAppearance)defaultItemAppearanceForPosition:(UIBarPosition)position {
  switch (position) {
    case UIBarPositionAny:
    case UIBarPositionTop:
      return MDCTabBarItemAppearanceTitles;

    case UIBarPositionBottom:
      return MDCTabBarItemAppearanceTitledImages;

    case UIBarPositionTopAttached:
      NSAssert(NO, @"MDCTabBar does not support UIBarPositionTopAttached");
      return YES;
  }
}

+ (id<MDCTabBarIndicatorTemplate>)defaultSelectionIndicatorTemplate {
  return [[MDCTabBarUnderlineIndicatorTemplate alloc] init];
}

- (MDCTabBarAlignment)computedAlignment {
  if (_hasDefaultAlignment) {
    return [[self class] defaultAlignmentForPosition:_barPosition];
  } else {
    return _alignmentOverride;
  }
}

- (MDCTabBarItemAppearance)computedItemAppearance {
  if (_hasDefaultItemAppearance) {
    return [[self class] defaultItemAppearanceForPosition:_barPosition];
  } else {
    return _itemAppearanceOverride;
  }
}

- (void)internalSetAlignment:(MDCTabBarAlignment)alignment animated:(BOOL)animated {
  if (_alignment != alignment) {
    _alignment = alignment;
    [_itemBar setAlignment:MDCItemBarAlignmentForTabBarAlignment(_alignment) animated:animated];
  }
}

- (void)internalSetItemAppearance:(MDCTabBarItemAppearance)itemAppearance {
  if (_itemAppearance != itemAppearance) {
    _itemAppearance = itemAppearance;
    [self updateItemBarStyle];
  }
}

- (void)updateItemBarPosition {
  UIBarPosition newPosition = UIBarPositionAny;
  id<MDCTabBarDelegate> delegate = _delegate;
  if (delegate && [delegate respondsToSelector:@selector(positionForBar:)]) {
    newPosition = [delegate positionForBar:self];
  }

  if (_barPosition != newPosition) {
    _barPosition = newPosition;
    [self updatePositionDerivedDefaultValues];
    [self updateItemBarStyle];
  }
}

- (void)updatePositionDerivedDefaultValues {
  [self internalSetAlignment:[self computedAlignment] animated:NO];
  [self internalSetItemAppearance:[self computedItemAppearance]];
}

/// Update the item bar's style property, which depends on the bar position and item appearance.
- (void)updateItemBarStyle {
  MDCItemBarStyle *style;

  style = [[self class] defaultStyleForPosition:_barPosition itemAppearance:_itemAppearance];

  if ([MDCTabBar isTopTabsForPosition:_barPosition]) {
    // Top tabs: Use provided fonts.
    style.selectedTitleFont = self.selectedItemTitleFont;
    style.unselectedTitleFont = self.unselectedItemTitleFont;
  } else {
    // Bottom navigation: Ignore provided fonts.
    style.selectedTitleFont = [[MDCTypography fontLoader] regularFontOfSize:12];
    style.unselectedTitleFont = [[MDCTypography fontLoader] regularFontOfSize:12];
  }

  style.selectionIndicatorTemplate = self.selectionIndicatorTemplate;
  style.selectionIndicatorColor = self.tintColor;
  style.inkColor = _inkColor;
  style.selectedTitleColor = (_selectedItemTintColor ? _selectedItemTintColor : self.tintColor);
  style.titleColor = _unselectedItemTintColor;
  style.displaysUppercaseTitles = self.displaysUppercaseTitles;

  [_itemBar applyStyle:style];

  // Layout depends on -[MDCItemBar sizeThatFits], which depends on the style.
  [self setNeedsLayout];
}

@end


text:
module Reek
  #
  # An exception that occured when loading the configuration file.
  #
  class ConfigFileException < RuntimeError
  end
end


text:
require "gilt/client"

module Gilt
  class Client
    class Sales < Gilt::Client
      domain DOMAIN

      required :apikey

      optional :affid

      get :active, "/sales/active.#{FORMAT}"

      get :active_in_store, "/sales/:store/active.#{FORMAT}"

      get :upcoming, "/sales/upcoming.#{FORMAT}"

      get :upcoming_in_store, "/sales/:store/upcoming.#{FORMAT}"

      get :detail, "/sales/:store/:sale_key/detail.#{FORMAT}"

      [ Gilt::Stores::WOMEN,
        Gilt::Stores::MEN,
        Gilt::Stores::KIDS,
        Gilt::Stores::HOME ].each do |store|
        define_method "active_in_#{store}" do |*args, &block|
          params = args.first || {}
          active_in_store params.merge({:store => store}), &block
        end
        alias_method "#{store}_active".intern, "active_in_#{store}".intern

        define_method "upcoming_in_#{store}" do |*args, &block|
          params = args.first || {}
          upcoming_in_store params.merge({:store => store}), &block
        end
        alias_method "#{store}_upcoming".intern, "upcoming_in_#{store}".intern
      end

    end
  end
end


text:
package my.jpa.controllers;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Created by Ivan Sliusar on 31.08.2018.
 * Red Line Soft corp.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(
        locations = "classpath:application-integrationtest.properties")
public class ServletIntegrationTest {
    /**
     * Autowired MockMvc.
     */
    @Autowired
    public MockMvc mvc;

    /**
     * Testing CRUD operation by User controller.
     *
     * @throws Exception
     */
    @Test
    @WithMockUser(username = "user@gmail.com", roles = {"User"})
    public void testUserController() throws Exception {

        // Test Create
        this.mvc.perform(
                post(UserServlet.USER_URI)
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content("{\"user\":{\"id\":\"1\",\"login\":\"TestUser\",\"email\":\"test@gmail.com\",\"password\":\"vfitymrf\",\"createDate\":\"null\"},\"command\":\"CREATE\"}"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(
                        content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                )
                .andExpect(jsonPath("$.id").value(1))
                .andExpect(jsonPath("$.login").value("TestUser"))
                .andReturn();
        // Get all
        this.mvc.perform(get(UserServlet.USER_URI).accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(status().isOk())
                .andExpect(
                        content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                )
                .andExpect(jsonPath("$[0].id").value(1))
                .andExpect(jsonPath("$[0].login").value("TestUser"))
                .andDo(print())
                .andReturn();
        //Test UPDATE
        this.mvc.perform(
                post(UserServlet.USER_URI)
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content("{\"user\":{\"id\":1,\"login\":\"UpdateUser\"},\"command\":\"UPDATE\"}")
        )
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(
                        content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)

                )
                .andExpect(jsonPath("$.login").value("UpdateUser"))
                .andReturn();

        //Test DELETE
        this.mvc.perform(
                post(UserServlet.USER_URI)
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content("{\"user\":{\"id\":1},\"command\":\"DELETE\"}")
        )
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn();
        this.mvc.perform(get(UserServlet.USER_URI).accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(status().isOk())
                .andExpect(
                        content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                )
                .andExpect(jsonPath("$.id").doesNotExist())
                .andDo(print())
                .andReturn();
    }

}


text:
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType

from cms.apps.pages.models import Page
from cms.apps.links.models import Link
from cms.externals import watson

class TestLinks(TestCase):

    def setUp(self):
        with watson.context_manager("update_index")():
            page = Page.objects.create(
                title = "Homepage",
                content_type = ContentType.objects.get_for_model(Link),
            )
            Link.objects.create(
                page = page,
                link_url = "http://www.example.com/",
            )

    def testLinkRedirect(self):
        response = self.client.get("/")
        self.assertEquals(response.status_code, 302)
        self.assertEquals(response["Location"], "http://www.example.com/")


text: A base website for Flask applications


text:
<?php
	include("connect.inc");

	@ob_clean();
	ob_start();
	phpinfo();
	$phpinfo = ob_get_contents();
	ob_end_clean();

	/* all versions should at least dump this minimum information */
	if (!stristr($phpinfo, "mysqli support"))
		printf("[001] ext/mysqli should have exposed itself.\n");

	if (!stristr($phpinfo, "client api library version"))
		printf("[002] ext/mysqli should have exposed the library version.\n");

	if (!stristr($phpinfo, "mysqli.default_host"))
		printf("[003] php.ini setting mysqli.default_host not shown.\n");

	if (!stristr($phpinfo, "mysqli.default_port"))
		printf("[004] php.ini setting mysqli.default_port not shown.\n");

	if (!stristr($phpinfo, "mysqli.default_pw"))
		printf("[005] php.ini setting mysqli.default_pw not shown.\n");

	if (!stristr($phpinfo, "mysqli.default_socket"))
		printf("[006] php.ini setting mysqli.default_socket not shown.\n");

	if (!stristr($phpinfo, "mysqli.default_user"))
		printf("[007] php.ini setting mysqli.default_user not shown.\n");

	if (!stristr($phpinfo, "mysqli.max_links"))
		printf("[008] php.ini setting mysqli.max_links not shown.\n");

	if (!stristr($phpinfo, "mysqli.reconnect"))
		printf("[009] php.ini setting mysqli.reconnect not shown.\n");

	if ($IS_MYSQLND) {
		$expected = array(
			'mysqlnd statistics',
			'bytes_sent', 'bytes_received', 'packets_sent', 'packets_received',
			'protocol_overhead_in', 'protocol_overhead_out', 'result_set_queries',
			'non_result_set_queries', 'no_index_used', 'bad_index_used',
			'buffered_sets', 'unbuffered_sets', 'ps_buffered_sets', 'ps_unbuffered_sets',
			'flushed_normal_sets', 'flushed_ps_sets', 'rows_fetched_from_server',
			'rows_fetched_from_client', 'rows_skipped', 'copy_on_write_saved',
			'copy_on_write_performed', 'command_buffer_too_small', 'connect_success',
			'connect_failure', 'connection_reused', 'explicit_close', 'implicit_close',
			'disconnect_close', 'in_middle_of_command_close', 'explicit_free_result',
			'implicit_free_result', 'explicit_stmt_close', 'implicit_stmt_close',
			'size',
			'mysqli.allow_local_infile',
			'mysqli.allow_persistent', 'mysqli.max_persistent'
		);
		foreach ($expected as $k => $entry)
			if (!stristr($phpinfo, $entry))
				printf("[010] Could not find entry for '%s'\n", $entry);
	}

	print "done!";
?>


text:
<?php
namespace Locations;

use Locations\Model\Locations;
use Locations\Model\LocationsTable;

use Countries\Model\Countries;
use Countries\Model\CountriesTable;

use Zend\Db\TableGateway\TableGateway;

use Zend\Stdlib\Hydrator\ObjectProperty;
use Zend\Db\ResultSet\HydratingResultSet;

class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
    public function getServiceConfig()
     {
         return array(
             'factories' => array(
                 'Locations\Model\LocationsTable' =>  function($sm) {
                     $tableGateway = $sm->get('LocationsTableGateway');
                     $table = new LocationsTable($tableGateway);
                     return $table;
                 },
                 'LocationsTableGateway' => function ($sm) {
                     $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');

                     $resultSetPrototype = new HydratingResultSet();
                     $resultSetPrototype->setHydrator(new ObjectProperty());
                     $resultSetPrototype->setObjectPrototype(new Locations());

                     return new TableGateway('locations', $dbAdapter, null, $resultSetPrototype);
                },

            ),
        );
    }
}


text:
A minimalistic [MessagePack](http://msgpack.org/index.html) encoder and decoder for JavaScript.

- Tiny Size (2.63 kB minified and gzipped)
- Fast performance (Slightly faster than [msgpack-lite](https://github.com/kawanet/msgpack-lite/))
- Extension support
- No other bells or whistles

By default, `msgpack` can encode numbers, strings, booleans, nulls, arrays, objects, and binary data (`Uint8Array`). However, additional types can be registered by using [extensions](#extensions).

## Installation

```bash
npm install --save tiny-msgpack
```

## Usage

```js
var msgpack = require('tiny-msgpack');

var uint8array = msgpack.encode({foo: 'bar', baz: 123});
var object = msgpack.decode(uint8array);
```

## Extensions

```js
var msgpack = require('tiny-msgpack');
var codec = new msgpack.Codec;

function encodeDate(date) {
  return msgpack.encode(+date);
}
function decodeDate(uint8array) {
  return new Date(msgpack.decode(uint8array));
}
codec.register(0x42, Date, encodeDate, decodeDate);

var uint8array = msgpack.encode({timestamp: new Date}, codec);
var object = msgpack.decode(uint8array, codec);
console.log(object.timestamp instanceof Date); // => true
```

## Browser Support

In the browser, `tiny-msgpack` requires the [Encoding API](https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API), which is currently only implemented by Chrome and Firefox. However, if you polyfill it, this package is supported by the following browsers:

- Chrome 9+
- Firefox 15+
- Safari 5.1+
- Opera 12.1+
- Internet Explorer 10+

## Zero copy

In the [MessagePack](http://msgpack.org/index.html) format, binary data is encoded as... binary data! To maximize performance, `tiny-msgpack` does not copy binary data when encoding or decoding it. So after decoding, the contents of a returned `Uint8Array` can be affected by modifying the input `Uint8Array` (the same can happen with encoding).

## License

[MIT](https://github.com/JoshuaWise/tiny-msgpack/blob/master/LICENSE)


text:
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.XPath;

using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.BuildEngine;
using SandcastleBuilder.Utils.PlugIn;

namespace SandcastleBuilder.PlugIns
{
    /// <summary>
    /// This plug-in class is used to copy the resulting help file output to
    /// a location other than the output folder (i.e. a file share, an FTP
    /// site, a web server, etc.).
    /// </summary>
    public class DeploymentPlugIn : IPlugIn
    {
        #region Private data members
        private ExecutionPointCollection executionPoints;

        private BuildProcess builder;

        // Plug-in configuration options
        private DeploymentLocation deployHelp1, deployHelp2, deployHelpViewer,
            deployWebsite;
        private bool deleteAfterDeploy;
        #endregion

        #region IPlugIn implementation
        //=====================================================================
        // IPlugIn implementation

        /// <summary>
        /// This read-only property returns a friendly name for the plug-in
        /// </summary>
        public string Name
        {
            get { return "Output Deployment"; }
        }

        /// <summary>
        /// This read-only property returns the version of the plug-in
        /// </summary>
        public Version Version
        {
            get
            {
                // Use the assembly version
                Assembly asm = Assembly.GetExecutingAssembly();
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(
                    asm.Location);

                return new Version(fvi.ProductVersion);
            }
        }

        /// <summary>
        /// This read-only property returns the copyright information for the
        /// plug-in.
        /// </summary>
        public string Copyright
        {
            get
            {
                // Use the assembly copyright
                Assembly asm = Assembly.GetExecutingAssembly();
                AssemblyCopyrightAttribute copyright =
                    (AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(
                        asm, typeof(AssemblyCopyrightAttribute));

                return copyright.Copyright;
            }
        }

        /// <summary>
        /// This read-only property returns a brief description of the plug-in
        /// </summary>
        public string Description
        {
            get
            {
                return "This plug-in is used to deploy the resulting help " +
                    "file output to a location other than the output folder " +
                    "(i.e. a file share, a web server, an FTP site, etc.).";
            }
        }

        /// <summary>
        /// This plug-in does not run in partial builds
        /// </summary>
        public bool RunsInPartialBuild
        {
            get { return false; }
        }

        /// <summary>
        /// This read-only property returns a collection of execution points
        /// that define when the plug-in should be invoked during the build
        /// process.
        /// </summary>
        public ExecutionPointCollection ExecutionPoints
        {
            get
            {
                if(executionPoints == null)
                {
                    executionPoints = new ExecutionPointCollection();

                    // This plug-in has a lower priority as it should execute
                    // after all other plug-ins in case they add other files
                    // to the set.
                    executionPoints.Add(new ExecutionPoint(
                        BuildStep.CompilingHelpFile,
                        ExecutionBehaviors.After, 200));
                    executionPoints.Add(new ExecutionPoint(
                        BuildStep.CopyingWebsiteFiles,
                        ExecutionBehaviors.After, 200));
                }

                return executionPoints;
            }
        }

        /// <summary>
        /// This method is used by the Sandcastle Help File Builder to let the
        /// plug-in perform its own configuration.
        /// </summary>
        /// <param name="project">A reference to the active project</param>
        /// <param name="currentConfig">The current configuration XML fragment</param>
        /// <returns>A string containing the new configuration XML fragment</returns>
        /// <remarks>The configuration data will be stored in the help file
        /// builder project.</remarks>
        public string ConfigurePlugIn(SandcastleProject project,
          string currentConfig)
        {
            using(DeploymentConfigDlg dlg = new DeploymentConfigDlg(
              currentConfig))
            {
                if(dlg.ShowDialog() == DialogResult.OK)
                    currentConfig = dlg.Configuration;
            }

            return currentConfig;
        }

        /// <summary>
        /// This method is used to initialize the plug-in at the start of the
        /// build process.
        /// </summary>
        /// <param name="buildProcess">A reference to the current build
        /// process.</param>
        /// <param name="configuration">The configuration data that the plug-in
        /// should use to initialize itself.</param>
        /// <exception cref="BuilderException">This is thrown if the plug-in
        /// configuration is not valid.</exception>
        public void Initialize(BuildProcess buildProcess,
          XPathNavigator configuration)
        {
            XPathNavigator root;
            string value;

            builder = buildProcess;

            builder.ReportProgress("{0} Version {1}\r\n{2}",
                this.Name, this.Version, this.Copyright);

            root = configuration.SelectSingleNode("configuration");
            value = root.GetAttribute("deleteAfterDeploy", String.Empty);

            if(!String.IsNullOrEmpty(value))
                deleteAfterDeploy = Convert.ToBoolean(value,
                    CultureInfo.InvariantCulture);

            if(root.IsEmptyElement)
                throw new BuilderException("ODP0001", "The Output Deployment " +
                    "plug-in has not been configured yet");

            deployHelp1 = DeploymentLocation.FromXPathNavigator(root, "help1x");
            deployHelp2 = DeploymentLocation.FromXPathNavigator(root, "help2x");
            deployHelpViewer = DeploymentLocation.FromXPathNavigator(root, "helpViewer");
            deployWebsite = DeploymentLocation.FromXPathNavigator(root, "website");

            // At least one deployment location must be defined
            if(deployHelp1.Location == null && deployHelp2.Location == null &&
              deployHelpViewer.Location == null && deployWebsite.Location == null)
                throw new BuilderException("ODP0002", "The output deployment " +
                    "plug-in must have at least one configured deployment " +
                    "location");

            // Issue a warning if the deployment location is null and the
            // associated help file format is active.
            if(deployHelp1.Location == null &&
              (builder.CurrentProject.HelpFileFormat & HelpFileFormat.HtmlHelp1) != 0)
                builder.ReportWarning("ODP0003", "HTML Help 1 will be generated " +
                    "but not deployed due to missing deployment location " +
                    "information");

            if(deployHelp2.Location == null &&
              (builder.CurrentProject.HelpFileFormat & HelpFileFormat.MSHelp2) != 0)
                builder.ReportWarning("ODP0003", "MS Help 2 will be generated " +
                    "but not deployed due to missing deployment location " +
                    "information");

            if(deployHelpViewer.Location == null &&
              (builder.CurrentProject.HelpFileFormat & HelpFileFormat.MSHelpViewer) != 0)
                builder.ReportWarning("ODP0003", "MS Help Viewer will be generated " +
                    "but not deployed due to missing deployment location " +
                    "information");

            if(deployWebsite.Location == null &&
              (builder.CurrentProject.HelpFileFormat & HelpFileFormat.Website) != 0)
                builder.ReportWarning("ODP0003", "Website will be generated " +
                    "but not deployed due to missing deployment location " +
                    "information");
        }

        /// <summary>
        /// This method is used to execute the plug-in during the build process
        /// </summary>
        /// <param name="context">The current execution context</param>
        public void Execute(ExecutionContext context)
        {
            // Deploy each of the selected help file formats
            if(builder.CurrentFormat == HelpFileFormat.HtmlHelp1)
            {
                builder.ReportProgress("Deploying HTML Help 1 file");
                this.DeployOutput(builder.Help1Files, deployHelp1);
            }

            if(builder.CurrentFormat == HelpFileFormat.MSHelp2)
            {
                builder.ReportProgress("Deploying MS Help 2 files");
                this.DeployOutput(builder.Help2Files, deployHelp2);
            }

            if(builder.CurrentFormat == HelpFileFormat.MSHelpViewer)
            {
                builder.ReportProgress("Deploying MS Help Viewer files");
                this.DeployOutput(builder.HelpViewerFiles, deployHelpViewer);
            }

            if(builder.CurrentFormat == HelpFileFormat.Website)
            {
                builder.ReportProgress("Deploying website files");
                this.DeployOutput(builder.WebsiteFiles, deployWebsite);
            }
        }
        #endregion

        #region Deploy project output
        /// <summary>
        /// Deploy the given list of files to the specified location
        /// </summary>
        /// <param name="files">The list of files to deploy</param>
        /// <param name="location">The deployment location</param>
        private void DeployOutput(Collection<string> files,
          DeploymentLocation location)
        {
            WebClient webClient = null;
            Uri destUri, target = location.Location;
            string rootPath, destFile, destPath;
            int basePathLength = builder.OutputFolder.Length;

            if(files.Count == 0)
            {
                builder.ReportProgress("No files found to deploy");
                return;
            }

            try
            {
                // Determine the path type
                if(!target.IsAbsoluteUri)
                    rootPath = Path.GetFullPath(target.OriginalString);
                else
                    if(target.IsFile || target.IsUnc)
                        rootPath = target.LocalPath;
                    else
                    {
                        // FTP, HTTP, etc.
                        rootPath = target.ToString();
                        webClient = new WebClient();

                        // Initialize the web client
                        if(!location.UserCredentials.UseDefaultCredentials)
                            webClient.Credentials = new NetworkCredential(
                                location.UserCredentials.UserName,
                                location.UserCredentials.Password);

                        webClient.CachePolicy = new RequestCachePolicy(
                            RequestCacheLevel.NoCacheNoStore);

                        if(location.ProxyCredentials.UseProxyServer)
                        {
                            webClient.Proxy = new WebProxy(
                                location.ProxyCredentials.ProxyServer, true);

                            if(!location.ProxyCredentials.Credentials.UseDefaultCredentials)
                                webClient.Proxy.Credentials =
                                    new NetworkCredential(
                                        location.ProxyCredentials.Credentials.UserName,
                                        location.ProxyCredentials.Credentials.Password);
                        }
                    }

                foreach(string sourceFile in files)
                {
                    destFile = Path.Combine(rootPath,
                        sourceFile.Substring(basePathLength));

                    if(webClient == null)
                    {
                        builder.ReportProgress("    Deploying {0} to {1}",
                            sourceFile, destFile);

                        destPath = Path.GetDirectoryName(destFile);

                        if(!Directory.Exists(destPath))
                            Directory.CreateDirectory(destPath);

                        File.Copy(sourceFile, destFile, true);
                    }
                    else
                    {
                        destUri = new Uri(destFile);
                        builder.ReportProgress("    Deploying {0} to {1}",
                            sourceFile, destUri);

                        webClient.UploadFile(destUri, sourceFile);
                    }

                    // If not wanted, remove the source file after deployment
                    if(deleteAfterDeploy)
                        File.Delete(sourceFile);
                }
            }
            finally
            {
                if(webClient != null)
                    webClient.Dispose();
            }
        }
        #endregion

        #region IDisposable implementation
        //=====================================================================
        // IDisposable implementation

        /// <summary>
        /// This handles garbage collection to ensure proper disposal of the
        /// plug-in if not done explicity with <see cref="Dispose()"/>.
        /// </summary>
        ~DeploymentPlugIn()
        {
            this.Dispose(false);
        }

        /// <summary>
        /// This implements the Dispose() interface to properly dispose of
        /// the plug-in object.
        /// </summary>
        /// <overloads>There are two overloads for this method.</overloads>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// This can be overridden by derived classes to add their own
        /// disposal code if necessary.
        /// </summary>
        /// <param name="disposing">Pass true to dispose of the managed
        /// and unmanaged resources or false to just dispose of the
        /// unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            // Nothing to dispose of in this one
        }
        #endregion
    }
}


text:
require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/ads/googleads/v10/enums/content_label_type.proto", :syntax => :proto3) do
    add_message "google.ads.googleads.v10.enums.ContentLabelTypeEnum" do
    end
    add_enum "google.ads.googleads.v10.enums.ContentLabelTypeEnum.ContentLabelType" do
      value :UNSPECIFIED, 0
      value :UNKNOWN, 1
      value :SEXUALLY_SUGGESTIVE, 2
      value :BELOW_THE_FOLD, 3
      value :PARKED_DOMAIN, 4
      value :JUVENILE, 6
      value :PROFANITY, 7
      value :TRAGEDY, 8
      value :VIDEO, 9
      value :VIDEO_RATING_DV_G, 10
      value :VIDEO_RATING_DV_PG, 11
      value :VIDEO_RATING_DV_T, 12
      value :VIDEO_RATING_DV_MA, 13
      value :VIDEO_NOT_YET_RATED, 14
      value :EMBEDDED_VIDEO, 15
      value :LIVE_STREAMING_VIDEO, 16
      value :SOCIAL_ISSUES, 17
    end
  end
end

module Google
  module Ads
    module GoogleAds
      module V10
        module Enums
          ContentLabelTypeEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v10.enums.ContentLabelTypeEnum").msgclass
          ContentLabelTypeEnum::ContentLabelType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v10.enums.ContentLabelTypeEnum.ContentLabelType").enummodule
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.hw.accountbook.mapper.TransactionMapper">
    <resultMap id="TransactionResultMap" type="com.hw.accountbook.domain.Transaction" autoMapping="true">
        <id column="tid" property="tid" />
        <association property="creator" autoMapping="true" columnPrefix="creator__" javaType="com.hw.accountbook.domain.User">
            <id column="uid" property="uid" />
        </association>
    </resultMap>

    <insert id="add" useGeneratedKeys="true" keyProperty="tid">
        INSERT INTO transaction (category, type, amount, creator_uid, memo) VALUES (#{category}, #{type}, #{amount}, #{creatorUid}, #{memo});
    </insert>

    <sql id="selectTransaction" >
        SELECT
            `transaction`.tid,
            `transaction`.category,
            `transaction`.type,
            `transaction`.amount,
            `transaction`.creator_uid,
            `transaction`.memo,
            `transaction`.create_time,
            `transaction`.update_time,
            `user`.uid as creator__uid,
            `user`.uname as creator__uname,
            `user`.name as creator__name,
            `user`.email as creator__email
        FROM `transaction`
            LEFT JOIN `user` ON `user`.uid=`transaction`.creator_uid
    </sql>

    <select id="findOne" resultMap="TransactionResultMap">
        <include refid="selectTransaction" />
        <where>
            <if test="tid!=null">
                AND `transaction`.tid=#{tid}
            </if>
        </where>
    </select>

    <update id="update">
        UPDATE `transaction`
        <set>
            <if test="type != null">
                `transaction`.`type`=#{type}
            </if>
            <if test="category != null">
                `transaction`.`category`=#{category}
            </if>
            <if test="amount != null">
                `transaction`.`amount`=#{amount}
            </if>
            <if test="creator_uid != null">
                `transaction`.`creator_uid`=#{creatorUid}
            </if>
            <if test="memo != null">
                `transaction`.`memo`=#{memo}
            </if>
            <if test="update_time != null">
                `transaction`.`update_time`=#{updateTime}
            </if>
        </set>
        <where>
            `transaction`.tid=#{tid}
            AND `transaction`.`creator_uid`=#{creatorUid}
        </where>
    </update>
</mapper>


text:
using RelhaxModpack.Database;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RelhaxModpack.UI
{
    /// <summary>
    /// A SelectionListTabItem provides additional functionality over a TabItem to indicate if child packages inside this ui component's package are enabled and checked.
    /// It enables highlight logic for ui interaction in the selection list.
    /// </summary>
    public class SelectionListTabItem : TabItem, INotifyPropertyChanged, IOnCheckedComponent
    {
        /// <summary>
        /// Override framework metadata from TabItem to this class's SelectionlistTabItem.
        /// </summary>
        static SelectionListTabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(SelectionListTabItem), new FrameworkPropertyMetadata(typeof(SelectionListTabItem)));
        }

        /// <summary>
        /// Create an instance of the SelectionListTabitem class.
        /// </summary>
        public SelectionListTabItem() : base()
        {

        }

        /// <summary>
        /// The package associated with this UI component
        /// </summary>
        public SelectablePackage Package { get; set; }

        private bool _isChildPackageChecked = false;

        /// <summary>
        /// Get or set if this component's package has any child packages that are enabled and checked.
        /// </summary>
        public bool IsChildPackageChecked
        {
            get { return _isChildPackageChecked; }
            set
            {
                _isChildPackageChecked = value;
                OnPropertyChanged(nameof(IsChildPackageChecked));
            }
        }

        /// <summary>
        /// Occurs after a property that uses OnPropertyChanged has been set.
        /// </summary>
        /// <seealso cref="OnPropertyChanged(string)"/>
        /// <seealso cref="INotifyPropertyChanged"/>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Called from a property in this class that wants to tell PropertyChanged listeners that it has changed.
        /// </summary>
        /// <param name="propertyName">The name of the property that has changed.</param>
        /// <seealso cref="PropertyChanged"/>
        /// <seealso cref="INotifyPropertyChanged"/>
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Handles ui logic processing when the associated package's checked property is set.
        /// </summary>
        /// <param name="Checked">The checked value from the package.</param>
        public void OnCheckedChanged(bool Checked)
        {
            if (Package.Visible && Package.IsStructureVisible)
            {
                if (Checked || Package.AnyPackagesChecked())
                {
                    this.IsChildPackageChecked = true;
                }
                else
                {
                    this.IsChildPackageChecked = false;
                }
            }
        }
    }
}