text:
@implementation NSManagedObjectContext (MagicalSaves)

- (void) MR_saveOnlySelfWithCompletion:(MRSaveCompletionHandler)completion;
{
    [self MR_saveWithOptions:MRSaveOptionNone completion:completion];
}

- (void) MR_saveOnlySelfAndWait;
{
    [self MR_saveWithOptions:MRSaveSynchronously completion:nil];
}

- (void) MR_saveToPersistentStoreWithCompletion:(MRSaveCompletionHandler)completion;
{
    [self MR_saveWithOptions:MRSaveParentContexts completion:completion];
}

- (void) MR_saveToPersistentStoreAndWait;
{
    [self MR_saveWithOptions:MRSaveParentContexts | MRSaveSynchronously completion:nil];
}

- (void) MR_saveWithOptions:(MRSaveOptions)mask completion:(MRSaveCompletionHandler)completion;
{
    if (![self hasChanges])
    {
        MRLogVerbose(@"NO CHANGES IN ** %@ ** CONTEXT - NOT SAVING", [self MR_workingName]);

        if (completion)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, nil);
            });
        }

        return;
    }

    BOOL shouldSaveParentContexts = ((mask & MRSaveParentContexts) == MRSaveParentContexts);
    BOOL shouldSaveSynchronously = ((mask & MRSaveSynchronously) == MRSaveSynchronously);
    BOOL shouldSaveSynchronouslyExceptRoot = ((mask & MRSaveSynchronouslyExceptRootContext) == MRSaveSynchronouslyExceptRootContext);

    BOOL saveSynchronously = (shouldSaveSynchronously && !shouldSaveSynchronouslyExceptRoot) || (shouldSaveSynchronouslyExceptRoot && (self != [[self class] MR_rootSavingContext]));

    MRLogInfo(@"→ Saving %@", [self MR_description]);
    MRLogVerbose(@"→ Save Parents? %@", shouldSaveParentContexts ? @"YES" : @"NO");
    MRLogVerbose(@"→ Save Synchronously? %@", saveSynchronously ? @"YES" : @"NO");

    id saveBlock = ^{
        BOOL saveResult = NO;
        NSError *error = nil;

        @try
        {
            saveResult = [self save:&error];
        }
        @catch(NSException *exception)
        {
            MRLogError(@"Unable to perform save: %@", (id)[exception userInfo] ?: (id)[exception reason]);
        }
        @finally
        {
            [MagicalRecord handleErrors:error];

            if (saveResult && shouldSaveParentContexts && [self parentContext])
            {
                // If we're saving parent contexts, do so
                [[self parentContext] MR_saveWithOptions:mask completion:completion];
            }
            else
            {
                if (saveResult)
                {
                    MRLogVerbose(@"→ Finished saving: %@", [self MR_description]);
                }

                if (completion)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completion(saveResult, error);
                    });
                }
            }
        }
    };

    if (saveSynchronously)
    {
        [self performBlockAndWait:saveBlock];
    }
    else
    {
        [self performBlock:saveBlock];
    }
}

@end

#pragma mark - Deprecated Methods — DO NOT USE
@implementation NSManagedObjectContext (MagicalSavesDeprecated)

- (void) MR_save;
{
    [self MR_saveToPersistentStoreAndWait];
}

- (void) MR_saveWithErrorCallback:(void (^)(NSError *error))errorCallback;
{
    [self MR_saveWithOptions:MRSaveSynchronously | MRSaveParentContexts completion:^(BOOL success, NSError *error) {
        if (!success && errorCallback)
        {
            errorCallback(error);
        }
    }];
}

- (void) MR_saveInBackgroundCompletion:(void (^)(void))completion;
{
    [self MR_saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
        if (success && completion)
        {
            completion();
        }
    }];
}

- (void) MR_saveInBackgroundErrorHandler:(void (^)(NSError *error))errorCallback;
{
    [self MR_saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
        if (!success && errorCallback)
        {
            errorCallback(error);
        }
    }];
}

- (void) MR_saveInBackgroundErrorHandler:(void (^)(NSError *error))errorCallback completion:(void (^)(void))completion;
{
    [self MR_saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
        if (success && completion)
        {
            completion();
        }
        else if (errorCallback)
        {
            errorCallback(error);
        }
    }];
}

- (void) MR_saveNestedContexts;
{
    [self MR_saveToPersistentStoreWithCompletion:nil];
}

- (void) MR_saveNestedContextsErrorHandler:(void (^)(NSError *error))errorCallback;
{
    [self MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (!success && errorCallback)
        {
            errorCallback(error);
        }
    }];
}

- (void) MR_saveNestedContextsErrorHandler:(void (^)(NSError *error))errorCallback completion:(void (^)(void))completion;
{
    [self MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (success && completion)
        {
            completion();
        }
        else if (errorCallback)
        {
            errorCallback(error);
        }
    }];
}

@end


text:
Package.describe({
	name: 'rocketchat:slider',
	version: '0.0.1',
	summary: 'UI slider component for input range.',
	git: '',
	documentation: 'README.md'
});

Package.onUse(function(api) {
	api.use('ecmascript');
	api.use('templating', 'client');
	api.use('rocketchat:theme');

	api.addFiles('rocketchat-slider.html', 'client');
	api.addFiles('rocketchat-slider.js', 'client');
});

redpajama_set_name: RedPajamaGithub


text:
//-----------------------------------------------------------------------
// <copyright file="DisableCodeGenerationAttribute.cs" company="Copacetic Software">
// Copyright (c) Copacetic Software.
// <author>Philip Pittle</author>
// <date>Friday, May 9, 2014 1:51:04 PM</date>
// Licensed under the Apache License, Version 2.0,
// you may not use this file except in compliance with this License.
//
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CopaceticSoftware.pMixins.Attributes
{
    /// <summary>
    /// Decorate an Assembly (in AssemblyInfo.cs) or a Class with this
    /// attribute to disable the Code Generator from running.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
    public class DisableCodeGenerationAttribute : Attribute, IPMixinAttribute
    {
    }
}


text:
from ordereddict import OrderedDict

from datetime import datetime
from dateutil import parser, tz
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.utils.encoding import smart_unicode
from django.utils.timezone import utc

import re
import simplejson as json
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

def parse_iso_8601(s):
    return parser.parse(s).astimezone(tz.tzutc())

class Field(object):

    def __init__(self, dictionary_key=None, ordinal=0, attribute_name=None, model_attribute=None, comparable=True, produceable=True, consumable=True, optional=False, blank=False, extended=False, modelizable=True):
        self.dictionary_key = dictionary_key
        self.ordinal = ordinal
        self.attribute_name = attribute_name
        self.model_attribute = model_attribute
        self.comparable = comparable
        self.produceable = produceable
        self.consumable = consumable
        self.optional = optional
        self.blank = blank
        self.extended = extended
        self.modelizable = modelizable

    def __cmp__(self, other):

        if self is not None and other is not None:

            if hasattr(self, 'ordinal') and hasattr(other, 'ordinal'):
                if self.ordinal < other.ordinal:
                    return -1
                if self.ordinal > other.ordinal:
                    return 1

        return 0

    def from_model_attribute(self, model):
        if not self.modelizable:
            return None

        return getattr(model, self.model_attribute)

    def from_object_literal(self, value):
        return value

    def to_model_attribute(self, value):
        return value

    def to_object_literal(self, value):
        return value

    def validate(self, obj, invalid_fields):
        if self.consumable and not self.optional:
            value = getattr(obj, self.attribute_name)
            if not value or value is None or value == '' or isinstance(value, Field):
                invalid_fields[self.dictionary_key] = 'Field is required'

class BooleanField(Field):

    def __init__(self, *args, **kwargs):
        super(BooleanField, self).__init__(*args, **kwargs)

    def from_model_attribute(self, model):
        if not self.modelizable:
            return None

        value = getattr(model, self.model_attribute)

        if value is None:
            return False

        return bool(value)

class DateField(Field):

    def from_model_attribute(self, model):
        value = getattr(model, self.model_attribute)
        return value

    def from_object_literal(self, value):
        if value is not None:
            try:
                return parser.parse(value).astimezone(tz.tzutc())
            except ValueError:
                pass

        return None

    def to_model_attribute(self, value):
        return value

    def to_object_literal(self, value):
        if value is not None and isinstance(value, datetime):
            return value.replace(tzinfo = utc).isoformat('T')
        return None

#    def validate(self, obj, invalid_fields):
#        if self.consumable:
#            try:
#                value = getattr(obj, self.attribute_name)
#                if value is not None and not isinstance(value, Field):
#                    parser.parse(value).astimezone(tz.tzutc())
#                    invalid_fields[self.dictionary_key] = 'Field is required'
#            except AttributeError:
#                pass

class LastModifiedDateField(DateField):

    def __init__(self, *args, **kwargs):
        kwargs['consumable'] = False
        kwargs['comparable'] = False
        super(LastModifiedDateField, self).__init__(*args, **kwargs)

class ExtendedDateField(DateField):

    def __init__(self, *args, **kwargs):
        kwargs['extended'] = True
        kwargs['consumable'] = False
        kwargs['comparable'] = False
        super(ExtendedDateField, self).__init__(*args, **kwargs)

class IntegerField(Field):

    def __init__(self, *args, **kwargs):
        super(IntegerField, self).__init__(*args, **kwargs)

    def from_model_attribute(self, model):
        value = getattr(model, self.model_attribute)
        if value is None:
            return 0
        return value

    def from_object_literal(self, value):
        if value is None:
            return 0
        return int(value)

    def to_model_attribute(self, value):
        return value

class ExtendedField(Field):

    def __init__(self, *args, **kwargs):
        kwargs['extended'] = True
        kwargs['consumable'] = False
        kwargs['comparable'] = False
        super(ExtendedField, self).__init__(*args, **kwargs)

class MessageTypeField(Field):

    def __init__(self, *args, **kwargs):
        super(MessageTypeField, self).__init__(*args, **kwargs)

    def from_model_attribute(self, model):
        if not self.modelizable:
            return None

        value = getattr(model, self.model_attribute)
        if value is None:
            return ''
        return value.surrogate_id

    def to_model_attribute(self, value):
        return None

class NetIdField(Field):

    def __init__(self, *args, **kwargs):
        super(NetIdField, self).__init__(*args, **kwargs)

    def from_model_attribute(self, model):
        value = getattr(model, self.model_attribute)
        if value is None:
            return ''
        return value.surrogate_id

    def to_model_attribute(self, value):
        return None

class LowerCaseField(Field):

    def to_model_attribute(self, value):
        if value and value is not None:
            return value.lower()
        return value

class UriField(Field):

    def __init__(self, *args, **kwargs):
        #kwargs['extended'] = True
        kwargs['produceable'] = False
        kwargs['consumable'] = False
        kwargs['comparable'] = False
        super(UriField, self).__init__(*args, **kwargs)

class ViewModelField(Field):

    def __init__(self, *args, **kwargs):
        self.view_model_type = kwargs.pop('view_model_type', None)
        kwargs['blank'] = True
        kwargs['consumable'] = False
        super(ViewModelField, self).__init__(*args, **kwargs)

class ViewModelBase(type):

    def __new__(cls, name, bases, dictionary):
        view_model = type.__new__(cls, name, bases, dictionary)

        view_model.fields = list()
        for name in dir(view_model):
            if isinstance(name, str):
                value = getattr(view_model, name)
                if isinstance(value, Field):
                    if value.attribute_name is None:
                        value.attribute_name = name
                    if value.model_attribute is None:
                        value.model_attribute = name

                    view_model.fields.append(value)

        view_model.fields.sort()
        return view_model

