text:
from django.db import models

from django.utils.encoding import force_unicode
from django.views.generic.edit import ModelFormMixin, UpdateView, CreateView, ProcessFormView, FormView
from django.views.generic.base import TemplateView, View
from django.views.generic import DetailView, ListView
import django.forms.models as model_forms
from guardian.decorators import permission_required
from django.utils.http import urlquote
from django.db.models import Q
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponseForbidden, HttpResponseRedirect, HttpResponse
from guardian.shortcuts import get_objects_for_user, assign
from django.core.exceptions import ImproperlyConfigured
from django import forms
from django.utils import simplejson
from django.conf.urls.defaults import patterns, url
from django.core.urlresolvers import reverse
import string

import widgets

def smart_url(url, id=None):
    """
    URLs that start with @ are reversed, using the passed in arguments.

    Otherwise a straight % substitution is applied.
    """
    if url.find("@") >= 0:
        (args, value) = url.split('@')

        if args:
            return reverse(value, args=[id])
        else:
            return reverse(value)
    else:
        return url % id

class SmartView(object):
    fields = None
    exclude = None
    field_config = { }
    title = None
    permission = None
    refresh = None

    def __init__(self, *args):
        """
        There are a few variables we want to mantain in the instance, not the
        class.
        """
        self.extra_context = {}
        return super(SmartView, self).__init__(*args)

    def derive_title(self):
        """
        Returns the title used on this page.
        """
        return self.title

    def has_permission(self, request, *args, **kwargs):

        """
        Figures out if the current user has permissions for this view.
        """
        if not self.permission:
            return True
        else:
            # we first check to see if we have full permission
            has_perm = request.user.has_perm(self.permission)

            self.kwargs = kwargs
            self.args = args
            self.request = request

            # if not, perhaps we have it per object
            if not has_perm:
                has_perm = self.has_object_permission('get_object')

            # if still no luck, check if we have permissions on the parent object
            if not has_perm:
                has_perm = self.has_object_permission('get_parent_object')

            return has_perm

    def has_object_permission(self, getter_name):

        """
        Checks for object level permission for an arbitrary getter
        """
        obj = None
        obj_getter = getattr(self, getter_name, None)

        # get object requires pk
        if getter_name == "get_object" and 'pk' not in self.kwargs:
            return False

        if obj_getter:
            obj = obj_getter()
            if obj:
                return self.request.user.has_perm(self.permission, obj)

    def dispatch(self, request, *args, **kwargs):
        """
        Overloaded to check permissions if appropriate
        """
        def wrapper(request, *args, **kwargs):
            if not self.has_permission(request, *args, **kwargs):
                path = urlquote(request.get_full_path())
                login_url = kwargs.pop('login_url', settings.LOGIN_URL)
                redirect_field_name = kwargs.pop('redirect_field_name', REDIRECT_FIELD_NAME)
                return HttpResponseRedirect("%s?%s=%s" % (login_url, redirect_field_name, path))
            else:
                response = self.pre_process(request, *args, **kwargs)
                if not response:
                    return super(SmartView, self).dispatch(request, *args, **kwargs)
                else:
                    return response

        return wrapper(request, *args, **kwargs)

    def pre_process(self, request, *args, **kwargs):
        """
        Gives the view an opportunity to intercept this response and return a different
        response instead.  This can be used to check some precondition for example and to
        redirect the user somewhere else if they are not met.

        Views which wish to use this should return a Response object.
        """
        return None

    def lookup_obj_attribute(self, obj, field):
        """
        Looks for a field's value from the passed in obj.  Note that this will strip
        leading attributes to deal with subelements if possible
        """
        curr_field = field
        rest = None

        if field.find('.') >= 0:
            curr_field = field.split('.')[0]
            rest = '.'.join(field.split('.')[1:])

        # next up is the object itself
        obj_field = getattr(obj, curr_field, None)

        # if it is callable, do so
        if obj_field and getattr(obj_field, '__call__', None):
            obj_field = obj_field()

        if obj_field and rest:
            return self.lookup_obj_attribute(obj_field, rest)
        else:
            return obj_field

    def lookup_field_value(self, context, obj, field):
        """
        Looks up the field value for the passed in object and field name.

        Note that this method is actually called from a template, but this provides a hook
        for subclasses to modify behavior if they wish to do so.

        This may be used for example to change the display value of a variable depending on
        other variables within our context.
        """
        # if this isn't a subfield, check the view to see if it has a get_ method
        if field.find('.') == -1:
            # view supercedes all, does it have a 'get_' method for this obj
            view_method = getattr(self, 'get_%s' % field, None)
            if view_method:
                return view_method(obj)

        return self.lookup_obj_attribute(obj, field)

    def lookup_field_label(self, context, field, default=None):
        """
        Figures out what the field label should be for the passed in field name.

        Our heuristic is as follows:
            1) we check to see if our field_config has a label specified
            2) if not, then we derive a field value from the field name
        """
        # if this is a subfield, strip off everything but the last field name
        if field.find('.') >= 0:
            return self.lookup_field_label(context, field.split('.')[-1], default)

        label = None

        # is there a label specified for this field
        if field in self.field_config and 'label' in self.field_config[field]:
            label = self.field_config[field]['label']

        # if we were given a default, use that
        elif default:
            label = default

        # check our model
        else:
            for model_field in self.model._meta.fields:
                if model_field.name == field:
                    return model_field.verbose_name.title()

        # otherwise, derive it from our field name
        if label is None:
            label = self.derive_field_label(field)

        return label

    def lookup_field_help(self, field, default=None):
        """
        Looks up the help text for the passed in field.
        """
        help = None

        # is there a label specified for this field
        if field in self.field_config and 'help' in self.field_config[field]:
            help = self.field_config[field]['help']

        # if we were given a default, use that
        elif default:
            help = default

        # try to see if there is a description on our model
        else:
            for model_field in self.model._meta.fields:
                if model_field.name == field:
                    help = model_field.help_text
                    break

        return help

    def lookup_field_class(self, field, obj=None, default=None):
        """
        Looks up any additional class we should include when rendering this field
        """
        css = ""

        # is there a class specified for this field
        if field in self.field_config and 'class' in self.field_config[field]:
            css = self.field_config[field]['class']

        # if we were given a default, use that
        elif default:
            css = default

        return css

    def derive_field_label(self, field, obj=None):
        """
        Derives a field label for the passed in field name.
        """
        # replace _'s with ' '
        label = field.replace('_', ' ').title()
        return label

    def derive_field_config(self):
        """
        Derives the field config for this instance.  By default we just use
        self.field_config
        """
        return self.field_config

    def get_template_names(self):
        """
        Returns the name of the template to use to render this request.

        Smartmin provides default templates as fallbacks, so appends it's own templates names to the end
        of whatever list is built by the generic views.

        Subclasses can override this by setting a 'template_name' variable on the class.
        """
        templates = []
        if hasattr(self, 'template_name') and self.template_name:
            templates.append(self.template_name)

        if hasattr(self, 'default_template'):
            templates.append(self.default_template)
        else:
            templates = super(SmartView, self).get_template_names()

        return templates

    def derive_fields(self):
        """
        Default implementation
        """
        fields = []
        if self.fields:
            fields.append(self.fields)

        return fields

    def derive_exclude(self):
        """
        Returns which fields we should exclude
        """
        exclude = []
        if self.exclude:
            exclude += self.exclude

        return exclude

    def get_context_data(self, **kwargs):
        """
        We supplement the normal context data by adding our fields and labels.
        """
        context = super(SmartView, self).get_context_data(**kwargs)

        # derive our field config
        self.field_config = self.derive_field_config()

        # add our fields
        self.fields = self.derive_fields()

        # stuff it all in our context
        context['fields'] = self.fields
        context['view'] = self
        context['field_config'] = self.field_config

        context['title'] = self.derive_title()

        # and any extra context the user specified
        context.update(self.extra_context)

        # by default, our base is 'base.html', but we might be pjax
        base_template = "base.html"
        if 'pjax' in self.request.REQUEST or 'pjax' in self.request.POST:
            base_template = "smartmin/pjax.html"
        context['base_template'] = base_template

        # set our refresh if we have one
        if self.refresh:
            context['refresh'] = self.refresh

        return context

    def as_json(self, context):
        """
        Responsible for turning our context into an dict that can then be serialized into an
        JSON response.
        """
        return context

    def render_to_response(self, context, **response_kwargs):
        """
        Overloaded to deal with _format arguments.
        """
        # should we actually render in json?
        if '_format' in self.request.REQUEST and self.request.REQUEST['_format'] == 'json':
          json = self.as_json(context)
          return HttpResponse(simplejson.dumps(json), mimetype='application/javascript')

        # otherwise, return normally
        else:
            return super(SmartView, self).render_to_response(context)

class SmartReadView(SmartView, DetailView):
    default_template = 'smartmin/read.html'
    edit_button = False

    def derive_title(self):
        """
        By default we just return the string representation of our object
        """
        return str(self.object)

    def derive_fields(self):
        """
        Derives our fields.  We first default to using our 'fields' variable if available,
        otherwise we figure it out from our object.
        """
        if self.fields:
            return list(self.fields)

        else:
            fields = []
            for field in self.object._meta.fields:
                fields.append(field.name)
            return fields

class SmartDeleteView(SmartView, DetailView, ProcessFormView):
    default_template = 'smartmin/delete_confirm.html'
    name_field = 'name'
    cancel_url = None
    redirect_url = None

    def get_cancel_url(self):
        if not self.cancel_url:
            raise ImproperlyConfigured("DeleteView must define a cancel_url")

        return smart_url(self.cancel_url)

    def pre_delete(self, request):
        pass

    def post(self, request, *args, **kwargs):
        self.pre_delete(request)
        self.get_object().delete()
        return HttpResponseRedirect(self.get_redirect_url())

    def get_redirect_url(self, **kwargs):
        if not self.redirect_url:
            raise ImproperlyConfigured("DeleteView must define a redirect_url")

        return smart_url(self.redirect_url)

    def get_context_data(self, **kwargs):
        """ Add in the field to use for the name field """
        context = super(SmartDeleteView, self).get_context_data(**kwargs)
        context['name_field'] = self.name_field
        context['cancel_url'] = self.get_cancel_url()
        return context

