text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable 414
namespace GoogleCalendaySync {

    ///
    [Microsoft.VisualStudio.Tools.Applications.Runtime.StartupObjectAttribute(0)]
    [global::System.Security.Permissions.PermissionSetAttribute(global::System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
    public sealed partial class ThisAddIn : Microsoft.Office.Tools.Outlook.OutlookAddInBase {

        internal Microsoft.Office.Tools.CustomTaskPaneCollection CustomTaskPanes;

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        private global::System.Object missing = global::System.Type.Missing;

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        internal Microsoft.Office.Interop.Outlook.Application Application;

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        public ThisAddIn(global::Microsoft.Office.Tools.Outlook.Factory factory, global::System.IServiceProvider serviceProvider) :
                base(factory, serviceProvider, "AddIn", "ThisAddIn") {
            Globals.Factory = factory;
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        protected override void Initialize() {
            base.Initialize();
            this.Application = this.GetHostItem<Microsoft.Office.Interop.Outlook.Application>(typeof(Microsoft.Office.Interop.Outlook.Application), "Application");
            Globals.ThisAddIn = this;
            global::System.Windows.Forms.Application.EnableVisualStyles();
            this.InitializeCachedData();
            this.InitializeControls();
            this.InitializeComponents();
            this.InitializeData();
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        protected override void FinishInitialization() {
            this.InternalStartup();
            this.OnStartup();
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        protected override void InitializeDataBindings() {
            this.BeginInitialization();
            this.BindToData();
            this.EndInitialization();
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        private void InitializeCachedData() {
            if ((this.DataHost == null)) {
                return;
            }
            if (this.DataHost.IsCacheInitialized) {
                this.DataHost.FillCachedData(this);
            }
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        private void InitializeData() {
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        private void BindToData() {
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        private void StartCaching(string MemberName) {
            this.DataHost.StartCaching(this, MemberName);
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        private void StopCaching(string MemberName) {
            this.DataHost.StopCaching(this, MemberName);
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        private bool IsCached(string MemberName) {
            return this.DataHost.IsCached(this, MemberName);
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        private void BeginInitialization() {
            this.BeginInit();
            this.CustomTaskPanes.BeginInit();
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        private void EndInitialization() {
            this.CustomTaskPanes.EndInit();
            this.EndInit();
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        private void InitializeControls() {
            this.CustomTaskPanes = Globals.Factory.CreateCustomTaskPaneCollection(null, null, "CustomTaskPanes", "CustomTaskPanes", this);
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        private void InitializeComponents() {
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        private bool NeedsFill(string MemberName) {
            return this.DataHost.NeedsFill(this, MemberName);
        }

        ///
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]
        protected override void OnShutdown() {
            this.CustomTaskPanes.Dispose();
            base.OnShutdown();
        }
    }

    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
    internal sealed partial class Globals {

        ///
        private Globals() {
        }

        private static ThisAddIn _ThisAddIn;

        private static global::Microsoft.Office.Tools.Outlook.Factory _factory;

        private static ThisRibbonCollection _ThisRibbonCollection;

        private static ThisFormRegionCollection _ThisFormRegionCollection;

        internal static ThisAddIn ThisAddIn {
            get {
                return _ThisAddIn;
            }
            set {
                if ((_ThisAddIn == null)) {
                    _ThisAddIn = value;
                }
                else {
                    throw new System.NotSupportedException();
                }
            }
        }

        internal static global::Microsoft.Office.Tools.Outlook.Factory Factory {
            get {
                return _factory;
            }
            set {
                if ((_factory == null)) {
                    _factory = value;
                }
                else {
                    throw new System.NotSupportedException();
                }
            }
        }

        internal static ThisRibbonCollection Ribbons {
            get {
                if ((_ThisRibbonCollection == null)) {
                    _ThisRibbonCollection = new ThisRibbonCollection(_factory.GetRibbonFactory());
                }
                return _ThisRibbonCollection;
            }
        }

        internal static ThisFormRegionCollection FormRegions {
            get {
                if ((_ThisFormRegionCollection == null)) {
                    _ThisFormRegionCollection = new ThisFormRegionCollection(Globals.ThisAddIn.GetFormRegions());
                }
                return _ThisFormRegionCollection;
            }
        }
    }

    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Tools.Office.ProgrammingModel.dll", "12.0.0.0")]
    internal sealed partial class ThisRibbonCollection : Microsoft.Office.Tools.Ribbon.RibbonCollectionBase {

        ///
        internal ThisRibbonCollection(global::Microsoft.Office.Tools.Ribbon.RibbonFactory factory) :
                base(factory) {
        }

        internal ThisRibbonCollection this[Microsoft.Office.Interop.Outlook.Inspector inspector] {
            get {
                return this.GetRibbonContextCollection<ThisRibbonCollection>(inspector);
            }
        }

        internal ThisRibbonCollection this[Microsoft.Office.Interop.Outlook.Explorer explorer] {
            get {
                return this.GetRibbonContextCollection<ThisRibbonCollection>(explorer);
            }
        }
    }

    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    internal sealed partial class ThisFormRegionCollection : Microsoft.Office.Tools.Outlook.FormRegionCollectionBase {

        ///
        public ThisFormRegionCollection(System.Collections.Generic.IList<Microsoft.Office.Tools.Outlook.IFormRegion> list) :
                base(list) {
        }

        internal WindowFormRegionCollection this[Microsoft.Office.Interop.Outlook.Explorer explorer] {
            get {
                return ((WindowFormRegionCollection)(Globals.ThisAddIn.GetFormRegions(explorer, typeof(WindowFormRegionCollection))));
            }
        }

        internal WindowFormRegionCollection this[Microsoft.Office.Interop.Outlook.Inspector inspector] {
            get {
                return ((WindowFormRegionCollection)(Globals.ThisAddIn.GetFormRegions(inspector, typeof(WindowFormRegionCollection))));
            }
        }
    }

    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    internal sealed partial class WindowFormRegionCollection : Microsoft.Office.Tools.Outlook.FormRegionCollectionBase {

        ///
        public WindowFormRegionCollection(System.Collections.Generic.IList<Microsoft.Office.Tools.Outlook.IFormRegion> list) :
                base(list) {
        }
    }
}


text:
@interface GSProfileManager()

@end

@implementation GSProfileManager

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static GSProfileManager *profileManager = nil;
    dispatch_once(&onceToken, ^{
        profileManager = [[GSProfileManager alloc] init];
    });
    return profileManager;
}

- (NSArray *)loadProfileData {

    // 解析profileData数据
    NSMutableArray *profileData = [NSMutableArray array];
    NSString *profileDirectory = [[GSFileManager sharedInstance] profileDirectory];
    NSArray *matchFileExtensions = @[@"mobileprovision",@"MOBILEPROVISION",@"provisionprofile",@"PROVISIONPROFILE"];
    NSArray *profileNames = [[[NSFileManager defaultManager] subpathsAtPath:profileDirectory] pathsMatchingExtensions:matchFileExtensions];

    if (!profileNames || !profileNames.count) {
        return nil;
    }

    [profileNames enumerateObjectsUsingBlock:^(NSString   * _Nonnull fileName, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *filePath = [NSString stringWithFormat:@"%@%@", profileDirectory, fileName];
        NSMutableDictionary *fileDic = [[self readPlistAtPath:filePath] mutableCopy];
        fileDic[@"filePath"] = filePath;
        [profileData addObject:fileDic];
    }];
    return profileData;
}

- (NSDictionary *)readPlistAtPath:(NSString *)path {

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSString *beginString = @"<?xml version";
        NSString *endString    = @"</plist>";

        NSData *rawData = [NSData dataWithContentsOfFile:path];
        NSData *beginData = [NSData dataWithBytes:[beginString UTF8String] length:beginString.length];
        NSData *endData = [NSData dataWithBytes:[endString UTF8String] length:endString.length];
        NSRange fullRange = NSMakeRange(0, rawData.length);

        NSRange beginRange = [rawData rangeOfData:beginData options:0 range:fullRange];
        NSRange endRange = [rawData rangeOfData:endData options:0 range:fullRange];

        NSRange plistRange = NSMakeRange(beginRange.location, endRange.location + endRange.length - beginRange.location);
        NSData *plistData = [rawData subdataWithRange:plistRange];

        NSError *error = nil;
        id obj = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListImmutable format:NULL error:&error];
        if (error) {
            NSLog(@"plist 文件解析错误");
            return nil;
        }

        if (![obj isKindOfClass:[NSDictionary class]]) {
            NSLog(@"解析出错, 不是字典");
            return nil;
        }

        return obj;
    }
    return nil;
}

- (NSDictionary *)parseCertificate:(NSData *)data {
    static NSString *const devCertSummaryKey = @"summary";
    static NSString *const devCertInvalidityDateKey = @"invalidity";

    NSMutableDictionary *detailsDict;
    SecCertificateRef certificateRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data);
    if (certificateRef) {
        CFStringRef summaryRef = SecCertificateCopySubjectSummary(certificateRef);
        NSString *summary = (NSString *)CFBridgingRelease(summaryRef);
        if (summary) {
            detailsDict = [NSMutableDictionary dictionaryWithObject:summary forKey:devCertSummaryKey];

            CFErrorRef error;
            CFDictionaryRef valuesDict = SecCertificateCopyValues(certificateRef, (__bridge CFArrayRef)@[(__bridge id)kSecOIDInvalidityDate], &error);
            if (valuesDict) {
                CFDictionaryRef invalidityDateDictionaryRef = CFDictionaryGetValue(valuesDict, kSecOIDInvalidityDate);
                if (invalidityDateDictionaryRef) {
                    CFTypeRef invalidityRef = CFDictionaryGetValue(invalidityDateDictionaryRef, kSecPropertyKeyValue);
                    CFRetain(invalidityRef);

                    // NOTE: the invalidity date type of kSecPropertyTypeDate is documented as a CFStringRef in the "Certificate, Key, and Trust Services Reference".
                    // In reality, it's a __NSTaggedDate (presumably a tagged pointer representing an NSDate.) But to sure, we'll check:
                    id invalidity = CFBridgingRelease(invalidityRef);
                    if (invalidity) {
                        if ([invalidity isKindOfClass:[NSDate class]]) {
                            // use the date directly
                            [detailsDict setObject:invalidity forKey:devCertInvalidityDateKey];
                        }
                        else {
                            // parse the date from a string
                            NSString *string = [invalidity description];
                            NSDateFormatter *invalidityDateFormatter = [NSDateFormatter new];
                            [invalidityDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
                            NSDate *invalidityDate = [invalidityDateFormatter dateFromString:string];
                            if (invalidityDate) {
                                [detailsDict setObject:invalidityDate forKey:devCertInvalidityDateKey];
                            }
                        }
                    }
                    else {
//                        NSLog(@"No invalidity date in '%@' certificate, dictionary = %@", summary, invalidityDateDictionaryRef);
                        [detailsDict setObject:@"No invalidity date" forKey:devCertInvalidityDateKey];
                    }
                }
                else {
//                    NSLog(@"No invalidity values in '%@' certificate, dictionary = %@", summary, valuesDict);
                    [detailsDict setObject:@"No invalidity values" forKey:devCertInvalidityDateKey];

                }

                CFRelease(valuesDict);
            }
            else {
//                NSLog(@"Could not get values in '%@' certificate, error = %@", summary, error);
            }

        }
        else {
//            NSLog(@"Could not get summary from certificate");
        }

        CFRelease(certificateRef);
    }
    return detailsDict;

}
@end

redpajama_set_name: RedPajamaGithub


text:
require File.dirname(__FILE__) + '/../spec_helper.rb'

describe GuidePhoto, "creation" do
  elastic_models( Observation )

  it { is_expected.to validate_length_of(:description).is_at_most(256).allow_blank }
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;

namespace OfficeTicTacToe.Common
{
    public class NavLink
    {
        public string Label { get; set; }
        public Symbol Symbol { get; set; }
        public Action Action { get; set; }
        public Type DestPage { get; set; }
        public object Arguments { get; set; }

    }
}


text:
"""Glue between OpenID and django.contrib.auth."""

__metaclass__ = type

from django.conf import settings
from django.contrib.auth.models import User, Group
from openid.consumer.consumer import SUCCESS
from openid.extensions import ax, sreg, pape

from django_openid_auth import teams
from django_openid_auth.models import UserOpenID
from django_openid_auth.exceptions import (
    IdentityAlreadyClaimed,
    DuplicateUsernameViolation,
    MissingUsernameViolation,
    MissingPhysicalMultiFactor,
    RequiredAttributeNotReturned,
)

class OpenIDBackend:
    """A django.contrib.auth backend that authenticates the user based on
    an OpenID response."""

    supports_object_permissions = False
    supports_anonymous_user = True

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

    def authenticate(self, **kwargs):
        """Authenticate the user based on an OpenID response."""
        # Require that the OpenID response be passed in as a keyword
        # argument, to make sure we don't match the username/password
        # calling conventions of authenticate.

        openid_response = kwargs.get('openid_response')
        if openid_response is None:
            return None

        if openid_response.status != SUCCESS:
            return None

        user = None
        try:
            user_openid = UserOpenID.objects.get(
                claimed_id__exact=openid_response.identity_url)
        except UserOpenID.DoesNotExist:
            if getattr(settings, 'OPENID_CREATE_USERS', False):
                user = self.create_user_from_openid(openid_response)
        else:
            user = user_openid.user

        if user is None:
            return None

        if getattr(settings, 'OPENID_UPDATE_DETAILS_FROM_SREG', False):
            details = self._extract_user_details(openid_response)
            self.update_user_details(user, details, openid_response)

        if getattr(settings, 'OPENID_PHYSICAL_MULTIFACTOR_REQUIRED', False):
            pape_response = pape.Response.fromSuccessResponse(openid_response)
            if pape_response is None or \
               pape.AUTH_MULTI_FACTOR_PHYSICAL not in pape_response.auth_policies:
                raise MissingPhysicalMultiFactor()

        teams_response = teams.TeamsResponse.fromSuccessResponse(
            openid_response)
        if teams_response:
            self.update_groups_from_teams(user, teams_response)
            self.update_staff_status_from_teams(user, teams_response)

        return user

    def _extract_user_details(self, openid_response):
        email = fullname = first_name = last_name = nickname = None
        sreg_response = sreg.SRegResponse.fromSuccessResponse(openid_response)
        if sreg_response:
            email = sreg_response.get('email')
            fullname = sreg_response.get('fullname')
            nickname = sreg_response.get('nickname')
        # If any attributes are provided via Attribute Exchange, use
        # them in preference.
        fetch_response = ax.FetchResponse.fromSuccessResponse(openid_response)
        if fetch_response:
            # The myOpenID provider advertises AX support, but uses
            # attribute names from an obsolete draft of the
            # specification.  We check for them first so the common
            # names take precedence.
            email = fetch_response.getSingle(
                'http://schema.openid.net/contact/email', email)
            fullname = fetch_response.getSingle(
                'http://schema.openid.net/namePerson', fullname)
            nickname = fetch_response.getSingle(
                'http://schema.openid.net/namePerson/friendly', nickname)

            email = fetch_response.getSingle(
                'http://axschema.org/contact/email', email)
            fullname = fetch_response.getSingle(
                'http://axschema.org/namePerson', fullname)
            first_name = fetch_response.getSingle(
                'http://axschema.org/namePerson/first', first_name)
            last_name = fetch_response.getSingle(
                'http://axschema.org/namePerson/last', last_name)
            nickname = fetch_response.getSingle(
                'http://axschema.org/namePerson/friendly', nickname)

        if fullname and not (first_name or last_name):
            # Django wants to store first and last names separately,
            # so we do our best to split the full name.
            fullname = fullname.strip()
            split_names = fullname.rsplit(None, 1)
            if len(split_names) == 2:
                first_name, last_name = split_names
            else:
                first_name = u''
                last_name = fullname

        return dict(email=email, nickname=nickname,
                    first_name=first_name, last_name=last_name)

    def _get_preferred_username(self, nickname, email):
        if nickname:
            return nickname
        if email and getattr(settings, 'OPENID_USE_EMAIL_FOR_USERNAME',
            False):
            suggestion = ''.join([x for x in email if x.isalnum()])
            if suggestion:
                return suggestion
        return 'openiduser'

    def _get_available_username(self, nickname, identity_url):
        # If we're being strict about usernames, throw an error if we didn't
        # get one back from the provider
        if getattr(settings, 'OPENID_STRICT_USERNAMES', False):
            if nickname is None or nickname == '':
                raise MissingUsernameViolation()

        # If we don't have a nickname, and we're not being strict, use a default
        nickname = nickname or 'openiduser'

        # See if we already have this nickname assigned to a username
        try:
            user = User.objects.get(username__exact=nickname)
        except User.DoesNotExist:
            # No conflict, we can use this nickname
            return nickname

        # Check if we already have nickname+i for this identity_url
        try:
            user_openid = UserOpenID.objects.get(
                claimed_id__exact=identity_url,
                user__username__startswith=nickname)
            # No exception means we have an existing user for this identity
            # that starts with this nickname.

            # If they are an exact match, the user already exists and hasn't
            # changed their username, so continue to use it
            if nickname == user_openid.user.username:
                return nickname

            # It is possible we've had to assign them to nickname+i already.
            oid_username = user_openid.user.username
            if len(oid_username) > len(nickname):
                try:
                    # check that it ends with a number
                    int(oid_username[len(nickname):])
                    return oid_username
                except ValueError:
                    # username starts with nickname, but isn't nickname+#
                    pass
        except UserOpenID.DoesNotExist:
            # No user associated with this identity_url
            pass

        if getattr(settings, 'OPENID_STRICT_USERNAMES', False):
            if User.objects.filter(username__exact=nickname).count() > 0:
                raise DuplicateUsernameViolation(
                    "The username (%s) with which you tried to log in is "
                    "already in use for a different account." % nickname)

        # Pick a username for the user based on their nickname,
        # checking for conflicts.  Start with number of existing users who's
        # username starts with this nickname to avoid having to iterate over
        # all of the existing ones.
        i = User.objects.filter(username__startswith=nickname).count() + 1
        while True:
            username = nickname
            if i > 1:
                username += str(i)
            try:
                user = User.objects.get(username__exact=username)
            except User.DoesNotExist:
                break
            i += 1
        return username

    def create_user_from_openid(self, openid_response):
        details = self._extract_user_details(openid_response)
        required_attrs = getattr(settings, 'OPENID_SREG_REQUIRED_FIELDS', [])
        if getattr(settings, 'OPENID_STRICT_USERNAMES', False):
            required_attrs.append('nickname')

        for required_attr in required_attrs:
            if required_attr not in details or not details[required_attr]:
                raise RequiredAttributeNotReturned(
                    "An attribute required for logging in was not "
                    "returned ({0}).".format(required_attr))

        nickname = self._get_preferred_username(details['nickname'],
            details['email'])
        email = details['email'] or ''

        username = self._get_available_username(nickname,
            openid_response.identity_url)

        user = User.objects.create_user(username, email, password=None)
        self.associate_openid(user, openid_response)
        self.update_user_details(user, details, openid_response)

        return user

    def associate_openid(self, user, openid_response):
        """Associate an OpenID with a user account."""
        # Check to see if this OpenID has already been claimed.
        try:
            user_openid = UserOpenID.objects.get(
                claimed_id__exact=openid_response.identity_url)
        except UserOpenID.DoesNotExist:
            user_openid = UserOpenID(
                user=user,
                claimed_id=openid_response.identity_url,
                display_id=openid_response.endpoint.getDisplayIdentifier())
            user_openid.save()
        else:
            if user_openid.user != user:
                raise IdentityAlreadyClaimed(
                    "The identity %s has already been claimed"
                    % openid_response.identity_url)

        return user_openid

    def update_user_details(self, user, details, openid_response):
        updated = False
        if details['first_name']:
            user.first_name = details['first_name'][:30]
            updated = True
        if details['last_name']:
            user.last_name = details['last_name'][:30]
            updated = True
        if details['email']:
            user.email = details['email']
            updated = True
        if getattr(settings, 'OPENID_FOLLOW_RENAMES', False):
            user.username = self._get_available_username(details['nickname'], openid_response.identity_url)
            updated = True

        if updated:
            user.save()

    def update_groups_from_teams(self, user, teams_response):
        teams_mapping_auto = getattr(settings, 'OPENID_LAUNCHPAD_TEAMS_MAPPING_AUTO', False)
        teams_mapping_auto_blacklist = getattr(settings, 'OPENID_LAUNCHPAD_TEAMS_MAPPING_AUTO_BLACKLIST', [])
        teams_mapping = getattr(settings, 'OPENID_LAUNCHPAD_TEAMS_MAPPING', {})
        if teams_mapping_auto:
            #ignore teams_mapping. use all django-groups
            teams_mapping = dict()
            all_groups = Group.objects.exclude(name__in=teams_mapping_auto_blacklist)
            for group in all_groups:
                teams_mapping[group.name] = group.name

        if len(teams_mapping) == 0:
            return

        current_groups = set(user.groups.filter(
                name__in=teams_mapping.values()))
        desired_groups = set(Group.objects.filter(
                name__in=[teams_mapping[lp_team]
                          for lp_team in teams_response.is_member
                          if lp_team in teams_mapping]))
        for group in current_groups - desired_groups:
            user.groups.remove(group)
        for group in desired_groups - current_groups:
            user.groups.add(group)

    def update_staff_status_from_teams(self, user, teams_response):
        if not hasattr(settings, 'OPENID_LAUNCHPAD_STAFF_TEAMS'):
            return

        staff_teams = getattr(settings, 'OPENID_LAUNCHPAD_STAFF_TEAMS', [])
        user.is_staff = False

        for lp_team in teams_response.is_member:
            if lp_team in staff_teams:
                user.is_staff = True
                break

        user.save()


text:
<?php

namespace lithium\tests\mocks\data\model;

class MockImage extends \lithium\tests\mocks\data\MockBase {

	public $belongsTo = array(
		'Gallery' => array('to' => 'lithium\tests\mocks\data\model\MockGallery')
	);

	public $hasMany = array(
		'ImageTag' => array('to' => 'lithium\tests\mocks\data\model\MockImageTag')
	);

	public static $connection = null;

	protected $_meta = array(
		'key' => 'id',
		'name' => 'Image',
		'source' => 'mock_image',
		'connection' => false
	);

	protected $_schema = array(
		'id' => array('type' => 'integer'),
		'title' => array('type' => 'string'),
		'image' => array('type' => 'string'),
		'gallery_id' => array('type' => 'integer')
	);
}

?>


text:
var resourceList = [

{ id : "robotFolder/arm_hand", src:"res/robotFolder/arm_hand.png"},
{ id : "robotFolder/arm_lower", src:"res/robotFolder/arm_lower.png"},
{ id : "robotFolder/arm_upper", src:"res/robotFolder/arm_upper.png"},
{ id : "robotFolder/head", src:"res/robotFolder/head.png"},
{ id : "robotFolder/leg_foot", src:"res/robotFolder/leg_foot.png"},
{ id : "robotFolder/leg_lower", src:"res/robotFolder/leg_lower.png"},
{ id : "robotFolder/leg_upper", src:"res/robotFolder/leg_upper.png"},
{ id : "robotFolder/lowerbody", src:"res/robotFolder/lowerbody.png"},
{ id : "robotFolder/upperbody", src:"res/robotFolder/upperbody.png"},

{
    id: "signIn",
    type: "fn",
    fn: function(loader, queue) {
        var Me = this;
        this.finished = true;
    },
    update: function() {

    },
    isFinished: function() {
        return this.finished;
    }
}, ];

var audioList = [

];


text:
""" error handling features, just a way of displaying errors
"""

import sys

import py

from rpython.flowspace.model import Variable
from rpython.rlib import jit

SHOW_TRACEBACK = False
SHOW_ANNOTATIONS = True
SHOW_DEFAULT_LINES_OF_CODE = 0

def source_lines1(graph, block, operindex=None, offset=None, long=False,
    show_lines_of_code=SHOW_DEFAULT_LINES_OF_CODE):
    if block is not None:
        if block is graph.returnblock:
            return ['<return block>']
    try:
        source = graph.source
    except AttributeError:
        return ['no source!']
    else:
        graph_lines = source.split("\n")
        if offset is not None:
            linestart = offset2lineno(graph.func.func_code, offset)
            linerange = (linestart, linestart)
            here = None
        else:
            if block is None or not block.operations:
                return []

            def toline(operindex):
                return offset2lineno(graph.func.func_code, block.operations[operindex].offset)
            if operindex is None:
                linerange = (toline(0), toline(-1))
                if not long:
                    return ['?']
                here = None
            else:
                operline = toline(operindex)
                if long:
                    linerange = (toline(0), toline(-1))
                    here = operline
                else:
                    linerange = (operline, operline)
                    here = None
        lines = ["Happened at file %s line %d" % (graph.filename, here or linerange[0]), ""]
        for n in range(max(0, linerange[0]-show_lines_of_code),
            min(linerange[1]+1+show_lines_of_code, len(graph_lines)+graph.startline)):
            if n == here:
                prefix = '==> '
            else:
                prefix = '    '
            lines.append(prefix + graph_lines[n-graph.startline])
        lines.append("")
        return lines

def source_lines(graph, *args, **kwds):
    lines = source_lines1(graph, *args, **kwds)
    return ['In %r:' % (graph,)] + lines

def gather_error(annotator, graph, block, operindex):
    msg = [""]

    if operindex is not None:
        oper = block.operations[operindex]
        if oper.opname == 'simple_call':
            format_simple_call(annotator, oper, msg)
    else:
        oper = None
    msg.append("    %s\n" % str(oper))
    msg += source_lines(graph, block, operindex, long=True)
    if oper is not None:
        if SHOW_ANNOTATIONS:
            msg += format_annotations(annotator, oper)
            msg += ['']
    return "\n".join(msg)

def format_annotations(annotator, oper):
    msg = []
    msg.append("Known variable annotations:")
    for arg in oper.args + [oper.result]:
        if isinstance(arg, Variable):
            try:
                msg.append(" " + str(arg) + " = " + str(annotator.binding(arg)))
            except KeyError:
                pass
    return msg

def format_blocked_annotation_error(annotator, blocked_blocks):
    text = []
    for block, (graph, index) in blocked_blocks.items():
        text.append("Blocked block -- operation cannot succeed")
        text.append(gather_error(annotator, graph, block, index))
    return '\n'.join(text)

def format_simple_call(annotator, oper, msg):
    msg.append("Occurred processing the following simple_call:")
    try:
        descs = annotator.binding(oper.args[0]).descriptions
    except (KeyError, AttributeError) as e:
        msg.append("      (%s getting at the binding!)" % (
            e.__class__.__name__,))
        return
    for desc in list(descs):
        func = desc.pyobj
        if func is None:
            r = repr(desc)
        else:
            try:
                if isinstance(func, type):
                    func_name = "%s.__init__" % func.__name__
                    func = func.__init__.im_func
                else:
                    func_name = func.func_name
                r = "function %s <%s, line %s>" % (func_name,
                       func.func_code.co_filename, func.func_code.co_firstlineno)
            except (AttributeError, TypeError):
                r = repr(desc)
        msg.append("  %s returning" % (r,))
        msg.append("")

def debug(drv, use_pdb=True):
    # XXX unify some code with rpython.translator.goal.translate
    from rpython.translator.tool.pdbplus import PdbPlusShow
    from rpython.translator.driver import log
    t = drv.translator

    class options:
        huge = 100

    tb = None
    import traceback
    errmsg = ["Error:\n"]
    exc, val, tb = sys.exc_info()

    errmsg.extend([" %s" % line for line in traceback.format_exception(exc, val, [])])
    block = getattr(val, '__annotator_block', None)
    if block:
        class FileLike:
            def write(self, s):
                errmsg.append(" %s" % s)
        errmsg.append("Processing block:\n")
        t.about(block, FileLike())
    log.ERROR(''.join(errmsg))

    log.event("start debugger...")

    if use_pdb:
        pdb_plus_show = PdbPlusShow(t)
        pdb_plus_show.start(tb)

@jit.elidable
def offset2lineno(c, stopat):
    # even position in lnotab denote byte increments, odd line increments.
    # see dis.findlinestarts in the python std. library for more details
    tab = c.co_lnotab
    line = c.co_firstlineno
    addr = 0
    for i in range(0, len(tab), 2):
        addr = addr + ord(tab[i])
        if addr > stopat:
            break
        line = line + ord(tab[i+1])
    return line


text:
require 'casserver/authenticators/base'

# Dummy authenticator used for testing.
# Accepts any username as valid as long as the password is "testpassword"; otherwise authentication fails.
# Raises an AuthenticationError when username is "do_error" (this is useful to test the Exception
# handling functionality).
class CASServer::Authenticators::Test < CASServer::Authenticators::Base
  def validate(credentials)
    read_standard_credentials(credentials)

    raise CASServer::AuthenticatorError, "Username is 'do_error'!" if @username == 'do_error'

    @extra_attributes[:test_utf_string] = "Ютф"
    @extra_attributes[:test_numeric] = 123.45
    @extra_attributes[:test_serialized] = {:foo => 'bar', :alpha => [1,2,3]}

    valid_password = options[:password] || "testpassword"

    return @password == valid_password
  end
end


text:
package org.apache.flink.table.planner.plan.stream.sql

import org.apache.flink.table.api.TableException
import org.apache.flink.table.planner.plan.utils.JavaUserDefinedAggFunctions.WeightedAvgWithMerge
import org.apache.flink.table.planner.utils.TableTestBase
import org.junit.Test

/**
 * Tests for window rank.
 */
class WindowRankTest extends TableTestBase {

  private val util = streamTestUtil()
  util.addTemporarySystemFunction("weightedAvg", classOf[WeightedAvgWithMerge])
  util.tableEnv.executeSql(
    s"""
       |CREATE TABLE MyTable (
       |  a INT,
       |  b BIGINT,
       |  c STRING NOT NULL,
       |  d DECIMAL(10, 3),
       |  e BIGINT,
       |  rowtime TIMESTAMP(3),
       |  proctime as PROCTIME(),
       |  WATERMARK FOR rowtime AS rowtime - INTERVAL '1' SECOND
       |) with (
       |  'connector' = 'values'
       |)
       |""".stripMargin)

  // ----------------------------------------------------------------------------------------
  // Tests for queries Rank on window TVF, Current does not support merge Window TVF into
  // WindowRank.
  // ----------------------------------------------------------------------------------------

  @Test
  def testCantMergeWindowTVF_Tumble(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, b, c, d, e
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY b DESC) as rownum
        |FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testCantMergeWindowTVF_TumbleOnProctime(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, b, c, d, e
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY b DESC) as rownum
        |FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(proctime), INTERVAL '15' MINUTE))
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testCantMergeWindowTVF_Hop(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, b, c, d, e
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY b DESC) as rownum
        |FROM TABLE(
        |  HOP(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '5' MINUTE, INTERVAL '10' MINUTE))
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testCantMergeWindowTVF_HopOnProctime(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, b, c, d, e
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY b DESC) as rownum
        |FROM TABLE(
        |  HOP(TABLE MyTable, DESCRIPTOR(proctime), INTERVAL '5' MINUTE, INTERVAL '10' MINUTE))
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testCantMergeWindowTVF_Cumulate(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, b, c, d, e
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY b DESC) as rownum
        |FROM TABLE(
        |  CUMULATE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '10' MINUTE, INTERVAL '1' HOUR))
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testCantMergeWindowTVF_CumulateOnProctime(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, b, c, d, e
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY b DESC) as rownum
        |FROM TABLE(
        |  CUMULATE(TABLE MyTable, DESCRIPTOR(proctime), INTERVAL '10' MINUTE, INTERVAL '1' HOUR))
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  // ----------------------------------------------------------------------------------------
  // Tests for queries Rank on window Aggregate
  // ----------------------------------------------------------------------------------------

  @Test
  def testOnTumbleWindowAggregate(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testOnTumbleWindowAggregateOnProctime(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(proctime), INTERVAL '15' MINUTE))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin

    thrown.expect(classOf[TableException])
    thrown.expectMessage("Processing time Window TopN is not supported yet.")
    util.verifyExplain(sql)
  }

  @Test
  def testOnHopWindowAggregate(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(
        |    HOP(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '5' MINUTE, INTERVAL '10' MINUTE))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testOnHopWindowAggregateOnProctime(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(
        |    HOP(TABLE MyTable, DESCRIPTOR(proctime), INTERVAL '5' MINUTE, INTERVAL '10' MINUTE))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin

    thrown.expect(classOf[TableException])
    thrown.expectMessage("Processing time Window TopN is not supported yet.")
    util.verifyExplain(sql)
  }

  @Test
  def testOnCumulateWindowAggregate(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(
        |     PARTITION BY window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(
        |    CUMULATE(
        |      TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '10' MINUTE, INTERVAL '1' HOUR))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testOnCumulateWindowAggregateOnProctime(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(
        |     PARTITION BY a, window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(
        |    CUMULATE(
        |      TABLE MyTable, DESCRIPTOR(proctime), INTERVAL '10' MINUTE, INTERVAL '1' HOUR))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin

    thrown.expect(classOf[TableException])
    thrown.expectMessage("Processing time Window TopN is not supported yet.")
    util.verifyExplain(sql)
  }

  // ----------------------------------------------------------------------------------------
  // Tests for queries window rank could propagate time attribute
  // ----------------------------------------------------------------------------------------
  @Test
  def testTimeAttributePropagateForWindowRank(): Unit = {
    util.tableEnv.executeSql(
      """
        |CREATE VIEW tmp AS
        |SELECT window_time as rowtime, a, b, c, d, e
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY b DESC) as rownum
        |FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |)
        |WHERE rownum <= 3
      """.stripMargin)
    val sql =
      """
        |SELECT
        |   a,
        |   window_start,
        |   window_end,
        |   count(*),
        |   sum(d),
        |   max(d) filter (where b > 1000),
        |   weightedAvg(b, e) AS wAvg,
        |   count(distinct c) AS uv
        |FROM TABLE(TUMBLE(TABLE tmp, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |GROUP BY a, window_start, window_end
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testTimeAttributePropagateForWindowRank1(): Unit = {
    util.tableEnv.executeSql(
      """
        |CREATE VIEW tmp1 AS
        |SELECT window_time as rowtime, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |  SELECT *,
        |    ROW_NUMBER() OVER(PARTITION BY a, window_start, window_end ORDER BY cnt DESC) as rownum
        |  FROM (
        |    SELECT
        |      a,
        |      window_start,
        |      window_end,
        |      window_time,
        |      count(*) as cnt,
        |      sum(d) as sum_d,
        |      max(d) filter (where b > 1000) as max_d,
        |      weightedAvg(b, e) AS wAvg,
        |      count(distinct c) AS uv
        |    FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |    GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin)
    val sql =
      """
        |SELECT
        |   a,
        |   window_start,
        |   window_end,
        |   sum(cnt),
        |   sum(sum_d),
        |   max(max_d)
        |FROM TABLE(TUMBLE(TABLE tmp1, DESCRIPTOR(rowtime), INTERVAL '1' HOUR))
        |GROUP BY a, window_start, window_end
      """.stripMargin
    util.verifyRelPlan(sql)
  }

  @Test
  def testRankFunction(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   RANK() OVER(PARTITION BY window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin

    thrown.expect(classOf[TableException])
    thrown.expectMessage(
      "RANK() function is not supported on Window TopN currently, only ROW_NUMBER() is supported.")
    util.verifyExplain(sql)
  }

  @Test
  def testDenseRankFunction(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   DENSE_RANK() OVER(PARTITION BY window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= 3
      """.stripMargin

    thrown.expect(classOf[TableException])
    thrown.expectMessage(
      "DENSE_RANK() function is not supported on Window TopN currently, " +
        "only ROW_NUMBER() is supported.")
    util.verifyExplain(sql)
  }

  @Test
  def testVariableRankRange(): Unit = {
    val sql =
      """
        |SELECT window_start, window_end, window_time, a, cnt, sum_d, max_d, wAvg, uv
        |FROM (
        |SELECT *,
        |   ROW_NUMBER() OVER(PARTITION BY window_start, window_end ORDER BY cnt DESC) as rownum
        |FROM (
        |  SELECT
        |    a,
        |    window_start,
        |    window_end,
        |    window_time,
        |    count(*) as cnt,
        |    sum(d) as sum_d,
        |    max(d) filter (where b > 1000) as max_d,
        |    max(b) as max_b,
        |    weightedAvg(b, e) AS wAvg,
        |    count(distinct c) AS uv
        |  FROM TABLE(TUMBLE(TABLE MyTable, DESCRIPTOR(rowtime), INTERVAL '15' MINUTE))
        |  GROUP BY a, window_start, window_end, window_time
        |  )
        |)
        |WHERE rownum <= max_b
      """.stripMargin

    thrown.expect(classOf[TableException])
    thrown.expectMessage("Rank strategy rankEnd=max_b is not supported on window rank currently.")
    util.verifyExplain(sql)
  }
}


text:
$LOAD_PATH.unshift(File.expand_path("../../../lib", __FILE__))
$LOAD_PATH.unshift(File.expand_path("../../../test", __FILE__))
require "thin"
require "benchmark"
require "benchmark/ips"
require "benchmark/memory"
require "semian"
require "semian/net_http"
require "toxiproxy"
require "yaml"
require "byebug"
require "minitest"

class LRUBenchmarker
  def run_ips_benchmark
    Benchmark.ips do |x|
      [500, 1000, 2500, 5000].each do |nb_resoures|
        x.report("#{nb_resoures} resources ") { create_resources(nb_resoures) }
      end
    end
  end

  def run_memory_benchmark
    Benchmark.memory do |x|
      [500, 1000].each do |nb_resoures|
        x.report("Memory usage for #{nb_resoures} resources ") { create_resources(nb_resoures) }
      end
    end
  end

  private

  def create_resources(number_of_resources)
    reset_semian_resource
    number_of_resources.times do |i|
      create_request(i)
    end
  end

  def create_request(i)
    # Creates a new resource and will randomly
    # make it a success or a failure
    random = rand(1...100)
    if random >= 0 && random <= 50
      Semian.register("testing_#{i}", bulkhead: true, tickets: 1, error_threshold: 2, error_timeout: 5,
        success_threshold: 1)
    else
      Semian.register("testing_#{i}", bulkhead: false, tickets: 1, error_threshold: 2, error_timeout: 5,
        success_threshold: 1)
    end
  end

  def reset_semian_resource
    Semian.reset!
  end
end

benchmarker = LRUBenchmarker.new
benchmarker.run_ips_benchmark
benchmarker.run_memory_benchmark


text:
<?php

final class PHUIFormIconSetControl
  extends AphrontFormControl {

  private $iconSet;

  public function setIconSet(PhabricatorIconSet $icon_set) {
    $this->iconSet = $icon_set;
    return $this;
  }

  public function getIconSet() {
    return $this->iconSet;
  }

  protected function getCustomControlClass() {
    return 'phui-form-iconset-control';
  }

  protected function renderInput() {
    Javelin::initBehavior('choose-control');

    $set = $this->getIconSet();

    $input_id = celerity_generate_unique_node_id();
    $display_id = celerity_generate_unique_node_id();

    $button = javelin_tag(
      'a',
      array(
        'href' => '#',
        'class' => 'button grey',
        'sigil' => 'phui-form-iconset-button',
      ),
      $set->getChooseButtonText());

    $icon = $set->getIcon($this->getValue());
    if ($icon) {
      $display = $set->renderIconForControl($icon);
    } else {
      $display = null;
    }

    $display_cell = phutil_tag(
      'td',
      array(
        'class' => 'phui-form-iconset-display-cell',
        'id' => $display_id,
      ),
      $display);

    $button_cell = phutil_tag(
      'td',
      array(
        'class' => 'phui-form-iconset-button-cell',
      ),
      $button);

    $row = phutil_tag(
      'tr',
      array(),
      array($display_cell, $button_cell));

    $layout = javelin_tag(
      'table',
      array(
        'class' => 'phui-form-iconset-table',
        'sigil' => 'phui-form-iconset',
        'meta' => array(
          'uri' => $set->getSelectURI(),
          'inputID' => $input_id,
          'displayID' => $display_id,
        ),
      ),
      $row);

    $hidden_input = phutil_tag(
      'input',
      array(
        'type' => 'hidden',
        'name' => $this->getName(),
        'value' => $this->getValue(),
        'id' => $input_id,
      ));

    return array(
      $hidden_input,
      $layout,
    );
  }

}


text:
@interface MTTableViewCell : UITableViewCell

//头像
@property (weak, nonatomic) IBOutlet UIImageView *imgVHead;
//昵称
@property (weak, nonatomic) IBOutlet UILabel *lblName;
//发布时间图标
@property (weak, nonatomic) IBOutlet UIImageView *imgVPushTime;
//发布时间
@property (weak, nonatomic) IBOutlet UILabel *lblPushTime;
//设备图标
@property (weak, nonatomic) IBOutlet UIImageView *imgVDevice;
//设备
@property (weak, nonatomic) IBOutlet UILabel *lblDevice;
//内容
@property (weak, nonatomic) IBOutlet UILabel *lblContent;
//点赞个数
@property (weak, nonatomic) IBOutlet UILabel *lblLikeCount;
//评论图标
@property (weak, nonatomic) IBOutlet UIImageView *imgVComment;
//评论个数
@property (weak, nonatomic) IBOutlet UILabel *lblCommentCount;
//点赞按钮
@property (weak, nonatomic) IBOutlet UIButton *btnLike;
//缩略图
@property (weak, nonatomic) IBOutlet UIImageView *imgVSmall;
//分割线
@property (weak, nonatomic) IBOutlet UILabel *lblCutLines;
//原图
@property(nonatomic,strong)UIImageView * imgVBig;

//内容区高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentHLayout;

//图片高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgHLayout;
//图片宽度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgWLayout;

//内容与图片高度
@property(nonatomic,assign)CGFloat tempH;

//设置内容方法
-(void)setCell:(TweetListXmlModel *)tweetListModel;

//设置内容区高度
-(CGFloat)getContentH;

@end


text:
struct CadPt2;
struct CadPt3;

bool Verify(const CadPt3 &before, float radians, const CadPt3 &after);
bool Verify(const std::vector<CadPt3> &input, float angle, const std::vector<CadPt3> &output);
bool Verify(const std::vector<float> &matrix);
bool Verify(const CadPt2 &pt, float width, float extent, bool inside);
bool Verify(std::vector<std::pair<int, int>> &duplicates, size_t expected);


text:
<title>strip - GNU Binary Utilities</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="GNU Binary Utilities">
<meta name="generator" content="makeinfo 4.7">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="strings.html#strings" title="strings">
<link rel="next" href="c_002b_002bfilt.html#c_002b_002bfilt" title="c++filt">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: c++filt,
Previous: strings,
Up: Top

8 strip

     strip [-F <var>bfdname</var> |--target=<var>bfdname</var>]
           [-I <var>bfdname</var> |--input-target=<var>bfdname</var>]
           [-O <var>bfdname</var> |--output-target=<var>bfdname</var>]
           [-s|--strip-all]
           [-S|-g|-d|--strip-debug]
           [-K <var>symbolname</var> |--keep-symbol=<var>symbolname</var>]
           [-N <var>symbolname</var> |--strip-symbol=<var>symbolname</var>]
           [-w|--wildcard]
           [-x|--discard-all] [-X |--discard-locals]
           [-R <var>sectionname</var> |--remove-section=<var>sectionname</var>]
           [-o <var>file</var>] [-p|--preserve-dates]
           [--keep-file-symbols]
           [--only-keep-debug]
           [-v |--verbose] [-V|--version]
           [--help] [--info]
           <var>objfile</var>...

gnu strip discards all symbols from object files
<var>objfile</var>.  The list of object files may include archives.
At least one object file must be given.

strip modifies the files named in its argument,
rather than writing modified copies under different names.

-F <var>bfdname</var>
--target=<var>bfdname</var>
Treat the original <var>objfile</var> as a file with the object
code format <var>bfdname</var>, and rewrite it in the same format.
See Target Selection, for more information.

--help
Show a summary of the options to strip and exit.

--info
Display a list showing all architectures and object formats available.

-I <var>bfdname</var>
--input-target=<var>bfdname</var>
Treat the original <var>objfile</var> as a file with the object
code format <var>bfdname</var>.
See Target Selection, for more information.

-O <var>bfdname</var>
--output-target=<var>bfdname</var>
Replace <var>objfile</var> with a file in the output format <var>bfdname</var>.
See Target Selection, for more information.

-R <var>sectionname</var>
--remove-section=<var>sectionname</var>
Remove any section named <var>sectionname</var> from the output file.  This
option may be given more than once.  Note that using this option
inappropriately may make the output file unusable.

-s
--strip-all
Remove all symbols.

-g
-S
-d
--strip-debug
Remove debugging symbols only.

--strip-unneeded
Remove all symbols that are not needed for relocation processing.

-K <var>symbolname</var>
--keep-symbol=<var>symbolname</var>
When stripping symbols, keep symbol <var>symbolname</var> even if it would
normally be stripped.  This option may be given more than once.

-N <var>symbolname</var>
--strip-symbol=<var>symbolname</var>
Remove symbol <var>symbolname</var> from the source file. This option may be
given more than once, and may be combined with strip options other than
-K.

-o <var>file</var>
Put the stripped output in <var>file</var>, rather than replacing the
existing file.  When this argument is used, only one <var>objfile</var>
argument may be specified.

-p
--preserve-dates
Preserve the access and modification dates of the file.

-w
--wildcard
Permit regular expressions in <var>symbolname</var>s used in other command
line options.  The question mark (?), asterisk (*), backslash (\) and
square brackets ([]) operators can be used anywhere in the symbol
name.  If the first character of the symbol name is the exclamation
point (!) then the sense of the switch is reversed for that symbol.
For example:

            -w -K !foo -K fo*

would cause strip to only keep symbols that start with the letters
“fo”, but to discard the symbol “foo”.

-x
--discard-all
Remove non-global symbols.

-X
--discard-locals
Remove compiler-generated local symbols.
(These usually start with L or ..)

--keep-file-symbols
When stripping a file, perhaps with --strip-debug or
--strip-unneeded, retain any symbols specifying source file names,
which would otherwise get stripped.

--only-keep-debug
Strip a file, removing contents of any sections that would not be
stripped by --strip-debug and leaving the debugging sections
intact.  In ELF files, this preserves all note sections in the output.

The intention is that this option will be used in conjunction with
--add-gnu-debuglink to create a two part executable.  One a
stripped binary which will occupy less space in RAM and in a
distribution and the second a debugging information file which is only
needed if debugging abilities are required.  The suggested procedure
to create these files is as follows:

Link the executable as normal.  Assuming that is is called
foo then...

Run objcopy --only-keep-debug foo foo.dbg to
create a file containing the debugging info.

Run objcopy --strip-debug foo to create a
stripped executable.

Run objcopy --add-gnu-debuglink=foo.dbg foo
to add a link to the debugging info into the stripped executable.

Note—the choice of .dbg as an extension for the debug info
file is arbitrary.  Also the --only-keep-debug step is
optional.  You could instead do this:

Link the executable as normal.

Copy foo to foo.full

Run strip --strip-debug foo

Run objcopy --add-gnu-debuglink=foo.full foo

i.e., the file pointed to by the --add-gnu-debuglink can be the
full executable.  It does not have to be a file created by the
--only-keep-debug switch.

Note—this switch is only intended for use on fully linked files.  It
does not make sense to use it on object files where the debugging
information may be incomplete.  Besides the gnu_debuglink feature
currently only supports the presence of one filename containing
debugging information, not multiple filenames on a one-per-object-file
basis.

-V
--version
Show the version number for strip.

-v
--verbose
Verbose output: list all object files modified.  In the case of
archives, strip -v lists all members of the archive.


text:
"use strict";

var error = require("./../../error");
var Util = require("./../../util");

var LocalSearch = module.exports = {
    LocalSearch : function(params, callback){
        var self           = this;
        self.name          = "LocalSearch";
        self.config        = self.__proto__.router[self.name];
        self.requestClient = self.__proto__.requestClient;

        if( self.config.defaults ){
            Util.extend(params, self.config.defaults, true);
        }

        self.options = {
            host : self.config.host,
            port : self.config.protocol == "http" ? 80 : 443,
            path : self.config.path + Util.makeParams(params),
            method : self.config.method
        };

        self.requestClient(self.config, self.options, callback);
    }
};


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">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Grayscale - Start Bootstrap Theme</title>

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

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

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">

Be accountable

You can achieve more when you are not alone.
Get a buddy today.

            <form action="//incented.us8.list-manage.com/subscribe/post?u=d11277dd0c6bb9114228d00e3&id=79922a588c" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Sign up to get matched with a buddy

* indicates required

                    Email Address  *

                    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

                    First Name
                    <input type="text" value="" name="FNAME" class="" id="mce-FNAME">

                    Last Name
                    <input type="text" value="" name="LNAME" class="" id="mce-LNAME">

<input type="text" name="b_d11277dd0c6bb9114228d00e3_79922a588c" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

            </form>


text:
#ifndef __ETHERCAT_H__
#define __ETHERCAT_H__

#ifdef USE_ETHERCAT

#include "setup.h"

#define EC_WATCHDOG_US 5000		//Signal an EC error if no PDO activity for this period
#define EC_SYS_TIME_ADDR 0x0910   //RJK edit for DC
#define EC_LATCH0_POS_EDG_ADDR 0x09B0
#define EC_LATCH1_POS_EDG_ADDR 0x09C0

int step_ethercat(void);
void setup_ethercat(void);
int eeprom_loaded(void);
void setup_spi(void);

extern unsigned long long dc_timestamp;  //RJK edit for DC

extern int ec_debug[];
extern int ec_flags[];
extern  int ec_wd_expired;
extern long ec_wd_timestamp;

//Move ActX1 to PDOV2 (smaller packet size)

#if defined PWR_0_2 || defined PWR_0_3
typedef M3PwrPdoV1Cmd ec_cmd_t;
typedef M3PwrPdoV1Status ec_stat_t;
#define PDO_COMMAND_SIZE MAX_PDO_ENTRY_SIZE*2
#define PDO_STATUS_SIZE MAX_PDO_ENTRY_SIZE*2
#define NUM_DBG_CH 1
#endif

#if defined PWR_0_4 || defined PWR_0_5
typedef M3PwrPdoV2Cmd ec_cmd_t;
typedef M3PwrPdoV2Status ec_stat_t;
#define PDO_COMMAND_SIZE MAX_PDO_ENTRY_SIZE*2
#define PDO_STATUS_SIZE MAX_PDO_ENTRY_SIZE*2
#define NUM_DBG_CH 1
#endif

//typedef M3AhFingerX1PdoV0Cmd ec_cmd_t;
//typedef M3AhFingerX1PdoV0Status ec_stat_t;
//#define PDO_COMMAND_SIZE MAX_PDO_ENTRY_SIZE*2
//#define PDO_STATUS_SIZE MAX_PDO_ENTRY_SIZE*2
//#define NUM_DBG_CH 1
//#endif

/////////////////////////////////////////////////////////////////
extern ec_cmd_t  ec_cmd;
extern ec_stat_t   ec_stat;
/////////////////////////////////////////////////////////////////
extern unsigned char pdo_cmd[];

#endif
#endif


text:
// Tests that passing a bad shape to RNG's output parameter causes a validation
// failure rather than causing a crash.

#include <memory>

#include "tensorflow/compiler/xla/client/computation.h"
#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {
namespace {

class BadRngShapeValidationTest : public ClientLibraryTestBase {};

TEST_F(BadRngShapeValidationTest, DefaultConstructedShapeCreatesError) {
  ComputationBuilder builder(client_, TestName());
  auto zero = builder.ConstantR0<float>(0.0);
  auto one = builder.ConstantR0<float>(1.0);
  Shape default_constructed;
  builder.RngUniform(zero, one, default_constructed);

  StatusOr<Computation> computation = builder.Build();
  EXPECT_FALSE(computation.ok());
  LOG(INFO) << "status received: " << computation.status();
  EXPECT_THAT(computation.status().error_message(),
              ::testing::HasSubstr("shape has invalid"));
}

TEST_F(BadRngShapeValidationTest, ShapeWithoutLayoutIsOk) {
  ComputationBuilder builder(client_, TestName());
  auto zero = builder.ConstantR0<float>(0.0);
  auto one = builder.ConstantR0<float>(1.0);
  Shape sans_layout;
  sans_layout.set_element_type(F32);
  sans_layout.add_dimensions(1);

  builder.RngUniform(zero, one, sans_layout);

  StatusOr<Computation> computation = builder.Build();
  ASSERT_TRUE(computation.ok());
  LOG(INFO) << computation.status();
}

}  // namespace
}  // namespace xla

int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendDebugOptionsFlags(&flag_list);
  xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
  if (!parse_result) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }
  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }
  return RUN_ALL_TESTS();
}


text:
<?php

namespace Kordy\Ticketit\Requests;

use App\Http\Requests\Request;
use Auth;

class TicketBlinkRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        if (auth()->check()) {
            $user = Auth::user();
        }

        return [
        ];
    }
}


text:
from setuptools import setup

long_description = """\
Jupyjet is a IPyhton notebook extention which allows you to dynamically genrates python file / module from a notebook.

Code portions registered with %jet or %jet-init magics will be written and updated into a python file.
This approach make possible to easily separate a notebook into several notebooks and bind them.
"""

setup(
    name='jupyjet',
    url='https://github.com/pelodelfuego/jupyjet',
    author='Clément CREPY',
    author_email='clement.crepy@gmail.com',
    version='0.3.0',
    py_modules=['jupyjet'],
    license='MIT',
    description='jupyter extention to generate python modules',
    long_description=long_description,
    keywords = ['jupyter', 'notebook', 'module', 'jupyjet'],
    install_requires = ['IPython>=0.13',
                        'codegen>=1.0',
                        'psutil>=5.1.3',
                        'requests>=2.4.3'],
)


text:
layout: page
title: Mccann Motors Executive Retreat
date: 2016-05-24
author: Diane Brock
tags: weekly links, java
status: published
summary: Ut commodo dignissim purus, eu.
banner: images/banner/people.jpg
booking:
  startDate: 10/08/2019
  endDate: 10/11/2019
  ctyhocn: WASWRHX
  groupCode: MMER
published: true
---
Vivamus tincidunt faucibus leo vestibulum fermentum. Fusce fermentum tincidunt sodales. Aliquam condimentum metus id purus gravida bibendum. Donec sit amet ligula a elit euismod ultricies ac vitae metus. Quisque fermentum ac dolor sed maximus. Donec ac sem ac enim pharetra cursus sed quis massa. Donec porttitor lectus scelerisque blandit congue. Ut tempus nisi quam, id tincidunt enim ornare sit amet. Vivamus maximus lorem vel ante auctor, accumsan mattis nibh ultricies. Aenean mi enim, facilisis porttitor eleifend eget, ultrices quis leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

* Duis semper ex eu mauris fringilla sollicitudin
* Nam non tellus placerat, eleifend nisi ac, ornare nunc.

Praesent id ex porta, gravida urna sed, accumsan quam. Vivamus eget sapien nec odio tincidunt sollicitudin ut ut erat. Nulla auctor ut nulla vitae euismod. Donec nibh arcu, commodo non facilisis sit amet, porta vel purus. Vestibulum vestibulum consequat nisl, vitae aliquam nunc varius sagittis. Sed tincidunt ultricies erat, ut tristique urna eleifend ut. Fusce vulputate porttitor orci, id sollicitudin metus interdum a. Nulla risus nunc, tristique sed lorem vel, scelerisque egestas turpis. Cras eleifend non dui in tincidunt. Duis iaculis risus vel nisl volutpat, a aliquet ligula fermentum. Nullam semper urna placerat nibh viverra, vel aliquam ante fermentum. Cras non dui eget ante sollicitudin egestas vitae nec erat.


text:
package com.streamsets.pipeline.stage.origin.jms;

import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.streamsets.pipeline.api.OnRecordError;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.api.service.dataformats.DataFormatParserService;
import com.streamsets.pipeline.lib.jms.config.InitialContextFactory;
import com.streamsets.pipeline.lib.jms.config.connection.JmsConnection;
import com.streamsets.pipeline.sdk.SourceRunner;
import com.streamsets.pipeline.sdk.StageRunner;
import com.streamsets.pipeline.sdk.service.SdkJsonDataFormatParserService;
import com.streamsets.pipeline.stage.origin.lib.BasicConfig;
import com.streamsets.pipeline.stage.origin.lib.MessageConfig;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerPlugin;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.security.AuthenticationUser;
import org.apache.activemq.security.SimpleAuthenticationPlugin;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class TestJmsSource {
  private static final Logger LOG = LoggerFactory.getLogger(TestJmsSource.class);

  private final static String INITIAL_CONTEXT_FACTORY = "org.apache.activemq.jndi.ActiveMQInitialContextFactory";
  private final static String CONNECTION_FACTORY = "ConnectionFactory";
  private final static String BROKER_BIND_URL = "tcp://localhost:61516";
  private final static  String DESTINATION_NAME = "test";
  private final static  String USERNAME = "user";
  private final static String PASSWORD = "pass";
  // specific for dynamic queues on ActiveMq
  public static final String JNDI_PREFIX = "dynamicQueues/";
  private File baseDir;
  private File tmpDir;
  private File dataDir;
  private File passwordFile;

  private Connection connection;
  private BrokerService broker;
  private BasicConfig basicConfig;
  private MessageConfig messageConfig;
  private JmsSourceConfig jmsSourceConfig;

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Before
  public void setUp() throws Exception {
    baseDir = Files.createTempDir();
    tmpDir = new File(baseDir, "tmp");
    dataDir = new File(baseDir, "data");
    Assert.assertTrue(tmpDir.mkdir());
    passwordFile = new File(baseDir, "password");
    Files.write(PASSWORD.getBytes(StandardCharsets.UTF_8), passwordFile);

    broker = new BrokerService();

    broker.addConnector(BROKER_BIND_URL);
    broker.setTmpDataDirectory(tmpDir);
    broker.setDataDirectoryFile(dataDir);
    List<AuthenticationUser> users = Lists.newArrayList();
    users.add(new AuthenticationUser(USERNAME, PASSWORD, ""));
    SimpleAuthenticationPlugin authentication = new SimpleAuthenticationPlugin(users);
    broker.setPlugins(new BrokerPlugin[]{authentication});
    broker.start();

    basicConfig = new BasicConfig();
    messageConfig = new MessageConfig();
    jmsSourceConfig = new JmsSourceConfig();
    jmsSourceConfig.connection = new JmsConnection();
    jmsSourceConfig.connection.useCredentials = true;
    jmsSourceConfig.connection.username = () -> USERNAME;
    jmsSourceConfig.connection.password = () -> PASSWORD;
    jmsSourceConfig.connection.initialContextFactory = INITIAL_CONTEXT_FACTORY;
    jmsSourceConfig.connection.connectionFactory = CONNECTION_FACTORY;
    jmsSourceConfig.destinationName = JNDI_PREFIX + DESTINATION_NAME;
    jmsSourceConfig.connection.providerURL = BROKER_BIND_URL;
    // Create a connection and start
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
        PASSWORD, BROKER_BIND_URL);
    connection = factory.createConnection();
    connection.start();
  }

  @After
  public void tearDown() throws Exception {
    if ( connection != null){
      connection.close();
    }

    if (broker != null) {
      broker.stop();
    }
  }

  private void putQueue(List<String> events) throws Exception {
    Session session = connection.createSession(true,
      Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    int i = 0;
    for(String event : events) {
      int remainder = i++ % 2;
      if (remainder == 0) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
      } else  {
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(event.getBytes(StandardCharsets.UTF_8));
        producer.send(message);
      }
    }
    session.commit();
    session.close();
  }

  private SourceRunner createRunner() {
    JmsSource origin = new JmsSource(basicConfig, jmsSourceConfig,
      new JmsMessageConsumerFactoryImpl(), new JmsMessageConverterImpl(messageConfig),
      new InitialContextFactory());
    SourceRunner runner = new SourceRunner.Builder(JmsDSource.class, origin)
      .addOutputLane("lane")
      .setOnRecordError(OnRecordError.TO_ERROR)
      .addService(DataFormatParserService.class, new SdkJsonDataFormatParserService())
      .build();
    return runner;
  }

  private void runInit(String expectedError) {
    SourceRunner runner = createRunner();
    try {
      runner.runInit();
      Assert.fail();
    } catch (StageException ex) {
      Assert.assertTrue(Utils.format("Expected {} got: {}", expectedError, ex), ex.getMessage().
        contains(expectedError + " "));
    }
  }

  @Test
  public void testInvalidInitialContext() throws Exception {
    jmsSourceConfig.connection.initialContextFactory = "invalid";
    runInit("JMS_00");
  }

  @Test
  public void testInvalidConnectionFactory() throws Exception {
    jmsSourceConfig.connection.connectionFactory = "invalid";
    runInit("JMS_01");
  }

  @Test
  public void testInvalidDestination() throws Exception {
    jmsSourceConfig.destinationName = "invalid";
    runInit("JMS_05");
  }

  @Test
  public void testInvalidCreds() throws Exception {
    jmsSourceConfig.connection.username = () -> "invalid";
    runInit("JMS_04");
  }

  @Test
  public void testNoBroker() throws Exception {
    broker.stop();
    runInit("JMS_03");
  }

  @Test
  public void testSuccess() throws Exception {
    int numRecords = 20;
    List<String> expected = Lists.newArrayList();
    List<String> expectedErrors = Lists.newArrayList();
    for (int i = 0; i < numRecords; i++) {
      if (i == 0) {
        expectedErrors.add(String.format("{ \"i\" == %d}", i)); // invalid
      } else {
        expected.add(String.format("{ \"i\": %d}", i));
      }
    }
    putQueue(expectedErrors);
    putQueue(expected);
    SourceRunner runner = createRunner();
    runner.runInit();
    try {
      // Check that existing rows are loaded.
      StageRunner.Output output = runner.runProduce(null, numRecords * 2);
      Map<String, List<Record>> recordMap = output.getRecords();
      List<Record> parsedRecords = recordMap.get("lane");
      Assert.assertEquals(numRecords - 1, parsedRecords.size());
      List<String> actual = Lists.newArrayList();
      for (Record record : parsedRecords) {
        actual.add(String.format("{ \"i\": %d}", record.get("/i").getValueAsInteger()));
      }
      Assert.assertEquals(expected, actual);
    } finally {
      runner.runDestroy();
    }
  }

  @Test
  public void testBatchSizeSpecification() throws Exception {
    int numRecords = 10;
    List<String> expected = Lists.newArrayList();
    for (int i = 0; i < numRecords; i++) {
      expected.add(String.format("{ \"i\": %d}", i));
    }
    putQueue(expected);

    // Validate that we will pick the smaller number of maxBatchSize (global config) and in the component config
    SourceRunner runner = createRunner();
    runner.runInit();
    try {
      StageRunner.Output output = runner.runProduce(null, 2);
      Map<String, List<Record>> recordMap = output.getRecords();
      List<Record> parsedRecords = recordMap.get("lane");
      Assert.assertEquals(2, parsedRecords.size());
    } finally {
      runner.runDestroy();
    }
  }
}


text:
<?php

namespace App\Jobs;

use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

use Mail;
use Illuminate\Contracts\Mail\Mailer;
class AlertEmail extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    protected $user, $subject, $content;

    public function __construct($user, $subject, $content)
    {
        $this->user = $user;
        $this->subject = $subject;
        $this->content = $content;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        Mail::send('shared.email', ['content' => $this->content], function ($message) {
            //$message->from('us@example.com', 'Laravel');
            $message->to($this->user)->subject($this->subject);
        });
    }
}


text: <!DOCTYPE html>


text:
package io.github.hapjava.services.impl;

import io.github.hapjava.accessories.WindowAccessory;
import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithHoldPosition;
import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithName;
import io.github.hapjava.accessories.optionalcharacteristic.AccessoryWithObstructionDetection;
import io.github.hapjava.characteristics.impl.common.NameCharacteristic;
import io.github.hapjava.characteristics.impl.common.ObstructionDetectedCharacteristic;
import io.github.hapjava.characteristics.impl.windowcovering.CurrentPositionCharacteristic;
import io.github.hapjava.characteristics.impl.windowcovering.HoldPositionCharacteristic;
import io.github.hapjava.characteristics.impl.windowcovering.PositionStateCharacteristic;
import io.github.hapjava.characteristics.impl.windowcovering.TargetPositionCharacteristic;

/** This service describes a motorized window. */
public class WindowService extends AbstractServiceImpl {

  public WindowService(
      CurrentPositionCharacteristic currentPositionCharacteristic,
      TargetPositionCharacteristic targetPositionCharacteristic,
      PositionStateCharacteristic positionStateCharacteristic) {
    super("0000008B-0000-1000-8000-0026BB765291");
    addCharacteristic(currentPositionCharacteristic);
    addCharacteristic(targetPositionCharacteristic);
    addCharacteristic(positionStateCharacteristic);
  }

  public WindowService(WindowAccessory accessory) {
    this(
        new CurrentPositionCharacteristic(
            accessory::getCurrentPosition,
            accessory::subscribeCurrentPosition,
            accessory::unsubscribeCurrentPosition),
        new TargetPositionCharacteristic(
            accessory::getTargetPosition,
            accessory::setTargetPosition,
            accessory::subscribeTargetPosition,
            accessory::unsubscribeTargetPosition),
        new PositionStateCharacteristic(
            accessory::getPositionState,
            accessory::subscribePositionState,
            accessory::unsubscribePositionState));
    if (accessory instanceof AccessoryWithName) {
      addOptionalCharacteristic(new NameCharacteristic(((AccessoryWithName) accessory)::getName));
    }
    if (accessory instanceof AccessoryWithHoldPosition) {
      addOptionalCharacteristic(
          new HoldPositionCharacteristic(((AccessoryWithHoldPosition) accessory)::setHoldPosition));
    }

    if (accessory instanceof AccessoryWithObstructionDetection) {
      addOptionalCharacteristic(
          new ObstructionDetectedCharacteristic(
              ((AccessoryWithObstructionDetection) accessory)::getObstructionDetected,
              ((AccessoryWithObstructionDetection) accessory)::subscribeObstructionDetected,
              ((AccessoryWithObstructionDetection) accessory)::unsubscribeObstructionDetected));
    }
  }

  public void addOptionalCharacteristic(NameCharacteristic name) {
    addCharacteristic(name);
  }

  public void addOptionalCharacteristic(HoldPositionCharacteristic holdPositionCharacteristic) {
    addCharacteristic(holdPositionCharacteristic);
  }

  public void addOptionalCharacteristic(
      ObstructionDetectedCharacteristic obstructionDetectedCharacteristic) {
    addCharacteristic(obstructionDetectedCharacteristic);
  }
}


text:
import { Injectable } from '@angular/core';
//import { Http, RequestOptions, Headers, Response } from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DocumentModel } from './model';
import { DocumentParser } from './doc-parser'
import { DocumentSerializer } from './doc-serializer'
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

@Injectable()
export class ScraperDataService {

  private cache:Array<DocumentModel> = null;
  public selectedDoc:DocumentModel = null;

  constructor(private http: HttpClient) {
  }
  clearCache() {
    this.cache = null;
  }

  saveDocument(newDoc:DocumentModel): Observable<Response> {
    return this.http.post(
      'http://localhost:3000/documents',
      DocumentSerializer.serializeToJSON(newDoc),
      {
        headers : new HttpHeaders().set('Content-Type', 'application/json' )
      })
      .map( res => {
        //if(res.ok) {
          let updatedCache:Array<DocumentModel>;
          updatedCache = this.cache.map(doc => {
            if( doc.getId() === newDoc.getId()) {
              return newDoc;
            } else {
              return doc;
            }
          });
          this.cache = updatedCache;
        //} else {
        //  console.error("response error",res);
        //}
        return res;
      });
  }

  /**
   * Returns a list of document retrieved from the server
   * or from the internal cache.
   * @return {Observable} [description]
   */
  list():Observable<Array<DocumentModel>> {
    var enableCache = true;
    if( enableCache && this.cache ) {
      return new Observable(observer => {
        observer.next(this.cache);
      });
    } else {
      return this.http.get('http://localhost:3000/documents' )
      .map( json => {
        console.log(json);
        /*
        this.cache =  json.map( doc => {
          console.log("processing item : ", doc);
          return DocumentParser.parseJSONString(doc);
        });*/
        return this.cache;
      });
    }
  }
}


text:
layout: page
title: Black Excellent Enterprises Seminar
date: 2016-05-24
author: Amy Sexton
tags: weekly links, java
status: published
summary: Fusce sed mauris eget enim tincidunt ullamcorper.
banner: images/banner/office-01.jpg
booking:
  startDate: 12/16/2016
  endDate: 12/19/2016
  ctyhocn: BRSNEHX
  groupCode: BEES
published: true
---
Vivamus ante nunc, tristique sed arcu eget, feugiat accumsan magna. Ut felis magna, cursus quis aliquam vitae, tristique non risus. Donec vitae purus in metus euismod aliquam. Sed quis maximus nulla. Sed dignissim porttitor lorem rutrum dignissim. Quisque feugiat ipsum eget risus tempus suscipit. Ut semper libero turpis, nec finibus enim lobortis sit amet. Sed vulputate et nunc ac tincidunt. Sed vulputate vulputate sem, quis fringilla sapien placerat vitae. Phasellus eleifend feugiat magna a elementum. Nunc ut nisi ultrices, convallis tortor id, egestas orci. Quisque sodales lorem ac mi vulputate hendrerit. Nullam eget finibus velit. Duis fermentum quis quam laoreet tempor. Duis dolor arcu, laoreet et vestibulum a, convallis a odio. Pellentesque congue sagittis mauris non porttitor.
Praesent imperdiet eu turpis in elementum. Praesent dolor ante, accumsan eleifend lectus nec, bibendum feugiat nulla. Maecenas nec viverra urna. Curabitur tincidunt finibus nisi, a consequat eros tincidunt quis. Duis rutrum nulla nec leo mattis, a laoreet est mollis. Vivamus dapibus sagittis enim, id mollis ante condimentum ac. Integer eget placerat quam. Curabitur mauris dolor, tempus sed condimentum ac, tempus quis orci. Sed eu nulla ut sapien tincidunt pellentesque. Cras posuere fringilla varius.

* Suspendisse vel metus dapibus nibh mollis mattis sit amet quis massa
* Phasellus iaculis massa et sem aliquam rhoncus
* Donec porttitor velit ut risus pulvinar, vel tincidunt eros consequat
* Pellentesque elementum mi volutpat porta tristique.

Nam vitae pharetra libero. Ut lorem elit, cursus a metus eu, sollicitudin scelerisque est. Nunc interdum dignissim lacus, quis scelerisque augue finibus tincidunt. Vestibulum id nisi ipsum. Vestibulum in lorem eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam odio nunc, tincidunt auctor nisl sit amet, placerat faucibus purus. Nullam pulvinar, nisi sit amet viverra sodales, sem lacus commodo lorem, ut tempus nisi eros ac lectus. In facilisis mattis eros, sit amet pharetra diam porta quis.