text:
<?php

namespace Sonata\MediaBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $node = $treeBuilder->root('sonata_media');

        $node
            ->children()
                ->scalarNode('db_driver')->isRequired()->end()
                ->scalarNode('default_context')->isRequired()->end()
            ->end()
        ;

        $this->addContextsSection($node);
        $this->addCdnSection($node);
        $this->addFilesystemSection($node);
        $this->addProvidersSection($node);
        $this->addExtraSection($node);
        $this->addModelSection($node);
        $this->addBuzzSection($node);
        $this->addResizerSection($node);

        return $treeBuilder;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addContextsSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('contexts')
                    ->useAttributeAsKey('id')
                    ->prototype('array')
                        ->children()
                            ->arrayNode('download')
                                ->addDefaultsIfNotSet()
                                ->children()
                                    ->scalarNode('strategy')->defaultValue('sonata.media.security.superadmin_strategy')->end()
                                    ->scalarNode('mode')->defaultValue('http')->end()
                                ->end()
                            ->end()
                            ->arrayNode('providers')
                                ->prototype('scalar')
                                    ->defaultValue(array())
                                ->end()
                            ->end()
                            ->arrayNode('formats')
                                ->isRequired()
                                ->useAttributeAsKey('id')
                                ->prototype('array')
                                    ->children()
                                        ->scalarNode('width')->defaultValue(false)->end()
                                        ->scalarNode('height')->defaultValue(false)->end()
                                        ->scalarNode('quality')->defaultValue(80)->end()
                                        ->scalarNode('format')->defaultValue('jpg')->end()
                                        ->scalarNode('constraint')->defaultValue(true)->end()
                                    ->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addCdnSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('cdn')
                    ->children()
                        ->arrayNode('server')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('path')->defaultValue('/uploads/media')->end()
                            ->end()
                        ->end()

                        ->arrayNode('panther')
                            ->children()
                                ->scalarNode('path')->isRequired()->end() // http://domain.pantherportal.com/uploads/media
                                ->scalarNode('site_id')->isRequired()->end()
                                ->scalarNode('password')->isRequired()->end()
                                ->scalarNode('username')->isRequired()->end()
                            ->end()
                        ->end()

                        ->arrayNode('fallback')
                            ->children()
                                ->scalarNode('master')->isRequired()->end()
                                ->scalarNode('fallback')->isRequired()->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addFilesystemSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('filesystem')
                    ->children()
                        ->arrayNode('local')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('directory')->defaultValue('%kernel.root_dir%/../web/uploads/media')->end()
                                ->scalarNode('create')->defaultValue(false)->end()
                            ->end()
                        ->end()

                        ->arrayNode('ftp')
                            ->children()
                                ->scalarNode('directory')->isRequired()->end()
                                ->scalarNode('host')->isRequired()->end()
                                ->scalarNode('username')->isRequired()->end()
                                ->scalarNode('password')->isRequired()->end()
                                ->scalarNode('port')->defaultValue(21)->end()
                                ->scalarNode('passive')->defaultValue(false)->end()
                                ->scalarNode('create')->defaultValue(false)->end()
                                ->scalarNode('mode')->defaultValue(defined('FTP_BINARY') ? FTP_BINARY : false)->end()
                            ->end()
                        ->end()

                        ->arrayNode('s3')
                            ->children()
                                ->scalarNode('directory')->defaultValue('')->end()
                                ->scalarNode('bucket')->isRequired()->end()
                                ->scalarNode('accessKey')->isRequired()->end()
                                ->scalarNode('secretKey')->isRequired()->end()
                                ->scalarNode('create')->defaultValue(false)->end()
                                ->scalarNode('storage')
                                    ->defaultValue('standard')
                                    ->validate()
                                    ->ifNotInArray(array('standard', 'reduced'))
                                        ->thenInvalid('Invalid storage type - "%s"')
                                    ->end()
                                ->end()
                                ->scalarNode('cache_control')->defaultValue('')->end()
                                ->scalarNode('acl')
                                    ->defaultValue('public')
                                    ->validate()
                                    ->ifNotInArray(array('private', 'public', 'open', 'auth_read', 'owner_read', 'owner_full_control'))
                                        ->thenInvalid('Invalid acl permission - "%s"')
                                    ->end()
                                ->end()
                                ->scalarNode('encryption')
                                    ->defaultValue('')
                                    ->validate()
                                    ->ifNotInArray(array('aes256'))
                                        ->thenInvalid('Invalid encryption type - "%s"')
                                    ->end()
                                ->end()
                                ->arrayNode('meta')
                                    ->useAttributeAsKey('name')
                                    ->prototype('scalar')
                                    ->end()
                                ->end()
                            ->end()
                        ->end()

                        ->arrayNode('mogilefs')
                            ->children()
                                ->scalarNode('domain')->isRequired()->end()
                                ->arrayNode('hosts')
                                    ->prototype('scalar')->end()
                                    ->isRequired()
                                ->end()
                            ->end()
                        ->end()

                        ->arrayNode('replicate')
                            ->children()
                                ->scalarNode('master')->isRequired()->end()
                                ->scalarNode('slave')->isRequired()->end()
                            ->end()
                        ->end()

                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addProvidersSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('providers')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->arrayNode('file')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('service')->defaultValue('sonata.media.provider.file')->end()
                                ->scalarNode('resizer')->defaultValue(false)->end()
                                ->scalarNode('filesystem')->defaultValue('sonata.media.filesystem.local')->end()
                                ->scalarNode('cdn')->defaultValue('sonata.media.cdn.server')->end()
                                ->scalarNode('generator')->defaultValue('sonata.media.generator.default')->end()
                                ->scalarNode('thumbnail')->defaultValue('sonata.media.thumbnail.format')->end()
                                ->arrayNode('allowed_extensions')
                                    ->prototype('scalar')->end()
                                    ->defaultValue(array(
                                        'pdf', 'txt', 'rtf',
                                        'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
                                        'odt', 'odg', 'odp', 'ods', 'odc', 'odf', 'odb',
                                        'csv',
                                        'xml',
                                    ))
                                ->end()
                                ->arrayNode('allowed_mime_types')
                                    ->prototype('scalar')->end()
                                    ->defaultValue(array(
                                        'application/pdf', 'application/x-pdf', 'application/rtf', 'text/html', 'text/rtf', 'text/plain',
                                        'application/excel', 'application/msword', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint',
                                        'application/vnd.ms-powerpoint', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.graphics', 'application/vnd.oasis.opendocument.presentation', 'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.chart', 'application/vnd.oasis.opendocument.formula', 'application/vnd.oasis.opendocument.database', 'application/vnd.oasis.opendocument.image',
                                        'text/comma-separated-values',
                                        'text/xml', 'application/xml',
                                        'application/zip', // seems to be used for xlsx document ...
                                    ))
                                ->end()
                            ->end()
                        ->end()

                        ->arrayNode('image')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('service')->defaultValue('sonata.media.provider.image')->end()
                                ->scalarNode('resizer')->defaultValue('sonata.media.resizer.simple')->end()
                                ->scalarNode('filesystem')->defaultValue('sonata.media.filesystem.local')->end()
                                ->scalarNode('cdn')->defaultValue('sonata.media.cdn.server')->end()
                                ->scalarNode('generator')->defaultValue('sonata.media.generator.default')->end()
                                ->scalarNode('thumbnail')->defaultValue('sonata.media.thumbnail.format')->end()
                                ->scalarNode('adapter')->defaultValue('sonata.media.adapter.image.gd')->end()
                                ->arrayNode('allowed_extensions')
                                    ->prototype('scalar')->end()
                                    ->defaultValue(array('jpg', 'png', 'jpeg'))
                                ->end()
                                ->arrayNode('allowed_mime_types')
                                    ->prototype('scalar')->end()
                                    ->defaultValue(array(
                                        'image/pjpeg',
                                        'image/jpeg',
                                        'image/png',
                                        'image/x-png',
                                    ))
                                ->end()
                            ->end()
                        ->end()

                        ->arrayNode('youtube')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('service')->defaultValue('sonata.media.provider.youtube')->end()
                                ->scalarNode('resizer')->defaultValue('sonata.media.resizer.simple')->end()
                                ->scalarNode('filesystem')->defaultValue('sonata.media.filesystem.local')->end()
                                ->scalarNode('cdn')->defaultValue('sonata.media.cdn.server')->end()
                                ->scalarNode('generator')->defaultValue('sonata.media.generator.default')->end()
                                ->scalarNode('thumbnail')->defaultValue('sonata.media.thumbnail.format')->end()
                                ->scalarNode('html5')->defaultValue(false)->end()
                            ->end()
                        ->end()

                        ->arrayNode('dailymotion')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('service')->defaultValue('sonata.media.provider.dailymotion')->end()
                                ->scalarNode('resizer')->defaultValue('sonata.media.resizer.simple')->end()
                                ->scalarNode('filesystem')->defaultValue('sonata.media.filesystem.local')->end()
                                ->scalarNode('cdn')->defaultValue('sonata.media.cdn.server')->end()
                                ->scalarNode('generator')->defaultValue('sonata.media.generator.default')->end()
                                ->scalarNode('thumbnail')->defaultValue('sonata.media.thumbnail.format')->end()
                            ->end()
                        ->end()

                        ->arrayNode('vimeo')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('service')->defaultValue('sonata.media.provider.vimeo')->end()
                                ->scalarNode('resizer')->defaultValue('sonata.media.resizer.simple')->end()
                                ->scalarNode('filesystem')->defaultValue('sonata.media.filesystem.local')->end()
                                ->scalarNode('cdn')->defaultValue('sonata.media.cdn.server')->end()
                                ->scalarNode('generator')->defaultValue('sonata.media.generator.default')->end()
                                ->scalarNode('thumbnail')->defaultValue('sonata.media.thumbnail.format')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addExtraSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('pixlr')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('enabled')->defaultValue(false)->end()
                        ->scalarNode('secret')->defaultValue(sha1(uniqid(rand(1, 9999), true)))->end()
                        ->scalarNode('referrer')->defaultValue('Sonata Media')->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addModelSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('class')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('media')->defaultValue('Application\\Sonata\\MediaBundle\\Entity\\Media')->end()
                        ->scalarNode('gallery')->defaultValue('Application\\Sonata\\MediaBundle\\Entity\\Gallery')->end()
                        ->scalarNode('gallery_has_media')->defaultValue('Application\\Sonata\\MediaBundle\\Entity\\GalleryHasMedia')->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addBuzzSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('buzz')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('connector')->defaultValue('sonata.media.buzz.connector.file_get_contents')->end()
                    ->end()
                ->end()
            ->end()
        ;
    }

    /**
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
     */
    private function addResizerSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('resizer')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->arrayNode('simple')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('mode')->defaultValue('inset')->end()
                            ->end()
                        ->end()
                        ->arrayNode('square')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('mode')->defaultValue('inset')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }
}