class SmartListView(SmartView, ListView):
    default_template = 'smartmin/list.html'

    link_url = None
    link_fields = None
    add_button = False
    search_fields = None
    paginate_by = 25
    pjax = None
    field_config = { 'is_active': dict(label=''), }
    default_order = None

    list_permission = None

    def derive_title(self):
        """
        Derives our title from our list
        """
        title = super(SmartListView, self).derive_title()

        if not title:
            return force_unicode(self.model._meta.verbose_name_plural).title()
        else:
            return title

    def derive_link_fields(self, context):
        """
        Used to derive which fields should be linked.  This should return a set() containing
        the names of those fields which should be linkable.
        """
        if not self.link_fields is None:
            return self.link_fields

        else:
            link_fields = set()
            if self.fields:
                for field in self.fields:
                    if field != 'is_active':
                        link_fields.add(field)
                        break

        return link_fields

    def lookup_field_link(self, context, field, obj):
        """
        By default we just return /view/{{ id }}/ for the current object.
        """
        return smart_url(self.link_url, str(obj.id))

    def lookup_field_orderable(self, field):
        """
        Returns whether the passed in field is sortable or not, by default all 'raw' fields, that
        is fields that are part of the model are sortable.
        """
        try:
            self.model._meta.get_field_by_name(field)
            return True
        except:
            # that field doesn't exist, so not sortable
            return False

    def get_context_data(self, **kwargs):
        """
        Add in what fields are linkable
        """
        context = super(SmartListView, self).get_context_data(**kwargs)

        # our linkable fields
        self.link_fields = self.derive_link_fields(context)

        # stuff it all in our context
        context['link_fields'] = self.link_fields

        # build up our current parameter string, EXCLUSIVE of our page.  These
        # are used to build pagination URLs
        url_params = "?"
        for key,value in self.request.REQUEST.items():
            if key != 'page' and key != 'pjax' and key[0] != '_':
                url_params += "%s=%s&" % (key, value)
        context['url_params'] = url_params
        context['pjax'] = self.pjax

        # our search term if any
        if 'search' in self.request.REQUEST:
            context['search'] = self.request.REQUEST['search']

        # our ordering field if any
        order = self.derive_ordering()
        if order:
            if order[0] == '-':
                context['order'] = order[1:]
                context['order_asc'] = False
            else:
                context['order'] = order
                context['order_asc'] = True

        return context

    def derive_queryset(self, **kwargs):
        """
        Derives our queryset.
        """
        # get our parent queryset
        queryset = super(SmartListView, self).get_queryset(**kwargs)

        # apply any filtering
        if self.search_fields and 'search' in self.request.REQUEST:
            terms = self.request.REQUEST['search'].split()

            query = Q(pk__gt=0)
            for term in terms:
                term_query = Q(pk__lt=0)
                for field in self.search_fields:
                    term_query |= Q(**{ field: term })
                query &= term_query

            queryset = queryset.filter(query)

        # return our queryset
        return queryset

    def get_queryset(self, **kwargs):
        """
        Gets our queryset.  This takes care of filtering if there are any
        fields to filter by.
        """
        queryset = self.derive_queryset(**kwargs)

        # if our list should be filtered by a permission as well, do so
        if self.list_permission:
            # only filter if this user doesn't have a global permission
            if not self.request.user.has_perm(self.list_permission):
                queryset = queryset.filter(id__in=get_objects_for_user(self.request.user, self.list_permission))

        return self.order_queryset(queryset)

    def derive_ordering(self):
        """
        Returns what field should be used for ordering (using a prepended '-' to indicate descending sort).

        If the default order of the queryset should be used, returns None
        """
        if '_order' in self.request.REQUEST:
            return self.request.REQUEST['_order']
        elif self.default_order:
            return self.default_order
        else:
            return None

    def order_queryset(self, queryset):
        """
        Orders the passed in queryset, returning a new queryset in response.  By default uses the _order query
        parameter.
        """
        order = self.derive_ordering()
        if order:
            queryset = queryset.order_by(order)

        return queryset

    def derive_fields(self):
        """
        Derives our fields.
        """
        if self.fields:
            return self.fields

        else:
            fields = []
            for field in self.object_list.model._meta.fields:
                if field.name != 'id':
                    fields.append(field.name)
            return fields

    def get_is_active(self, obj):
        """
        Default implementation of get_is_active which returns a simple div so as to
        render a green dot for active items and nothing for inactive ones.

        Users of SmartModel will get this rendering for free.
        """
        if obj.is_active:
            return '

'
        else:
            return ''

class SmartFormMixin(object):
    field_config = { 'modified_blurb': dict(label="Modified"),
                     'created_blurb': dict(label="Created") }

    def derive_title(self):
        """
        Derives our title from our object
        """
        title = super(SmartFormMixin, self).derive_title()

        if not title:
            return "Form"
        else:
            return title

    def get_form(self, form_class):
        """
        Returns an instance of the form to be used in this view.
        """
        self.form = super(SmartFormMixin, self).get_form(form_class)

        # we specified our own form class, which means we need to apply any field filtering
        # ourselves.. this is ugly but the only way to make exclude and fields work the same
        # despite specifying your own form class
        if self.form_class:
            # only exclude?  then remove those items there
            exclude = self.derive_exclude()
            exclude += self.derive_readonly()

            fields = self.fields

            # remove any excluded fields
            for field in exclude:
                if field in self.form.fields:
                    del self.form.fields[field]

            if self.fields:
                # if we have explicit fields, limit to those as well
                for name, field in self.form.fields.items():
                    if not name in self.fields:
                        del self.form.fields[name]

        # stuff in our referer as the default location for where to return
        location = forms.CharField(widget=forms.widgets.HiddenInput(), required=False)

        if ('HTTP_REFERER' in self.request.META):
            location.initial = self.request.META['HTTP_REFERER']

        # add the location to our form fields
        self.form.fields['loc'] = location

        if self.fields:
            self.fields = list(self.fields)
            self.fields.append('loc')

        # provides a hook to programmatically customize fields before rendering
        for (name, field) in self.form.fields.items():
            field = self.customize_form_field(name, field)
            self.form.fields[name] = field

        return self.form

    def customize_form_field(self, name, field):
        """
        Allows views to customize their form fields.  By default, Smartmin replaces the plain textbox
        date input with it's own DatePicker implementation.
        """
        if isinstance(field, forms.fields.DateField) and isinstance(field.widget, forms.widgets.DateInput):
            field.widget = widgets.DatePickerWidget()

        if isinstance(field, forms.fields.ImageField) and isinstance(field.widget, forms.widgets.ClearableFileInput):
            field.widget = widgets.ImageThumbnailWidget()

        return field

    def lookup_field_label(self, context, field, default=None):
        """
        Figures out what the field label should be for the passed in field name.

        We overload this so as to use our form to see if there is label set there.  If so
        then we'll pass that as the default instead of having our parent derive
        the field from the name.
        """
        default = None

        for form_field in self.form:
            if form_field.name == field:
                default = form_field.label
                break

        return super(SmartFormMixin, self).lookup_field_label(context, field, default=default)

    def lookup_field_help(self, field, default=None):
        """
        Looks up the help text for the passed in field.

        This is overloaded so that we can check whether our form has help text set
        explicitely.  If so, we will pass this as the default to our parent function.
        """
        default = None

        for form_field in self.form:
            if form_field.name == field:
                default = form_field.help_text
                break

        return super(SmartFormMixin, self).lookup_field_help(field, default=default)

    def derive_readonly(self):
        """
        Figures out what fields should be readonly.  We iterate our field_config to find all
        that have a readonly of true
        """
        readonly = []
        for key, value in self.field_config.items():
            if 'readonly' in value and value['readonly']:
                readonly.append(key)

        return readonly

    def derive_fields(self):
        """
        Derives our fields.
        """
        fields = []
        if self.fields:
            fields = list(self.fields)

        else:
            form = self.form
            fields = []
            for field in form:
                fields.append(field.name)

            # this is slightly confusing but we add in readonly fields here because they will still
            # need to be displayed
            readonly = self.derive_readonly()
            if readonly:
                fields += readonly

        # remove any excluded fields
        for exclude in self.derive_exclude():
            if exclude in fields:
                fields.remove(exclude)

        return fields

    def get_form_class(self):
        """
        Returns the form class to use in this view
        """
        form_class = None

        if self.form_class:
            form_class = self.form_class

        else:
            if self.model is not None:
                # If a model has been explicitly provided, use it
                model = self.model
            elif hasattr(self, 'object') and self.object is not None:
                # If this view is operating on a single object, use
                # the class of that object
                model = self.object.__class__
            else:
                # Try to get a queryset and extract the model class
                # from that
                model = self.get_queryset().model

            # run time parameters when building our form
            factory_kwargs = self.get_factory_kwargs()
            form_class = model_forms.modelform_factory(model, **factory_kwargs)

        return form_class

    def get_factory_kwargs(self):
        """
        Let's us specify any extra parameters we might want to call for our form factory.

        These can include: 'form', 'fields', 'exclude' or 'formfield_callback'
        """
        params = dict()

        exclude = self.derive_exclude()
        exclude += self.derive_readonly()

        if self.fields:
            fields = list(self.fields)
            for ex in exclude:
                if ex in fields:
                    fields.remove(ex)

            params['fields'] = fields

        if exclude:
            params['exclude'] = exclude

        return params

    def get_success_url(self):
        """
        By default we use the referer that was stuffed in our
        form when it was created
        """
        if self.success_url:
            return smart_url(self.success_url, self.object.pk)

        elif 'loc' in self.form.cleaned_data:
            return self.form.cleaned_data['loc']

        raise ImproperlyConfigured("No redirect location found, override get_success_url to not use redirect urls")

    def get_form_kwargs(self):
        """
        We override this, using only those fields specified if they are specified.

        Otherwise we include all fields in a standard ModelForm.
        """
        kwargs = super(SmartFormMixin, self).get_form_kwargs()
        return kwargs;