class ViewModel(object):
    __metaclass__ = ViewModelBase

    def __init__(self, *args, **kwargs):
        object_literal = kwargs.pop('object_literal', None)
        model = kwargs.pop('model', None)

        if object_literal is not None:
            self.from_object_literal(object_literal)
        elif model is not None:
            self.from_model(model)

    def __eq__(self, other):

        for f in self.fields:
            if f.comparable:
                v1 = getattr(self, f.attribute_name, None)
                v2 = getattr(other, f.attribute_name, None)

                if v1 is not None and isinstance(v1, Field):
                    v1 = None
                if v2 is not None and isinstance(v2, Field):
                    v2 = None

                if v1 is None and v2 is None:
                    continue

                if v1 is None or v2 is None or v1 != v2:
                    logger.debug('Model not equal because %s != %s', v1, v2)
                    return False

        return True

    def __ne__(self, other):

        return not self.__eq__(other)

    def to_model(self, model):
        for f in self.fields:
            value = getattr(self, f.attribute_name)
            if f.consumable and f.modelizable and value and value is not None and not isinstance(value, Field):
                attribute_value = f.to_model_attribute(value)
                if attribute_value is not None:
                    setattr(model, f.model_attribute, attribute_value)
        return model

    def from_model(self, model):
        for f in self.fields:
            if f.produceable:
                value = f.from_model_attribute(model)
                if not isinstance(value, bool) and not isinstance(value, int) and not value:
                    value = None
                if isinstance(f, ViewModelField):
                    instance = f.view_model_type(model=value)
                    setattr(self, f.attribute_name, instance)
                else:
                    setattr(self, f.attribute_name, value)

        return self

    def from_object_literal(self, object_literal):
        if object_literal is not None:
            try:
                object_literal = object_literal[self.model_name]
            except KeyError:
                pass
            except TypeError:
                pass

            for f in self.fields:
                value = object_literal.get(f.dictionary_key)
                if not isinstance(f, ViewModelField):
                    setattr(self, f.attribute_name, f.from_object_literal(value))
                elif f.view_model_type is not None and value is not None:
                    instance = f.view_model_type()
                    instance.from_object_literal(value)
                    setattr(self, f.attribute_name, instance)
        return self

    def get_last_modified(self):
        if not self.last_modified or isinstance(self.last_modified, Field):
            return None
        return self.last_modified

    def to_object_literal(self, partial=False, child=False):
        dictionary = OrderedDict()

        for f in self.fields:
            value = getattr(self, f.attribute_name)
            if not isinstance(value, bool) and not isinstance(value, int) and not value:
                value = None
            elif isinstance(value, Field):
                value = None
            elif isinstance(value, str) and value == '':
                value = None

            if value is None:
                show_blank = not child and not f.blank
                if partial and f.extended:
                    show_blank = False
                if not f.produceable:
                    show_blank = False

                if show_blank:
                    if isinstance(f, BooleanField):
                        dictionary[f.dictionary_key] = False
                    elif isinstance(f, IntegerField):
                        dictionary[f.dictionary_key] = 0
                    else:
                        dictionary[f.dictionary_key] = None
            else:
                if isinstance(f, ViewModelField):
                    dictionary[f.dictionary_key] = value.to_object_literal(partial=partial, child=True)
                elif not child or not f.extended:
                    dictionary[f.dictionary_key] = f.to_object_literal(value)

        return dictionary

    def to_display_object_literal(self, partial=False):
        wrapper = OrderedDict()
        wrapper[self.model_name] = self.to_object_literal(partial=partial)
        return wrapper

    def validate(self):
        invalid_fields = {}
        for f in self.fields:
            f.validate(self, invalid_fields)

        return invalid_fields

class ListViewModel(object):

    def __init__(self, *args, **kwargs):
        object_literal = kwargs.pop('object_literal', None)
        models = kwargs.pop('models', None)
        total = kwargs.pop('total', None)
        query_params = kwargs.pop('query_params', None)
        self.view_models = list()
        if object_literal is not None:
            self.from_object_literal(object_literal)
        elif models is not None:
            self.from_models(models)
        self.total = total
        self.query_params = query_params

    def __eq__(self, other):

        for i in range(len(self.view_models)):
            m1 = self.view_models[i]
            if i < len(other.view_models):
                m2 = other.view_models[i]
            else:
                m2 = None

            if m1 != m2:
                return False

        return True

    def __ne__(self, other):

        return not self.__eq__(other)

    def add(self, view_model):
        self.view_models.append(view_model)

    def get_first_view_model(self):
        if not self.view_models or isinstance(self.view_models, Field) or len(self.view_models) <= 0:
            return None
        return self.view_models[0]

    def from_models(self, models):
        if models is not None:
            for model in models:
                view_model = self.view_model_type(model=model)
                self.view_models.append(view_model)

    def from_object_literal(self, object_literal):
        if object_literal is not None:
            try:
                object_literal = object_literal[self.model_name]
            except KeyError:
                object_literal = object_literal
            except TypeError:
                object_literal = object_literal

            for item in object_literal:
                view_model = self.view_model_type(object_literal=item)
                self.view_models.append(view_model)

        return self

    def to_object_literal(self, channel_model=None, partial=False, child=True):
        list_of_dictionaries = list()
        if self.view_models is not None:
            for view_model in self.view_models:
                if view_model is not None:
                    list_of_dictionaries.append(view_model.to_object_literal(partial=partial, child=child))

        return list_of_dictionaries;

    def to_display_object_literal(self, total=None, query_params=None, partial=False):
        wrapper = OrderedDict()
        wrapper[self.model_name] = self.to_object_literal(partial=partial)
        if query_params is not None:
            wrapper['QueryParams'] = query_params
        elif self.query_params is not None:
            wrapper['QueryParams'] = self.query_params
        if total is not None:
            wrapper['TotalCount'] = total
        elif self.total is not None:
            wrapper['TotalCount'] = self.total
        return wrapper

class DictionaryViewModel(ViewModel):

    def __init__(self):
        self.view_models = list()

    def __eq__(self, other):

        name_value_map = {}
        for view_model in self.view_models:
            name_value_map[view_model.name] = view_model.value

        for view_model in other.view_models:
            value = name_value_map[view_model.name]
            if value == view_model.value:
                del name_value_map[view_model.name]

        if len(name_value_map) > 0:
            return False

        return True

    def __ne__(self, other):

        return not self.__eq__(other)

    def add(self, view_model):
        self.view_models.append(view_model)

    def from_object_literal(self, object_literal):
        for k, v in object_literal.iteritems():
            self.add(ParameterDetailViewModel(k,v))
        return self

    def to_object_literal(self, partial=False, child=True):
        dictionary = OrderedDict()
        if self.view_models is not None:
            for view_model in self.view_models:
                dictionary[view_model.name] = view_model.value

        return dictionary

class Endpoint(ViewModel):

    model_name = 'Endpoint'
    view_name = 'endpoint-detail'

    endpoint_id = Field('EndpointID', 1, optional=True)
    endpoint_uri = UriField('EndpointURI', 2)
    endpoint_address = Field('EndpointAddress', 3)
    carrier = Field('Carrier', 4, optional=True)
    protocol = LowerCaseField('Protocol', 5)
    user = NetIdField('SubscriberID', 6, optional=True)
    owner = NetIdField('OwnerID', 7)
    status = Field('Status', 8, optional=True, comparable=False, consumable=False)
    active = BooleanField('Active', 9, consumable=False)
    created = ExtendedDateField('Created', 11)
    last_modified = LastModifiedDateField('LastModified', 12)
    modified_by = ExtendedField('ModifiedBy', 13)

    def get_endpoint_id(self):
        if not self.endpoint_id or isinstance(self.endpoint_id, Field):
            return None
        return self.endpoint_id

    def get_owner_net_id(self):
        if not self.owner or isinstance(self.owner, Field):
            return None
        return self.owner

    def get_user_net_id(self):
        if not self.user or isinstance(self.user, Field):
            return None
        return self.user

    def get_endpoint_address(self):
        if self.protocol is not None:
            if self.protocol.lower() == 'sms':
                regex1 = re.compile('^\+1\d{10}$')
                regex2 = re.compile('^\d{3}\-\d{3}-\d{4}$')
                regex3 = re.compile('^\(\d{3}\)\d{3}-\d{4}$')
                phone_number = smart_unicode(self.endpoint_address)

                if regex1.search(phone_number):
                    return phone_number

                if regex2.search(phone_number):
                    return "+1{0}{1}{2}".format(phone_number[0:3], phone_number[4:7], phone_number[8:12])

                if regex3.search(phone_number):
                    return "+1{0}{1}{2}".format(phone_number[1:4], phone_number[5:8], phone_number[9:13])

        return self.endpoint_address

    def validate(self):
        invalid_fields = ViewModel.validate(self)

        if self.protocol is not None:
            if self.protocol.lower() == 'email':
                try:
                    validate_email(self.endpoint_address)
                except ValidationError:
                    invalid_fields['EndpointAddress'] = 'Invalid format for an email address'
            elif self.protocol.lower() == 'sms':
                regex1 = re.compile('^\+1\d{10}$')
                regex2 = re.compile('^\d{3}\-\d{3}-\d{4}$')
                regex3 = re.compile('^\(\d{3}\)\d{3}-\d{4}$')
                phone_number = smart_unicode(self.endpoint_address)
                if not regex1.search(phone_number) and not regex2.search(phone_number) and not regex3.search(phone_number):
                    invalid_fields['EndpointAddress'] = 'Invalid format for a phone number; should be one or these: +###########, ###-###-####, or (###)###-####'

        return invalid_fields

class EndpointList(ListViewModel):

    model_name = 'Endpoints'
    view_model_type = Endpoint

class Job(ViewModel):

    model_name = 'Job'
    view_name = 'job-detail'

    job_id = Field('JobID', 1, optional=True)
    job_uri = UriField('JobURI', 2)
    job_type = LowerCaseField('JobType', 3)
    execution_type = LowerCaseField('ExecutionType', 4, optional=True)
    created = ExtendedDateField('Created', 11)
    last_modified = LastModifiedDateField('LastModified', 12)
    modified_by = ExtendedField('ModifiedBy', 13)

class JobList(ListViewModel):

    model_name = 'Jobs'
    view_model_type = Job

class ParameterDetailViewModel(ViewModel):

    name = Field('Name', 1)
    value = Field('Value', 2)

    def __init__(self, name=None, value=None):
        super(ParameterDetailViewModel, self).__init__(self, object_literal=None, model=None)
        self.name = name
        self.value = value

    def __eq__(self, other):

        if self.name == other.name and self.value == other.value:
            return True
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def to_object_literal(self):
        dictionary = OrderedDict()
        k = getattr(self, 'name')
        v = getattr(self, 'value')
        if k and v and not isinstance(k, Field) and not isinstance(v, Field):
            dictionary[k] = v

        return dictionary

class Channel(ViewModel):

    model_name = 'Channel'
    view_name = 'channel-detail'

    channel_id = Field('ChannelID', 1, optional=True)
    channel_uri = UriField('ChannelURI', 2)
    surrogate_id = Field('SurrogateID', 3)
    type = Field('Type', 4, model_attribute='channel_type')
    name = Field('Name', 5)
    tags = ViewModelField('Tags', 6, view_model_type=DictionaryViewModel, produceable=False)
    description = Field('Description', 8, optional=True)
    expires = DateField('Expires', 10, optional=True, comparable=False)
    created = ExtendedDateField('Created', 11)
    last_modified = LastModifiedDateField('LastModified', 12)
    modified_by = ExtendedField('ModifiedBy', 13)

    def get_channel_id(self):
        if not self.channel_id or isinstance(self.channel_id, Field):
            return None
        return self.channel_id

    def add_tag(self, name, value):
        if not self.tags or isinstance(self.tags, ViewModelField):
            self.tags = DictionaryViewModel()
        tag = ParameterDetailViewModel(name, value)
        self.tags.add(tag)
        return tag

    def get_tags(self):
        if not self.tags or isinstance(self.tags, ViewModelField):
            return None
        return self.tags.view_models