redpajama_set_name: RedPajamaGithub


text: A scripting/programming language that I am designing


text:
@implementation
SentrySession (Equality)

- (BOOL)isEqual:(id _Nullable)other
{
    if (other == self)
        return YES;
    if (!other || ![[other class] isEqual:[self class]])
        return NO;

    return [self isEqualToSession:other];
}

- (BOOL)isEqualToSession:(SentrySession *)session
{
    if (self == session)
        return YES;
    if (session == nil)
        return NO;
    if (self.sessionId != session.sessionId && ![self.sessionId isEqual:session.sessionId])
        return NO;
    if (self.started != session.started && ![self.started isEqualToDate:session.started])
        return NO;
    if (self.status != session.status)
        return NO;
    if (self.errors != session.errors)
        return NO;
    if (self.sequence != session.sequence)
        return NO;
    if (self.distinctId != session.distinctId
        && ![self.distinctId isEqualToString:session.distinctId])
        return NO;
    if (self.timestamp != session.timestamp && ![self.timestamp isEqualToDate:session.timestamp])
        return NO;
    if (self.duration != session.duration && ![self.duration isEqualToNumber:session.duration])
        return NO;
    if (self.releaseName != session.releaseName
        && ![self.releaseName isEqualToString:session.releaseName])
        return NO;
    if (self.environment != session.environment
        && ![self.environment isEqualToString:session.environment])
        return NO;
    if (self.user != session.user && ![self.user isEqual:session.user])
        return NO;
    if (self.flagInit != session.flagInit && ![self.flagInit isEqualToNumber:session.flagInit])
        return NO;
    return YES;
}

- (NSUInteger)hash
{
    NSUInteger hash = 17;

    hash = hash * 23 + [self.sessionId hash];
    hash = hash * 23 + [self.started hash];
    hash = hash * 23 + self.status;
    hash = hash * 23 + self.errors;
    hash = hash * 23 + self.sequence;
    hash = hash * 23 + [self.distinctId hash];
    hash = hash * 23 + [self.flagInit hash];
    hash = hash * 23 + [self.timestamp hash];
    hash = hash * 23 + [self.releaseName hash];
    hash = hash * 23 + [self.environment hash];
    hash = hash * 23 + [self.user hash];

    return hash;
}

@end


text:
MODx.Component = function(config) {
    config = config || {};
    MODx.Component.superclass.constructor.call(this,config);
    this.config = config;

    this._loadForm();
    if (this.config.tabs) {
        this._loadTabs();
    }
    this._loadComponents();
    this._loadActionButtons();
    MODx.activePage = this;
};
Ext.extend(MODx.Component,Ext.Component,{
    fields: {}
    ,form: null
    ,action: false

    ,_loadForm: function() {
        if (!this.config.form) { return false; }
        this.form = new Ext.form.BasicForm(Ext.get(this.config.form),{ errorReader : MODx.util.JSONReader });

        if (this.config.fields) {
            for (var i in this.config.fields) {
                if (this.config.fields.hasOwnProperty(i)) {
                    var f = this.config.fields[i];
                    if (f.xtype) {
                        f = Ext.ComponentMgr.create(f);
                    }
                    this.fields[i] = f;
                    this.form.add(f);
                }
            }
        }
        return this.form.render();
    }

    ,_loadActionButtons: function() {
        if (!this.config.buttons) { return false; }

        this.ab = MODx.load({
            xtype: 'modx-actionbuttons'
            ,form: this.form || null
            ,formpanel: this.config.formpanel || null
            ,actions: this.config.actions || null
            ,items: this.config.buttons || []
            ,loadStay: this.config.loadStay || false
        });
        return this.ab;
    }

    ,_loadTabs: function() {
        if (!this.config.tabs) { return false; }
        var o = this.config.tabOptions || {};
        Ext.applyIf(o,{
            xtype: 'modx-tabs'
            ,renderTo: this.config.tabs_div || 'tabs_div'
            ,items: this.config.tabs
        });
        return MODx.load(o);
    }

    ,_loadComponents: function() {
        if (!this.config.components) { return false; }
        var l = this.config.components.length;

        var cp = Ext.getCmp('modx-content');
        for (var i=0;i<l;i=i+1) {
            var a = MODx.load(this.config.components[i]);
            if (cp) {
                cp.add(a);
            }
        }
        if (cp) {
            cp.doLayout();
        }
        return true;
    }

    ,submitForm: function(listeners,options,otherParams) {
        listeners = listeners || {};
        otherParams = otherParams || {};
        if (!this.config.formpanel || !this.config.action) { return false; }
        f = Ext.getCmp(this.config.formpanel);
        if (!f) { return false; }

        for (var i in listeners) {
            if (typeof listeners[i] == 'function') {
                f.on(i,listeners[i],this);
            } else if (listeners[i] && typeof listeners[i] == 'object' && listeners[i].fn) {
                f.on(i,listeners[i].fn,listeners[i].scope || this);
            }
        }

        Ext.apply(f.baseParams,{
            'action':this.config.action
        });
        Ext.apply(f.baseParams,otherParams);
        options = options || {};
        options.headers = {
            'Powered-By': 'MODx'
            ,'modAuth': MODx.siteId
        };
        f.submit(options);
        return true;
    }
});
Ext.reg('modx-component',MODx.Component);