class SmartFormView(SmartFormMixin, SmartView, FormView):
    template_name = 'smartmin/form.html'

class SmartModelFormView(SmartFormMixin, SmartView, ModelFormMixin):
    grant_permissions = None
    javascript_submit = None

    field_config = { 'modified_blurb': dict(label="Modified"),
                     'created_blurb': dict(label="Created") }

    def derive_title(self):
        """
        Derives our title from our object
        """
        title = super(SmartModelFormView, self).derive_title()

        if not title:
            return "Edit %s" % force_unicode(self.model._meta.verbose_name).title()
        else:
            return title

    def pre_save(self, obj):
        """
        Called before an object is saved away
        """
        return obj

    def save(self, obj):
        """
        Actually does the saving of this object, this is when the object is committed
        """
        self.object.save()
        self.save_m2m()

    def form_valid(self, form):
        self.object = form.save(commit=False)

        self.object = self.pre_save(self.object)
        self.save(self.object)
        self.object = self.post_save(self.object)

        return HttpResponseRedirect(self.get_success_url())

    def save_m2m(self):
        """
        By default saves the form's m2m, can be overridden if a more complicated m2m model exists
        """
        self.form.save_m2m()

    def post_save(self, obj):
        """
        Called after an object is successfully saved
        """
        # if we have permissions to grant, do so
        if self.grant_permissions:
            for permission in self.grant_permissions:
                # if the user doesn't have this permission globally already
                if not self.request.user.has_perm(permission):
                    # then assign it for this object
                    assign(permission, self.request.user, self.object)

        return obj

    def get_context_data(self, **kwargs):
        context = super(SmartModelFormView, self).get_context_data(**kwargs)
        context['javascript_submit'] = self.javascript_submit
        return context

class SmartUpdateView(SmartModelFormView, UpdateView):
    default_template = 'smartmin/update.html'
    exclude = ()
    readonly = ()

    # allows you to specify the name of URL to use for a remove link that will automatically be shown
    delete_url = None

    def pre_save(self, obj):
        # auto populate modified_by if it is present
        if hasattr(obj, 'modified_by_id') and self.request.user.id > 0:
            obj.modified_by = self.request.user

        return obj

    def get_context_data(self, **kwargs):
        context = super(SmartUpdateView, self).get_context_data(**kwargs)

        if self.delete_url:
            context['delete_url'] = smart_url(self.delete_url, self.object.id)

        return context

    def derive_readonly(self):
        """
        Figures out what fields should be readonly.  We iterate our field_config to find all
        that have a readonly of true
        """
        readonly = list(self.readonly)
        for key, value in self.field_config.items():
            if 'readonly' in value and value['readonly']:
                readonly.append(key)

        return readonly

    def get_modified_blurb(self, obj):
        return "%s by %s" % (obj.modified_on.strftime("%B %d, %Y at %I:%M %p"), obj.modified_by)

    def get_created_blurb(self, obj):
        return "%s by %s" % (obj.created_on.strftime("%B %d, %Y at %I:%M %p"), obj.created_by)

class SmartMultiFormView(SmartView, TemplateView):
    default_template = 'smartmin/multi_form.html'
    forms = {}

    # allows you to specify the name of URL to use for a remove link that will automatically be shown
    delete_url = None

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        page_forms = []
        for prefix, form in self.forms.items():
            f = form(prefix=prefix)
            page_forms.append(f)

        context['forms'] = page_forms

        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        # process our forms
        page_forms = []
        valid = True
        for prefix, form in self.forms.items():
            f = form(request.POST, prefix=prefix)
            valid = valid and f.is_valid()
            page_forms.append(f)

        if not valid:
            context['forms'] = page_forms
            return self.render_to_response(context)
        else:
            # redirect to success page
            pass

    def get_context_data(self, **kwargs):
        context = super(SmartMultiFormView, self).get_context_data(**kwargs)

        if self.delete_url:
            context['delete_url'] = smart_url(self.delete_url, self.object.id)

        return context

class SmartCreateView(SmartModelFormView, CreateView):
    default_template = 'smartmin/create.html'
    exclude = ('created_by', 'modified_by', 'is_active')

    def pre_save(self, obj):
        # auto populate created_by if it is present
        if hasattr(obj, 'created_by_id') and self.request.user.id > 0:
            obj.created_by = self.request.user

        # auto populate modified_by if it is present
        if hasattr(obj, 'modified_by_id') and self.request.user.id > 0:
            obj.modified_by = self.request.user

        return obj

    def derive_title(self):
        """
        Derives our title from our object
        """
        if not self.title:
            return "Create %s" % force_unicode(self.model._meta.verbose_name).title()
        else:
            return self.title

class SmartListUpdateView(SmartListView, ListView, ModelFormMixin, ProcessFormView):
    """
    SmartListUpdateView operates just like a SmartListView except it allows the implementor
    to wrap the entire list in a single form and declare which fields are mutable.
    """
    default_template = 'smartmin/list_update.html'

    def post(self, request, *args, **kwargs):
        """
        Override post so we can use the proper formset on submission.
        """
        form_class = self.get_form()
        self.form_post = form_class(request.POST)

        if self.form_post.is_valid():
            return self.form_valid(self.form_post)
        else:

            self.object_list = self.get_queryset()
            allow_empty = self.get_allow_empty()
            if not allow_empty and len(self.object_list) == 0:
                raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.") % {'class_name': self.__class__.__name__})

            context = self.get_context_data(object_list=self.object_list)
            context['formset'] = self.form_post
            return self.render_to_response(context)

    def is_field_required(self, field):
        """
        Determine if field is optional
        """
        try:
            if field.name in self.required_fields:
                return True
        except:
            pass

        return False

    def get_field_filter(self, field):
        """
        The filter to apply to a form field
        """
        return None

    def get_context_data(self, **kwargs):
        """
        Override context data so we can stuff in our formset and update fields.
        """
        context = super(SmartListUpdateView, self).get_context_data(**kwargs)
        form = self.get_form()
        context['formset'] = form(queryset=self.get_queryset())

        try:
            context['update_fields'] = self.update_fields
        except:
            pass

        return context

    """
    Apply custom field options if any are specified. This method is called when
    the creates a FormSet based on our model for each field inside the model spec.
    """
    def formfield_options(self, field):
        queryset = None
        if self.update_fields and field.name in self.update_fields:
            queryset = self.get_field_filter(field)

        if queryset:
            return field.formfield(queryset=queryset, required=self.is_field_required(field))
        else:
            return field.formfield(required=self.is_field_required(field))

        # Nothing to do, return a field with default attributes
        return field.formfield()

    """
    We override success url since we need to look inside our formset to get at
    an instance variable to use the absolute url if the success url is undefined.
    """
    def get_success_url(self):
        if self.success_url:
            url = smart_url(self.success_url, self.object.pk)
        else:
            try:
                if self.form_post.forms:
                    url = self.form_post.forms[0].instance.get_absolute_url()
            except AttributeError:
                raise ImproperlyConfigured(
                    "No URL to redirect to.  Either provide a url or define"
                    " a get_absolute_url method on the Model.")
        return url

    """
    Get a ModelFormSet for our specified model
    """
    def get_form(self):
        # for now, we only work with models
        if not self.model:
            raise ImproperlyConfigured("SmartListUpdateView requires that a model be defined")

        # infer what our formset should be from the model and any other
        # provided configuration on our view

        update_fields = ()

        try:
            if self.update_fields:
                update_fields = self.update_fields
        except:
            pass

        self.form = model_forms.modelformset_factory(
            self.model,
            fields=update_fields,
            extra=0,
            formfield_callback=self.formfield_options)

        return self.form