class ChannelList(ListViewModel):

    model_name = 'Channels'
    view_model_type = Channel

class Subscription(ViewModel):

    model_name = 'Subscription'
    view_name = 'subscription-detail'

    subscription_id = Field('SubscriptionID', 1, optional=True)
    subscription_uri = UriField('SubscriptionURI', 2)
    subscription_type = Field('SubscriptionType', 3, optional=True, blank=True)
    channel = ViewModelField('Channel', 4, view_model_type=Channel)
    endpoint = ViewModelField('Endpoint', 5, view_model_type=Endpoint)
    created = ExtendedDateField('Created', 11)
    last_modified = LastModifiedDateField('LastModified', 12)
    modified_by = ExtendedField('ModifiedBy', 13)

    def get_subscription_id(self):
        if not self.subscription_id or isinstance(self.subscription_id, Field):
            return None
        return self.subscription_id

    def get_channel(self):
        if not self.channel or isinstance(self.channel, ViewModelField):
            return None
        return self.channel

    def get_endpoint(self):
        if not self.endpoint or isinstance(self.endpoint, ViewModelField):
            return None
        return self.endpoint

class SubscriptionList(ListViewModel):

    model_name = 'Subscriptions'
    view_model_type = Subscription

class Receipt(ViewModel):

    model_name = 'Receipt'
    view_name = 'receipt-detail'

    receipt_id = Field('ReceiptID', 1, optional=True)
    #receipt_uri = UriField('ReceiptURI', 2)
    surrogate_id = Field('SurrogateID', 2)
    status = Field('Status', 3)
    dispatched_on = DateField('DispatchedOn', 4, consumable=False, comparable=False)
    dispatched_by = Field('DispatchedBy', 5, consumable=False, comparable=False)
    dispatch_status = Field('DispatchStatus', 6)
    retries = IntegerField('NumberOfRetries', 7)
    endpoint = ViewModelField('Endpoint', 8, view_model_type=Endpoint, optional=True)
    created = ExtendedDateField('Created', 9)
    last_modified = LastModifiedDateField('LastModified', 10)
    modified_by = ExtendedField('ModifiedBy', 11)

    def get_endpoint(self):
        if not self.endpoint or isinstance(self.endpoint, ViewModelField):
            return None
        return self.endpoint

class ReceiptList(ListViewModel):

    model_name = 'Receipts'
    view_model_type = Receipt

    def to_object_literal(self, channel_model=None, partial=False, child=True):
        list_of_dictionaries = list()
        if self.view_models is not None:
            for view_model in self.view_models:
                if view_model is not None:
                    list_of_dictionaries.append(view_model.to_object_literal(partial=partial, child=False))

        return list_of_dictionaries;

class MessageType(ViewModel):

    model_name = 'MessageType'
    view_name = 'message-type-detail'

    message_type_id = Field('MessageTypeID', 1, optional=True)
    message_type_uri = UriField('MessageTypeURI', 2)
    surrogate_id = Field('SurrogateID', 3)
    content_type = Field('ContentType', 4)
    destination_id = Field('DestinationID', 5)
    destination_type = Field('DestinationType', 6)
    sender = Field('From', 7)
    to = Field('To', 8)
    subject = Field('Subject', 9)
    body = Field('Body', 10)
    short = Field('Short', 11)
    created = ExtendedDateField('Created', 12)
    last_modified = LastModifiedDateField('LastModified', 13)
    modified_by = ExtendedField('ModifiedBy', 14)

class MessageTypeList(ListViewModel):

    model_name = 'MessageTypes'
    view_model_type = MessageType

class Message(ViewModel):

    model_name = 'Message'
    view_name = 'message-detail'

    message_id = Field('MessageID', 1, optional=True)
    message_uri = UriField('MessageURI', 2)
    message_type = MessageTypeField('MessageType', 3)
    direction = LowerCaseField('Direction', 4)
    subject = Field('Subject', 5)
    body = Field('Body', 6)
    short = Field('Short', 7)
    receipts = ViewModelField('Receipts', 8, view_model_type=ReceiptList, optional=True, produceable=False)
    created = ExtendedDateField('Created', 9)
    last_modified = LastModifiedDateField('LastModified', 10)
    modified_by = ExtendedField('ModifiedBy', 11)

    def get_message_id(self):
        if not self.message_id or isinstance(self.message_id, Field):
            return None
        return self.message_id

    def add_receipt(self, receipt_view_model):
        if not self.receipts or isinstance(self.receipts, ViewModelField):
            self.receipts = ReceiptList()
        self.receipts.add(receipt_view_model)
        return self.receipts

class MessageList(ListViewModel):

    model_name = 'Messages'
    view_model_type = Message

class Dispatch(ViewModel):

    model_name = 'Dispatch'
    view_name = 'dispatch-detail'

    dispatch_id = Field('DispatchID', 1, optional=True)
    dispatch_uri = UriField('DispatchURI', 2)
    message_type = MessageTypeField('MessageType', 3, modelizable=False, produceable=False)
    message = ViewModelField('Message', 4, view_model_type=Message)
    content = Field('Content', 5, comparable=False)
    directive = LowerCaseField('Directive', 6, optional=True)
    recipients = IntegerField('NumberOfRecipients', 7, consumable=False)
    locked = BooleanField('Locked', 8, optional=True, modelizable=False)
    lock_id = Field('LockID', 9, optional=True, produceable=False)
    locked_on = Field('LockedOn', 10, optional=True, produceable=False)
    locked_by = Field('LockedBy', 11, optional=True, produceable=False)
    last_modified = LastModifiedDateField('LastModified', 11)

    def get_content(self):
        if not self.content or isinstance(self.content, Field):
            return None
        return self.content

    def get_message(self):
        if not self.message or isinstance(self.message, ViewModelField):
            return None
        return self.message

    def get_message_type(self):
        if not self.message_type or isinstance(self.message_type, MessageTypeField):
            return None
        return self.message_type

class DispatchList(ListViewModel):

    model_name = 'Dispatches'
    view_model_type = Dispatch

class Person(ViewModel):

    model_name = 'Person'
    view_name = 'person-detail'

    person_id = Field('PersonID', 1, optional=True)
    person_uri = UriField('PersonURI', 2)
    surrogate_id = Field('SurrogateID', 3)
    attributes = ViewModelField('Attributes', 6, view_model_type=DictionaryViewModel, produceable=False)
    default_endpoint = ViewModelField('DefaultEndpoint', 8, view_model_type=Endpoint, produceable=False)
    endpoints = ViewModelField('Endpoints', 9, view_model_type=EndpointList, produceable=False)
    created = ExtendedDateField('Created', 10)
    last_modified = LastModifiedDateField('LastModified', 11)
    modified_by = ExtendedField('ModifiedBy', 12)

    def add_attribute(self, name, *options):
        if len(options) > 1:
            logger.debug("just use add_attribute(name, value) for attribute %s" % name)
        value = None
        for option in options:
            if option is not None:
                value = option

        if not self.attributes or isinstance(self.attributes, ViewModelField):
            self.attributes = DictionaryViewModel()

        attribute = ParameterDetailViewModel(name, value)
        self.attributes.add(attribute)
        return attribute

    def get_attributes(self):
        if not self.attributes or isinstance(self.attributes, ViewModelField):
            return None
        return self.attributes.view_models

    def get_endpoints(self):
        if not self.endpoints or isinstance(self.endpoints, ViewModelField):
            return None
        return self.endpoints.view_models

    def get_default_endpoint(self):
        if not self.default_endpoint or isinstance(self.default_endpoint, ViewModelField):
            return None
        return self.default_endpoint

    def validate(self):
        invalid_fields = ViewModel.validate(self)

        if self.surrogate_id is not None:
            try:
                validate_email(self.surrogate_id)
            except ValidationError:
                invalid_fields['SurrogateID'] = 'Invalid format for an eduPersonPrincipalName (EPPN)'

        return invalid_fields

class PersonList(ListViewModel):

    model_name = 'People'
    view_model_type = Person

class MessageSummary(ViewModel):

    message_uri = UriField('MessageDetailURI', 1)
    direction = Field('Direction', 2)
    protocol = Field('Protocol', 3)
    content = Field('Content', 6)

class MessageSummaryList(ListViewModel):

    model_name = 'MessageSummaries'
    view_model_type = MessageSummary

class Activity(ViewModel):

    activity_detail_uri = UriField('ActivityDetailURI', 4)
    activity_type = Field('Type', 3)
    description = Field('Description', 4)
    value = Field('Value', 5)
    activity_date = Field('ActivityDate', 6)

class ActivityList(ListViewModel):

    model_name = 'Activities'
    view_model_type = Activity

class Status(ViewModel):

    model_name = 'Status'
    view_name = 'status-detail'

    last_success_delay = Field('SecondsToDispatchLastSuccessfulHeartbeat', 1)
    last_success_since = Field('SecondsSinceLastSuccessfulHeartbeat', 2)

    last_heartbeat_since = Field('SecondsSinceLastHeartbeat', 3)
    last_heartbeat_status = Field('LastHeartbeatStatus', 4)

    number_of_locks = Field('NumberOfLocks', 5)
    last_job = Field('SecondsSinceLastJob', 6)
    last_message = Field('SecondsSinceLastMessage', 7)
    dispatch_queue_size = Field('SizeOfDispatchQueue', 8)

class Serializer(object):

    def deserialize(self, view_model, data, force_consume=True):
        object_literal = json.loads(data, object_pairs_hook=OrderedDict)
        view_model.from_object_literal(object_literal)
        return view_model

    def serialize(self, view_model, partial=False):
        return json.dumps(view_model.to_display_object_literal(partial=partial), indent='\t')


text:
'use strict';

angular.module('cmaManagementApp').controller('vendorInfoEditController',
    function(constantLoader, vendorBusiness, commonUtility, generalUtility){

        var vm = this;
        vm.vendorInfo = {};
        vm.countryList = [];

        function initialized(){
            loadCountries();
            loadVendorDetails();
        }

        function loadCountries(){
            generalUtility.loadCountries().then(function(response){
                if(response.data.success){
                    vm.countryList = commonUtility.getCustomSortedList(response.data.result,
                        constantLoader.defaultValues.COUNTRY_ENDED_LIST,
                        constantLoader.defaultValues.COUNTRY_SEARCH_FIELD,
                        constantLoader.defaultValues.COUNTRY_SORT_FIELD);
                } else{
                    commonUtility.showAlert(response.data.statusText);
                }
            }, function(error){
                commonUtility.showAlert(error.data.statusText);
            });
        }

        function loadVendorDetails(){
            vendorBusiness.loadVendorInfo(commonUtility.getRootScopeProperty(
                constantLoader.rootScopeTypes.ID)).then(function(response){
                if(response.data.success){
                    vm.vendorInfo = response.data.result;
                }else{
                    commonUtility.showAlert(response.data.statusText);
                    commonUtility.redirectTo(constantLoader.routeTypes.VENDOR_PROFILE);
                }
            }, function(error){
                commonUtility.showAlert(error.data.statusText);
                commonUtility.redirectTo(constantLoader.routeTypes.VENDOR_PROFILE);
            });
        }

        vm.onSaveClick = function(frmData){
            if(!frmData.vendorInfoForm.$valid){
                return false;
            }
            var vendor = {};
            vendor.vendId = commonUtility.getRootScopeProperty(
                constantLoader.rootScopeTypes.ID);
            vendor.name = vm.vendorInfo.name;
            vendor.pin = vm.vendorInfo.pin;
            vendor.description = vm.vendorInfo.description;
            vendor.address = vm.vendorInfo.address;
            vendor.country = vm.vendorInfo.country;
            vendor.state = vm.vendorInfo.state;
            vendor.city = vm.vendorInfo.city;

            vendorBusiness.updateVendorDetails(vendor).then(function(response){
                if(response.data.success){
                    commonUtility.setRootScopeProperty(
                        constantLoader.rootScopeTypes.NAME, vendor.name);
                    commonUtility.showAlert(response.data.statusText,
                        constantLoader.alertTypes.SUCCESS);
                    commonUtility.redirectTo(constantLoader.routeTypes.VENDOR_PROFILE);
                } else{
                    commonUtility.showAlert(response.data.statusText);
                }
            }, function(error){
                commonUtility.showAlert(error.data.statusText);
            });
        };

        vm.onCancelClick = function(){
            commonUtility.redirectTo(constantLoader.routeTypes.VENDOR_PROFILE);
        };

        initialized();
    }
);