MODx.toolbar.ActionButtons = function(config) {
    config = config || {};
    Ext.applyIf(config,{
        actions: { 'close': MODx.action.welcome }
        ,formpanel: false
        ,id: 'modx-action-buttons'
        ,loadStay: false
        ,params: {}
        ,items: []
        ,renderTo: 'modAB'
    });
    if (config.formpanel) {
        this.setupDirtyButtons(config.formpanel);
    }
    if (config.loadStay === true) {
        config.items.push('-',this.getStayMenu());
    }
    this.checkDirtyBtns = [];
    MODx.toolbar.ActionButtons.superclass.constructor.call(this,config);
    this.config = config;
};
Ext.extend(MODx.toolbar.ActionButtons,Ext.Toolbar,{
    id: ''
    ,buttons: []
    ,options: { a_close: 'welcome' }
    ,stay: 'stay'

    ,add: function() {
        var a = arguments, l = a.length;
        for(var i = 0; i < l; i++) {
            var el = a[i];
            var ex = ['-','->','<-','',' '];
            if (ex.indexOf(el) != -1 || (el.xtype && el.xtype == 'switch')) {
                MODx.toolbar.ActionButtons.superclass.add.call(this,el);
                continue;
            }

            var id = el.id || Ext.id();
            Ext.applyIf(el,{
                xtype: 'button'
                ,cls: (el.icon ? 'x-btn-icon bmenu' : 'x-btn-text bmenu')
                ,scope: this
                ,disabled: el.checkDirty ? true : false
                ,listeners: {}
                ,id: id
            });
            if (el.button) {
                MODx.toolbar.ActionButtons.superclass.add.call(this,el);
            }

            if (el.handler === null && el.menu === null) {
                el.handler = this.checkConfirm;
            } else if (el.confirm && el.handler) {
                el.handler = function() {
                    Ext.Msg.confirm(_('warning'),el.confirm,function(e) {
                      if (e === 'yes') { Ext.callback(el.handler,this); }
                    },el.scope || this);
                };
            } else if (el.handler) {} else { el.handler = this.handleClick; }

            /* if javascript is specified, run it when button is click, before this.checkConfirm is run */
            if (el.javascript) {
                el.listeners['click'] = {fn:this.evalJS,scope:this};
            }

            /* if checkDirty, disable until field change */
            if (el.xtype == 'button') {
                el.listeners['render'] = {fn:function(btn) {
                    if (el.checkDirty && btn) {
                        this.checkDirtyBtns.push(btn);
                    }
                },scope:this}
            }

            if (el.keys) {
                el.keyMap = new Ext.KeyMap(Ext.get(document));
                for (var j = 0; j < el.keys.length; j++) {
                    var key = el.keys[j];
                    Ext.applyIf(key,{
                        scope: this
                        ,stopEvent: true
                        ,fn: function(e) {
                            var b = Ext.getCmp(id);
                            if (b) this.checkConfirm(b,e);
                        }
                    });
                    el.keyMap.addBinding(key);
                }
                el.listeners['destroy'] = {fn:function(btn) {
                    btn.keyMap.disable();
                },scope:this}
            }

            /* add button to toolbar */
            MODx.toolbar.ActionButtons.superclass.add.call(this,el);
        }
    }

    ,evalJS: function(itm,e) {
        if (!eval(itm.javascript)) {
            e.stopEvent();
            e.preventDefault();
        }
    }

    ,checkConfirm: function(itm,e) {
        if (itm.confirm !== null && itm.confirm !== undefined) {
            this.confirm(itm,function() {
                this.handleClick(itm,e);
            },this);
        } else { this.handleClick(itm,e); }
        return false;
    }

    ,confirm: function(itm,callback,scope) {
        /* if no message go ahead and redirect...we dont like blank questions */
        if (itm.confirm === null) { return true; }

        Ext.Msg.confirm('',itm.confirm,function(e) {
            /* if the user is okay with the action */
            if (e === 'yes') {
                if (callback === null) { return true; }
                if (typeof(callback) === 'function') { /* if callback is a function, run it, and pass Button */
                    Ext.callback(callback,scope || this,[itm]);
                } else { location.href = callback; }
            }
            return true;
        },this);
        return true;
    }

    ,reloadPage: function() {
        location.href = location.href;
    }

    ,handleClick: function(itm,e) {
        var o = this.config;
        if (o.formpanel === false || o.formpanel === undefined || o.formpanel === null) return false;

        if (itm.method === 'remote') { /* if using connectors */
            MODx.util.Progress.reset();
            o.form = Ext.getCmp(o.formpanel);
            if (!o.form) return false;

            var f = o.form.getForm ? o.form.getForm() : o.form;
            var isv = true;
            if (f.items && f.items.items) {
                for (var fld in f.items.items) {
                    if (f.items.items[fld] && f.items.items[fld].validate) {
                        var fisv = f.items.items[fld].validate();
                        if (!fisv) {
                            f.items.items[fld].markInvalid();
                            isv = false;
                        }
                    }
                }
            }

            if (isv) {
                Ext.applyIf(o.params,{
                    action: itm.process
                   ,'modx-ab-stay': MODx.config.stay
                });

                Ext.apply(f.baseParams,o.params);

                o.form.on('success',function(r) {
                    if (o.form.clearDirty) o.form.clearDirty();
                    /* allow for success messages */
                    MODx.msg.status({
                        title: _('success')
                        ,message: r.result.message || _('save_successful')
                        ,dontHide: r.result.message != '' ? true : false
                    });
                    Ext.callback(this.redirectStay,this,[o,itm,r.result],1000);

                    this.resetDirtyButtons(r.result);
                },this);
                o.form.submit({
                    headers: {
                        'Powered-By': 'MODx'
                        ,'modAuth': MODx.siteId
                    }
                });
            } else {
                Ext.Msg.alert(_('error'),_('correct_errors'));
            }
        } else { /* if just doing a URL redirect */
            Ext.applyIf(itm.params || {},o.baseParams || {});
            MODx.loadPage('?'+Ext.urlEncode(itm.params));
        }
        return false;
    }

    ,resetDirtyButtons: function(r) {
        for (var i=0;i<this.checkDirtyBtns.length;i=i+1) {
            var btn = this.checkDirtyBtns[i];
            btn.setDisabled(true);
        }
    }

    ,checkStay: function(itm,e) {
        this.stay = itm.value;
    }

    ,redirectStay: function(o,itm,res) {
        o = this.config;
        itm.params = itm.params || {};
        Ext.applyIf(itm.params,o.baseParams);
        var stay = Ext.state.Manager.get('modx.stay.'+MODx.request.a,'stay');
        switch (stay) {
            case 'new': /* if user selected 'new', then always redirect */
                if (o.form.hasListener('actionNew')) {
                    o.form.fireEvent('actionNew',itm.params);
                } else if (o.actions) {
                    if (MODx.request.parent) { itm.params.parent = MODx.request.parent; }
                    if (MODx.request.context_key) { itm.params.context_key = MODx.request.context_key; }
                    if (MODx.request.class_key) { itm.params.class_key = MODx.request.class_key; }
                    var params = Ext.urlEncode(itm.params);
                    MODx.loadPage(o.actions['new'], params);
                }
                break;
            case 'stay':
                var url;
                if (o.form.hasListener('actionContinue')) {
                    o.form.fireEvent('actionContinue',itm.params);
                } else if (o.actions) {
                    /* if Continue Editing, then don't reload the page - just hide the Progress bar
                       unless the user is on a 'Create' page...if so, then redirect
                       to the proper Edit page */
                    if ((itm.process === 'create' || itm.process === 'duplicate' || itm.reload) && res.object.id) {
                        itm.params.id = res.object.id;
                        if (MODx.request.parent) { itm.params.parent = MODx.request.parent; }
                        if (MODx.request.context_key) { itm.params.context_key = MODx.request.context_key; }
                        url = Ext.urlEncode(itm.params);
                        MODx.loadPage(o.actions.edit, url);

                    } else if (itm.process === 'delete') {
                        itm.params.a = o.actions.cancel;
                        url = Ext.urlEncode(itm.params);
                        MODx.loadPage('?'+url);
                    }
                }
                break;
            case 'close': /* redirect to the cancel action */
                if (o.form.hasListener('actionClose')) {
                    o.form.fireEvent('actionClose',itm.params);
                } else if (o.actions) {
                    MODx.loadPage(o.actions.cancel, Ext.encode(itm.params));
                }
                break;
        }
    }

    ,getStayMenu: function() {
        var stay = Ext.state.Manager.get('modx.stay.'+MODx.request.a,'stay');
        var a = 0;
        switch (stay) {
            case 'new': a = 0; break;
            case 'close': a = 2; break;
            case 'stay': default: a = 1; break;
        }
        return {
            xtype:'switch'
            ,id: 'modx-stay-menu'
            ,activeItem: a
            ,items: [{
                tooltip: _('stay_new')
                ,value: 'new'
                ,menuIndex: 0
                ,id: 'modx-stay-new'
                ,iconCls:'icon-list-new'
            },{
                tooltip: _('stay')
                ,value: 'stay'
                ,menuIndex: 1
                ,id: 'modx-stay-stay'
                ,iconCls:'icon-mark-active'
            },{
                tooltip: _('close')
                ,value: 'close'
                ,menuIndex: 2
                ,id: 'modx-stay-close'
                ,iconCls:'icon-mark-complete'
            }]
            ,listeners: {
                change: function(btn,itm){
                    Ext.state.Manager.set('modx.stay.'+MODx.request.a,itm.value);
                }
                ,scope: this
                ,delay: 10
            }
        };
    }

    ,refreshTreeNode: function(tree,node,self) {
        var t = parent.Ext.getCmp(tree);
        t.refreshNode(node,self || false);
        return false;
    }

    ,setupDirtyButtons: function(f) {
        var fp = Ext.getCmp(f);
        if (fp) {
            fp.on('fieldChange',function(o) {
               for (var i=0;i<this.checkDirtyBtns.length;i=i+1) {
                    var btn = this.checkDirtyBtns[i];
                    btn.setDisabled(false);
               }
            },this);
        }
    }
});
Ext.reg('modx-actionbuttons',MODx.toolbar.ActionButtons);


text:
var Tools = require('./tools');
var fs = require("fs");

var index = [];

index = index.concat(Object.keys(Tools.data.Pokedex).map(function(x){return x+' pokemon'}));
index = index.concat(Object.keys(Tools.data.Movedex).map(function(x){return x+' move'}));
index = index.concat(Object.keys(Tools.data.Items).map(function(x){return x+' item'}));
index = index.concat(Object.keys(Tools.data.Abilities).map(function(x){return x+' ability'}));
index = index.concat(Object.keys(Tools.data.TypeChart).map(function(x){return toId(x)+' type'}));
index = index.concat(['physical', 'special', 'status'].map(function(x){return toId(x)+' category'}));
index = index.concat(['monster', 'water1', 'bug', 'flying', 'field', 'fairy', 'grass', 'humanlike', 'water3', 'mineral', 'amorphous', 'water2', 'ditto', 'dragon', 'undiscovered'].map(function(x){return toId(x)+' egggroup'}));

index.sort();

// manually rearrange
index[index.indexOf('grass type')] = 'grass egggroup';
index[index.indexOf('grass egggroup')] = 'grass type';

index[index.indexOf('fairy type')] = 'fairy egggroup';
index[index.indexOf('fairy egggroup')] = 'fairy type';

index[index.indexOf('flying type')] = 'flying egggroup';
index[index.indexOf('flying egggroup')] = 'flying type';

index[index.indexOf('dragon type')] = 'dragon egggroup';
index[index.indexOf('dragon egggroup')] = 'dragon type';

index[index.indexOf('bug type')] = 'bug egggroup';
index[index.indexOf('bug egggroup')] = 'bug type';

BattleSearchIndex = index.map(function(x){return x.split(' ')[0]});
BattleSearchIndexType = index.map(function(x){return x.split(' ')[1]});

BattleSearchIndexOffset = BattleSearchIndex.map(function(id, i){
	var name='';
	switch (BattleSearchIndexType[i]) {
	case 'pokemon':
		var name = Tools.getTemplate(id).species;
		break;
	case 'move':
		var name = Tools.getMove(id).name;
		break;
	case 'item':
		var name = Tools.getItem(id).name;
		break;
	case 'ability':
		var name = Tools.getAbility(id).name;
		break;
	}
	var res = '';
	var nonAlnum = 0;
	for (var i=0,j=0; i<id.length; i++,j++) {
		while (!/[a-zA-Z0-9]/.test(name[j])) {
			j++;
			nonAlnum++;
		}
		res += nonAlnum;
	}
	if (nonAlnum) return res;
	return '';
});

BattleSearchCountIndex = {};
for (var type in Tools.data.TypeChart) {
	BattleSearchCountIndex[type+' move'] = Object.keys(Tools.data.Movedex).filter(function(id){ if (Tools.data.Movedex[id].type === type) return true; }).length;
}

for (var type in Tools.data.TypeChart) {
	BattleSearchCountIndex[type+' pokemon'] = Object.keys(Tools.data.Pokedex).filter(function(id){ if (Tools.data.Pokedex[id].types.indexOf(type) >= 0) return true; }).length;
}

var buf = '// automatically built with cache-index.js in the Gen 6 Learnsets repository\n\n';

buf += 'exports.BattleSearchIndex = '+JSON.stringify(BattleSearchIndex)+';\n\n';

buf += 'exports.BattleSearchIndexType = '+JSON.stringify(BattleSearchIndexType)+';\n\n';

buf += 'exports.BattleSearchIndexOffset = '+JSON.stringify(BattleSearchIndexOffset)+';\n\n';

buf += 'exports.BattleSearchCountIndex = '+JSON.stringify(BattleSearchCountIndex)+';\n';

fs.writeFileSync('data/search-index.js', buf);

console.log("Done.");