class SmartCRUDL(object):
    actions = ('create', 'read', 'update', 'delete', 'list')
    model_name = None
    app_name = None
    module_name = None
    path = None

    permissions = False

    def __init__(self, model=None, path=None, actions=None):
        # set our model if passed in
        if model:
            self.model = model

        # derive our model name
        if not self.model_name:
            self.model_name = self.model._meta.object_name

        # derive our app name
        if not self.app_name:
            self.app_name = self.model._meta.app_label

        # derive our path from our class name
        if not path and not self.path:
            self.path = self.model_name.lower()

        # derive our module name from our class's module
        if not self.module_name:
            self.module_name = self.__class__.__module__.split(".")[0]

        # set our actions if set
        if actions:
            self.actions = actions

    def permission_for_action(self, action):
        """
        Returns the permission to use for the passed in action
        """
        return "%s.%s_%s" % (self.app_name.lower(), self.model_name.lower(), action)

    def url_name_for_action(self, action):
        """
        Returns the permission to use for the passed in action
        """
        return "%s.%s_%s" % (self.module_name, self.model_name.lower(), action)

    def view_for_action(self, action):
        """
        Returns the appropriate view class for the passed in action
        """
        class_name = action.capitalize()
        view = None

        # see if we have a custom class defined for this action
        if hasattr(self, class_name):
            # return that one
            view = getattr(self, class_name)

            # no model set?  set it ourselves
            if not getattr(view, 'model', None):
                view.model = self.model

            # no permission and we are supposed to set them, do so
            if not getattr(view, 'permission', None) and self.permissions:
                view.permission = self.permission_for_action(action)

            # set our link URL based on read and update
            if not getattr(view, 'link_url', None):
                if 'read' in self.actions:
                    view.link_url = "id@%s.%s_read" % (self.module_name, self.model_name.lower())
                elif 'update' in self.actions:
                    view.link_url = "id@%s.%s_update" % (self.module_name, self.model_name.lower())
                else:
                    view.link_fields = ()

            # set add_button based on existance of Create view if add_button not explicitely set
            if not getattr(view, 'add_button', None) and (action == 'list' and 'create' in self.actions):
                view.add_button = True

            # if update or create, set success url if not set
            if not getattr(view, 'success_url', None) and (action == 'update' or action == 'create'):
                view.success_url = "@%s.%s_list" % (self.module_name, self.model_name.lower())

            view.parent = self
            return view

        # otherwise, use our defaults
        else:
            options = dict(model=self.model)

            # set permissions if appropriate
            if self.permissions:
                options['permission'] = self.permission_for_action(action)

            if action == 'create':
                view = type("%sCreateView" % self.model_name, (SmartCreateView,),
                            options)

            elif action == 'read':
                if 'update' in self.actions:
                    options['edit_button'] = True

                view = type("%sReadView" % self.model_name, (SmartReadView,),
                            options)

            elif action == 'update':
                if 'delete' in self.actions:
                    options['delete_url'] = "id@%s.%s_delete" % (self.module_name, self.model_name.lower())

                view = type("%sUpdateView" % self.model_name, (SmartUpdateView,),
                            options)

            elif action == 'delete':
                if 'list' in self.actions:
                    options['cancel_url'] = "@%s.%s_list" % (self.module_name, self.model_name.lower())
                    options['redirect_url'] = "@%s.%s_list" % (self.module_name, self.model_name.lower())

                view = type("%sDeleteView" % self.model_name, (SmartDeleteView,),
                            options)

            elif action == 'list':
                if 'read' in self.actions:
                    options['link_url'] = "id@%s.%s_read" % (self.module_name, self.model_name.lower())
                elif 'update' in self.actions:
                    options['link_url'] = "id@%s.%s_update" % (self.module_name, self.model_name.lower())
                else:
                    options['link_fields'] = ()

                if 'create' in self.actions:
                    options['add_button'] = True

                view = type("%sListView" % self.model_name, (SmartListView,),
                            options)

        if not view:
            # couldn't find a view?  blow up
            raise Exception("No view found for action: %s" % action)

        view.parent = self
        return view

    def pattern_for_action(self, action):
        """
        Returns the pattern for the passed in action.
        """
        if action == 'create':
            return r'^%s/create/$' % self.path

        elif action == 'read':
            return r'^%s/read/(?P<pk>\d+)/$' % self.path

        elif action == 'update':
            return r'^%s/update/(?P<pk>\d+)/$' % self.path

        elif action == 'delete':
            return r'^%s/delete/(?P<pk>\d+)/$' % self.path

        elif action == 'list':
            return '^%s/$' % self.path

        else:
            return '^%s/%s/$' % (self.path, action.lower())

    def as_urlpatterns(self):
        """
        Creates the appropriate URL patterns for this object.
        """
        urlpatterns = patterns('')

        # for each of our actions
        for action in self.actions:
            view_class = self.view_for_action(action)
            view_pattern = self.pattern_for_action(action)
            name = self.url_name_for_action(action)
            urlpatterns += patterns('', url(view_pattern, view_class.as_view(), name=name))

        return urlpatterns


text:
/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * OffsetDateTimeUnserializer.java                        *
 *                                                        *
 * OffsetDateTime unserializer class for Java.            *
 *                                                        *
 * LastModified: Aug 3, 2016                              *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

package hprose.io.unserialize.java8;

import static hprose.io.HproseTags.TagDate;
import static hprose.io.HproseTags.TagEmpty;
import static hprose.io.HproseTags.TagString;
import static hprose.io.HproseTags.TagTime;
import hprose.io.convert.java8.OffsetDateTimeConverter;
import hprose.io.unserialize.BaseUnserializer;
import hprose.io.unserialize.Reader;
import hprose.io.unserialize.ReferenceReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.OffsetDateTime;

public final class OffsetDateTimeUnserializer extends BaseUnserializer<OffsetDateTime> {

    public final static OffsetDateTimeUnserializer instance = new OffsetDateTimeUnserializer();

    @Override
    public OffsetDateTime unserialize(Reader reader, int tag, Type type) throws IOException {
        OffsetDateTimeConverter converter = OffsetDateTimeConverter.instance;
        switch (tag) {
            case TagString: return OffsetDateTime.parse(ReferenceReader.readString(reader));
            case TagDate: return converter.convertTo(ReferenceReader.readDateTime(reader));
            case TagTime: return converter.convertTo(ReferenceReader.readTime(reader));
            case TagEmpty: return null;
        }
        return super.unserialize(reader, tag, type);
    }