text:
/* font style defaults */
body {
	color: maroon;
	font-family: "Verdana", sans-serif;

}

/* styling for level-select page */
.level-icons img {
	border: 2px solid maroon;
	padding: 20px;
	margin: 1cm;
	background-color: #CCFFFF;
}

/* styling for accordions */
#accordion-head {
	background-color: #CCFF99;
	border-color: #228B22;
	border-width: 2px;
}

#accordion-body {
	background-color: #FFFFCC;
	border: none;
	border-color: #228B22;
	border-width: 2px;
}

#accordion2-head {
	background-color: #FFCC99;
	border: none;
	border-color: #B22222;
	border-width: 2px;
}

#accordion2-body {
	background-color: #FFCCCC;
	border: none;
	border-color: #B22222;
	border-width: 2px;
}

.panel-title {
	font-family: "Chalkboard", cursive;
	font-size: 18pt;
	font-weight: bold;
	font-color: #228B22;
}

a.paragraph-link:link {
	font-family: "Chalkboard", cursive;
	font-size: 12pt;
	text-decoration: none;
	color: black;
}

a.paragraph-link .visited {
	font-family: "Chalkboard", cursive;
	font-size: 12pt;
	text-decoration: none;
	color: orange;
}

a.paragraph-link:hover {
	font-size: 14pt;
	color: #B22222;
}

/* styling for modal window */
.modal-header {
	background-color: #CCCCFF;
	border-style:solid;
	border-bottom-width:4px;
	border-color: white;
	padding: none;
}

.modal-footer {
	background-color: #CCCCFF;
	border-style:solid;
	border-color: white;
}

.modal-body {
	background-color: #CCFFFF;
	border-style:solid;
	border-color: white;
}

.modal-bannerpic {
	border: 1px solid purple;
	margin: 0px;
	padding: none;
}

@media screen and (min-width: 768px) {
    .custom-class {
        width: 80%; /* either % (e.g. 60%) or px (400px) */
    }
}

#readback-text {
	font-family: "Chalkboard", cursive;
	font-size: 28pt;
	color: #660000;
	border: none;
	padding: none;
}


text:
Mortroid::Mortroid()
{
	health = 120;
	damage = 80;
	hostile = true;
	name = "Mortroid";
	description = " Mortroids are humanoid swarm robots. Stealthier cousins of Dreadbots who sacrifices firepower for mobility and ability resist hacking. ";
}

Mortroid::~Mortroid()
{
}


text:
using System;

public class TypeGetArrayRank
{
    #region Private Variables
    private const int c_DEFAULT_ARRAY_DIMENSION = 2;
    #endregion

    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;
        retVal = PosTest3() && retVal;