text:
/* eslint-disable no-unused-expressions */
/* eslint-disable no-invalid-this */
import { expect } from 'chai'
import sinon from 'sinon'
import { shallow } from 'enzyme'
import proxyquire from 'proxyquire'
import React from 'react'
import DisabledPlugin from '../js/rendererjs/disabledplugin.js'

let running = true
const mock = {
	'react-dom': {
		render: sinon.spy(),
	},
	'sia.js': {
		isRunning: () => new Promise((resolve) => {
			resolve(running)
		}),
		launch: sinon.spy(),
	},
	'electron': {
		remote: {
			getCurrentWindow: sinon.spy(),
			getGlobal: (name) => {
				if (name === 'config') {
					return {
						siad: {
							path: 'testpath/siad',
							datadir: 'testpath/datadir',
							detached: false,
						},
					}
				}
				return null
			},
			dialog: {
				showOpenDialog: sinon.spy(),
				showSaveDialog: sinon.spy(),
				showMessageBox: sinon.spy(),
				showErrorBox: sinon.spy(),
			},
			require: sinon.spy(),
		},
	},
}

proxyquire('../js/rendererjs/pluginapi.js', mock)

describe('plugin API', () => {
	it('creates a SiaAPI window object', () => {
		expect(window.SiaAPI).to.exist
	})
	it('does not mount disabled plugin component if siad is running', function(done) {
		running = true
		this.timeout(10000)
		const poll = setInterval(() => {
			if (mock['react-dom'].render.called === false) {
				clearInterval(poll)
				done()
			}
		}, 50)
	})
	it('mounts disabled plugin if siad is not running', function(done) {
		running = false
		this.timeout(10000)
		const poll = setInterval(() => {
			if (mock['react-dom'].render.called === true) {
				clearInterval(poll)
				done()
			}
		}, 50)
	})
	describe('DisabledPlugin component', () => {
		it('calls siajs.launch on click', () => {
			const component = shallow(<DisabledPlugin startSiad={mock['sia.js'].launch} />)
			component.find('button').first().simulate('click')
			expect(mock['sia.js'].launch.called).to.be.true
		})
	})
})
/* eslint-enable no-unused-expressions */
/* eslint-enable no-invalid-this */


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows
{
  public partial class SizeChangedEventArgs : RoutedEventArgs
  {
    #region Methods and constructors
    protected override void InvokeEventHandler(Delegate genericHandler, Object genericTarget)
    {
    }

    internal SizeChangedEventArgs()
    {
    }
    #endregion

    #region Properties and indexers
    public bool HeightChanged
    {
      get
      {
        return default(bool);
      }
    }

    public Size NewSize
    {
      get
      {
        return default(Size);
      }
    }

    public Size PreviousSize
    {
      get
      {
        return default(Size);
      }
    }

    public bool WidthChanged
    {
      get
      {
        return default(bool);
      }
    }
    #endregion
  }
}


text:
/*
 * arch/arm/plat-orion/include/plat/common.h
 *
 * Marvell Orion SoC common setup code used by different mach-/common.c
 *
 * This file is licensed under the terms of the GNU General Public
 * License version 2.  This program is licensed "as is" without any
 * warranty of any kind, whether express or implied.
 */

#ifndef __PLAT_COMMON_H
#include <linux/mv643xx_eth.h>

struct dsa_platform_data;

void __init orion_uart0_init(unsigned int membase,
			     resource_size_t mapbase,
			     unsigned int irq,
			     struct clk *clk);

void __init orion_uart1_init(unsigned int membase,
			     resource_size_t mapbase,
			     unsigned int irq,
			     struct clk *clk);

void __init orion_uart2_init(unsigned int membase,
			     resource_size_t mapbase,
			     unsigned int irq,
			     struct clk *clk);

void __init orion_uart3_init(unsigned int membase,
			     resource_size_t mapbase,
			     unsigned int irq,
			     struct clk *clk);

void __init orion_rtc_init(unsigned long mapbase,
			   unsigned long irq);

void __init orion_ge00_init(struct mv643xx_eth_platform_data *eth_data,
			    unsigned long mapbase,
			    unsigned long irq,
			    unsigned long irq_err);

void __init orion_ge01_init(struct mv643xx_eth_platform_data *eth_data,
			    unsigned long mapbase,
			    unsigned long irq,
			    unsigned long irq_err);

void __init orion_ge10_init(struct mv643xx_eth_platform_data *eth_data,
			    unsigned long mapbase,
			    unsigned long irq,
			    unsigned long irq_err);

void __init orion_ge11_init(struct mv643xx_eth_platform_data *eth_data,
			    unsigned long mapbase,
			    unsigned long irq,
			    unsigned long irq_err);

void __init orion_ge00_switch_init(struct dsa_platform_data *d,
				   int irq);

void __init orion_i2c_init(unsigned long mapbase,
			   unsigned long irq,
			   unsigned long freq_m);

void __init orion_i2c_1_init(unsigned long mapbase,
			     unsigned long irq,
			     unsigned long freq_m);

void __init orion_spi_init(unsigned long mapbase);

void __init orion_spi_1_init(unsigned long mapbase);

void __init orion_wdt_init(void);

void __init orion_xor0_init(unsigned long mapbase_low,
			    unsigned long mapbase_high,
			    unsigned long irq_0,
			    unsigned long irq_1);

void __init orion_xor1_init(unsigned long mapbase_low,
			    unsigned long mapbase_high,
			    unsigned long irq_0,
			    unsigned long irq_1);

void __init orion_ehci_init(unsigned long mapbase,
			    unsigned long irq,
			    enum orion_ehci_phy_ver phy_version);

void __init orion_ehci_1_init(unsigned long mapbase,
			      unsigned long irq);

void __init orion_ehci_2_init(unsigned long mapbase,
			      unsigned long irq);

void __init orion_sata_init(struct mv_sata_platform_data *sata_data,
			    unsigned long mapbase,
			    unsigned long irq);

void __init orion_crypto_init(unsigned long mapbase,
			      unsigned long srambase,
			      unsigned long sram_size,
			      unsigned long irq);

void __init orion_clkdev_add(const char *con_id, const char *dev_id,
			     struct clk *clk);

void __init orion_clkdev_init(struct clk *tclk);
#endif


text:
{{event.event_date | date: 'MMMM'}} {{event.event_date | date: 'y'}}

{{event.event_date | date: 'dd'}}

{{host.name}}

{{host.short_description}}


text:
- Update various dependencies (Kotlin, google-cloud-storage, Gradle plugin publish plugin)

## 1.0.0-alpha06

- Warn when a user incorrectly configures GCP bucket to be used for the cache.

## 1.0.0-alpha05

- Downloads `Blob`s to an intermediate `Buffer` or a `File` depending on the size of the blob.
- The underlying `FileHandleInputStream` gets cleaned up automatically after the `InputStream` is closed.
- This way we can avoid flakes from the build cache, that is caused by intermittent `StorageException`s
- Retry on fetches given they are being fetched to an intermediate location.

## 1.0.0-alpha04

- Handles exceptions when fetching `BlobInfo`s and `ReadChannel`s from the storage service.

## 1.0.0-alpha03

- Fixes issue [19](https://github.com/androidx/gcp-gradle-build-cache/issues/19).
    - Remove retry-ing of RPCs.
    - When writes fail, we fail silently and treat subsequent reads as a cache-miss.
    - Set the `chunkSize` for reads to equal the size of the `Blob`.
      This way, we only make 1 RPC per blob input stream. This is safe because
      the size of the objects in cache are not very large.


text:
package io.strimzi.operator.common;

import java.security.SecureRandom;

/**
 * Class for generating passwords for SASL users
 */
public class PasswordGenerator {
    private final SecureRandom rng = new SecureRandom();
    private final int length;
    private final String firstCharacterAlphabet;
    private final String alphabet;

    /**
     * Constructor to initialize the PasswordGenerator with alphabets and password length.
     * It distinguishes between the alphabet for the first character of the password and the rest.
     * This is needed because of how Java JAAS parses the configuration string.
     *
     * @param length    The length of the generated passwords
     * @param firstCharacterAlphabet    A String with characters which will be used to generate the first character of the password
     * @param alphabet  A String with characters which will be used to generate the character of the password starting with the second character
     */
    public PasswordGenerator(int length, String firstCharacterAlphabet, String alphabet) {
        this.length = length;
        this.firstCharacterAlphabet = firstCharacterAlphabet;
        this.alphabet = alphabet;
    }

    public PasswordGenerator(int length) {
        this(length, "abcdefghijklmnopqrstuvwxyz" +
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                "abcdefghijklmnopqrstuvwxyz" +
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                "0123456789");
    }

    /**
     * Generates the password
     *
     * @return String with new password
     */
    public String generate() {
        StringBuilder sb = new StringBuilder();

        sb.append(firstCharacterAlphabet.charAt(rng.nextInt(firstCharacterAlphabet.length())));

        for (int i = 1; i < length; i++) {
            sb.append(alphabet.charAt(rng.nextInt(alphabet.length())));
        }

        return sb.toString();
    }
}


text:
package org.virtue.config.db.dbtabletype;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.virtue.cache.Archive;
import org.virtue.cache.ReferenceTable;
import org.virtue.config.ConfigDecoder;
import org.virtue.config.Js5ConfigGroup;

public class DBTableTypeList extends ConfigDecoder<DBTableType> {

	/**
	 * The {@link Logger} instance
	 */
	private static Logger logger = LoggerFactory.getLogger(DBTableTypeList.class);

	public DBTableTypeList(ReferenceTable configTable, Archive archive) {
		super(configTable, archive, Js5ConfigGroup.DBTABLETYPE, DBTableType.class);
		logger.info("Found "+getCapacity()+" DBTableType definitions.");
	}
}


text:
import { factory } from '../../../utils/factory';
var name = 'algorithm12';
var dependencies = ['typed', 'DenseMatrix'];
export var createAlgorithm12 =
/* #__PURE__ */
factory(name, dependencies, function (_ref) {
  var typed = _ref.typed,
      DenseMatrix = _ref.DenseMatrix;

  /**
   * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
   * Callback function invoked MxN times.
   *
   *
   *          ┌  f(Sij, b)  ; S(i,j) !== 0
   * C(i,j) = ┤
   *          └  f(0, b)    ; otherwise
   *
   *
   * @param {Matrix}   s                 The SparseMatrix instance (S)
   * @param {Scalar}   b                 The Scalar value
   * @param {Function} callback          The f(Aij,b) operation to invoke
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(b,Sij)
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
   */
  return function algorithm12(s, b, callback, inverse) {
    // sparse matrix arrays
    var avalues = s._values;
    var aindex = s._index;
    var aptr = s._ptr;
    var asize = s._size;
    var adt = s._datatype; // sparse matrix cannot be a Pattern matrix

    if (!avalues) {
      throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
    } // rows & columns

    var rows = asize[0];
    var columns = asize[1]; // datatype

    var dt; // callback signature to use

    var cf = callback; // process data types

    if (typeof adt === 'string') {
      // datatype
      dt = adt; // convert b to the same datatype

      b = typed.convert(b, dt); // callback

      cf = typed.find(callback, [dt, dt]);
    } // result arrays

    var cdata = []; // matrix

    var c = new DenseMatrix({
      data: cdata,
      size: [rows, columns],
      datatype: dt
    }); // workspaces

    var x = []; // marks indicating we have a value in x for a given column

    var w = []; // loop columns

    for (var j = 0; j < columns; j++) {
      // columns mark
      var mark = j + 1; // values in j

      for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
        // row
        var r = aindex[k]; // update workspace

        x[r] = avalues[k];
        w[r] = mark;
      } // loop rows

      for (var i = 0; i < rows; i++) {
        // initialize C on first column
        if (j === 0) {
          // create row array
          cdata[i] = [];
        } // check sparse matrix has a value @ i,j

        if (w[i] === mark) {
          // invoke callback, update C
          cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);
        } else {
          // dense matrix value @ i, j
          cdata[i][j] = inverse ? cf(b, 0) : cf(0, b);
        }
      }
    } // return sparse matrix

    return c;
  };
});


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Web messaging demo</title>