    public OffsetDateTime read(Reader reader) throws IOException {
        return read(reader, OffsetDateTime.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface MiaoShaJiLu_YiJieXiaoCell : UITableViewCell

@property (nonatomic, strong) LQModelProductDetail *model;

+ (MiaoShaJiLu_YiJieXiaoCell *)cellWithTableView:(UITableView *)tableView;

@end


text:
from functools import wraps

import os
import sys
import binascii
from libcloud.utils.py3 import httplib

import socket
from datetime import datetime, timedelta
import time

from libcloud.common.exceptions import RateLimitReachedError

DEFAULT_TIMEOUT = 30
DEFAULT_SLEEP = 1
DEFAULT_BACKCOFF = 1
EXCEPTION_TYPES = (RateLimitReachedError, socket.error, socket.gaierror,
                   httplib.NotConnected, httplib.ImproperConnectionState)

__all__ = [
    'find',
    'get_driver',
    'set_driver',
    'merge_valid_keys',
    'get_new_obj',
    'str2dicts',
    'dict2str',
    'reverse_dict',
    'lowercase_keys',
    'get_secure_random_string',
    'retry',

    'ReprMixin'
]

def find(l, predicate):
    results = [x for x in l if predicate(x)]
    return results[0] if len(results) > 0 else None

def get_driver(drivers, provider):
    """
    Get a driver.

    :param drivers: Dictionary containing valid providers.
    :param provider: Id of provider to get driver
    :type provider: :class:`libcloud.types.Provider`
    """
    if provider in drivers:
        mod_name, driver_name = drivers[provider]
        _mod = __import__(mod_name, globals(), locals(), [driver_name])
        return getattr(_mod, driver_name)

    raise AttributeError('Provider %s does not exist' % (provider))

def set_driver(drivers, provider, module, klass):
    """
    Sets a driver.

    :param drivers: Dictionary to store providers.
    :param provider: Id of provider to set driver for
    :type provider: :class:`libcloud.types.Provider`
    :param module: The module which contains the driver
    :type module: L
    :param klass: The driver class name
    :type klass:
    """

    if provider in drivers:
        raise AttributeError('Provider %s already registered' % (provider))

    drivers[provider] = (module, klass)

    # Check if this driver is valid
    try:
        driver = get_driver(drivers, provider)
    except (ImportError, AttributeError):
        exp = sys.exc_info()[1]
        drivers.pop(provider)
        raise exp

    return driver

def merge_valid_keys(params, valid_keys, extra):
    """
    Merge valid keys from extra into params dictionary and return
    dictionary with keys which have been merged.

    Note: params is modified in place.
    """
    merged = {}
    if not extra:
        return merged

    for key in valid_keys:
        if key in extra:
            params[key] = extra[key]
            merged[key] = extra[key]

    return merged

def get_new_obj(obj, klass, attributes):
    """
    Pass attributes from the existing object 'obj' and attributes
    dictionary to a 'klass' constructor.
    Attributes from 'attributes' dictionary are only passed to the
    constructor if they are not None.
    """
    kwargs = {}
    for key, value in list(obj.__dict__.items()):
        if isinstance(value, dict):
            kwargs[key] = value.copy()
        elif isinstance(value, (tuple, list)):
            kwargs[key] = value[:]
        else:
            kwargs[key] = value

    for key, value in list(attributes.items()):
        if value is None:
            continue

        if isinstance(value, dict):
            kwargs_value = kwargs.get(key, {})
            for key1, value2 in list(value.items()):
                if value2 is None:
                    continue

                kwargs_value[key1] = value2
            kwargs[key] = kwargs_value
        else:
            kwargs[key] = value

    return klass(**kwargs)

def str2dicts(data):
    """
    Create a list of dictionaries from a whitespace and newline delimited text.

    For example, this:
    cpu 1100
    ram 640

    cpu 2200
    ram 1024

    becomes:
    [{'cpu': '1100', 'ram': '640'}, {'cpu': '2200', 'ram': '1024'}]
    """
    list_data = []
    list_data.append({})
    d = list_data[-1]

    lines = data.split('\n')
    for line in lines:
        line = line.strip()

        if not line:
            d = {}
            list_data.append(d)
            d = list_data[-1]
            continue

        whitespace = line.find(' ')

        if not whitespace:
            continue

        key = line[0:whitespace]
        value = line[whitespace + 1:]
        d.update({key: value})

    list_data = [val for val in list_data if val != {}]
    return list_data

def str2list(data):
    """
    Create a list of values from a whitespace and newline delimited text
    (keys are ignored).

    For example, this:
    ip 1.2.3.4
    ip 1.2.3.5
    ip 1.2.3.6

    becomes:
    ['1.2.3.4', '1.2.3.5', '1.2.3.6']
    """
    list_data = []

    for line in data.split('\n'):
        line = line.strip()

        if not line:
            continue

        try:
            splitted = line.split(' ')
            # key = splitted[0]
            value = splitted[1]
        except Exception:
            continue

        list_data.append(value)

    return list_data

def dict2str(data):
    """
    Create a string with a whitespace and newline delimited text from a
    dictionary.

    For example, this:
    {'cpu': '1100', 'ram': '640', 'smp': 'auto'}

    becomes:
    cpu 1100
    ram 640
    smp auto

    cpu 2200
    ram 1024
    """
    result = ''
    for k in data:
        if data[k] is not None:
            result += '%s %s\n' % (str(k), str(data[k]))
        else:
            result += '%s\n' % str(k)

    return result

def reverse_dict(dictionary):
    return dict([(value, key) for key, value in list(dictionary.items())])

def lowercase_keys(dictionary):
    return dict(((k.lower(), v) for k, v in dictionary.items()))

def get_secure_random_string(size):
    """
    Return a string of ``size`` random bytes. Returned string is suitable for
    cryptographic use.

    :param size: Size of the generated string.
    :type size: ``int``

    :return: Random string.
    :rtype: ``str``
    """
    value = os.urandom(size)
    value = binascii.hexlify(value)
    value = value.decode('utf-8')[:size]
    return value

class ReprMixin(object):
    """
    Mixin class which adds __repr__ and __str__ methods for the attributes
    specified on the class.
    """

    _repr_attributes = []

    def __repr__(self):
        attributes = []
        for attribute in self._repr_attributes:
            value = getattr(self, attribute, None)
            attributes.append('%s=%s' % (attribute, value))

        values = (self.__class__.__name__, ', '.join(attributes))
        result = '<%s %s>' % values
        return result

    def __str__(self):
        return str(self.__repr__())

def retry(retry_exceptions=EXCEPTION_TYPES, retry_delay=None,
          timeout=None, backoff=None):
    """
    Retry method that helps to handle common exception.

    :param retry_exceptions: types of exceptions to retry on.
    :param retry_delay: retry delay between the attempts.
    :param timeout: maximum time to wait.
    :param backoff: multiplier added to delay between attempts.

    :Example:

    retry_request = retry(timeout=1, retry_delay=1, backoff=1)
    retry_request(self.connection.request)()
    """
    def deco_retry(func):
        @wraps(func)
        def retry_loop(*args, **kwargs):
            delay = retry_delay
            end = datetime.now() + timedelta(seconds=timeout)
            exc_info = None
            while datetime.now() < end:
                try:
                    result = func(*args, **kwargs)
                    return result
                except retry_exceptions:
                    e = sys.exc_info()[1]

                    if isinstance(e, RateLimitReachedError):
                        time.sleep(e.retry_after)
                        end = datetime.now() + timedelta(
                            seconds=e.retry_after + timeout)
                    else:
                        exc_info = e
                        time.sleep(delay)
                        delay *= backoff
            if exc_info:
                raise exc_info
            return func(*args, **kwargs)
        return retry_loop
    return deco_retry


text:
__all__ = ['register']

def register(crudconf_class):
    """
    Registers the crudconf_class on the associated model.
    After register was called, the model's crudconf can be accessed
    via modelinstance.crudconf.
    """

    def get_crudconf(model_instance):
        return crudconf_class(model_instance)

    setattr(crudconf_class.model, 'crudconf', property(get_crudconf))


text:
"""
usage:
    zhangTestShortcut.py [options] <port>

options:
    -h, --help       show this
    -v, --version    show version
    -t, --time  TIMEOUT     set time

arguments:
    N               A number
    TIMEOUT         timeout interval

"""

from docopt import docopt

if __name__ == "__main__":
    arguments = docopt(__doc__)
    print(arguments)


text:
function slideSwitch(switchSpeed) {
    var $active = $('#slideshow img.active');

    if ( $active.length == 0 ) $active = $('#slideshow img:last');

    var $next =  $active.next('img').length ? $active.next('img')
        : $('#slideshow img:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, switchSpeed, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval ( "slideSwitch(1000)", 5000 );
});


text:
package io.requery.reactivex;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.requery.BlockingEntityStore;
import io.requery.TransactionListenable;
import io.requery.meta.Type;
import io.requery.query.BaseResult;
import io.requery.query.Result;
import io.requery.query.element.QueryElement;
import io.requery.query.element.QueryWrapper;
import io.requery.rx.RxSupport;
import org.reactivestreams.Subscriber;

import java.util.Collections;
import java.util.Set;

/**
 * Support class for use with RxJava 2.0
 */
public final class ReactiveSupport {

    private static final TransactionListenerSupplier typeChanges = new TransactionListenerSupplier();

    private ReactiveSupport() {
    }

    public static <S> ReactiveEntityStore<S> toReactiveStore(BlockingEntityStore<S> store) {
        return new WrappedEntityStore<>(store);
    }

    public static <T> Observable<Result<T>> toObservableResult(final Result<T> result) {
        if (!(result instanceof TransactionListenable)) {
            throw new UnsupportedOperationException();
        }
        TransactionListenable listenable = (TransactionListenable) result;
        final QueryElement<?> element = ((QueryWrapper) result).unwrapQuery();
        // ensure the transaction listener is added in the target data store
        listenable.addTransactionListener(typeChanges);
        return typeChanges.commitSubject()
            .filter(new Predicate<Set<Type<?>>>() {
                @Override
                public boolean test(Set<Type<?>> types) {
                    return !Collections.disjoint(element.entityTypes(), types) ||
                           RxSupport.referencesType(element.entityTypes(), types);
                }
            }).map(new Function<Set<Type<?>>, Result<T>>() {
                @Override
                public Result<T> apply(Set<Type<?>> types) {
                    return result;
                }
            }).startWith(result);
    }

    public static <E> Flowable<E> toFlowable(final BaseResult<E> result) {
        return new Flowable<E>() {
            @Override
            protected void subscribeActual(Subscriber<? super E> s) {
                s.onSubscribe(new QuerySubscription<>(result, s));
            }
        };
    }
}


text:
package com.huntor.mscrm.app2.ui.component;

import android.content.Context;
import android.util.AttributeSet;
import android.view.*;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Scroller;

/**
 * Created by IDEA
 * User : SL
 * on 2015/4/29 0029
 * 13:14.
 */

/**
 * 实现侧滑的ListView
 */
public class SlideListView extends ListView {

    /**
     * 当前滑动的ListView position
     */
    private int slidePosition;
    /**
     * 手指按下X的坐标
     */
    private int downY;
    /**
     * 手指按下Y的坐标
     */
    private int downX;
    /**
     * 屏幕宽度
     */
    private int screenWidth;
    /**
     * ListView的item
     */
    private View itemView;
    /**
     * 滑动类
     */
    private Scroller scroller;
    private static final int SNAP_VELOCITY = 600;
    /**
     * 速度追踪对象
     */
    private VelocityTracker velocityTracker;
    /**
     * 是否响应滑动,默认为不响应
     */
    private boolean isSlide = false;
    /**
     * 认为是用户滑动的最小距离
     */
    private int mTouchSlop;
    /**
     * 移除item后的回调接口
     */
    private RemoveListener mRemoveListener;
    /**
     * 标示是否移除
     */
    private boolean isRemove = false;
    /**
     * 用来指示item滑出屏幕的方向,向左或者向右,用一个枚举值来标记
     */
    private RemoveDirection removeDirection;

    // 滑动删除方向的枚举值

    public enum RemoveDirection {
        RIGHT, LEFT, NONE;
    }

    public SlideListView(Context context) {
        super(context);
        init(context);
    }

    public SlideListView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    public SlideListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context);
    }

    private void init(Context context) {
        screenWidth = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
        scroller = new Scroller(context);
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }

    public void setmRemoveListener(RemoveListener mRemoveListener) {
        this.mRemoveListener = mRemoveListener;
    }

    /**
     * 分发事件,主要做的是判断点击的是那个item, 以及通过postDelayed来设置响应左右滑动事件
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                System.out.println("dispatch-->" + "down");
                addVelocityTracker(event);

                // 假如scroller滚动还没有结束,我们直接返回
                if (!scroller.isFinished()) {
                    return false;
                }
                downX = (int) event.getX();
                downY = (int) event.getY();

                slidePosition = pointToPosition(downX, downY);

                // 无效的position, 不做任何处理
                if (slidePosition == AdapterView.INVALID_POSITION) {
                    return super.dispatchTouchEvent(event);
                }

                // 获取我们点击的item view
                itemView = getChildAt(slidePosition - getFirstVisiblePosition());
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                System.out.println("dispatch-->" + "move");
                if (Math.abs(getScrollVelocity()) > SNAP_VELOCITY
                        || (Math.abs(event.getX() - downX) > mTouchSlop && Math
                        .abs(event.getY() - downY) < mTouchSlop)) {
                    isSlide = true;

                }
                break;
            }
            case MotionEvent.ACTION_UP:
                recycleVelocityTracker();
                break;
        }

        return super.dispatchTouchEvent(event);
    }

    /**
     * 处理我们拖动ListView item的逻辑
     */
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isSlide && slidePosition != AdapterView.INVALID_POSITION) {
            System.out.println("touch-->" + "开始");
            requestDisallowInterceptTouchEvent(true);
            addVelocityTracker(ev);
            final int action = ev.getAction();
            int x = (int) ev.getX();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    System.out.println("touch-->" + "down");
                    break;
                case MotionEvent.ACTION_MOVE:
                    System.out.println("touch-->" + "move");
                    MotionEvent cancelEvent = MotionEvent.obtain(ev);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                            (ev.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    onTouchEvent(cancelEvent);

                    int deltaX = downX - x;

                    // 手指拖动itemView滚动, deltaX大于0向左滚动,小于0向右滚
                    itemView.scrollTo(deltaX, 0);
                    // 根据手指滑动的距离,调整透明度
                    itemView.setAlpha(1f - Math.abs((float) deltaX / screenWidth));

                    return true;  //拖动的时候ListView不滚动
                case MotionEvent.ACTION_UP:
                    System.out.println("touch-->" + "up");
                    // 手指离开的时候就不响应左右滚动
                    isSlide = false;
                    int velocityX = getScrollVelocity();
                    if (velocityX > SNAP_VELOCITY) {
                        scrollRight();
                    } else if (velocityX < -SNAP_VELOCITY) {
                        scrollLeft();
                    } else {
                        scrollByDistanceX();
                    }

                    recycleVelocityTracker();

                    break;
            }
        }