        TestLibrary.TestFramework.LogInformation("[Negative]");
        retVal = NegTest1() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    public bool PosTest1()
    {
        bool retVal = true;
        int size = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Get rank of an one dimension array");

        try
        {
            // Do not make a large array
            size = TestLibrary.Generator.GetByte(-55);

            int[] array = new int[size];
            for (int i = 0; i < size; ++i)
            {
                array[i] = TestLibrary.Generator.GetInt32(-55);
            }

            Type type = array.GetType();
            int rank = type.GetArrayRank();
            if (rank != 1)
            {
                TestLibrary.TestFramework.LogError("001", "Get rank of an one dimension array returns " + rank.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e + "; with size = " + size);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest2()
    {
        bool retVal = true;
        int size = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Get rank of an multiple dimensions array");

        try
        {
            // Do not make a large array
            size = TestLibrary.Generator.GetByte(-55);

            int[,] array = new int[c_DEFAULT_ARRAY_DIMENSION, size];
            for (int i = 0; i < c_DEFAULT_ARRAY_DIMENSION; ++i)
            {
                for (int j = 0; j < size; ++j)
                {
                    array[i, j] = TestLibrary.Generator.GetInt32(-55);
                }
            }

            Type type = array.GetType();
            int rank = type.GetArrayRank();
            if (rank != c_DEFAULT_ARRAY_DIMENSION)
            {
                TestLibrary.TestFramework.LogError("003", "Get rank of an multiple dimensions array returns " + rank.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e + "; with size = " + size);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest3()
    {
        bool retVal = true;
        int size = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Get rank of an multiple dimensions jagged array");

        try
        {
            // Do not make a large array
            size = TestLibrary.Generator.GetByte(-55);

            int[][] array = new int[size][];

            for (int i = 0; i < size; ++i)
            {
                int subArrayLength = TestLibrary.Generator.GetByte(-55);
                int[] subArray = new int[subArrayLength];

                for (int j = 0; j < subArrayLength; ++j)
                {
                    subArray[j] = TestLibrary.Generator.GetInt32(-55);
                }

                array[i] = subArray;
            }

            Type type = array.GetType();
            int rank = type.GetArrayRank();
            if (rank != 1)
            {
                TestLibrary.TestFramework.LogError("005", "Get rank of an multiple dimensions jagged array returns " + rank.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion

    #region Nagetive Test Cases
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: Check ArgumentException will be thrown");

        try
        {
            Type t1 = typeof(Exception);

            int returnObject = t1.GetArrayRank();
            TestLibrary.TestFramework.LogError("101", "ArgumentException is not thrown when calling typeof(Exception).GetArrayRank()");
            retVal = false;
        }
        catch (ArgumentException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion
    #endregion

    public static int Main()
    {
        TypeGetArrayRank test = new TypeGetArrayRank();

        TestLibrary.TestFramework.BeginTestCase("TypeGetArrayRank");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
}


text:
package org.yy.studymybatis.util;

import org.apache.ibatis.session.SqlSession;

public  interface SessionAction<Tr>{
	public Tr execute(SqlSession session);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Parsley, the ultimate frontend javascript form validation library">
    <meta name="author" content="Guillaume Potier">

    <title>Parsley - Download the pieces</title>

    <link href="../bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet">

    <link href="assets/docs.css" rel="stylesheet">

Parsley

            Tweet

Home

Examples

Documentation

Download

Help

Annotated source

Tests

Download Parsley v2.0.0

Whole project..

$ bower install -S parsleyjs

$ npm install --save parsleyjs

parsley.zip 250ko

..or pick & go!

parsley.js 17kb gz

parsley.min.js 6.6kb gz

parsley.remote.js 2.4kb gz

parsley.remote.js 18.9kb gz

parsley.remote.min.js 7ko gz

© Guillaume Potier 2014 - @Wisembly


text:
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 1998-2009 The OpenLDAP Foundation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */
/* Portions Copyright (c) 1990 Regents of the University of Michigan.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that this notice is preserved and that due credit is given
 * to the University of Michigan at Ann Arbor. The name of the University
 * may not be used to endorse or promote products derived from this
 * software without specific prior written permission. This software
 * is provided ``as is'' without express or implied warranty.
 */

#ifndef _LBER_INT_H
#define _LBER_INT_H

#include "lber.h"
#include "ldap_log.h"
#include "lber_pvt.h"
#include "ldap_queue.h"

LDAP_BEGIN_DECL

typedef void (*BER_LOG_FN)(FILE *file,
	const char *subsys, int level, const char *fmt, ... );

LBER_V (BER_ERRNO_FN) ber_int_errno_fn;

#ifdef LDAP_MEMORY_TRACE
# ifndef LDAP_MEMORY_DEBUG
#  define LDAP_MEMORY_DEBUG 1
# endif
#endif

#ifdef LDAP_MEMORY_DEBUG
LBER_V (long)	ber_int_meminuse;
#endif
#if defined(LDAP_MEMORY_DEBUG) && ((LDAP_MEMORY_DEBUG +0) & 2)
# define LDAP_MEMORY_DEBUG_ASSERT assert
#else
# define LDAP_MEMORY_DEBUG_ASSERT(expr) ((void) 0)
#endif

struct lber_options {
	short lbo_valid;
	unsigned short		lbo_options;
	int			lbo_debug;
};

LBER_F( int ) ber_pvt_log_output(
	const char *subsystem,
	int level,
	const char *fmt, ... );

#define LBER_UNINITIALIZED		0x0
#define LBER_INITIALIZED		0x1
#define LBER_VALID_BERELEMENT	0x2
#define LBER_VALID_SOCKBUF		0x3

LBER_V (struct lber_options) ber_int_options;
#define ber_int_debug ber_int_options.lbo_debug

struct berelement {
	struct		lber_options ber_opts;
#define ber_valid		ber_opts.lbo_valid
#define ber_options		ber_opts.lbo_options
#define ber_debug		ber_opts.lbo_debug

	/* Do not change the order of these 3 fields! see ber_get_next */
	ber_tag_t	ber_tag;
	ber_len_t	ber_len;
	ber_tag_t	ber_usertag;

	char		*ber_buf;
	char		*ber_ptr;
	char		*ber_end;

	struct seqorset	*ber_sos;
	char		*ber_rwptr;
	void		*ber_memctx;
};
#define LBER_VALID(ber)	((ber)->ber_valid==LBER_VALID_BERELEMENT)

#define ber_pvt_ber_remaining(ber)	((ber)->ber_end - (ber)->ber_ptr)
#define ber_pvt_ber_total(ber)		((ber)->ber_end - (ber)->ber_buf)
#define ber_pvt_ber_write(ber)		((ber)->ber_ptr - (ber)->ber_buf)

struct sockbuf {
	struct lber_options sb_opts;
	Sockbuf_IO_Desc		*sb_iod;		/* I/O functions */
#define	sb_valid		sb_opts.lbo_valid
#define	sb_options		sb_opts.lbo_options
#define	sb_debug		sb_opts.lbo_debug
	ber_socket_t		sb_fd;
	ber_len_t			sb_max_incoming;
   	unsigned int		sb_trans_needs_read:1;
   	unsigned int		sb_trans_needs_write:1;
#ifdef LDAP_PF_LOCAL_SENDMSG
	char				sb_ungetlen;
	char				sb_ungetbuf[8];
#endif
};

#define SOCKBUF_VALID( sb )	( (sb)->sb_valid == LBER_VALID_SOCKBUF )

struct seqorset {
	BerElement	*sos_ber;
	ber_len_t	sos_clen;
	ber_tag_t	sos_tag;
	char		*sos_first;
	char		*sos_ptr;
	struct seqorset	*sos_next;
};

/*
 * decode.c, encode.c
 */

/* Simplest OID max-DER-component to implement in both decode and encode */
#define LBER_OID_COMPONENT_MAX ((unsigned long)-1 - 128)

/*
 * io.c
 */
LBER_F( int )
ber_realloc LDAP_P((
	BerElement *ber,
	ber_len_t len ));

LBER_F (char *) ber_start LDAP_P(( BerElement * ));
LBER_F (int) ber_len LDAP_P(( BerElement * ));
LBER_F (int) ber_ptrlen LDAP_P(( BerElement * ));
LBER_F (void) ber_rewind LDAP_P(( BerElement * ));

/*
 * bprint.c
 */
#define ber_log_printf ber_pvt_log_printf

LBER_F( int )
ber_log_bprint LDAP_P((
	int errlvl,
	int loglvl,
	const char *data,
	ber_len_t len ));

LBER_F( int )
ber_log_dump LDAP_P((
	int errlvl,
	int loglvl,
	BerElement *ber,
	int inout ));

LBER_F( int )
ber_log_sos_dump LDAP_P((
	int errlvl,
	int loglvl,
	Seqorset *sos ));

LBER_V (BER_LOG_FN) ber_int_log_proc;
LBER_V (FILE *) ber_pvt_err_file;

/* memory.c */
	/* simple macros to realloc for now */
LBER_V (BerMemoryFunctions *)	ber_int_memory_fns;
LBER_F (char *)	ber_strndup( LDAP_CONST char *, ber_len_t );
LBER_F (char *)	ber_strndup_x( LDAP_CONST char *, ber_len_t, void *ctx );

#define LBER_MALLOC(s)		ber_memalloc((s))
#define LBER_CALLOC(n,s)	ber_memcalloc((n),(s))
#define LBER_REALLOC(p,s)	ber_memrealloc((p),(s))
#define LBER_FREE(p)		ber_memfree((p))
#define LBER_VFREE(v)		ber_memvfree((void**)(v))
#define LBER_STRDUP(s)		ber_strdup((s))
#define LBER_STRNDUP(s,l)	ber_strndup((s),(l))

/* sockbuf.c */

LBER_F(	int )
ber_int_sb_init LDAP_P(( Sockbuf *sb ));

LBER_F( int )
ber_int_sb_close LDAP_P(( Sockbuf *sb ));

LBER_F(	int )
ber_int_sb_destroy LDAP_P(( Sockbuf *sb ));

LBER_F( ber_slen_t )
ber_int_sb_read LDAP_P(( Sockbuf *sb, void *buf, ber_len_t len ));

LBER_F( ber_slen_t )
ber_int_sb_write LDAP_P(( Sockbuf *sb, void *buf, ber_len_t len ));

LDAP_END_DECL

#endif /* _LBER_INT_H */


text:
namespace parquet {
namespace encryption {
namespace internal {

// Acceptable key lengths in number of bits, used to validate the data key lengths
// configured by users and the master key lengths fetched from KMS server.
static constexpr const int32_t kAcceptableDataKeyLengths[] = {128, 192, 256};

std::string EncryptKeyLocally(const std::string& key_bytes, const std::string& master_key,
                              const std::string& aad) {
  AesEncryptor key_encryptor(ParquetCipher::AES_GCM_V1,
                             static_cast<int>(master_key.size()), false);

  int encrypted_key_len =
      static_cast<int>(key_bytes.size()) + key_encryptor.CiphertextSizeDelta();
  std::string encrypted_key(encrypted_key_len, '\0');
  encrypted_key_len = key_encryptor.Encrypt(
      reinterpret_cast<const uint8_t*>(key_bytes.data()),
      static_cast<int>(key_bytes.size()),
      reinterpret_cast<const uint8_t*>(master_key.data()),
      static_cast<int>(master_key.size()), reinterpret_cast<const uint8_t*>(aad.data()),
      static_cast<int>(aad.size()), reinterpret_cast<uint8_t*>(&encrypted_key[0]));

  return ::arrow::util::base64_encode(
      ::arrow::util::string_view(encrypted_key.data(), encrypted_key_len));
}

std::string DecryptKeyLocally(const std::string& encoded_encrypted_key,
                              const std::string& master_key, const std::string& aad) {
  std::string encrypted_key = ::arrow::util::base64_decode(encoded_encrypted_key);

  AesDecryptor key_decryptor(ParquetCipher::AES_GCM_V1,
                             static_cast<int>(master_key.size()), false);

  int decrypted_key_len =
      static_cast<int>(encrypted_key.size()) - key_decryptor.CiphertextSizeDelta();
  std::string decrypted_key(decrypted_key_len, '\0');

  decrypted_key_len = key_decryptor.Decrypt(
      reinterpret_cast<const uint8_t*>(encrypted_key.data()),
      static_cast<int>(encrypted_key.size()),
      reinterpret_cast<const uint8_t*>(master_key.data()),
      static_cast<int>(master_key.size()), reinterpret_cast<const uint8_t*>(aad.data()),
      static_cast<int>(aad.size()), reinterpret_cast<uint8_t*>(&decrypted_key[0]));

  return decrypted_key;
}

bool ValidateKeyLength(int32_t key_length_bits) {
  int32_t* found_key_length = std::find(
      const_cast<int32_t*>(kAcceptableDataKeyLengths),
      const_cast<int32_t*>(std::end(kAcceptableDataKeyLengths)), key_length_bits);
  return found_key_length != std::end(kAcceptableDataKeyLengths);
}

}  // namespace internal
}  // namespace encryption
}  // namespace parquet


text:
<?php

namespace Migrations\Shell\Task;

use Cake\Core\App;
use Cake\Core\Plugin;
use Cake\Database\Schema\Collection;
use Cake\Datasource\ConnectionManager;
use Cake\Filesystem\Folder;
use Cake\ORM\TableRegistry;
use ReflectionClass;

/**
 * Trait needed for all "snapshot" type of bake operations.
 * Snapshot type operations are : baking a snapshot and baking a diff.
 */
trait SnapshotTrait
{

    /**
     * Tables to skip
     *
     * @var array
     */
    public $skipTables = ['phinxlog'];

    /**
     * Regex of Table name to skip
     *
     * @var string
     */
    public $skipTablesRegex = '_phinxlog';

    /**
     * After a file has been successfully created, we mark the newly
     * created migration as applied
     *
     * @param string $path Where to put the file.
     * @param string $contents Content to put in the file.
     * @return bool Success
     */
    public function createFile($path, $contents)
    {
        $createFile = parent::createFile($path, $contents);

        if ($createFile) {
            $this->markSnapshotApplied($path);

            if (!isset($this->params['no-lock']) || !$this->params['no-lock']) {
                $this->refreshDump();
            }
        }

        return $createFile;
    }

    /**
     * Will mark a snapshot created, the snapshot being identified by its
     * full file path.
     *
     * @param string $path Path to the newly created snapshot
     * @return void
     */
    protected function markSnapshotApplied($path)
    {
        $fileName = pathinfo($path, PATHINFO_FILENAME);
        list($version, ) = explode('_', $fileName, 2);

        $dispatchCommand = 'migrations mark_migrated -t ' . $version . ' -o';
        if (!empty($this->params['connection'])) {
            $dispatchCommand .= ' -c ' . $this->params['connection'];
        }

        if (!empty($this->params['plugin'])) {
            $dispatchCommand .= ' -p ' . $this->params['plugin'];
        }

        $this->_io->out('Marking the migration ' . $fileName . ' as migrated...');
        $this->dispatchShell($dispatchCommand);
    }

    /**
     * After a file has been successfully created, we refresh the dump of the database
     * to be able to generate a new diff afterward.
     *
     * @return void
     */
    protected function refreshDump()
    {
        $dispatchCommand = 'migrations dump';
        if (!empty($this->params['connection'])) {
            $dispatchCommand .= ' -c ' . $this->params['connection'];
        }

        if (!empty($this->params['plugin'])) {
            $dispatchCommand .= ' -p ' . $this->params['plugin'];
        }

        $this->_io->out('Creating a dump of the new database state...');
        $this->dispatchShell($dispatchCommand);
    }

    /**
     * Gets a list of table to baked based on the Collection instance passed and the options passed to
     * the shell call.
     *
     * @param \Cake\Database\Schema\Collection $collection Instance of the collection of a specific database
     * connection.
     * @param array $options Array of options passed to a shell call.
     * @return array
     */
    protected function getTablesToBake(Collection $collection, $options = [])
    {
        $options = array_merge(['require-table' => false, 'plugin' => null], $options);
        $tables = $collection->listTables();

        if (empty($tables)) {
            return $tables;
        }

        if ($options['require-table'] === true || $options['plugin']) {
            $tableNamesInModel = $this->getTableNames($options['plugin']);

            if (empty($tableNamesInModel)) {
                return [];
            }

            foreach ($tableNamesInModel as $num => $table) {
                if (strpos($table, '.') !== false) {
                    $splitted = array_reverse(explode('.', $table, 2));

                    $config = ConnectionManager::config($this->connection);
                    $key = isset($config['schema']) ? 'schema' : 'database';
                    if ($config[$key] === $splitted[1]) {
                        $table = $splitted[0];
                    }
                }

                if (!in_array($table, $tables)) {
                    unset($tableNamesInModel[$num]);
                }
            }
            $tables = $tableNamesInModel;
        } else {
            foreach ($tables as $num => $table) {
                if ((in_array($table, $this->skipTables)) || (strpos($table, $this->skipTablesRegex) !== false)) {
                    unset($tables[$num]);
                    continue;
                }
            }
        }

        return $tables;
    }

    /**
     * Gets list Tables Names
     *
     * @param string|null $pluginName Plugin name if exists.
     * @return array
     */
    protected function getTableNames($pluginName = null)
    {
        if ($pluginName !== null && !Plugin::loaded($pluginName)) {
            return [];
        }
        $list = [];
        $tables = $this->findTables($pluginName);

        if (empty($tables)) {
            return [];
        }

        foreach ($tables as $num => $table) {
            $list = array_merge($list, $this->fetchTableName($table, $pluginName));
        }

        return array_unique($list);
    }

    /**
     * Find Table Class
     *
     * @param string $pluginName Plugin name if exists.
     * @return array
     */
    protected function findTables($pluginName = null)
    {
        $path = 'Model' . DS . 'Table' . DS;
        if ($pluginName) {
            $path = Plugin::path($pluginName) . 'src' . DS . $path;
        } else {
            $path = APP . $path;
        }

        if (!is_dir($path)) {
            return false;
        }

        $tableDir = new Folder($path);
        $tableDir = $tableDir->find('.*\.php');
        return $tableDir;
    }

    /**
     * fetch TableName From Table Object
     *
     * @param string $className Name of Table Class.
     * @param string|null $pluginName Plugin name if exists.
     * @return array
     */
    protected function fetchTableName($className, $pluginName = null)
    {
        $tables = [];
        $className = str_replace('Table.php', '', $className);
        if ($pluginName !== null) {
            $className = $pluginName . '.' . $className;
        }

        $namespacedClassName = App::className($className, 'Model/Table', 'Table');

        if (!class_exists($namespacedClassName)) {
            return $tables;
        }

        $reflection = new ReflectionClass($namespacedClassName);
        if (!$reflection->isInstantiable()) {
            return $tables;
        }

        $table = TableRegistry::get($className);
        foreach ($table->associations()->keys() as $key) {
            if ($table->associations()->get($key)->type() === 'belongsToMany') {
                $tables[] = $table->associations()->get($key)->junction()->table();
            }
        }
        $tableName = $table->table();
        $splitted = array_reverse(explode('.', $tableName, 2));
        if (isset($splitted[1])) {
            $config = ConnectionManager::config($this->connection);
            $key = isset($config['schema']) ? 'schema' : 'database';
            if ($config[$key] === $splitted[1]) {
                $tableName = $splitted[0];
            }
        }
        $tables[] = $tableName;

        return $tables;
    }
}


text:
title: Community Demo Mar 20, 2019
author: Dana Walker
tags:
  - demo
---
The Community Demo is available on the [Pulp YouTube Channel](https://www.youtube.com/PulpProject). See the agenda below.

<iframe width="560" height="315" src="https://www.youtube.com/embed/GHsJDvimDrA" frameborder="0" allowfullscreen></iframe>

[Community Update (bmbouter)](http://www.youtube.com/watch?v=GHsJDvimDrA&t=0m24s)

[Pulp on S3 (daviddavis) (3.0)](http://www.youtube.com/watch?v=GHsJDvimDrA&t=7m33s)

[Chunked Uploads (daviddavis) (3.0)](http://www.youtube.com/watch?v=GHsJDvimDrA&t=13m36s)

[Repository Version Counts Reported by Type (bmbouter) (3.0)](http://www.youtube.com/watch?v=GHsJDvimDrA&t=17m16s)

[mariadb/mysql support (daviddavis) (3.0)](http://www.youtube.com/watch?v=GHsJDvimDrA&t=22m12s)

[Disabling batching in the Stages API for specific content (bmbouter) (3.0)](http://www.youtube.com/watch?v=GHsJDvimDrA&t=26m51s)


text:
<?php

namespace Websoftwares\Domain\User;

use League\Container\ServiceProvider;

/**
 * class UserProvider.
 *
 * @license http://opensource.org/licenses/MIT
 * @author Boris <boris@websoftwar.es>
 */
class UserProvider extends ServiceProvider
{
    /**
     * $provides.
     *
     * @var array
     */
    protected $provides = [
        'Websoftwares\Domain\User\UserService',
        'Websoftwares\Domain\User\UserFilter',
        'Websoftwares\Domain\User\UserFactory',
        'Websoftwares\Domain\User\UserGateway',
    ];

    public function register()
    {
        $container = $this->getContainer();

        $container->add('Websoftwares\Domain\User\UserGateway',
            function () {
                $pdo = new \PDO(
                    'mysql:dbname='.$_ENV['DB_NAME'].';host='.$_ENV['DB_HOST'],
                    $_ENV['DB_USERNAME'], $_ENV['DB_PASSWORD'],
                    [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
                    );

                return new \Websoftwares\Domain\User\UserGateway($pdo);
            });

        $container->add('Monolog\Logger')
            ->withArgument('user')
            ->withMethodCall('pushHandler', [
                new \Monolog\Handler\StreamHandler(__DIR__.'/../../logs/domain.log', \Monolog\Logger::WARNING), ]);

        $container->add('Websoftwares\Domain\User\UserFactory');
        $container->add('Websoftwares\Domain\User\UserFilter');
        $container->add('Websoftwares\Domain\User\UserService')
            ->withArgument('Websoftwares\Domain\User\UserGateway')
            ->withArgument('Websoftwares\Domain\User\UserFilter')
            ->withArgument('Websoftwares\Domain\User\UserFactory')
            ->withArgument('FOA\DomainPayload\PayloadFactory')
            ->withArgument('Monolog\Logger');
    }
}


text:
package org.knowm.xchange.campbx.dto;

import static org.fest.assertions.api.Assertions.assertThat;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.knowm.xchange.campbx.dto.marketdata.CampBXTicker;

/**
 * Test BitstampTicker JSON parsing
 */
public class TickerJSONTest {

  @Test
  public void testUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = TickerJSONTest.class.getResourceAsStream("/marketdata/example-ticker-data.json");

    ObjectMapper mapper = new ObjectMapper();
    CampBXTicker campBXTicker = mapper.readValue(is, CampBXTicker.class);

    // Verify that the example data was unmarshalled correctly
    assertThat(campBXTicker.getLast()).isEqualTo(new BigDecimal("13.30"));
    assertThat(campBXTicker.getBid()).isEqualTo(new BigDecimal("13.30"));
    assertThat(campBXTicker.getAsk()).isEqualTo(new BigDecimal("13.52"));
  }

}


text:
package edu.polyu.comp.ws;

import java.io.InputStream;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.fasterxml.jackson.databind.ObjectMapper;

import edu.polyu.comp.domain.User;
import edu.polyu.comp.service.UserService;
import edu.polyu.comp.util.StringUtil;

@Path("createUser")
public class P2pCreateUser {

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	public Response processInputRequest(InputStream requestBodyStream) {
		String output = "";

		try {
			output = StringUtil.convertInputStreamToString(requestBodyStream);

			// convert the incoming JSON message body into POJO
			ObjectMapper jackson = new ObjectMapper();
			User user = jackson.readValue(output, User.class);

			// add JDBC call here to create user account in DBMS
			boolean isSuccess = new UserService().createUser(user);
			if (isSuccess) {
				return Response.status(Response.Status.OK).entity(jackson.writeValueAsString(user)).build();
			} else {
				return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
			}
		} catch (Exception e) {
			e.printStackTrace(); // log the error
			return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
		}
	}

}


text:
<?php

namespace YourNameSpace;

/**
 * The plugin bootstrap file
 *
 * @link              http://www.foo.bar
 * @since             0.0.1
 * @package           YourPlugin
 *
 * @wordpress-plugin
 * Plugin Name:       Your Plugin
 * Plugin URI:        http://www.waboot.com/
 * Description:       Sample Plugin
 * Version:           0.1.0
 * Author:            Jon Doe
 * Author URI:        http://www.jon.doe/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       your-plugin
 * Domain Path:       /languages
 *
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/********************************************************/
/****************** PLUGIN BEGIN ************************
/********************************************************/

// Custom plugin autoloader function
spl_autoload_register( function($class){
	$prefix = "YourNameSpace\\";
	$plugin_path = plugin_dir_path( __FILE__ );
	$base_dir = $plugin_path."src/";
	// does the class use the namespace prefix?
	$len = strlen($prefix);
	if (strncmp($prefix, $class, $len) !== 0) {
		// no, move to the next registered autoloader
		return;
	}
	// get the relative class name
	$relative_class = substr($class, $len);
	// replace the namespace prefix with the base directory, replace namespace
	// separators with directory separators in the relative class name, append
	// with .php
	$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
	// if the file exists, require it
	if (file_exists($file)) {
		require_once $file;
	}
});


text:
case "$OSTYPE" in
  darwin*)  READLINK=greadlink;;
  *)        READLINK=readlink;;
esac

CURDIR=`${READLINK} -f \`dirname $0\``

source "${CURDIR}/../../scripts/logger.sh"

function getCommand() {
    if which oc &> /dev/null; then
        CMD=oc
    elif which kubectl &> /dev/null; then
        CMD=kubectl
    else
        err_and_exit "Cannot find oc or kubectl command, please check path to ensure it is installed"
    fi
    echo ${CMD}
}

function setup_test_openshift() {
    TEMPLATES_INSTALL_DIR=$1
    KUBEADM=$2
    IMAGE_NAMESPACE=${3:-"enmasseci"}

    export_required_env

    info "Deploying enmasse with templates dir: ${TEMPLATES_INSTALL_DIR}, kubeadmin: ${KUBEADM}, namespace: ${KUBERNETES_NAMESPACE}, image namespace: ${IMAGE_NAMESPACE}, iot: ${DEPLOY_IOT}"

    rm -rf ${TEST_LOGDIR}
    mkdir -p ${TEST_LOGDIR}

    oc login -u ${OPENSHIFT_USER} -p ${OPENSHIFT_PASSWD} --insecure-skip-tls-verify=true ${KUBERNETES_API_URL}
    OC_VERSION=${OC_VERSION:-"3.11"}
    if [[ ${OC_VERSION} != "4" ]]; then
        oc adm --config ${KUBEADM} policy add-cluster-role-to-user cluster-admin ${OPENSHIFT_USER}
        oc policy add-role-to-group system:image-puller system:serviceaccounts:${KUBERNETES_NAMESPACE} --namespace=${IMAGE_NAMESPACE}
    fi
    export KUBERNETES_API_TOKEN=`oc whoami -t`

    if [[ "${SKIP_DEPENDENCIES}" == "false" ]]; then
        ansible-playbook ${CURDIR}/../ansible/playbooks/systemtests-dependencies.yml
    fi
    INVENTORY_FILE=systemtests.inventory
    if [[ ${OC_VERSION} == "4" ]]; then
        echo "using openshift4 ansible inventory file"
        INVENTORY_FILE=systemtests.ocp4.inventory
    fi
    ansible-playbook ${TEMPLATES_INSTALL_DIR}/ansible/playbooks/openshift/deploy_all.yml -i ${CURDIR}/../ansible/inventory/${INVENTORY_FILE} --extra-vars "{\"namespace\": \"${KUBERNETES_NAMESPACE}\", \"admin_user\": \"${OPENSHIFT_USER}\", \"enable_iot\": \"${DEPLOY_IOT}\" }"
    wait_until_enmasse_up 'openshift' ${KUBERNETES_NAMESPACE}
}

function login_user() {
    SET_CLUSTER_USER=${1:-true}

    export_required_env

    if [[ "${SET_CLUSTER_USER}" == "true" ]]; then
        oc login system:admin --insecure-skip-tls-verify=true ${KUBERNETES_API_URL} --config $(get_kubeconfig_path)
        oc adm policy add-cluster-role-to-user cluster-admin ${OPENSHIFT_USER} --rolebinding-name=cluster-admin --config $(get_kubeconfig_path)
        oc policy add-role-to-group system:image-puller system:serviceaccounts:${KUBERNETES_NAMESPACE} --namespace=enmasseci --config $(get_kubeconfig_path)
    fi
    oc login -u ${OPENSHIFT_USER} -p ${OPENSHIFT_PASSWD} ${KUBERNETES_API_URL} --insecure-skip-tls-verify=true
    export KUBERNETES_API_TOKEN=`oc whoami -t`
}

function export_required_env {
    SANITIZED_NAMESPACE=${OPENSHIFT_PROJECT}
    SANITIZED_NAMESPACE=${SANITIZED_NAMESPACE//_/-}
    SANITIZED_NAMESPACE=${SANITIZED_NAMESPACE//\//-}
    KUBERNETES_NAMESPACE=${SANITIZED_NAMESPACE}

    if oc config view -o jsonpath='{.clusters[0].cluster.server}' > /dev/null 2>&1; then
        API_URL=$(oc config view -o jsonpath='{.clusters[0].cluster.server}')
    fi
    export KUBERNETES_API_URL=${KUBERNETES_API_URL:-${API_URL}}
    export OPENSHIFT_USER=${OPENSHIFT_USER:-test}
    export OPENSHIFT_PASSWD=${OPENSHIFT_PASSWD:-test}
    export KUBERNETES_NAMESPACE=${KUBERNETES_NAMESPACE:-enmasseci}
    export TEST_LOGDIR=${TEST_LOGDIR:-/tmp/testlogs}
    export ARTIFACTS_DIR=${ARTIFACTS_DIR:-artifacts}
    export CURDIR=`${READLINK} -f \`dirname $0\``
    export DEFAULT_AUTHSERVICE=standard
}

function wait_until_enmasse_up() {
    CLUSTER_TYPE=${1:-openshift}
    NAMESPACE=${2:-KUBERNETES_NAMESPACE}
    UPGRADE=${3:-false}

    expected_pods=7
    if [[ ${OC_VERSION} == "4" ]]; then
        # no service catalog nor service broker in ocp4
        expected_pods=$(($expected_pods - 1))
    fi
    if [[ "${CLUSTER_TYPE}" == "kubernetes" ]]; then
        # console won't be deployed on kubernettes by default
        expected_pods=$(($expected_pods - 2))
    fi

    wait_until_up ${expected_pods} ${NAMESPACE} ${UPGRADE}
    wait_code=$?
    if [[ ${wait_code} -ne 0 ]]; then
        err_and_exit 1
    fi

}
function wait_until_up() {
    POD_COUNT=$1
    ADDR_SPACE=$2
    UPGRADED=$3
    ${CURDIR}/wait_until_up.sh ${POD_COUNT} ${ADDR_SPACE} ${UPGRADED} || return 1
}

function wait_until_cluster_up() {
    local timeout=${1}

    NOW=$(date +%s)
    END=$(($NOW + timeout))
    info "Now: $(date -d@${NOW} -u +%F:%H:%M:%S)"
    info "Waiting ${timeout} seconds until: $(date -d@${END} -u +%F:%H:%M:%S)"

    oc cluster status
    while [[ $? -gt 0 ]]
    do
        NOW=$(date +%s)
        if [[ ${NOW} -gt ${END} ]]; then
            err_and_exit "ERROR: Timed out waiting for openshift cluster to come up!"
        fi
        sleep 5
        oc cluster status
    done
}

function run_test() {
    PROFILE=${1:-systemtests}
    TESTCASE=${2}

    if [[ -n "${TESTCASE}" ]]; then
        EXTRA_TEST_ARGS="-Dtest=${TESTCASE}"
    fi
    mvn -B test -pl systemtests -am -P${PROFILE} -Djava.net.preferIPv4Stack=true -DfailIfNoTests=false -Djansi.force=true -Dstyle.color=always -DskipTests ${EXTRA_TEST_ARGS}
}

function teardown_test() {
    PROJECT_NAME=$1
    CMD=${2:-oc}
    if [[ ${DEBUG} == 'false' ]]; then
        if [[ ${CMD} == "oc" ]]; then
            ansible-playbook -i ${CURDIR}/../ansible/inventory/systemtests.inventory ${CURDIR}/../../ansible/playbooks/openshift/uninstall.yml --extra-vars "{\"namespace\": \"${KUBERNETES_NAMESPACE}\"}"
        fi
        ${CMD} delete namespace ${PROJECT_NAME}
    fi
    info "End of teardown"
}

function create_address_space() {
    NAMESPACE=$1
    ADDRESS_SPACE_NAME=$2
    TYPE=$3
    PLAN=$4
    AUTH_SERVICE=$5
    API_VERSION=$6
    if [[ "${API_VERSION}" == "v1alpha1" ]]; then
        cat <<EOF | oc create -f -
apiVersion: enmasse.io/${API_VERSION}
kind: AddressSpace
metadata:
    name: ${ADDRESS_SPACE_NAME}
    namespace: ${NAMESPACE}
spec:
    type: ${TYPE}
    plan: ${PLAN}
authenticationService:
    type: standard
EOF
    else
        cat <<EOF | oc create -f -
apiVersion: enmasse.io/${API_VERSION}
kind: AddressSpace
metadata:
    name: ${ADDRESS_SPACE_NAME}
    namespace: ${NAMESPACE}
spec:
    type: ${TYPE}
    plan: ${PLAN}
    authenticationService:
        name: ${AUTH_SERVICE}
EOF
    fi
}

function create_address() {
    NAMESPACE=$1
    ADDRESS_SPACE=$2
    NAME=$3
    ADDRESS=$4
    TYPE=$5
    PLAN=$6
    API_VERSION=$7

    cat <<EOF | oc create -f -
apiVersion: enmasse.io/${API_VERSION}
kind: Address
metadata:
    name: $(echo ${ADDRESS_SPACE}.${NAME//_})
    namespace: ${NAMESPACE}
spec:
    address: ${ADDRESS}
    type: ${TYPE}
    plan: ${PLAN}
EOF
}

function create_user() {
    USER=$1
    PASSWORD=$2
    NAMESPACE=$3
    ADDRESS_SPACE_NAME=$4
    API_VERSION=$5

    cat <<EOF | oc create -f -
apiVersion: user.enmasse.io/${API_VERSION}
kind: MessagingUser
metadata:
    name: $(echo ${ADDRESS_SPACE_NAME}.${USER//_})
    namespace: ${NAMESPACE}
spec:
    username: ${USER}
    authentication:
      type: password
      password: $(echo -n ${PASSWORD} | base64)
    authorization:
    - addresses: [ "*" ]
      operations: [ "send", "recv", "view" ]
    - operations: [ "manage" ]
EOF
}

function get_kubernetes_info() {
    LOG_DIR=${1}
    RESOURCE=${2}
    NAMESPACE=${3}
    SUFIX=${4}
    CMD=$(getCommand)
    FILE_NAME="openshift-${RESOURCE}-${NAMESPACE}${SUFIX}.log"
    ${CMD} get ${RESOURCE} -n ${NAMESPACE} > "${LOG_DIR}/${FILE_NAME}"
    ${CMD} get ${RESOURCE} -n ${NAMESPACE} -o yaml >> "${LOG_DIR}/${FILE_NAME}"
}

#store previous logs from restarted pods
function get_previous_logs() {
    LOG_DIR=${1}
    ADDRESS_SPACE=${2}
    CMD=$(getCommand)
    pods_id=$(${CMD} get pods -n ${ADDRESS_SPACE} | awk 'NR >1 {print $1}')
    for pod_id in ${pods_id}
    do
        restart_count=$(${CMD} get -o json pod -n ${ADDRESS_SPACE} ${pod_id} -o jsonpath={.status.containerStatuses[0].restartCount})
        if (( ${restart_count} > 0 ))
        then
            echo "pod ${pod_id} was restarted"
            ${CMD} logs -p ${pod_id} -n ${ADDRESS_SPACE} > "${LOG_DIR}/${pod_id}.previous.log"
        fi
    done
}

function get_all_events() {
    LOG_DIR=${1}
    ${CMD} get events --all-namespaces \
                      --output="custom-columns=LAST SEEN:{lastTimestamp},FIRST SEEN:{firstTimestamp},COUNT:{count},NAME:{metadata.name},KIND:{involvedObject.kind},SUBOBJECT:{involvedObject.fieldPath},TYPE:{type},REASON:{reason},SOURCE:{source.component},MESSAGE:{message}" \
                      --sort-by="{.lastTimestamp}" > ${LOG_DIR}/all_events.log
}

function stop_and_check_openshift() {
    if ! oc; then
        info "oc command not found, nothing to stop"
        return
    fi
    if oc whoami; then
        oc logout
    fi
    oc cluster down #for the case that cluster is already running
    openshift_pids=$(ps aux | grep 'openshift' | grep -v 'grep\|setup-openshift' | awk '{print $2}')
    if [[ -n ${openshift_pids} ]]; then
        warn "OpenShift cluster didn't stop properly, trying to kill OpenShift processes..."
        kill -9 "${openshift_pids}"
    fi

    if oc cluster status; then
        err_and_exit "shutting down of openshift cluster failed, tests won't be executed"
    fi
    info "cluster turned off successfully"
}

function clean_docker_images() {
    DOCKER=${DOCKER:-docker}

    containers_run=$(docker ps -q)
    if [[ -n ${containers_run} ]];then
        ${DOCKER} stop $(docker ps -q)
    else
        info "No running containers"
    fi

    containers_all=$(docker ps -a -q)
    if [[ -n ${containers_all} ]];then
        ${DOCKER} rm $(docker ps -a -q) -f
    else
        info "No containers to remove"
    fi

    images=$(docker images -q)
    if [[ -n ${images} ]];then
        ${DOCKER} rmi $(docker images -q) -f
    else
        info "No images to remove"
    fi
}

function print_images() {
    DOCKER=${DOCKER:-docker}
    ${DOCKER} images
}
function clean_oc_location() {
    info "Removing previous openshift data"
    if [[ $(get_openshift_version) == '3.9'* ]]; then
        info "Cleaning OpenShift work directory /var/lib/origin"
        sudo find  /var/lib/origin -type d -exec mountpoint --quiet {} \; -exec umount --types tmpfs {} \;
        sudo rm -rf /var/lib/origin
    else
        info "Cleaning OpenShift work directory openshift.local.clusterup"
        OLD_OC_LOCATIONS=$(sudo find /home/cloud-user/ -type d -name 'openshift.local.clusterup')
        for i in ${OLD_OC_LOCATIONS}; do sudo find "${i}" -type d -exec mountpoint --quiet {} \; -exec umount --types tmpfs {} \; && rm sudo -rf "${i}"; done
    fi
    sudo rm -rf /var/log/containers/*
    sudo rm -rf /var/log/pods/*
}

function check_if_ansible_ready() {
    info "Running: check if ansible is already installed"
    if ! sudo rpm -qa | grep -qw ansible; then
        info "Ansible is not installed, running install command"
        sudo yum -y install --enablerepo=epel ansible
    fi
}

function get_openshift_version() {
    echo $(oc version | sed -nre '/^oc/s/^.*v(([0-9]+\.)*[0-9]+).*$/\1/p')
}

function get_kubeconfig_path() {
    OC_39='/var/lib/origin/openshift.local.config/master/admin.kubeconfig'
    OC_310='./openshift.local.clusterup/kube-apiserver/admin.kubeconfig'

    if [[ $(get_openshift_version) == '3.9'* ]]; then
        echo $OC_39
    else
        echo $OC_310
    fi
}

function get_oc_args() {
    OC_39="--public-hostname=$(hostname -I | awk '{print $1}') --service-catalog"
    OC_310="--public-hostname=$(hostname -I | awk '{print $1}') --enable=*,service-catalog,web-console --insecure-skip-tls-verify=true"

    if [[ $(get_openshift_version) == '3.9'* ]]; then
        echo $OC_39
    else
        echo $OC_310
    fi
}

function download_enmasse_release() {
    VERSION=${1:-0.23.1}
    wget https://github.com/EnMasseProject/enmasse/releases/download/${VERSION}/enmasse-${VERSION}.tgz
    rm -rf ${CURDIR}/../../templates/default/build/enmasse-${VERSION}
    mkdir ${CURDIR}/../../templates/build/deafult -p
    tar zxvf enmasse-${VERSION}.tgz -C ${CURDIR}/../../templates/build/default
}

function get_oc_url() {
    OC_VERSION=${OC_VERSION:-"3.11"}

    if [[ ${OC_VERSION} == "3.11" ]]; then
        echo "https://github.com/openshift/origin/releases/download/v3.11.0/openshift-origin-client-tools-v3.11.0-0cbc58b-linux-64bit.tar.gz"
    elif [[ ${OC_VERSION} == "3.10" ]]; then
        echo "https://github.com/openshift/origin/releases/download/v3.10.0/openshift-origin-client-tools-v3.10.0-dd10d17-linux-64bit.tar.gz"
    elif [[ ${OC_VERSION} == "4" ]]; then
        echo "https://github.com/openshift/origin/releases/download/v3.11.0/openshift-origin-client-tools-v3.11.0-0cbc58b-linux-64bit.tar.gz"
        # workaround because 3.11 tar.gz has a folder inside and 4.1.X tar.gz hasn't, TODO modify systemtests/ansible/playbooks/environment.yml to work with both
        # echo "https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.1.3/openshift-client-linux-4.1.3.tar.gz"
    fi
}

function wait_until_file_close() {
    FOLDER=$1

    TIMEOUT=120
    NOW=$(date +%s)
    END=$(($NOW + $TIMEOUT))
    info "Waiting until ${END}"
    while true
    do
        NOW=$(date +%s)
        if [[ ${NOW} -gt ${END} ]]; then
            warn "Timed out waiting for closing files!"
            kill -9 $(lsof -t +D ${FOLDER}) || true
        fi
        if [[ -n "$(lsof +D ${FOLDER})" ]]; then
            lsof +D "${FOLDER}" || true
            info "Files in ${FOLDER} are still opened"
        else
            info "All files in ${FOLDER} are closed"
            return  0
        fi
        sleep 5
    done
}


text:
package com.siyeh.igfixes.style.replace_with_string;

class ConstructorArgument {
  void m() {

      String s = "init-" + "appended";
  }
}


text:
<?php

declare(strict_types=1);

namespace MsgPhp\User\Command\Handler;

use MsgPhp\Domain\DomainMessageBus;
use MsgPhp\Domain\Event\Disable;
use MsgPhp\Domain\Event\EventSourcingCommandHandlerTrait;
use MsgPhp\Domain\Factory\DomainObjectFactory;
use MsgPhp\User\Command\DisableUser;
use MsgPhp\User\Event\UserDisabled;
use MsgPhp\User\Repository\UserRepository;

/**
 * @author Roland Franssen <franssen.roland@gmail.com>
 */
final class DisableUserHandler
{
    use EventSourcingCommandHandlerTrait;

    private $factory;
    private $bus;
    private $repository;

    public function __construct(DomainObjectFactory $factory, DomainMessageBus $bus, UserRepository $repository)
    {
        $this->factory = $factory;
        $this->bus = $bus;
        $this->repository = $repository;
    }

    public function __invoke(DisableUser $command): void
    {
        $user = $this->repository->find($command->userId);

        if ($this->handleEvent($user, $this->factory->create(Disable::class))) {
            $this->repository->save($user);
            $this->bus->dispatch($this->factory->create(UserDisabled::class, compact('user')));
        }
    }
}


text:
/* globals Orders:true */
import includes from 'lodash.includes';
import { Mongo } from 'meteor/mongo';
import { Roles } from 'meteor/alanning:roles';

Orders = new Mongo.Collection('orders');

function isAdmin(user) {
  return Roles.userIsInRole(user, 'admin');
}

Orders.allow({
  insert(userId, order) {
    // you can only order something for yourself
    if (isAdmin(userId)) { return true; }
    return userId && order.user === userId;
  },
  fetch: ['user', 'status'],
  update(userId) {
    return isAdmin(userId);
  },
  remove(userId) {
    return userId && isAdmin(userId);
  },
});

Orders.deny({
  fetch: ['user', 'status'],
  update(userId, subscription, fields, modifier) {
    if (includes(fields, 'user')) {
      return true;
    }

    if (subscription.status === 'cancelled' && !isAdmin(userId)) {
      return true;
    }
  },
});


text:
layout: leaf-node
title: "How to Structure Quantitative Research Questions"
title-url: "http://dissertation.laerd.com/how-to-structure-quantitative-research-questions.php"
author:
groups: research-principles-and-methodologies
categories: quantitative-research
topics: introductory-resources
summary: >
    There is no "one best way" to structure a quantitative research question. However, to create a well-structured quantitative research question, we recommend an approach that is based on four steps: (1) Choosing the type of quantitative research question you are trying to create (i.e., descriptive, comparative or relationship-based); (2) Identifying the different types of variables you are trying to measure, manipulate and/or control, as well as any groups you may be interested in; (3) Selecting the appropriate structure for the chosen type of quantitative research question, based on the variables and/or groups involved; and (4) Writing out the problem or issues you are trying to address in the form of a complete research question. In this article, we discuss each of these four steps, as well as providing examples for the three types of quantitative research question you may want to create: descriptive, comparative and relationship-based research questions.
cite: >
     Lund Research Ltd 2012. Retrieved from: http://dissertation.laerd.com/how-to-structure-quantitative-research-questions.php. April 26, 2017.
pub-date:
added-date: 2017-04-27
resource-type: external-page
---


text:
package kaflib.applications.scripts;

import java.io.File;

import kaflib.gui.components.KFrame;
import kaflib.types.Directory;
import kaflib.types.Percent;
import kaflib.utils.FileUtils;
import kaflib.utils.GUIUtils;
import kaflib.utils.RandomUtils;

public class SplitImages {
	public static final Percent A_PERCENT = new Percent(.90);

	public static void main(String args[]) {
		try {
			KFrame frame = new KFrame();
			Directory d = GUIUtils.chooseDirectory(frame);
			if (d == null) {
				return;
			}
			File files[] = d.listFiles();

			Directory a = new Directory(d, "a");
			Directory b = new Directory(d, "b");
			if (a.exists() || b.exists()) {
				System.err.println("Need to be able to create a an b subdirs.");
			}
			a.mkdir();
			b.mkdir();

			for (File file : files) {
				if (file.isDirectory()) {
					continue;
				}
				if (RandomUtils.randomBoolean(A_PERCENT)) {
					FileUtils.copyTo(a, file);
					file.delete();
				}
				else {
					FileUtils.copyTo(b, file);
					file.delete();
				}
			}

		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

}


text:
package com.github.twitch4j.helix.webhooks.topics;

import com.github.twitch4j.helix.domain.ExtensionTransactionList;
import lombok.Getter;
import lombok.NonNull;

import java.util.TreeMap;

/**
 * Sends a notification when a new transaction is created for an extension.
 */
@Getter
public class ExtensionTransactionsTopic extends TwitchWebhookTopic<ExtensionTransactionList> {

    public static final String PATH = "/extensions/transactions";

    private static TreeMap<String, Object> mapParameters(String extensionId) {
        TreeMap<String, Object> parameterMap = new TreeMap<>();
        parameterMap.put("extension_id", extensionId);
        parameterMap.put("first", 1);
        return parameterMap;
    }

    /**
     * @return The ID of the extension to listen to for transactions.
     */
    private final String extensionId;

    /**
     * Sends a notification when a new transaction is created for an extension.
     *
     * @param extensionId Required. The ID of the extension to listen to for transactions.
     * @deprecated Will be decommissioned after 2021-09-16 in favor of EventSub
     */
    @Deprecated
    public ExtensionTransactionsTopic(@NonNull String extensionId) {
        super(
            PATH,
            ExtensionTransactionList.class,
            mapParameters(extensionId)
        );
        this.extensionId = extensionId;
    }

}


text:
package de.ids_mannheim.korap.web.utils;

/**
 * @author hanl
 * @date 12/04/2014
 */
public class HTMLBuilder {

    private StringBuilder html;
    private StringBuilder body;
    private String bodyAttr;

    public HTMLBuilder () {
        html = new StringBuilder();
        body = new StringBuilder();
        bodyAttr = "";
        html.append("");
    }

    public void addHeader (String header, int h) {
        html.append("<h" + h + ">");
        html.append(header);
        html.append("</h" + h + ">");
    }

    public void addToBody (String body) {
        this.body.append(body);
    }

    public void addToBody (String body, String attributes) {
        this.body.append(body);
        bodyAttr = attributes;
    }

    public String build () {
        if (bodyAttr.isEmpty())
            html.append("");
        else {
            html.append("");
        }

        html.append(body);
        html.append("");
        html.append("");
        return html.toString();
    }

    @Override
    public String toString () {
        return build();
    }
}


text:
using System.Collections.Generic;

namespace Transition
{
   /// <summary>
   /// An executable state machine.
   /// </summary>
   public class Machine<T> where T : Context
   {
      /// <summary>
      /// The unique Name of the machine
      /// </summary>
      public string Name { get; set; }

      /// <summary>
      /// All of the states that make up the machine. States are indexed
      /// by their position in this list.
      /// </summary>
      public List<State<T>> States { get; private set; }

      /// <summary>
      /// A lookup table of actions to run when a message is recieved
      /// </summary>
      public Dictionary<string, Action<T>> OnActions { get; private set; }

      /// <summary>
      /// The first action that the state takes on it's first tick before any state is executed.
      /// It MUST transition to the first state.
      /// </summary>
      /// <remarks>
      /// The Parser ensures that this exists and so null checking is unecessary.
      /// </remarks>
      public Action<T> EnterAction { get; set; }

      public Machine()
      {
         States = new List<State<T>>();
         OnActions = new Dictionary<string, Action<T>>(0);
      }

      /// <summary>
      /// Run the state machine for one tick. The resulting state of the Machine will be
      /// stored in the context.
      /// </summary>
      public void Tick(T context)
      {
         context.ResetError();
         if (context.StateId == -1) {
            var result = EnterAction.Tick(context);
            if (result.ResultType != TickResultType.Transition) {
               context.RaiseError(ErrorCode.Exec_Machine_Tick_MachineActionMustReturnTransition);
               return;
            }
            Transition(context, result.TransitionId);
         } else {
            var currentState = CurrentState(context);
            if (currentState == null) {
               context.RaiseError(ErrorCode.Exec_Machine_Tick_CurrentStateDoesNotExist);
               return;
            }
            var result = currentState.Tick(context);
            if (result.ResultType == TickResultType.Transition) {
               Transition(context, result.TransitionId);
            }
         }
      }

      /// <summary>
      /// Sends the message to the active state in the machine. May result in a state transition.
      /// </summary>
      public void SendMessage(T context, MessageEnvelope message)
      {

         TickResult result;
         // see if the current state can handle it first
         var currentState = CurrentState(context);
         if (currentState != null && currentState.CanHandleMessage(message)) {
            result = currentState.SendMessage(context, message);
         } else {
            // otherwise handle it ourselves
            Action<T> handler;
            if (OnActions.TryGetValue(message.Key, out handler)) {
               context.Message = message;
               result = handler.Tick(context);
               context.Message = null;
            } else {
               // no one can handle the message so exit early
               return;
            }
         }
         if (result.ResultType == TickResultType.Transition) {
            Transition(context, result.TransitionId);
         } else {
            context.RaiseError(ErrorCode.Exec_State_SendMessage_MessageHandlerDidNotReturnTransitionOrDone);
         }
      }

      /// <summary>
      /// Add a state to the machine.
      /// </summary>
      public void AddState(State<T> state)
      {
         States.Add(state);
      }

      private void Transition(T context, int destinationStateId)
      {
         var currentState = CurrentState(context);
         if (currentState != null) {
            currentState.Exit(context);
         }
         context.StateId = destinationStateId;
         currentState = CurrentState(context);
         // ensure we land on a state
         if (currentState == null) {
            context.RaiseError(ErrorCode.Exec_Machine_Transition_DestinationStateDoesNotExist);
            return;
         }
         currentState.Enter(context);
      }

      private State<T> CurrentState(T context)
      {
         var stateId = context.StateId;
         if (stateId < 0 || stateId >= States.Count)
            return null;

         return States[stateId];
      }

      /// <summary>
      /// Adds an action to the OnActions collection
      /// </summary>
      public void AddOnAction(string key, Action<T> action)
      {
         OnActions.Add(key, action);
      }
   }
}


text:
struct CPVT_WordRange {
  CPVT_WordRange() = default;

  CPVT_WordRange(const CPVT_WordPlace& begin, const CPVT_WordPlace& end)
      : BeginPos(begin), EndPos(end) {
    Normalize();
  }

  inline bool IsEmpty() const { return BeginPos == EndPos; }
  inline bool operator==(const CPVT_WordRange& wr) const {
    return wr.BeginPos == BeginPos && wr.EndPos == EndPos;
  }
  inline bool operator!=(const CPVT_WordRange& wr) const {
    return !(*this == wr);
  }

  void Normalize() {
    if (BeginPos > EndPos)
      std::swap(BeginPos, EndPos);
  }

  CPVT_WordPlace BeginPos;
  CPVT_WordPlace EndPos;
};

#endif  // CORE_FPDFDOC_CPVT_WORDRANGE_H_