postMessage recipient (iframe; same domain)


text:
<?php

use yii\helpers\Html;
?>

P2 Grayscale

A free, responsive, one page Bootstrap theme.

Created by Start Bootstrap & p2made.


text:
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/mlir_generated/base_gpu_op.h"

namespace tensorflow {

GENERATE_AND_REGISTER_UNARY_GPU_KERNEL(Square, DT_HALF);
GENERATE_AND_REGISTER_UNARY_GPU_KERNEL(Square, DT_FLOAT);
GENERATE_AND_REGISTER_UNARY_GPU_KERNEL(Square, DT_DOUBLE);
GENERATE_AND_REGISTER_UNARY_GPU_KERNEL(Square, DT_INT64);

}  // namespace tensorflow


text:
require_relative 'boot'

# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
require "action_cable/engine"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Orientation
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # prefer indented sass syntax
    config.sass.preferred_syntax = :sass

    # https://robots.thoughtbot.com/content-compression-with-rack-deflater
    config.middleware.use Rack::Deflater

    config.generators do |g|
      g.test_framework :rspec
      g.view_specs false
      g.helper_specs false
    end

    config.active_job.queue_adapter = :delayed_job

    # We load environment-specific configuration values from
    # config/orientation.yml into Rails.configuration.orientation
    #
    # You can find example values in config/orientation.example.yml
    #
    # Once the application has booted you can assign values directly like this:
    #   Rails.configuration.orientation["transactional_mailer"] = :mandrill
    # And you can read those same values with:
    #   Rails.configuration.orientation["transactional_mailer"]
    #
    config.orientation = config_for(:orientation)
  end
end


text:
// Copyright 2017 Jose Luis Rovira Martin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Essence.Util.Collections
{
    [TestClass]
    public class RangeListTest
    {
        [TestMethod]
        public void TestNormal()
        {
            IList<int> aux = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            AssertEqualsList(new RangeList<int>(aux, 0, 10),
                             new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });

            AssertEqualsList(new RangeList<int>(aux, 0, 1),
                             new[] { 0 });

            AssertEqualsList(new RangeList<int>(aux, 4, 6),
                             new[] { 4, 5, 6, 7, 8, 9 });

            AssertEqualsList(new RangeList<int>(aux, 7, 3),
                             new[] { 7, 8, 9 });

            try
            {
                new RangeList<int>(aux, 7, 4);
                Assert.Fail();
            }
            catch (Exception exception)
            {
            }
        }

        [TestMethod]
        public void TestCircular()
        {
            IList<int> aux = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            AssertEqualsList(new RangeList<int>(aux, 7, 4, true),
                             new[] { 7, 8, 9, 0 });

            AssertEqualsList(new RangeList<int>(aux, 7, 8, true),
                             new[] { 7, 8, 9, 0, 1, 2, 3, 4 });

            AssertEqualsList(new RangeList<int>(aux, 7, 10, true),
                             new[] { 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 });

            try
            {
                new RangeList<int>(aux, 7, 11, true);
                Assert.Fail();
            }
            catch (Exception exception)
            {
            }
        }

        private static void AssertEqualsList<T>(IList<T> list1, IList<T> list2)
        {
            Assert.IsTrue(list1 != null && list2 != null);
            Assert.IsTrue(list1.Count == list2.Count);
            for (int i = 0; i < list1.Count; i++)
            {
                Assert.IsTrue(Equals(list1[i], list2[i]));
            }
        }
    }
}


text:
import pytz

from collections import defaultdict
from datetime import datetime

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.db.models import ObjectDoesNotExist
from django.dispatch import receiver
from django.utils.text import slugify

from rest_framework.authtoken.models import Token
from survey.models import Instrument

class Place(models.Model):
    name = models.CharField(max_length=32, unique=True, db_index=True)
    slug = models.SlugField(max_length=32, unique=True, db_index=True)

    # We'll let users add their own places, but we want to indicate that
    # some are used for suggestions or as primary places
    primary = models.BooleanField(
        default=False,
        help_text="Use this place as a suggestion for users."
    )

    updated_on = models.DateTimeField(auto_now=True)
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{}".format(self.name)

    class Meta:
        ordering = ['name']
        verbose_name = "Place"
        verbose_name_plural = "Places"

    def _format_name(self):
        self.name = self.name.title()
        self.name = "{}{}".format(  # fix for the `Joe'S` bug
            self.name[:-1],
            self.name[-1].lower()
        )

    def _format_slug(self):
        self.slug = slugify(self.name)

    def save(self, *args, **kwargs):
        self._format_name()
        self._format_slug()
        super().save(*args, **kwargs)