        //否则直接交给ListView来处理onTouchEvent事件
        return super.onTouchEvent(ev);
    }

    @Override
    public void computeScroll() {
        // 调用startScroll的时候scroller.computeScrollOffset()返回true,
        if (scroller.computeScrollOffset()) {
            // 让ListView item根据当前的滚动偏移量进行滚动
            itemView.scrollTo(scroller.getCurrX(), scroller.getCurrY());

            itemView.setAlpha(1f - Math.abs((float) scroller.getCurrX() / screenWidth));

            postInvalidate();

            // 滚动动画结束的时候调用回调接口
            if (scroller.isFinished() && removeDirection != RemoveDirection.NONE) {
                if (mRemoveListener == null) {
                    throw new NullPointerException("RemoveListener is null, we should called setRemoveListener()");
                }
                itemView.scrollTo(0, 0);
                itemView.setAlpha(1f);
                mRemoveListener.removeItem(removeDirection, slidePosition);
            }
        }
    }

    /**
     * 往右滑动,getScrollX()返回的是左边缘的距离,就是以View左边缘为原点到开始滑动的距离,所以向右边滑动为负值
     */
    private void scrollRight() {
        removeDirection = RemoveDirection.RIGHT;
        final int delta = (screenWidth + itemView.getScrollX());
        // 调用startScroll方法来设置一些滚动的参数,我们在computeScroll()方法中调用scrollTo来滚动item
        scroller.startScroll(itemView.getScrollX(), 0, -delta, 0,
                Math.abs(delta));
        postInvalidate(); // 刷新itemView
    }

    /**
     * 向左滑动,根据上面我们知道向左滑动为正值
     */
    private void scrollLeft() {
        removeDirection = RemoveDirection.LEFT;
        final int delta = (screenWidth - itemView.getScrollX());
        // 调用startScroll方法来设置一些滚动的参数,我们在computeScroll()方法中调用scrollTo来滚动item
        scroller.startScroll(itemView.getScrollX(), 0, delta, 0,
                Math.abs(delta));
        postInvalidate(); // 刷新itemView
    }

    /**
     *  滑动会原来的位置
     */
    private void scrollBack(){
        removeDirection = RemoveDirection.NONE;
        scroller.startScroll(itemView.getScrollX(), 0, -itemView.getScrollX(), 0,
                Math.abs(itemView.getScrollX()));
        postInvalidate(); // 刷新itemView
    }

    /**
     * 根据手指滚动itemView的距离来判断是滚动到开始位置还是向左或者向右滚动
     */
    private void scrollByDistanceX() {
       // 如果向左滚动的距离大于屏幕的二分之一,就让其删除
        if (itemView.getScrollX() >= screenWidth / 2) {
            scrollLeft();
        } else if (itemView.getScrollX() <= -screenWidth / 2) {
            scrollRight();
        } else {
            // 滚回到原始位置
            scrollBack();
        }

    }

    /**
     * 添加用户的速度跟踪器
     *
     * @param event
     */
    private void addVelocityTracker(MotionEvent event) {
        if (velocityTracker == null) {
            velocityTracker = VelocityTracker.obtain();
        }

        velocityTracker.addMovement(event);
    }

    /**
     * 移除用户速度跟踪器
     */
    private void recycleVelocityTracker() {
        if (velocityTracker != null) {
            velocityTracker.recycle();
            velocityTracker = null;
        }
    }

    /**
     * 获取X方向的滑动速度,大于0向右滑动,反之向左
     *
     * @return
     */
    private int getScrollVelocity() {
        velocityTracker.computeCurrentVelocity(1000);
        return (int) velocityTracker.getXVelocity();
    }

    /**
     * 当ListView item滑出屏幕,回调这个接口
     * 我们需要在回调方法removeItem()中移除该Item,然后刷新ListView
     */
    public interface RemoveListener {
        public void removeItem(RemoveDirection direction, int position);
    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>windows::overlapped_ptr::get</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../windows__overlapped_ptr.html" title="windows::overlapped_ptr">
<link rel="prev" href="complete.html" title="windows::overlapped_ptr::complete">
<link rel="next" href="get/overload1.html" title="windows::overlapped_ptr::get (1 of 2 overloads)">

Home
Libraries
People
FAQ
More

windows::overlapped_ptr::get

Get the contained OVERLAPPED object.

OVERLAPPED * get();
  » more...

const OVERLAPPED * get() const;
  » more...

Copyright © 2003-2012 Christopher M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
namespace DLaB.Xrm.Entities
{

	/// <summary>
	/// Office Graph Documents Description
	/// </summary>
	[System.Runtime.Serialization.DataContractAttribute()]
	[Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("officegraphdocument")]
	[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "8.0.1.7297")]
	public partial class OfficeGraphDocument : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
	{

		public struct Fields
		{
			public const string AuthorNames = "authornames";
			public const string CreatedBy = "createdby";
			public const string CreatedOnBehalfBy = "createdonbehalfby";
			public const string CreatedTime = "createdtime";
			public const string DocumentId = "documentid";
			public const string DocumentLastModifiedBy = "documentlastmodifiedby";
			public const string DocumentLastModifiedOn = "documentlastmodifiedon";
			public const string DocumentPreviewMetadata = "documentpreviewmetadata";
			public const string ExchangeRate = "exchangerate";
			public const string FileExtension = "fileextension";
			public const string FileType = "filetype";
			public const string ModifiedBy = "modifiedby";
			public const string ModifiedOnBehalfBy = "modifiedonbehalfby";
			public const string ModifiedTime = "modifiedtime";
			public const string OfficeGraphDocumentId = "officegraphdocumentid";
			public const string Id = "officegraphdocumentid";
			public const string OrganizationId = "organizationid";
			public const string PreviewImageUrl = "previewimageurl";
			public const string QueryType = "querytype";
			public const string Rank = "rank";
			public const string ReadUrl = "readurl";
			public const string SecondaryFileExtension = "secondaryfileextension";
			public const string SiteTitle = "sitetitle";
			public const string SiteUrl = "siteurl";
			public const string TimeZoneRuleVersionNumber = "timezoneruleversionnumber";
			public const string Title = "title";
			public const string TransactionCurrencyId = "transactioncurrencyid";
			public const string UTCConversionTimeZoneCode = "utcconversiontimezonecode";
			public const string VersionNumber = "versionnumber";
			public const string ViewCount = "viewcount";
			public const string WebLocationUrl = "weblocationurl";
			public const string lk_officegraphdocument_createdonbehalfby = "lk_officegraphdocument_createdonbehalfby";
			public const string lk_officegraphdocument_modifiedonbehalfby = "lk_officegraphdocument_modifiedonbehalfby";
			public const string organization_officegraphdocument = "organization_officegraphdocument";
			public const string TransactionCurrency_officegraphdocument = "TransactionCurrency_officegraphdocument";
		}

		/// <summary>
		/// Default Constructor.
		/// </summary>
		[System.Diagnostics.DebuggerNonUserCode()]
		public OfficeGraphDocument() :
				base(EntityLogicalName)
		{
		}

		public const string EntityLogicalName = "officegraphdocument";

		public const int EntityTypeCode = 9950;

		public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

		public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;

		[System.Diagnostics.DebuggerNonUserCode()]
		private void OnPropertyChanged(string propertyName)
		{
			if ((this.PropertyChanged != null))
			{
				this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
			}
		}

		[System.Diagnostics.DebuggerNonUserCode()]
		private void OnPropertyChanging(string propertyName)
		{
			if ((this.PropertyChanging != null))
			{
				this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName));
			}
		}

		/// <summary>
		/// Shows Author Names of Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("authornames")]
		public string AuthorNames
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("authornames");
			}
		}

		/// <summary>
		/// Shows Created By of Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")]
		public string CreatedBy
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("createdby");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("CreatedBy");
				this.SetAttributeValue("createdby", value);
				this.OnPropertyChanged("CreatedBy");
			}
		}

		/// <summary>
		/// Unique identifier of the delegate user who created the record.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")]
		public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("CreatedOnBehalfBy");
				this.SetAttributeValue("createdonbehalfby", value);
				this.OnPropertyChanged("CreatedOnBehalfBy");
			}
		}

		/// <summary>
		/// Date and time when the record was created.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdtime")]
		public System.Nullable<System.DateTime> CreatedTime
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdtime");
			}
		}

		/// <summary>
		/// Document Id.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("documentid")]
		public string DocumentId
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("documentid");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("DocumentId");
				this.SetAttributeValue("documentid", value);
				this.OnPropertyChanged("DocumentId");
			}
		}

		/// <summary>
		/// Document Last Modified By
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("documentlastmodifiedby")]
		public string DocumentLastModifiedBy
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("documentlastmodifiedby");
			}
		}

		/// <summary>
		/// Document Last Modified On
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("documentlastmodifiedon")]
		public System.Nullable<System.DateTime> DocumentLastModifiedOn
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<System.DateTime>>("documentlastmodifiedon");
			}
		}

		/// <summary>
		/// document preview metadata
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("documentpreviewmetadata")]
		public string DocumentPreviewMetadata
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("documentpreviewmetadata");
			}
		}

		/// <summary>
		/// Exchange rate for the currency associated with the Office Graph Document with respect to the base currency.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("exchangerate")]
		public System.Nullable<decimal> ExchangeRate
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<decimal>>("exchangerate");
			}
		}

		/// <summary>
		/// File Extension of Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("fileextension")]
		public string FileExtension
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("fileextension");
			}
		}

		/// <summary>
		/// Shows the File Type of Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("filetype")]
		public string FileType
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("filetype");
			}
		}

		/// <summary>
		/// Shows modified by of Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")]
		public string ModifiedBy
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("modifiedby");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("ModifiedBy");
				this.SetAttributeValue("modifiedby", value);
				this.OnPropertyChanged("ModifiedBy");
			}
		}

		/// <summary>
		/// Unique identifier of the delegate user who modified the record.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")]
		public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedonbehalfby");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("ModifiedOnBehalfBy");
				this.SetAttributeValue("modifiedonbehalfby", value);
				this.OnPropertyChanged("ModifiedOnBehalfBy");
			}
		}

		/// <summary>
		/// Date and time when the record was modified.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedtime")]
		public System.Nullable<System.DateTime> ModifiedTime
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<System.DateTime>>("modifiedtime");
			}
		}

		/// <summary>
		/// Unique identifier for entity instances
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("officegraphdocumentid")]
		public System.Nullable<System.Guid> OfficeGraphDocumentId
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<System.Guid>>("officegraphdocumentid");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("OfficeGraphDocumentId");
				this.SetAttributeValue("officegraphdocumentid", value);
				if (value.HasValue)
				{
					base.Id = value.Value;
				}
				else
				{
					base.Id = System.Guid.Empty;
				}
				this.OnPropertyChanged("OfficeGraphDocumentId");
			}
		}

		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("officegraphdocumentid")]
		public override System.Guid Id
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return base.Id;
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OfficeGraphDocumentId = value;
			}
		}

		/// <summary>
		/// Unique identifier for the organization
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")]
		public Microsoft.Xrm.Sdk.EntityReference OrganizationId
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("organizationid");
			}
		}

		/// <summary>
		/// Shows the Preview Image Url Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("previewimageurl")]
		public string PreviewImageUrl
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("previewimageurl");
			}
		}

		/// <summary>
		/// Shows Query Type of child folders
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("querytype")]
		public System.Nullable<int> QueryType
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<int>>("querytype");
			}
		}

		/// <summary>
		/// The relevancy rank of the document retrieved
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("rank")]
		public System.Nullable<int> Rank
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<int>>("rank");
			}
		}

		/// <summary>
		/// The online read url
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("readurl")]
		public string ReadUrl
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("readurl");
			}
		}

		/// <summary>
		/// Secondary File Extension of Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("secondaryfileextension")]
		public string SecondaryFileExtension
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("secondaryfileextension");
			}
		}

		/// <summary>
		/// The title of the parent document site
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("sitetitle")]
		public string SiteTitle
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("sitetitle");
			}
		}

		/// <summary>
		/// The site url for the parent document site
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("siteurl")]
		public string SiteUrl
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("siteurl");
			}
		}

		/// <summary>
		/// For internal use only.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("timezoneruleversionnumber")]
		public System.Nullable<int> TimeZoneRuleVersionNumber
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<int>>("timezoneruleversionnumber");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("TimeZoneRuleVersionNumber");
				this.SetAttributeValue("timezoneruleversionnumber", value);
				this.OnPropertyChanged("TimeZoneRuleVersionNumber");
			}
		}

		/// <summary>
		/// The title of the entity.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("title")]
		public string Title
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("title");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("Title");
				this.SetAttributeValue("title", value);
				this.OnPropertyChanged("Title");
			}
		}

		/// <summary>
		/// Exchange rate for the currency associated with the Office Graph Document with respect to the base currency.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("transactioncurrencyid")]
		public Microsoft.Xrm.Sdk.EntityReference TransactionCurrencyId
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("transactioncurrencyid");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("TransactionCurrencyId");
				this.SetAttributeValue("transactioncurrencyid", value);
				this.OnPropertyChanged("TransactionCurrencyId");
			}
		}

		/// <summary>
		/// Time zone code that was in use when the record was created.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("utcconversiontimezonecode")]
		public System.Nullable<int> UTCConversionTimeZoneCode
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<int>>("utcconversiontimezonecode");
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("UTCConversionTimeZoneCode");
				this.SetAttributeValue("utcconversiontimezonecode", value);
				this.OnPropertyChanged("UTCConversionTimeZoneCode");
			}
		}

		/// <summary>
		///
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")]
		public System.Nullable<long> VersionNumber
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<long>>("versionnumber");
			}
		}

		/// <summary>
		/// Shows View Count of child folders.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("viewcount")]
		public System.Nullable<int> ViewCount
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<System.Nullable<int>>("viewcount");
			}
		}

		/// <summary>
		/// Shows the Web Location Url of Office Graph Document.
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("weblocationurl")]
		public string WebLocationUrl
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetAttributeValue<string>("weblocationurl");
			}
		}

		/// <summary>
		/// N:1 lk_officegraphdocument_createdonbehalfby
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")]
		[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_officegraphdocument_createdonbehalfby")]
		public Entities.SystemUser lk_officegraphdocument_createdonbehalfby
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetRelatedEntity<Entities.SystemUser>("lk_officegraphdocument_createdonbehalfby", null);
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("lk_officegraphdocument_createdonbehalfby");
				this.SetRelatedEntity<Entities.SystemUser>("lk_officegraphdocument_createdonbehalfby", null, value);
				this.OnPropertyChanged("lk_officegraphdocument_createdonbehalfby");
			}
		}

		/// <summary>
		/// N:1 lk_officegraphdocument_modifiedonbehalfby
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")]
		[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_officegraphdocument_modifiedonbehalfby")]
		public Entities.SystemUser lk_officegraphdocument_modifiedonbehalfby
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetRelatedEntity<Entities.SystemUser>("lk_officegraphdocument_modifiedonbehalfby", null);
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("lk_officegraphdocument_modifiedonbehalfby");
				this.SetRelatedEntity<Entities.SystemUser>("lk_officegraphdocument_modifiedonbehalfby", null, value);
				this.OnPropertyChanged("lk_officegraphdocument_modifiedonbehalfby");
			}
		}

		/// <summary>
		/// N:1 organization_officegraphdocument
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")]
		[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("organization_officegraphdocument")]
		public Entities.Organization organization_officegraphdocument
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetRelatedEntity<Entities.Organization>("organization_officegraphdocument", null);
			}
		}

		/// <summary>
		/// N:1 TransactionCurrency_officegraphdocument
		/// </summary>
		[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("transactioncurrencyid")]
		[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("TransactionCurrency_officegraphdocument")]
		public Entities.TransactionCurrency TransactionCurrency_officegraphdocument
		{
			[System.Diagnostics.DebuggerNonUserCode()]
			get
			{
				return this.GetRelatedEntity<Entities.TransactionCurrency>("TransactionCurrency_officegraphdocument", null);
			}
			[System.Diagnostics.DebuggerNonUserCode()]
			set
			{
				this.OnPropertyChanging("TransactionCurrency_officegraphdocument");
				this.SetRelatedEntity<Entities.TransactionCurrency>("TransactionCurrency_officegraphdocument", null, value);
				this.OnPropertyChanged("TransactionCurrency_officegraphdocument");
			}
		}

		/// <summary>
		/// Constructor for populating via LINQ queries given a LINQ anonymous type
		/// <param name="anonymousType">LINQ anonymous type.</param>
		/// </summary>
		[System.Diagnostics.DebuggerNonUserCode()]
		public OfficeGraphDocument(object anonymousType) :
				this()
		{
            foreach (var p in anonymousType.GetType().GetProperties())
            {
                var value = p.GetValue(anonymousType, null);
                var name = p.Name.ToLower();

                if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum))
                {
                    value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value);
                    name = name.Remove(name.Length - "enum".Length);
                }

                switch (name)
                {
                    case "id":
                        base.Id = (System.Guid)value;
                        Attributes["officegraphdocumentid"] = base.Id;
                        break;
                    case "officegraphdocumentid":
                        var id = (System.Nullable<System.Guid>) value;
                        if(id == null){ continue; }
                        base.Id = id.Value;
                        Attributes[name] = base.Id;
                        break;
                    case "formattedvalues":
                        // Add Support for FormattedValues
                        FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value);
                        break;
                    default:
                        Attributes[name] = value;
                        break;
                }
            }
		}
	}
}


text:
package proc

import (
	"fmt"
	"runtime"
)

// Represents a single breakpoint. Stores information on the break
// point including the byte of data that originally was stored at that
// address.
type Breakpoint struct {
	// File & line information for printing.
	FunctionName string
	File         string
	Line         int

	Addr         uint64 // Address breakpoint is set for.
	OriginalData []byte // If software breakpoint, the data we replace with breakpoint instruction.
	ID           int    // Monotonically increasing ID.
	Temp         bool   // Whether this is a temp breakpoint (for next'ing).

	// Breakpoint information
	Tracepoint bool     // Tracepoint flag
	Stacktrace int      // Number of stack frames to retrieve
	Goroutine  bool     // Retrieve goroutine information
	Variables  []string // Variables to evaluate

	hardware bool // Breakpoint using CPU debug registers.
	reg      int  // If hardware breakpoint, what debug register it belongs to.

}

func (bp *Breakpoint) String() string {
	return fmt.Sprintf("Breakpoint %d at %#v %s:%d", bp.ID, bp.Addr, bp.File, bp.Line)
}

// Clear this breakpoint appropriately depending on whether it is a
// hardware or software breakpoint.
func (bp *Breakpoint) Clear(thread *Thread) (*Breakpoint, error) {
	if bp.hardware {
		if err := thread.dbp.clearHardwareBreakpoint(bp.reg, thread.Id); err != nil {
			return nil, err
		}
		return bp, nil
	}
	if _, err := thread.writeMemory(uintptr(bp.Addr), bp.OriginalData); err != nil {
		return nil, fmt.Errorf("could not clear breakpoint %s", err)
	}
	return bp, nil
}

// Returned when trying to set a breakpoint at
// an address that already has a breakpoint set for it.
type BreakpointExistsError struct {
	file string
	line int
	addr uint64
}

func (bpe BreakpointExistsError) Error() string {
	return fmt.Sprintf("Breakpoint exists at %s:%d at %x", bpe.file, bpe.line, bpe.addr)
}

// InvalidAddressError represents the result of
// attempting to set a breakpoint at an invalid address.
type InvalidAddressError struct {
	address uint64
}

func (iae InvalidAddressError) Error() string {
	return fmt.Sprintf("Invalid address %#v\n", iae.address)
}