class UserPlace(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    profile = models.ForeignKey('UserProfile')
    place = models.ForeignKey(Place)
    latitude = models.DecimalField(max_digits=8, decimal_places=4, db_index=True)
    longitude = models.DecimalField(max_digits=8, decimal_places=4, db_index=True)
    updated_on = models.DateTimeField(auto_now=True)
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{0} ({1}, {2})".format(self.place, self.latitude, self.longitude)

    class Meta:
        unique_together = ('user', 'place')
        order_with_respect_to = "user"
        verbose_name = "User Place"
        verbose_name_plural = "User Places"

    @property
    def latlon(self):
        return (self.latitude, self.longitude)

class UserProfile(models.Model):
    """A *profile* for a single user; This model contains additional info
    about a user or their account. It also serves as a way to aggregate and
    expose some data for a user.

    """
    SEX_CHOICES = (
        ('female', 'Female'),
        ('male', 'Male'),
        ('', 'Prefer not to answer'),
    )

    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        help_text="The user to whom this profile belongs"
    )
    ip_address = models.GenericIPAddressField(
        blank=True,
        null=True,
        protocol='both',
        unpack_ipv4=True,
    )
    timezone = models.CharField(
        max_length=64,
        default="America/Chicago",
        blank=True,
        choices=[(tz, tz) for tz in pytz.all_timezones]
    )
    maximum_daily_notifications = models.IntegerField(default=3, blank=True)
    needs_onboarding = models.BooleanField(default=True, blank=True)

    # Profile fields.
    phone = models.CharField(max_length=32, blank=True, null=True)
    zipcode = models.CharField(max_length=32, blank=True, null=True)
    birthday = models.DateField(blank=True, null=True)
    sex = models.CharField(
        max_length=32,
        blank=True,
        default="",
        choices=SEX_CHOICES
    )
    employed = models.BooleanField(default=False, blank=True)
    is_parent = models.BooleanField(default=False, blank=True)
    in_relationship = models.BooleanField(default=False, blank=True)
    has_degree = models.BooleanField(default=False, blank=True)

    # Additional Google profile fields
    google_image = models.URLField(max_length=512, default='', blank=True)
    google_token = models.TextField(default='', blank=True)

    # app interaction fields
    # app_logins is updated when a user requests an auth token via the api;
    # see api.ObtainAuthorization
    app_logins = models.IntegerField(
        default=0,
        help_text="Number of times the user has logged into the app."
    )

    # Timestamps
    updated_on = models.DateTimeField(auto_now=True, null=True)
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{}".format(self.user)

    class Meta:
        order_with_respect_to = "user"
        verbose_name = "User Profile"
        verbose_name_plural = "User Profiles"

    def set_needs_onboarding(self, save=True):
        self.needs_onboarding = True
        if save:
            self.save()

    def get_absolute_url(self):
        return reverse("userprofile:detail", args=[self.pk])

    def get_update_url(self):
        return reverse("userprofile:update", args=[self.pk])

    @property
    def age(self):
        # NOTE: uses the birthday field, not the old survey.
        if self.birthday:
            delta = datetime.today() - self.birthday
            return int(delta.days / 365)
        return None

    # ------------------------------------------------
    # TODO: Kill off all these survey-related fields.
    # ------------------------------------------------
    def _response(self, question):
        """Given a Question, return the user's latest response."""
        m = {
            'binaryquestion': 'binaryresponse_set',
            'likertquestion': 'likertresponse_set',
            'multiplechoicequestion': 'multiplechoiceresponse_set',
            'openendedquestion': 'openendedresponse_set'
        }
        # Get the responses for the given type of question, then filter
        # those for the current user, and return the latest
        responses = getattr(question, m[question.question_type])
        return responses.filter(user=self.user).latest()

    def _get_bio_responses(self, question_type, question_id):
        qid = 'question_id'
        qtype = 'question_type'
        return [
            d for d in self.bio
            if d[qid] == question_id and d[qtype] == question_type
        ]

    def _get_profile_survey_responses(self, question_type, question_id):
        qid = 'question_id'
        qtype = 'question_type'
        return [
            d for d in self.profile_survey
            if d[qid] == question_id and d[qtype] == question_type
        ]

    # -------------------------------------------------------------------------
    # Bio/Onboarding survey responses.
    # -------------------------------------------------------------------------
    @property
    def survey_zipcode(self):
        question_id = 2  # My zip code is
        answer_key = 'response'
        for d in self._get_bio_responses('openendedquestion', question_id):
            return d.get(answer_key, None)
        return None

    @property
    def survey_birthday(self):
        question_id = 1  # I was born on
        answer_key = 'response'
        birthdate = None
        try:
            for d in self._get_bio_responses('openendedquestion', question_id):
                if d.get(answer_key):
                    birthdate = datetime.strptime(d[answer_key], "%Y-%m-%d")
        except:
            pass
        return birthdate

    @property
    def has_relationship(self):
        return self.in_relationship

    @property
    def gender(self):
        """Returns the user's gender choice, converted to lowercase."""
        question_id = 1  # Gender: I am ...
        answer_key = 'selected_option_text'
        for d in self._get_bio_responses('multiplechoicequestion', question_id):
            if d.get(answer_key):
                return d[answer_key].lower().strip()
        return None

    @property
    def num_children(self):
        question_id = 6  # Children: I have...
        answer_key = 'selected_option_text'
        for d in self._get_bio_responses('multiplechoicequestion', question_id):
            return d.get(answer_key)
        return None

    # -------------------------------------------------------------------------
    # Initial Profile survey responses.
    # -------------------------------------------------------------------------
    @property
    def survey_employed(self):
        """Returns True or False. """
        question_id = 13  # I am currently employed.
        answer_key = 'selected_option'
        for d in self._get_profile_survey_responses('binaryquestion', question_id):
            return d.get(answer_key)
        return False

    @property
    def survey_in_relationship(self):
        """Returns True or False. """
        question_id = 14  # I am currently in a romantic relationship.
        answer_key = 'selected_option'
        for d in self._get_profile_survey_responses('binaryquestion', question_id):
            return d.get(answer_key)
        return False

    @property
    def survey_is_parent(self):
        """Returns True or False. """
        question_id = 16  # I am a parent.
        answer_key = 'selected_option'
        for d in self._get_profile_survey_responses('binaryquestion', question_id):
            return d.get(answer_key)
        return False

    @property
    def survey_has_degree(self):
        """Returns True or False. """
        question_id = 12  # I have a college degree.
        answer_key = 'selected_option'
        for d in self._get_profile_survey_responses('binaryquestion', question_id):
            return d.get(answer_key)
        return False

    @property
    def survey_sex(self):
        """Returns a string: 'Male' or 'Female' or None. """
        question_id = 8  # My sex is:
        answer_key = 'selected_option_text'
        qtype = 'multiplechoicequestion'
        result = None
        for d in self._get_profile_survey_responses(qtype, question_id):
            if d.get(answer_key):
                result = d.get(answer_key)
        if result is None:  # Fall back to gender
            result = self.gender
        return result

    def _get_survey_instrument_results(self, instrument_id):
        # UGH. We shoe-horned this shit into a survey and now there's no
        # clean way to get what *should* be a 1-to-1 relationship between
        # a user and some responses. I'm just hard-coding this for now because
        # i hate future me.
        results = []
        try:
            inst = Instrument.objects.get(pk=instrument_id)
            for qtype, question in inst.questions:
                data = {
                    'question_id': question.id,
                    'question_type': question.question_type,
                    'question_text': "{0}".format(question),
                    'response_url': question.get_api_response_url(),
                    'question_url': question.get_survey_question_url(),
                    'response_id': None,
                    'object_type': "surveyresult"
                }
                option_types = [
                    'binaryquestion', 'likertquestion', 'multiplechoicequestion'
                ]
                if question.question_type in option_types:
                    data['selected_option'] = None
                    data['selected_option_text'] = ''
                elif question.question_type == 'openendedquestion':
                    data['response'] = None
                    data['question_input_type'] = question.input_type

                # Fill in any of the user's responses.
                try:
                    r = self._response(question)
                    data['response_id'] = r.id
                    if question.question_type in ['binaryquestion', 'likertquestion']:
                        data['selected_option'] = r.selected_option
                        data['selected_option_text'] = r.selected_option_text
                    elif question.question_type == 'openendedquestion':
                        data['response'] = r.response
                    elif question.question_type == 'multiplechoicequestion':
                        data['selected_option'] = r.selected_option.id
                        data['selected_option_text'] = r.selected_option_text
                except ObjectDoesNotExist:
                    pass
                results.append(data)

        except Instrument.DoesNotExist:
            pass

        return results

    @property
    def profile_survey(self):
        return self._get_survey_instrument_results(6)

    @property
    def bio(self):
        return self._get_survey_instrument_results(4)

    @property
    def surveys(self):
        """
        # TODO: Figure out what to do with this and if/when we need it (probably
        for users to go back to their survey questions or directly complete
        surveys; it'll need to be re-worked)

        Return a simple representation of the survey questions that the
        user has answered.

        """
        # NOTE: I'm not sure what the best approach is, here, because our
        # questions are M2M fields under Instruments; That means there's possibly
        # no 1-to-1 relationship between a User's response and the instrument
        # in which it's placed.

        # Get all the questions & return a dict of primitive types
        # (dicts & lists; so it's easy to serialize)
        surveys = defaultdict(list)
        for resp in self.user.binaryresponse_set.all():
            for inst in resp.question.instruments.all():
                surveys[inst.id].append({
                    'id': resp.id,
                    'instrument': {
                        "id": inst.id,
                        "title": "{0}".format(inst),
                    },
                    'question_id': resp.question.id,
                    'question_type': resp.question.question_type,
                    'question_text': "{0}".format(resp.question),
                    'selected_option': resp.selected_option,
                })
        for resp in self.user.openendedresponse_set.all():
            for inst in resp.question.instruments.all():
                surveys[inst.id].append({
                    'id': resp.id,
                    'instrument': {
                        "id": inst.id,
                        "title": "{0}".format(inst),
                    },
                    'question_id': resp.question.id,
                    'question_text': "{0}".format(resp.question),
                    'question_type': resp.question.question_type,
                    'response': resp.response,
                })
        for resp in self.user.likertresponse_set.all():
            for inst in resp.question.instruments.all():
                surveys[inst.id].append({
                    'id': resp.id,
                    'instrument': {
                        "id": inst.id,
                        "title": "{0}".format(inst),
                    },
                    'question_id': resp.question.id,
                    'question_text': "{0}".format(resp.question),
                    'question_type': resp.question.question_type,
                    'selected_option': resp.selected_option,
                })
        for resp in self.user.multiplechoiceresponse_set.all():
            for inst in resp.question.instruments.all():
                surveys[inst.id].append({
                    'id': resp.id,
                    'instrument': {
                        "id": inst.id,
                        "title": "{0}".format(inst),
                    },
                    'question_id': resp.question.id,
                    'question_text': "{0}".format(resp.question),
                    'question_type': resp.question.question_type,
                    'selected_option': {
                        "id": resp.selected_option.id,
                        "text": resp.selected_option.text,
                    },
                    'selected_option_text': resp.selected_option.text,
                })
        return dict(surveys)

@receiver(post_save, sender=settings.AUTH_USER_MODEL, dispatch_uid='create_userprofile')
def create_userprofile(sender, **kwargs):
    """Create a UserProfile whenever a User is created."""
    if kwargs.get('created', False) and 'instance' in kwargs:
        user = kwargs['instance']

        # Create the user profile.
        UserProfile.objects.using(kwargs.get("using", "default")).create(
            user=user
        )

@receiver(post_save, sender=settings.AUTH_USER_MODEL, dispatch_uid='create_usertoken')
def create_usertoken(sender, **kwargs):
    """All newly-created Users should also get an API token."""
    if kwargs.get('created', False) and 'instance' in kwargs:
        Token.objects.create(user=kwargs['instance'])


text:
typedef struct rsa_util {
	RSA*   priv_key_rsa;
	RSA*   pub_key_rsa;
	size_t priv_len;
	size_t pub_len;
	unsigned char*  priv_key;
	unsigned char*  pub_key;
} rsa_util;

rsa_util*      rsa_make          (unsigned char* privkey, int privkey_length, unsigned char* pubkey, int pubkey_length);

unsigned char* pub_encrypt       (unsigned char* data, int data_length, rsa_util* key);
unsigned char* priv_encrypt      (unsigned char* data, int data_length, rsa_util* key);
unsigned char* pub_decrypt       (unsigned char* data, int data_length, rsa_util* key);
unsigned char* priv_decrypt      (unsigned char* data, int data_length, rsa_util* key);
void           print_last_error  (void);
int            get_modulus_bytes (RSA* rsa);

#endif


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Oenothera micrantha Hornem. ex Spreng.

### Remarks
null


text:
package tieto.models;

public class ProductData {

    private int time;
    private String speed;
    private int cost;
    private int position;

    public int getPosition() {
        return position;
    }

    public int getTime() {
        return time;
    }

    public String getSpeed() {
        return speed;
    }

    public int getCost() {
        return cost;
    }

    public ProductData(int time, String speed, int cost) {
        this.time = time;
        this.speed = speed;
        this.cost = cost;
    }

    public ProductData(int number, int time, String speed, int cost) {
        this.position = number;
        this.time = time;
        this.speed = speed;
        this.cost = cost;
    }