func (dbp *Process) setBreakpoint(tid int, addr uint64, temp bool) (*Breakpoint, error) {
	if bp, ok := dbp.FindBreakpoint(addr); ok {
		return nil, BreakpointExistsError{bp.File, bp.Line, bp.Addr}
	}

	f, l, fn := dbp.goSymTable.PCToLine(uint64(addr))
	if fn == nil {
		return nil, InvalidAddressError{address: addr}
	}

	newBreakpoint := &Breakpoint{
		FunctionName: fn.Name,
		File:         f,
		Line:         l,
		Addr:         addr,
		Temp:         temp,
	}

	if temp {
		dbp.tempBreakpointIDCounter++
		newBreakpoint.ID = dbp.tempBreakpointIDCounter
	} else {
		dbp.breakpointIDCounter++
		newBreakpoint.ID = dbp.breakpointIDCounter
	}

	// Try and set a hardware breakpoint.
	for i, used := range dbp.arch.HardwareBreakpointUsage() {
		if runtime.GOOS == "darwin" { // TODO(dp): Implement hardware breakpoints on OSX.
			break
		}
		if used {
			continue
		}
		for tid, t := range dbp.Threads {
			if t.running {
				err := t.Halt()
				if err != nil {
					return nil, err
				}
				defer t.Continue()
			}
			if err := dbp.setHardwareBreakpoint(i, tid, addr); err != nil {
				return nil, fmt.Errorf("could not set hardware breakpoint on thread %d: %s", t, err)
			}
		}
		dbp.arch.SetHardwareBreakpointUsage(i, true)
		newBreakpoint.reg = i
		newBreakpoint.hardware = true
		dbp.Breakpoints[addr] = newBreakpoint
		return dbp.Breakpoints[addr], nil
	}

	// Fall back to software breakpoint.
	thread := dbp.Threads[tid]
	originalData, err := thread.readMemory(uintptr(addr), dbp.arch.BreakpointSize())
	if err != nil {
		return nil, err
	}
	if err := dbp.writeSoftwareBreakpoint(thread, addr); err != nil {
		return nil, err
	}
	newBreakpoint.OriginalData = originalData
	dbp.Breakpoints[addr] = newBreakpoint

	return newBreakpoint, nil
}

func (dbp *Process) writeSoftwareBreakpoint(thread *Thread, addr uint64) error {
	_, err := thread.writeMemory(uintptr(addr), dbp.arch.BreakpointInstruction())
	return err
}

// Error thrown when trying to clear a breakpoint that does not exist.
type NoBreakpointError struct {
	addr uint64
}

func (nbp NoBreakpointError) Error() string {
	return fmt.Sprintf("no breakpoint at %#v", nbp.addr)
}


text:
#include "../transport.h"
#include "../protocol.h"

#include "sock.h"
#include "ep.h"

#include "../utils/err.h"
#include "../utils/fast.h"

/*  Internal pipe states. */
#define NN_PIPEBASE_STATE_IDLE 1
#define NN_PIPEBASE_STATE_ACTIVE 2
#define NN_PIPEBASE_STATE_FAILED 3

#define NN_PIPEBASE_INSTATE_DEACTIVATED 0
#define NN_PIPEBASE_INSTATE_IDLE 1
#define NN_PIPEBASE_INSTATE_RECEIVING 2
#define NN_PIPEBASE_INSTATE_RECEIVED 3
#define NN_PIPEBASE_INSTATE_ASYNC 4

#define NN_PIPEBASE_OUTSTATE_DEACTIVATED 0
#define NN_PIPEBASE_OUTSTATE_IDLE 1
#define NN_PIPEBASE_OUTSTATE_SENDING 2
#define NN_PIPEBASE_OUTSTATE_SENT 3
#define NN_PIPEBASE_OUTSTATE_ASYNC 4

void nn_pipebase_init (struct nn_pipebase *self,
    const struct nn_pipebase_vfptr *vfptr, struct nn_epbase *epbase)
{
    nn_assert (epbase->ep->sock);

    nn_fsm_init (&self->fsm, NULL, NULL, 0, self, &epbase->ep->sock->fsm);
    self->vfptr = vfptr;
    self->state = NN_PIPEBASE_STATE_IDLE;
    self->instate = NN_PIPEBASE_INSTATE_DEACTIVATED;
    self->outstate = NN_PIPEBASE_OUTSTATE_DEACTIVATED;
    self->sock = epbase->ep->sock;
    memcpy (&self->options, &epbase->ep->options,
        sizeof (struct nn_ep_options));
    nn_fsm_event_init (&self->in);
    nn_fsm_event_init (&self->out);
}

void nn_pipebase_term (struct nn_pipebase *self)
{
    nn_assert_state (self, NN_PIPEBASE_STATE_IDLE);

    nn_fsm_event_term (&self->out);
    nn_fsm_event_term (&self->in);
    nn_fsm_term (&self->fsm);
}

int nn_pipebase_start (struct nn_pipebase *self)
{
    int rc;

    nn_assert_state (self, NN_PIPEBASE_STATE_IDLE);

    self->state = NN_PIPEBASE_STATE_ACTIVE;
    self->instate = NN_PIPEBASE_INSTATE_ASYNC;
    self->outstate = NN_PIPEBASE_OUTSTATE_IDLE;
    rc = nn_sock_add (self->sock, (struct nn_pipe*) self);
    if (nn_slow (rc < 0)) {
        self->state = NN_PIPEBASE_STATE_FAILED;
        return rc;
    }
    if (self->sock)
        nn_fsm_raise (&self->fsm, &self->out, NN_PIPE_OUT);

    return 0;
}

void nn_pipebase_stop (struct nn_pipebase *self)
{
    if (self->state == NN_PIPEBASE_STATE_ACTIVE)
        nn_sock_rm (self->sock, (struct nn_pipe*) self);
    self->state = NN_PIPEBASE_STATE_IDLE;
}

void nn_pipebase_received (struct nn_pipebase *self)
{
    if (nn_fast (self->instate == NN_PIPEBASE_INSTATE_RECEIVING)) {
        self->instate = NN_PIPEBASE_INSTATE_RECEIVED;
        return;
    }
    nn_assert (self->instate == NN_PIPEBASE_INSTATE_ASYNC);
    self->instate = NN_PIPEBASE_INSTATE_IDLE;
    if (self->sock)
        nn_fsm_raise (&self->fsm, &self->in, NN_PIPE_IN);
}

void nn_pipebase_sent (struct nn_pipebase *self)
{
    if (nn_fast (self->outstate == NN_PIPEBASE_OUTSTATE_SENDING)) {
        self->outstate = NN_PIPEBASE_OUTSTATE_SENT;
        return;
    }
    nn_assert (self->outstate == NN_PIPEBASE_OUTSTATE_ASYNC);
    self->outstate = NN_PIPEBASE_OUTSTATE_IDLE;
    if (self->sock)
        nn_fsm_raise (&self->fsm, &self->out, NN_PIPE_OUT);
}

void nn_pipebase_getopt (struct nn_pipebase *self, int level, int option,
    void *optval, size_t *optvallen)
{
    int rc;
    int intval;

    if (level == NN_SOL_SOCKET) {
        switch (option) {

        /*  Endpoint options  */
        case NN_SNDPRIO:
            intval = self->options.sndprio;
            break;
        case NN_RCVPRIO:
            intval = self->options.rcvprio;
            break;
        case NN_IPV4ONLY:
            intval = self->options.ipv4only;
            break;

        /*  Fallback to socket options  */
        default:
            rc = nn_sock_getopt_inner (self->sock, level,
                option, optval, optvallen);
            errnum_assert (rc == 0, -rc);
            return;
        }

        memcpy (optval, &intval,
            *optvallen < sizeof (int) ? *optvallen : sizeof (int));
        *optvallen = sizeof (int);

        return;
    }

    rc = nn_sock_getopt_inner (self->sock, level, option, optval, optvallen);
    errnum_assert (rc == 0, -rc);
}

int nn_pipebase_ispeer (struct nn_pipebase *self, int socktype)
{
    return nn_sock_ispeer (self->sock, socktype);
}

void nn_pipe_setdata (struct nn_pipe *self, void *data)
{
    ((struct nn_pipebase*) self)->data = data;
}

void *nn_pipe_getdata (struct nn_pipe *self)
{
    return ((struct nn_pipebase*) self)->data;
}

int nn_pipe_send (struct nn_pipe *self, struct nn_msg *msg)
{
    int rc;
    struct nn_pipebase *pipebase;

    pipebase = (struct nn_pipebase*) self;
    nn_assert (pipebase->outstate == NN_PIPEBASE_OUTSTATE_IDLE);
    pipebase->outstate = NN_PIPEBASE_OUTSTATE_SENDING;
    rc = pipebase->vfptr->send (pipebase, msg);
    errnum_assert (rc >= 0, -rc);
    if (nn_fast (pipebase->outstate == NN_PIPEBASE_OUTSTATE_SENT)) {
        pipebase->outstate = NN_PIPEBASE_OUTSTATE_IDLE;
        return rc;
    }
    nn_assert (pipebase->outstate == NN_PIPEBASE_OUTSTATE_SENDING);
    pipebase->outstate = NN_PIPEBASE_OUTSTATE_ASYNC;
    return rc | NN_PIPEBASE_RELEASE;
}

int nn_pipe_recv (struct nn_pipe *self, struct nn_msg *msg)
{
    int rc;
    struct nn_pipebase *pipebase;

    pipebase = (struct nn_pipebase*) self;
    nn_assert (pipebase->instate == NN_PIPEBASE_INSTATE_IDLE);
    pipebase->instate = NN_PIPEBASE_INSTATE_RECEIVING;
    rc = pipebase->vfptr->recv (pipebase, msg);
    errnum_assert (rc >= 0, -rc);

    if (nn_fast (pipebase->instate == NN_PIPEBASE_INSTATE_RECEIVED)) {
        pipebase->instate = NN_PIPEBASE_INSTATE_IDLE;
        return rc;
    }
    nn_assert (pipebase->instate == NN_PIPEBASE_INSTATE_RECEIVING);
    pipebase->instate = NN_PIPEBASE_INSTATE_ASYNC;
    return rc | NN_PIPEBASE_RELEASE;
}

void nn_pipe_getopt (struct nn_pipe *self, int level, int option,
    void *optval, size_t *optvallen)
{

    struct nn_pipebase *pipebase;

    pipebase = (struct nn_pipebase*) self;
    nn_pipebase_getopt (pipebase, level, option, optval, optvallen);
}