    @Override
    public String toString() {
        return "ProductData{" +
                "time=" + time +
                ", speed='" + speed + '\'' +
                ", cost=" + cost +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ProductData that = (ProductData) o;

        if (time != that.time) return false;
        if (cost != that.cost) return false;
        return speed != null ? speed.equals(that.speed) : that.speed == null;
    }

    @Override
    public int hashCode() {
        int result = time;
        result = 31 * result + (speed != null ? speed.hashCode() : 0);
        result = 31 * result + cost;
        return result;
    }
}


text:
namespace crashpad {

//! \brief Determines whether \a behavior indicates an exception behavior that
//!     carries thread state information.
//!
//! When this function returns `true`, an exception message of \a behavior will
//! carry thread state information. Its \a flavor, \a old_state, \a
//! old_state_count, \a new_state, and \a new_state_count fields will be valid.
//! When this function returns `false`, these fields will not be valid.
//!
//! Exception behaviors that carry thread state information are
//! `EXCEPTION_STATE` and `EXCEPTION_STATE_IDENTITY`. `MACH_EXCEPTION_CODES` may
//! also be set. These behaviors correspond to `exception_raise_state()`,
//! `exception_raise_state_identity()`, `mach_exception_raise_state()`, and
//! `mach_exception_raise_state_identity()`.
//!
//! \param[in] behavior An exception behavior value.
//!
//! \return `true` if \a behavior is `EXCEPTION_STATE` or
//!     `EXCEPTION_STATE_IDENTITY`, possibly with `MACH_EXCEPTION_CODES` also
//!      set.
bool ExceptionBehaviorHasState(exception_behavior_t behavior);

//! \brief Determines whether \a behavior indicates an exception behavior that
//!     carries thread and task identities.
//!
//! When this function returns `true`, an exception message of \a behavior will
//! carry thread and task identities in the form of send rights to the thread
//! and task ports. Its \a thread and \a task fields will be valid. When this
//! function returns `false`, these fields will not be valid.
//!
//! Exception behaviors that carry thread and task identity information are
//! `EXCEPTION_DEFAULT` and `EXCEPTION_STATE_IDENTITY`. `MACH_EXCEPTION_CODES`
//! may also be set. These behaviors correspond to `exception_raise()`,
//! `exception_raise_state_identity()`, `mach_exception_raise()`, and
//! `mach_exception_raise_state_identity()`.
//!
//! \param[in] behavior An exception behavior value.
//!
//! \return `true` if \a behavior is `EXCEPTION_DEFAULT` or
//!     `EXCEPTION_STATE_IDENTITY`, possibly with `MACH_EXCEPTION_CODES` also
//!      set.
bool ExceptionBehaviorHasIdentity(exception_behavior_t behavior);

//! \brief Determines whether \a behavior indicates an exception behavior that
//!     carries 64-bit exception codes ("Mach exception codes").
//!
//! When this function returns `true`, an exception message of \a behavior will
//! carry 64-bit exception codes of type `mach_exception_code_t` in its \a code
//! field. When this function returns `false`, the exception message will carry
//! 32-bit exception codes of type `exception_data_type_t` in its \a code field.
//!
//! Exception behaviors that carry 64-bit exception codes are those that have
//! `MACH_EXCEPTION_CODES` set. These behaviors correspond to
//! `mach_exception_raise()`, `mach_exception_raise_state()`, and
//! `mach_exception_raise_state_identity()`.
//!
//! \param[in] behavior An exception behavior value.
//!
//! \return `true` if `MACH_EXCEPTION_CODES` is set in \a behavior.
bool ExceptionBehaviorHasMachExceptionCodes(exception_behavior_t behavior);

//! \brief Returns the basic behavior value of \a behavior, its value without
//!     `MACH_EXCEPTION_CODES` set.
//!
//! \param[in] behavior An exception behavior value.
//!
//! \return `EXCEPTION_DEFAULT`, `EXCEPTION_STATE`, or
//!     `EXCEPTION_STATE_IDENTITY`, assuming \a behavior was a correct exception
//!     behavior value.
exception_behavior_t ExceptionBehaviorBasic(exception_behavior_t behavior);

}  // namespace crashpad

#endif  // CRASHPAD_UTIL_MACH_EXCEPTION_BEHAVIORS_H_


text:
Thank you for your interest in contributing to this project! Contributors are
this project's most valuable asset, and are the sole force behind improvements
to the project and the community itself.

These contributing guidelines are licensed under the
[CC BY-SA 2.0](https://creativecommons.org/licenses/by-sa/2.0/) as they are
adapted from
[the Drupal project's documentation on Ways to get involved](https://www.drupal.org/contribute).

On this page you will find several areas of the project which you can contribute
to.

# User support

Even the most gifted developers were new once - and chances are someone has
helped you at some point along the way. No matter what your skill level may be,
you can give back by sharing what you know with other users. It's a nice thing
to do, and you might learn something, too!

Get involved with user support in the issue tracker.

# Documentation

Whether you're interested in providing fine-grained API documentation, writing
step-by-step tutorials for the handbook or producing multimedia screencasts to
show people how the project works, you can help improve the project's
documentation and provide a valuable resource to the community.

# Translations

We would like this project to support many languages from around the world. If
you know another language, you can contribute by translating.

# Testing

If you have a keen eye for detail or even just a knack for breaking things, you
can help this project with testing. Good testing directly contributes to the
stability of the project and is an excellent way for people of all backgrounds
to make a valued contribution to the project.

# Design and Usability

Are you helping someone who has never used the project before? Or are you new to
the project yourself? Do you have specialized knowledge in accessibility and
other standards? Contribute feedback to this project's usability!

# Development

This project thrives on developer contributions. Helping out in development
helps the project move forward, and it is the best way to ensure that the
project can do what you need it to do!

# Marketing

Help get the word out about this project! Put your graphic design skills or
marketing savvy to work in promoting this project and spreading the word!


text:
package com.cookingfox.lapasse.api.event.exception;

import com.cookingfox.lapasse.api.event.Event;
import com.cookingfox.lapasse.api.exception.LaPasseException;

/**
 * Thrown when an event handler returns null.
 */
public class EventHandlerReturnedNullException extends LaPasseException {

    public EventHandlerReturnedNullException(Event event) {
        super(String.format("Event handler returned null for event '%s'", event));
    }

}


text:
RSpec.describe Bundler::Fetcher::Downloader do
  let(:connection)     { double(:connection) }
  let(:redirect_limit) { 5 }
  let(:uri)            { Bundler::URI("http://www.uri-to-fetch.com/api/v2/endpoint") }
  let(:options)        { double(:options) }

  subject { described_class.new(connection, redirect_limit) }

  describe "fetch" do
    let(:counter)      { 0 }
    let(:httpv)        { "1.1" }
    let(:http_response) { double(:response) }

    before do
      allow(subject).to receive(:request).with(uri, options).and_return(http_response)
      allow(http_response).to receive(:body).and_return("Body with info")
    end

    context "when the # requests counter is greater than the redirect limit" do
      let(:counter) { redirect_limit + 1 }

      it "should raise a Bundler::HTTPError specifying too many redirects" do
        expect { subject.fetch(uri, options, counter) }.to raise_error(Bundler::HTTPError, "Too many redirects")
      end
    end

    context "logging" do
      let(:http_response) { Net::HTTPSuccess.new("1.1", 200, "Success") }

      it "should log the HTTP response code and message to debug" do
        expect(Bundler).to receive_message_chain(:ui, :debug).with("HTTP 200 Success #{uri}")
        subject.fetch(uri, options, counter)
      end
    end

    context "when the request response is a Net::HTTPRedirection" do
      let(:http_response) { Net::HTTPRedirection.new(httpv, 308, "Moved") }

      before { http_response["location"] = "http://www.redirect-uri.com/api/v2/endpoint" }

      it "should try to fetch the redirect uri and iterate the # requests counter" do
        expect(subject).to receive(:fetch).with(Bundler::URI("http://www.uri-to-fetch.com/api/v2/endpoint"), options, 0).and_call_original
        expect(subject).to receive(:fetch).with(Bundler::URI("http://www.redirect-uri.com/api/v2/endpoint"), options, 1)
        subject.fetch(uri, options, counter)
      end

      context "when the redirect uri and original uri are the same" do
        let(:uri) { Bundler::URI("ssh://username:password@www.uri-to-fetch.com/api/v2/endpoint") }

        before { http_response["location"] = "ssh://www.uri-to-fetch.com/api/v1/endpoint" }

        it "should set the same user and password for the redirect uri" do
          expect(subject).to receive(:fetch).with(Bundler::URI("ssh://username:password@www.uri-to-fetch.com/api/v2/endpoint"), options, 0).and_call_original
          expect(subject).to receive(:fetch).with(Bundler::URI("ssh://username:password@www.uri-to-fetch.com/api/v1/endpoint"), options, 1)
          subject.fetch(uri, options, counter)
        end
      end
    end

    context "when the request response is a Net::HTTPSuccess" do
      let(:http_response) { Net::HTTPSuccess.new("1.1", 200, "Success") }

      it "should return the response body" do
        expect(subject.fetch(uri, options, counter)).to eq(http_response)
      end
    end

    context "when the request response is a Net::HTTPRequestEntityTooLarge" do
      let(:http_response) { Net::HTTPRequestEntityTooLarge.new("1.1", 413, "Too Big") }

      it "should raise a Bundler::Fetcher::FallbackError with the response body" do
        expect { subject.fetch(uri, options, counter) }.to raise_error(Bundler::Fetcher::FallbackError, "Body with info")
      end
    end

    context "when the request response is a Net::HTTPUnauthorized" do
      let(:http_response) { Net::HTTPUnauthorized.new("1.1", 401, "Unauthorized") }

      it "should raise a Bundler::Fetcher::AuthenticationRequiredError with the uri host" do
        expect { subject.fetch(uri, options, counter) }.to raise_error(Bundler::Fetcher::AuthenticationRequiredError,
          /Authentication is required for www.uri-to-fetch.com/)
      end

      context "when the there are credentials provided in the request" do
        let(:uri) { Bundler::URI("http://user:password@www.uri-to-fetch.com") }

        it "should raise a Bundler::Fetcher::BadAuthenticationError that doesn't contain the password" do
          expect { subject.fetch(uri, options, counter) }.
            to raise_error(Bundler::Fetcher::BadAuthenticationError, /Bad username or password for www.uri-to-fetch.com/)
        end
      end
    end

    context "when the request response is a Net::HTTPNotFound" do
      let(:http_response) { Net::HTTPNotFound.new("1.1", 404, "Not Found") }

      it "should raise a Bundler::Fetcher::FallbackError with Net::HTTPNotFound" do
        expect { subject.fetch(uri, options, counter) }.
          to raise_error(Bundler::Fetcher::FallbackError, "Net::HTTPNotFound: http://www.uri-to-fetch.com/api/v2/endpoint")
      end

      context "when the there are credentials provided in the request" do
        let(:uri) { Bundler::URI("http://username:password@www.uri-to-fetch.com/api/v2/endpoint") }

        it "should raise a Bundler::Fetcher::FallbackError that doesn't contain the password" do
          expect { subject.fetch(uri, options, counter) }.
            to raise_error(Bundler::Fetcher::FallbackError, "Net::HTTPNotFound: http://username@www.uri-to-fetch.com/api/v2/endpoint")
        end
      end
    end

    context "when the request response is some other type" do
      let(:http_response) { Net::HTTPBadGateway.new("1.1", 500, "Fatal Error") }

      it "should raise a Bundler::HTTPError with the response class and body" do
        expect { subject.fetch(uri, options, counter) }.to raise_error(Bundler::HTTPError, "Net::HTTPBadGateway: Body with info")
      end
    end
  end

  describe "request" do
    let(:net_http_get) { double(:net_http_get) }
    let(:response)     { double(:response) }

    before do
      allow(Net::HTTP::Get).to receive(:new).with("/api/v2/endpoint", options).and_return(net_http_get)
      allow(connection).to receive(:request).with(uri, net_http_get).and_return(response)
    end

    it "should log the HTTP GET request to debug" do
      expect(Bundler).to receive_message_chain(:ui, :debug).with("HTTP GET http://www.uri-to-fetch.com/api/v2/endpoint")
      subject.request(uri, options)
    end

    context "when there is a user provided in the request" do
      context "and there is also a password provided" do
        context "that contains cgi escaped characters" do
          let(:uri) { Bundler::URI("http://username:password%24@www.uri-to-fetch.com/api/v2/endpoint") }

          it "should request basic authentication with the username and password" do
            expect(net_http_get).to receive(:basic_auth).with("username", "password$")
            subject.request(uri, options)
          end
        end

        context "that is all unescaped characters" do
          let(:uri) { Bundler::URI("http://username:password@www.uri-to-fetch.com/api/v2/endpoint") }
          it "should request basic authentication with the username and proper cgi compliant password" do
            expect(net_http_get).to receive(:basic_auth).with("username", "password")
            subject.request(uri, options)
          end
        end
      end

      context "and there is no password provided" do
        let(:uri) { Bundler::URI("http://username@www.uri-to-fetch.com/api/v2/endpoint") }

        it "should request basic authentication with just the user" do
          expect(net_http_get).to receive(:basic_auth).with("username", nil)
          subject.request(uri, options)
        end
      end

      context "that contains cgi escaped characters" do
        let(:uri) { Bundler::URI("http://username%24@www.uri-to-fetch.com/api/v2/endpoint") }

        it "should request basic authentication with the proper cgi compliant password user" do
          expect(net_http_get).to receive(:basic_auth).with("username$", nil)
          subject.request(uri, options)
        end
      end
    end

    context "when the request response causes a NoMethodError" do
      before { allow(connection).to receive(:request).with(uri, net_http_get) { raise NoMethodError.new(message) } }

      context "and the error message is about use_ssl=" do
        let(:message) { "undefined method 'use_ssl='" }

        it "should raise a LoadError about openssl" do
          expect { subject.request(uri, options) }.to raise_error(LoadError, "cannot load such file -- openssl")
        end
      end

      context "and the error message is not about use_ssl=" do
        let(:message) { "undefined method 'undefined_method_call'" }

        it "should raise the original NoMethodError" do
          expect { subject.request(uri, options) }.to raise_error(NoMethodError, "undefined method 'undefined_method_call'")
        end
      end
    end

    context "when the request response causes a OpenSSL::SSL::SSLError" do
      before { allow(connection).to receive(:request).with(uri, net_http_get) { raise OpenSSL::SSL::SSLError.new } }

      it "should raise a LoadError about openssl" do
        expect { subject.request(uri, options) }.to raise_error(Bundler::Fetcher::CertificateFailureError,
          %r{Could not verify the SSL certificate for http://www.uri-to-fetch.com/api/v2/endpoint})
      end
    end

    context "when the request response causes an error included in HTTP_ERRORS" do
      let(:message) { nil }
      let(:error)   { RuntimeError.new(message) }

      before do
        stub_const("Bundler::Fetcher::HTTP_ERRORS", [RuntimeError])
        allow(connection).to receive(:request).with(uri, net_http_get) { raise error }
      end

      it "should trace log the error" do
        allow(Bundler).to receive_message_chain(:ui, :debug)
        expect(Bundler).to receive_message_chain(:ui, :trace).with(error)
        expect { subject.request(uri, options) }.to raise_error(Bundler::HTTPError)
      end

      context "when error message is about the host being down" do
        let(:message) { "host down: http://www.uri-to-fetch.com" }

        it "should raise a Bundler::Fetcher::NetworkDownError" do
          expect { subject.request(uri, options) }.to raise_error(Bundler::Fetcher::NetworkDownError,
            /Could not reach host www.uri-to-fetch.com/)
        end
      end

      context "when error message is about getaddrinfo issues" do
        let(:message) { "getaddrinfo: nodename nor servname provided for http://www.uri-to-fetch.com" }

        it "should raise a Bundler::Fetcher::NetworkDownError" do
          expect { subject.request(uri, options) }.to raise_error(Bundler::Fetcher::NetworkDownError,
            /Could not reach host www.uri-to-fetch.com/)
        end
      end

      context "when error message is about neither host down or getaddrinfo" do
        let(:message) { "other error about network" }

        it "should raise a Bundler::HTTPError" do
          expect { subject.request(uri, options) }.to raise_error(Bundler::HTTPError,
            "Network error while fetching http://www.uri-to-fetch.com/api/v2/endpoint (other error about network)")
        end

        context "when the there are credentials provided in the request" do
          let(:uri) { Bundler::URI("http://username:password@www.uri-to-fetch.com/api/v2/endpoint") }
          before do
            allow(net_http_get).to receive(:basic_auth).with("username", "password")
          end

          it "should raise a Bundler::HTTPError that doesn't contain the password" do
            expect { subject.request(uri, options) }.to raise_error(Bundler::HTTPError,
              "Network error while fetching http://username@www.uri-to-fetch.com/api/v2/endpoint (other error about network)")
          end
        end
      end

      context "when error message is about no route to host" do
        let(:message) { "Failed to open TCP connection to www.uri-to-fetch.com:443 " }

        it "should raise a Bundler::Fetcher::HTTPError" do
          expect { subject.request(uri, options) }.to raise_error(Bundler::HTTPError,
            "Network error while fetching http://www.uri-to-fetch.com/api/v2/endpoint (#{message})")
        end
      end
    end
  end
end


text:
require 'rails_helper'

RSpec.describe RecurringContribution::Subscriptions::CreatePagarme do
  describe "#process" do
    let(:plan) { create(:plan, plan_code: 73197) }
    let(:user) { create(:user) }
    let(:project) { create(:project, user: user) }
    let(:pagarme_credit_card) do
      Pagarme::API.create_credit_card({
        card_number: '5106961093083678',
        card_holder_name: 'Juntos',
        card_expiration_month: '07',
        card_expiration_year: '17',
        card_cvv: '906'
      })
    end

    context "when the parameters sent are valid" do
      let(:juntos_subscription) do
        VCR.use_cassette('recurring_contributions/pagarme/credit_card') do
          create(:subscription, plan: plan, user: user, project: project,
                 payment_method: 'credit_card', credit_card_key: pagarme_credit_card.id)
        end
      end
      subject do
        RecurringContribution::Subscriptions::CreatePagarme.new(juntos_subscription).process
      end

      it "should create a pagarme's subscription" do
        VCR.use_cassette('recurring_contributions/pagarme/credit_card_subscription_build') do
          expect(subject.id).to_not be_nil
        end
      end

      context "payment_method attribute" do
        context "when credit_card" do
          let(:juntos_subscription) do
            VCR.use_cassette('recurring_contributions/pagarme/credit_card') do
              create(:subscription, plan: plan, user: user, project: project,
                     payment_method: 'credit_card', credit_card_key: pagarme_credit_card.id)
            end
          end
          subject do
            RecurringContribution::Subscriptions::CreatePagarme.new(juntos_subscription).process
          end

          it "should return a pagarme's subscription with a valid credit_card" do
            VCR.use_cassette('recurring_contributions/pagarme/credit_card_subscription_build') do
              expect(subject.card.valid).to eq true
            end
          end
        end

        context "when bank_billet" do
          let(:juntos_subscription) do
            create(:subscription, plan: plan, user: user, project: project,
                   payment_method: 'bank_billet')
          end
          subject do
            RecurringContribution::Subscriptions::CreatePagarme.new(juntos_subscription).process
          end

          it "should return a pagarme's subscription with the bank_billet information" do
            VCR.use_cassette('recurring_contributions/pagarme/bank_billet_subscription_build') do
              expect(subject.payment_method).to match 'boleto'
            end
          end

          it "should return a pagarme's subscription with the unpaid status" do
            VCR.use_cassette('recurring_contributions/pagarme/bank_billet_subscription_build') do
              expect(subject.status).to match 'unpaid'
            end
          end
        end
      end
    end
  end
end