text:
/*
 * Created by IntelliJ IDEA.
 * User: martin
 * Date: 3/13/11
 * Time: 1:42 PM
 */
package simx.components.editor.gui

import swing._
import scala.collection.mutable
import java.io.File
import simx.components.editor.filesystem._
import swing.event.{ButtonClicked, SelectionChanged}
import simx.components.editor.AvailableViewsChanged
import simx.core.svaractor.SVarActor
import scala.reflect.runtime.universe.TypeTag
import scala.reflect.ClassTag

class SVarSetterPanel(
  val node: EnSVar,
  sVarIdentifier: Symbol,
  man: ClassTag[_],
  sVarSetters: mutable.Map[Symbol,
  DynamicReloader[SVarSetterGeneratorBase]],
  availableSetters: mutable.Set[DynamicReloader[SVarSetterGeneratorBase]],
  editorActor: SVarActor.Ref,
  sourceDir: File
) extends DetailsView {

  private var updateFunc: () => Unit = () => {}

  /*Minor Components*/
  val editButton = new Button("e"){
    maximumSize = new Dimension(20, 20)
    minimumSize = new Dimension(20, 20)
    preferredSize = new Dimension(20, 20)

    peer.setMargin(new java.awt.Insets(1, 2, 1, 2))

    listenTo(this)
    reactions += {
      case ButtonClicked(source) if source == this =>
        val selectedItem: DynamicReloader[SVarSetterGeneratorBase]  = list.selection.item
        if(selectedItem != SVarViewPanel.default)
          selectedItem.showInIDE()
    }

  }
  val addButton = new Button("+"){
    maximumSize = new Dimension(20, 20)
    minimumSize = new Dimension(20, 20)
    preferredSize = new Dimension(20, 20)

    peer.setMargin(new java.awt.Insets(1, 2, 1, 2))

    listenTo(this)

    reactions += {
      case ButtonClicked(source) if source == this =>
        val typeName = man.toString()
        val importRequired = man.runtimeClass.getPackage != null
        val shortClassName =
          typeName.substring(typeName.lastIndexOf('.') + 1) +
          "SVarSetterGenerator" +
          java.util.UUID.randomUUID.toString.replace("-", "")
        val fullClassName = "simx.components.editor.gui." + shortClassName
        val file = new File(sourceDir, shortClassName + ".scala")
        val dr = new DynamicReloader[SVarSetterGeneratorBase] (
          ClassFile(file, fullClassName),
          SVarSetterPanel.compilerSettings(sourceDir),
          Some(SVarSetterPanel.generateClassTemplateFor(shortClassName, typeName, importRequired)),
          (svarViewGenBaseOption: Option[SVarSetterGeneratorBase]) => {list.repaint(); updateSVarView()}
        ) {
          override def toString: String = {
            getCurrentClass match {
              case Some(clazz) => clazz.toString()
              case None => "Class loaded with errors"
            }
          }
        }
        availableSetters.add(dr)
        publish(AvailableViewsChanged())
    }
  }
  val removeButton = new Button("-"){
    maximumSize = new Dimension(20, 20)
    minimumSize = new Dimension(20, 20)
    preferredSize = new Dimension(20, 20)

    peer.setMargin(new java.awt.Insets(1, 2, 1, 2))

    listenTo(this)
    reactions += {
      case ButtonClicked(source) if source == this =>
        val selectedItem: DynamicReloader[SVarSetterGeneratorBase]  = list.selection.item

        availableSetters.remove(selectedItem)
        sVarSetters.get(sVarIdentifier).collect{
          case dr => if(dr == selectedItem) sVarSetters.remove(sVarIdentifier)
        }
        println("Removing file " + selectedItem.classFile.file.getName)
        selectedItem.classFile.file.deleteOnExit()
        publish(AvailableViewsChanged())

    }
  }

  private val initialListItems =
    if(availableSetters.isEmpty) Seq(SVarSetterPanel.defaultListItem) else availableSetters.toSeq

  val list = new AdvComboBox[DynamicReloader[SVarSetterGeneratorBase]](initialListItems){
    listenTo(this)

    sVarSetters.get(sVarIdentifier).collect{
      case dr =>
        selection.item = dr
    }

    reactions += {
      case SelectionChanged(source) if source == this =>
        val selectedItem: DynamicReloader[SVarSetterGeneratorBase]  = selection.item
        //println("Updating " + sVarIdentifier.name)
        sVarSetters.update(sVarIdentifier, selectedItem)
        updateSVarView()
    }

    if((getItems.size == 1) && (getItems(0) == SVarSetterPanel.defaultListItem)) enabled = false
  }

  private def updateSVarView(){
    if(list.enabled) {
      if(list.selection.item.getCurrentClass.isDefined) {
        val newSVarSetterBase: SVarSetterBase = list.selection.item.getCurrentClass.get.generate
        newSVarSetterBase.changeRegisteredSvarTo(node.sVar)
        pane.contents = newSVarSetterBase.component
        list.selection.item.onLoad =
          (svarViewGenBaseOption: Option[SVarSetterGeneratorBase]) => {list.repaint(); updateSVarView()}
        updateFunc = () => {newSVarSetterBase.internalUpdate(node.children.head.asInstanceOf[EnSVarValue].value)}
        updateFunc.apply()
      }
      else {
        pane.contents = new Label("Error on loading SVar setter")
      }
    }
    else
      pane.contents = new Label("No SVar setter selected.")
  }

  val pane = new ScrollPane
  /*Minor Components END*/

  //Set the sVarView
  updateSVarView()

  /*Main Component*/
  val component = new GridBagPanel() {

    listenTo(addButton)
    listenTo(removeButton)

    val gbc = new Constraints()
    gbc.fill = GridBagPanel.Fill.Both
    gbc.gridy = 0
    gbc.gridx = 0
    gbc.weighty = 1.0
    gbc.weightx = 1.0
    add(pane, gbc)
    gbc.gridy = 1
    gbc.gridx = 0
    gbc.weighty = 0.0
    gbc.weightx = 0.0
    add(new BoxPanel(Orientation.Horizontal) {
      contents += addButton
      contents += removeButton
      contents += editButton
      contents += list
    }, gbc)
    border = Swing.EmptyBorder(10, 10, 10, 10)

    reactions += {
      case event: AvailableViewsChanged =>
        val sel = list.selection.item
        val listItems = if(availableSetters.isEmpty) Seq(SVarSetterPanel.defaultListItem) else availableSetters.toSeq
        list.setItems(listItems)
        if(list.getItems.contains(sel)) list.selection.item = sel

        if((list.getItems.size == 1) && (list.getItems(0) == SVarSetterPanel.defaultListItem))
          list.enabled = false
        else
          list.enabled = true
    }
  }

  //TODO: refactor class structure. Update is not used for a setter
  def update() { updateFunc.apply() }
  /*Main component END*/

}

object SVarSetterPanel {

  val defaultListItem =
    new DynamicReloader[SVarSetterGeneratorBase](
      classFile = ClassFile(null, ""),
      compilerSettings = CompilerSettings(null, List[File](), List[File]()),
      classTemplate = None,
      onLoad = (o : Option[SVarSetterGeneratorBase]) => {})
    {
      private val viewGen = Some(new SVarSetterGeneratorBase {
        val name = "No setter available."

        def generate: SVarSetterBase = {
          throw new Exception {
            override def toString = "SVarSetterPanel.defaultListItem this should not be called"
          }
          null.asInstanceOf[SVarSetterBase]
        }
      })

      currentClass = viewGen

      override def showInIDE() {}
      override protected def init() {}

      override def toString: String = {
        currentClass match {
          case Some(clazz) => clazz.toString()
          case None => "Class loaded with errors"
        }
      }
    }

  def compilerSettings(sourceDir: File) = CompilerSettings(
    outputPath = sourceDir,
    additionalClassPaths = SimXProperties.simXLibs ::: SimXProperties.simXClassPath ::: SimXProperties.scalaLibs
  )

  def generateClassTemplateFor(className: String, typeName: String, importRequired: Boolean = true): String = {
    val shortTypeName = typeName.substring(typeName.lastIndexOf('.') + 1)

"""//AutoGenerated Begin
//DO NOT EDIT!
package simx.components.editor.gui

import scala.swing._""" + (if(importRequired) "\nimport " + typeName + "\n" else "") + """

class """ + className + """ extends SVarSetterGenerator[""" + shortTypeName + """] {

  def generate: SVarSetter[""" + shortTypeName + """] = new SVarSetter[""" + shortTypeName + """] {

//AutoGenerated END
//Put your code below

    /**
     *  The scala.swing.Component that visualizes the SVar setter.
     *  Call
     *  setSvar(newValue: """ + shortTypeName + """): Unit
     *  to set new svar value.
     */
    //Todo: Implement yourself!
    val component = new Button("Click me to set the svar") {
      listenTo(this)
      reactions += {
        case event: event.ButtonClicked =>
          Dialog.showMessage(null, "Use 'e' button to edit the code", "Setter not implemented yet")

          /*
          setSvar(...)
          */
      }
    }

    /**
     * Override update if you want to use the current value of the SVar.
     * This function is initially called once and then every time the value of the SVar changes.
     */
    // override def update(newValue: """ + shortTypeName + """) {}

  }

  /**
   *  The name of this visualizer.
   *  This must not be unique.
   */
  //Todo: Name it!
  val name: String = """" + shortTypeName + """ Setter"

}"""
  }

}


text:
// Code generated by k8s code-generator DO NOT EDIT.

// Code generated by informer-gen. DO NOT EDIT.

package internalinterfaces

import (
	time "time"

	versioned "github.com/kubeflow/arena/pkg/operators/spark-operator/client/clientset/versioned"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	cache "k8s.io/client-go/tools/cache"
)

// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer.
type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer

// SharedInformerFactory a small interface to allow for adding an informer without an import cycle
type SharedInformerFactory interface {
	Start(stopCh <-chan struct{})
	InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer
}

// TweakListOptionsFunc is a function that transforms a v1.ListOptions.
type TweakListOptionsFunc func(*v1.ListOptions)

redpajama_set_name: RedPajamaGithub


text:
require 'fountain/session/aggregate_tracker'
require 'fountain/session/event_tracker'
require 'fountain/session/transaction_manager'
require 'fountain/session/unit'
require 'fountain/session/unit_factory'
require 'fountain/session/unit_listener'
require 'fountain/session/unit_listener_list'
require 'fountain/session/unit_stack'

module Fountain
  module Session
    # @return [Unit]
    def self.current_unit
      UnitStack.current
    end
  end
end


text:
var BaseViewApp = Backbone.View.extend({

    initialize: function(options){
        this.translationContext = options.context;
        this.offeredLanguages = options.offeredLanguages;

        this.customInitialization(options);

        this.listenTo(this.translationCollection, 'add', this.onAddTranslation);
        this.listenTo(this.translationCollection, 'reset', this.onResetTranslationCollection);

        this.translationCollection.fetch({
            data: {context: this.translationContext.id },
            reset: true
        });
    },

    onResetTranslationCollection: function(){
        var contextId = this.translationContext.id;
        this.translationCollection.each(this.onAddTranslation, this);

        // iterate through all languages and create a dummy translation for those that don't have
        _.each(this.offeredLanguages, function(item, key, list){
            var hasTranslation = item.hasTranslation || false;

            if (!hasTranslation) {
                var modelData = this.getPrototypeModelData(item, contextId);

                if ('en' == item.iso) {
                    // we don't want to save english translation
                    this.translationCollection.add(modelData);
                } else {
                    var collection = this.translationCollection;
                    var createdTranslation = this.translationCollection.create(modelData, {success: function(response) {
                        collection.add(createdTranslation);
                    }});
                }
            }

        }, this);
    },

    onAddTranslation: function(translation){
        var languageForIso = {};
        var currentIso = translation.get('languageIso');

        // get the language data for this ISO code
        _.each(this.offeredLanguages, function(item, key, list){
            if (item.iso == currentIso){
                languageForIso = item;
                return false;
            }
        });

        if ('en' == currentIso) {
            var englishAttribute = this.translationContext;
            englishAttribute.id = 0;

            translation.set(englishAttribute);
        }

        var view = this.getTranslationWidgetView(translation, languageForIso, this.translationContext);

        view.render();
        $('#translations_container').append(view.$el);
    },

    // override for extending view init
    customInitialization: function(options){

    },

    // override to include necessary values
    getPrototypeModelData: function(item,contextId){
        var modelData = {
            languageIso: item.iso,
            context: contextId
        };

        return modelData;
    },

    // override for custom widget view
    getTranslationWidgetView: function(model, language, context){
        var view = new TranslationView({
            model: model,
            language: language,
            context: context
        });

        return view;
    }
});


text:
// @flow weak

import React from 'react';
import { assert } from 'chai';
import { spy } from 'sinon';
import { createShallow, createMount, getClasses } from '../test-utils';
import Textarea from './Textarea';
import Input, { hasValue, isDirty } from './Input';

describe('<Input />', () => {
  let shallow;
  let classes;
  let mount;

  before(() => {
    shallow = createShallow({ dive: true });
    mount = createMount();
    classes = getClasses(<Input />);
  });

  after(() => {
    mount.cleanUp();
  });

  it('should render a <div />', () => {
    const wrapper = shallow(<Input />);
    assert.strictEqual(wrapper.name(), 'div');
    assert.strictEqual(wrapper.hasClass(classes.root), true);
    assert.strictEqual(wrapper.hasClass(classes.inkbar), true, 'should have the inkbar class');
    assert.strictEqual(
      wrapper.hasClass(classes.underline),
      true,
      'should have the underline class',
    );
  });

  it('should render an <input /> inside the div', () => {
    const wrapper = shallow(<Input />);
    const input = wrapper.find('input');
    assert.strictEqual(input.name(), 'input');
    assert.strictEqual(input.props().type, 'text', 'should pass the text type prop');
    assert.strictEqual(input.hasClass(classes.input), true, 'should have the input class');
    assert.strictEqual(input.prop('aria-required'), undefined);
  });

  it('should render an <Textarea /> when passed the multiline prop', () => {
    const wrapper = shallow(<Input multiline />);
    assert.strictEqual(wrapper.find(Textarea).length, 1);
  });

  it('should render an <textarea /> when passed the multiline and rows props', () => {
    const wrapper = shallow(<Input multiline rows="4" />);
    assert.strictEqual(wrapper.find('textarea').length, 1);
  });

  it('should render a disabled <input />', () => {
    const wrapper = shallow(<Input disabled />);
    const input = wrapper.find('input');
    assert.strictEqual(input.name(), 'input');
    assert.strictEqual(input.hasClass(classes.input), true, 'should have the input class');
    assert.strictEqual(
      input.hasClass(classes.inputDisabled),
      true,
      'should have the disabled class',
    );
  });

  it('should disabled the underline', () => {
    const wrapper = shallow(<Input disableUnderline />);
    const input = wrapper.find('input');
    assert.strictEqual(wrapper.hasClass(classes.inkbar), false, 'should not have the inkbar class');
    assert.strictEqual(input.name(), 'input');
    assert.strictEqual(input.hasClass(classes.input), true, 'should have the input class');
    assert.strictEqual(
      input.hasClass(classes.underline),
      false,
      'should not have the underline class',
    );
  });

  it('should fire event callbacks', () => {
    const events = ['onChange', 'onFocus', 'onBlur', 'onKeyUp', 'onKeyDown'];
    const handlers = events.reduce((result, n) => {
      result[n] = spy();
      return result;
    }, {});

    const wrapper = shallow(<Input {...handlers} />);

    events.forEach(n => {
      const event = n.charAt(2).toLowerCase() + n.slice(3);
      wrapper.find('input').simulate(event);
      assert.strictEqual(handlers[n].callCount, 1, `should have called the ${n} handler`);
    });
  });

  describe('controlled', () => {
    ['', 0].forEach(value => {
      describe(`${typeof value} value`, () => {
        let wrapper;
        let handleDirty;
        let handleClean;

        before(() => {
          handleClean = spy();
          handleDirty = spy();
          wrapper = shallow(<Input value={value} onDirty={handleDirty} onClean={handleClean} />);
        });

        it('should check that the component is controlled', () => {
          const instance = wrapper.instance();
          assert.strictEqual(instance.isControlled(), true, 'isControlled() should return true');
        });

        // don't test number because zero is a dirty state, whereas '' is not
        if (typeof value !== 'number') {
          it('should have called the handleClean callback', () => {
            assert.strictEqual(handleClean.callCount, 1, 'should have called the onClean cb');
          });

          it('should fire the onDirty callback when dirtied', () => {
            assert.strictEqual(
              handleDirty.callCount,
              0,
              'should not have called the onDirty cb yet',
            );
            wrapper.setProps({ value: typeof value === 'number' ? 2 : 'hello' });
            assert.strictEqual(handleDirty.callCount, 1, 'should have called the onDirty cb');
          });

          it('should fire the onClean callback when dirtied', () => {
            assert.strictEqual(
              handleClean.callCount,
              1,
              'should have called the onClean cb once already',
            );
            wrapper.setProps({ value });
            assert.strictEqual(handleClean.callCount, 2, 'should have called the onClean cb again');
          });
        }
      });
    });
  });

  describe('prop: component', () => {
    it('should accept any component', () => {
      const wrapper = shallow(<Input component="span" />);
      assert.strictEqual(wrapper.find('span').length, 1);
    });
  });

  /**
   * Note the initial callback when
   * uncontrolled only fires for a full mount
   */
  describe('uncontrolled', () => {
    let wrapper;
    let handleDirty;
    let handleClean;

    before(() => {
      handleClean = spy();
      handleDirty = spy();
      wrapper = mount(
        <Input.Naked
          classes={{}}
          onDirty={handleDirty}
          defaultValue="hell"
          onClean={handleClean}
        />,
      );
    });

    it('should check that the component is uncontrolled', () => {
      const instance = wrapper.instance();
      assert.strictEqual(instance.isControlled(), false, 'isControlled() should return false');
    });

    it('should fire the onDirty callback when dirtied', () => {
      assert.strictEqual(handleDirty.callCount, 1, 'should not have called the onDirty cb yet');
      wrapper.instance().input.value = 'hello';
      wrapper.find('input').simulate('change');
      assert.strictEqual(handleDirty.callCount, 2, 'should have called the onDirty cb');
    });

    it('should fire the onClean callback when cleaned', () => {
      // Because of shallow() this hasn't fired since there is no mounting
      assert.strictEqual(handleClean.callCount, 0, 'should not have called the onClean cb yet');
      wrapper.instance().input.value = '';
      wrapper.find('input').simulate('change');
      assert.strictEqual(handleClean.callCount, 1, 'should have called the onClean cb');
    });
  });

  describe('with muiFormControl context', () => {
    let wrapper;
    let muiFormControl;

    function setFormControlContext(muiFormControlContext) {
      muiFormControl = muiFormControlContext;
      wrapper.setContext({ ...wrapper.context(), muiFormControl });
    }

    beforeEach(() => {
      wrapper = shallow(<Input />);
    });

    it('should have the formControl class', () => {
      setFormControlContext({});
      assert.strictEqual(wrapper.hasClass(classes.formControl), true);
    });

    describe('callbacks', () => {
      let handleDirty;
      let handleClean;

      beforeEach(() => {
        handleDirty = spy();
        handleClean = spy();
        // Mock the input ref
        wrapper.setProps({
          onDirty: handleDirty,
          onClean: handleClean,
        });
        wrapper.instance().input = { value: '' };
        setFormControlContext({
          onDirty: spy(),
          onClean: spy(),
        });
      });

      it('should fire the onDirty muiFormControl and props callback when dirtied', () => {
        wrapper.instance().input.value = 'hello';
        wrapper.find('input').simulate('change');
        assert.strictEqual(handleDirty.callCount, 1, 'should have called the onDirty props cb');
        assert.strictEqual(
          muiFormControl.onDirty.callCount,
          1,
          'should have called the onDirty muiFormControl cb',
        );
      });

      it('should fire the onClean muiFormControl and props callback when cleaned', () => {
        wrapper.instance().input.value = '';
        wrapper.find('input').simulate('change');
        assert.strictEqual(handleClean.callCount, 1, 'should have called the onClean props cb');
        assert.strictEqual(
          muiFormControl.onClean.callCount,
          1,
          'should have called the onClean muiFormControl cb',
        );
      });
    });

    describe('error', () => {
      beforeEach(() => {
        setFormControlContext({ error: true });
      });

      it('should have the error class', () => {
        assert.strictEqual(wrapper.hasClass(classes.error), true);
      });

      it('should be overridden by props', () => {
        assert.strictEqual(wrapper.hasClass(classes.error), true);
        wrapper.setProps({ error: false });
        assert.strictEqual(wrapper.hasClass(classes.error), false);
        wrapper.setProps({ error: true });
        assert.strictEqual(wrapper.hasClass(classes.error), true);
      });
    });

    describe('margin', () => {
      describe('context margin: dense', () => {
        beforeEach(() => {
          setFormControlContext({ margin: 'dense' });
        });

        it('should have the inputDense class', () => {
          assert.strictEqual(wrapper.find('input').hasClass(classes.inputDense), true);
        });
      });

      it('should be overridden by props', () => {
        assert.strictEqual(wrapper.find('input').hasClass(classes.inputDense), false);
        wrapper.setProps({ margin: 'dense' });
        assert.strictEqual(wrapper.find('input').hasClass(classes.inputDense), true);
      });
    });

    describe('required', () => {
      it('should have the aria-required prop with value true', () => {
        setFormControlContext({ required: true });
        const input = wrapper.find('input');
        assert.strictEqual(input.prop('aria-required'), true);
      });
    });
  });

  describe('componentDidMount', () => {
    let wrapper;
    let instance;

    before(() => {
      wrapper = mount(<Input.Naked classes={classes} />);
      instance = wrapper.instance();
    });

    beforeEach(() => {
      instance.checkDirty = spy();
    });

    it('should not call checkDirty if controlled', () => {
      instance.isControlled = () => true;
      instance.componentDidMount();
      assert.strictEqual(instance.checkDirty.callCount, 0);
    });

    it('should call checkDirty if controlled', () => {
      instance.isControlled = () => false;
      instance.componentDidMount();
      assert.strictEqual(instance.checkDirty.callCount, 1);
    });

    it('should call checkDirty with input value', () => {
      instance.isControlled = () => false;
      instance.input = 'woofinput';
      instance.componentDidMount();
      assert.strictEqual(instance.checkDirty.calledWith(instance.input), true);
    });

    it('should call or not call checkDirty consistently', () => {
      instance.isControlled = () => true;
      instance.componentDidMount();
      assert.strictEqual(instance.checkDirty.callCount, 0);
      instance.isControlled = () => false;
      instance.componentDidMount();
      assert.strictEqual(instance.checkDirty.callCount, 1);
      instance.isControlled = () => true;
      instance.componentDidMount();
      assert.strictEqual(instance.checkDirty.callCount, 1);
    });
  });

  describe('mount', () => {
    it('should be able to access the native input', () => {
      const handleRef = spy();
      mount(<Input inputRef={handleRef} />);
      assert.strictEqual(handleRef.callCount, 1);
    });

    it('should be able to access the native textarea', () => {
      const handleRef = spy();
      mount(<Input multiline inputRef={handleRef} />);
      assert.strictEqual(handleRef.callCount, 1);
    });
  });

  describe('hasValue', () => {
    ['', 0].forEach(value => {
      it(`is true for ${value}`, () => {
        assert.strictEqual(hasValue(value), true);
      });
    });

    [null, undefined].forEach(value => {
      it(`is false for ${value}`, () => {
        assert.strictEqual(hasValue(value), false);
      });
    });
  });

  describe('isDirty', () => {
    [' ', 0].forEach(value => {
      it(`is true for value ${value}`, () => {
        assert.strictEqual(isDirty({ value }), true);
      });

      it(`is true for SSR defaultValue ${value}`, () => {
        assert.strictEqual(isDirty({ defaultValue: value }, true), true);
      });
    });
    [null, undefined, ''].forEach(value => {
      it(`is false for value ${value}`, () => {
        assert.strictEqual(isDirty({ value }), false);
      });
      it(`is false for SSR defaultValue ${value}`, () => {
        assert.strictEqual(isDirty({ defaultValue: value }, true), false);
      });
    });
  });
});


text:
#include "config.h"
#include "core/layout/PendingSelection.h"

#include "core/dom/Document.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleUnits.h"
#include "core/html/HTMLTextFormControlElement.h"

namespace blink {

PendingSelection::PendingSelection()
    : m_affinity(SEL_DEFAULT_AFFINITY)
    , m_hasPendingSelection(false)
    , m_shouldShowBlockCursor(false)
{
    clear();
}

void PendingSelection::setSelection(const FrameSelection& selection)
{
    m_start = selection.start();
    m_end = selection.end();
    m_extent = selection.extent();
    m_affinity = selection.affinity();
    m_shouldShowBlockCursor = selection.shouldShowBlockCursor();
    m_hasPendingSelection = true;
}

void PendingSelection::clear()
{
    m_hasPendingSelection = false;
    m_start.clear();
    m_end.clear();
    m_extent.clear();
    m_affinity = SEL_DEFAULT_AFFINITY;
    m_shouldShowBlockCursor = false;
}

bool PendingSelection::isInDocument(const Document& document) const
{
    if (m_start.isNotNull() && (!m_start.inDocument() || m_start.document() != document))
        return false;
    if (m_end.isNotNull() && (!m_end.inDocument() || m_end.document() != document))
        return false;
    if (m_extent.isNotNull() && (!m_extent.inDocument() || m_extent.document() != document))
        return false;
    return true;
}

VisibleSelection PendingSelection::calcVisibleSelection() const
{
    SelectionType selectionType = VisibleSelection::selectionType(m_start, m_end);

    Position start = m_start;
    Position end = m_end;

    bool paintBlockCursor = m_shouldShowBlockCursor && selectionType == SelectionType::CaretSelection && !isLogicalEndOfLine(VisiblePosition(end, m_affinity));
    VisibleSelection selection;
    if (enclosingTextFormControl(start)) {
        Position endPosition = paintBlockCursor ? m_extent.next() : m_end;
        selection.setWithoutValidation(start, endPosition);
        return selection;
    }

    VisiblePosition visibleStart = VisiblePosition(start, selectionType == SelectionType::RangeSelection ? DOWNSTREAM : m_affinity);
    if (paintBlockCursor) {
        VisiblePosition visibleExtent(end, m_affinity);
        visibleExtent = visibleExtent.next(CanSkipOverEditingBoundary);
        return VisibleSelection(visibleStart, visibleExtent);
    }
    VisiblePosition visibleEnd(end, selectionType == SelectionType::RangeSelection ? UPSTREAM : m_affinity);
    return VisibleSelection(visibleStart, visibleEnd);
}

DEFINE_TRACE(PendingSelection)
{
    visitor->trace(m_start);
    visitor->trace(m_end);
    visitor->trace(m_extent);
}

} // namespace blink


text:
'use strict';
const testHelper = require('../../../../test_helper');
const fse = require('fs-extra');
const path = require('path');
const expect = testHelper.expect;
const sinon = testHelper.sinon;
const MergeConflicts = testHelper.requireSourceModule(module);
const Config = testHelper.requireSourceModule(module, 'lib/config');
const HookContextPreCommit = testHelper.requireSourceModule(module, 'lib/hook-context/pre-commit');
const utils = testHelper.requireSourceModule(module, 'lib/utils');

describe('MergeConflicts', function () {
  beforeEach('setup hook context', function() {
    this.oldCwd = process.cwd();
    this.repoPath = testHelper.tempRepo();
    process.chdir(this.repoPath);

    this.sandbox = sinon.sandbox.create();
    this.config = new Config({});
    this.context = new HookContextPreCommit(this.config, [], {});
    this.hook = new MergeConflicts(this.config, this.context);
    this.stagedFile = 'filename.txt';

    this.sandbox.stub(this.config, 'concurrency').returns(1);
    this.sandbox.stub(this.hook, 'command').returns('grep');
    this.sandbox.stub(this.hook, 'flags').returns(['-IHn', '^<<<<<<<[ \t]']);
    this.sandbox.stub(this.hook, 'applicableFiles');
  });

  afterEach('reset cwd on process', function() {
    if(!this.oldCwd) { return; }

    process.chdir(this.oldCwd);
    testHelper.cleanupDirectory(this.repoPath);
    this.sandbox.restore();
  });

  it('fails when the file contains a merge conflict marker', function() {
    let filePath = path.join(this.repoPath, this.stagedFile);
    fse.writeFileSync(filePath, 'Just\n<<<<<<< HEAD:filename.txt\nconflicting text');

    utils.execSync('git add ' + this.stagedFile);
    this.hook.applicableFiles.returns([filePath]);

    return this.hook.run().then((hookResult) => {
      expect(hookResult).to.have.length(2);
      expect(hookResult[0]).to.equal('fail');
    });
  });

  it('passes when the file has no merge conflicts', function() {
    let filePath = path.join(this.repoPath, this.stagedFile);
    fse.writeFileSync(filePath, 'Just some text, yo');

    utils.execSync('git add ' + this.stagedFile);
    this.hook.applicableFiles.returns([filePath]);

    return this.hook.run().then((hookResult) => {
      expect(hookResult).to.equal('pass');
    });
  });

  it('passes when the file almost has conflict markers', function() {
    let filePath = path.join(this.repoPath, this.stagedFile);
    fse.writeFileSync(filePath, 'Just some <<<<<<<<<<< arrows, yo');

    utils.execSync('git add ' + this.stagedFile);
    this.hook.applicableFiles.returns([filePath]);

    return this.hook.run().then((hookResult) => {
      expect(hookResult).to.equal('pass');
    });
  });
});


text:
import module_cu0 = require("./cu")
import module_dq1 = require("./dq")
import module_cs2 = require("./cs")
import module_ce3 = require("./ce")
import module_dm4 = require("./dm")
import module_cg5 = require("./cg")
import module_cc6 = require("./cc")
import module_dq7 = require("./dq")
import module_dr8 = require("./dr")
import module_cg9 = require("./cg")

R.doSomething()
E.doSomething()
S.doSomething()
module_cu0.doSomething()
module_dq1.doSomething()
module_cs2.doSomething()
module_ce3.doSomething()
module_dm4.doSomething()
module_cg5.doSomething()
module_cc6.doSomething()
module_dq7.doSomething()
module_dr8.doSomething()
module_cg9.doSomething()
export function doSomething() { }


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>CodeIgniter User Guide</title>

<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />
<meta name='author' content='Rick Ellis' />
<meta name='description' content='CodeIgniter User Guide' />

CodeIgniter User Guide Version 1.5.4

Table of Contents Page

CodeIgniter Home  ›
User Guide Home  ›
Directory Helper

<form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide  <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" /> <input type="submit" class="submit" name="sa" value="Go" /></form>

Directory Helper

The Directory Helper file contains functions that assist in working with directories.

Loading this Helper

This helper is loaded using the following code:

$this->load->helper('directory');

The following functions are available:

directory_map('<var>source directory</var>')

This function reads the directory path specified in the first parameter
and builds an array representation of it and all its contained files. Example:

$map = directory_map('./mydirectory/');

Note: Paths are almost always relative to your main index.php file.

Sub-folders contained within the directory will be mapped as well.  If you wish to map
only the top level directory set the second parameter to <var>true</var> (boolean):

$map = directory_map('./mydirectory/', TRUE);

Each folder name will be an array index, while its contained files will be numerically indexed.
Here is an example of a typical array:

Array

(

   [libraries] => Array

   (

       [0] => benchmark.html

       [1] => config.html

       [database] => Array

       (

             [0] => active_record.html

             [1] => binds.html

             [2] => configuration.html

             [3] => connecting.html

             [4] => examples.html

             [5] => fields.html

             [6] => index.html

             [7] => queries.html

        )

       [2] => email.html

       [3] => file_uploading.html

       [4] => image_lib.html

       [5] => input.html

       [6] => language.html

       [7] => loader.html

       [8] => pagination.html

       [9] => uri.html

)

Previous Topic:  Date Helper
   ·
Top of Page   ·
User Guide Home   ·
Next Topic:  Download Helper

CodeIgniter  ·  Copyright © 2007  ·  Ellislab, Inc.


text:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sync = require('gulp-sync')(gulp);
var config = require('./gulp/config')
var requireDir = require('require-dir');
var tasks = requireDir('gulp', {recurse: true});

// create a task that ensures the `js` task is complete before
// reloading browsers
gulp.task('js-watch', function (done) {
    browserSync.reload();
    done();
});

// use default task to launch Browsersync and watch JS files
gulp.task('serve', function () {

    // Serve files from the root of this project
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });

    // add browserSync.reload to the tasks array to make
    // all browsers reload after tasks are complete.
    gulp.watch("src/*.js", ['js-watch']);
});

gulp.task('dist', sync.sync(['cleanBuild', ['usemin']]), function(){

});


text:
package org.sonarqube.shell.dto.conf;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.util.ArrayList;
import java.util.Collection;

import static java.util.stream.Collectors.joining;

@Getter
@ToString
@EqualsAndHashCode
@XmlAccessorType(XmlAccessType.FIELD)
public class Axis {
    @XmlElement(name = "name")
    private String name;
    @XmlElement(name = "rules")
    private Collection<String> rules;

    public Axis() {
        this("", new ArrayList<>());
    }

    public Axis(String name, Collection<String> rules) {
        this.name = name;
        this.rules = rules;
    }

    public String getRulesAsString() {
        return rules.stream().collect(joining(",", "", ""));
    }

    public boolean isValid() {
        return !(name.isEmpty() || rules.isEmpty());
    }
}


text:
var util = require('../util');
var PixelSegments = require('../pixel-segments.js');

module.exports = function(pixels, id){
  var pixelSegments = PixelSegments(pixels);
  var unrolledSegments = [];
  for(var row=0; row < pixelSegments.length; row++){
    unrolledSegments.push.apply(unrolledSegments, pixelSegments[row]);
  }

  var styles = [];
  for(var i=0; i < unrolledSegments.length; i++){
    var segment = unrolledSegments[i];
    segment.styles = [
      util.format('background: {0}', segment.value.css()),
      util.format('width: {0}px', segment.length)
    ];
    styles.push(segment.styles);
  }
  var fmt = Formatter.fromStylesElements(styles);

  return {
    css: util.format('#{0} { width: {1}px; margin: 0; overflow: hidden }\n'+
                     '#{0} * { float: left; height: 1px; vertical-align: baseline; margin: 0; padding: 0; border-collapse: collapse }\n'+
                     '#{0} *:before, #{0}:after { content: "" }\n',
                     id, pixels.cols) +
         fmt.styles('#'+id).join('\n'),

    html: util.format('
{1}
', id,
                      unrolledSegments.map(function(s){
                        return fmt.elementFor(s.styles);
                      }).join('')),

    js: null
  };
};

function bestMatch(tags, stylesElement){
  for(var tag in tags){
    if(util.arrayEquals(tags[tag], stylesElement)){
      return {
        tag: tag,
        unmatchedStyles: []
      };
    }
  }

  /* Tag matches one thing */
  for(var t in tags){
    for(var i=0; i < stylesElement.length; i++){
      var tagStyles = tags[t];
      if(t.length < 3 && tags[t].indexOf(stylesElement[i]) != -1){
        return {
          tag: t,
          unmatchedStyles: util.arrayDiff(stylesElement, tagStyles || [])
        };
      }
    }
  }
  return {
    tag: null,
    unmatchedStyles: stylesElement
  };
}

var Aggregator = module.exports.Aggregator = function(stylesElements){
  var tags = function(){
    var counter = util.counter();
    stylesElements.forEach(function(stylesElement){
      counter.add(stylesElement.join(';'));
    });

    var sortedCounter = counter.sortByMostFrequent();
    var generator = util.generator([
      'i', 'b', 'a', 'p', 'q', 'u', 's',
      'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'dl',
      'dfn', 'kbd', 'var', 'ins', 'del', 'sup', 'sub', 'nav', 'pre', 'div', 'bdi',
      'span', 'samp', 'code', 'abbr', 'form', 'cite', 'mark', 'menu',
      'small', 'aside', 'table'
    ]);
    var tags = {};
    for(var i=0; i < sortedCounter.length; i++){
      var key = sortedCounter[i][0];
      var val = sortedCounter[i][1];
      var nextTag = generator();
      if(val <= 1 || nextTag === null){
        break;
      }
      tags[nextTag] = key.split(';');
    }
    return tags;
  }();

  return {
    tags: tags,
    classes: function(){
      var counter = util.counter();
      stylesElements.forEach(function(stylesElement){
        var unmatchedStyles = bestMatch(tags, stylesElement).unmatchedStyles;
        for(var i=0; i < unmatchedStyles.length; i++){
          counter.add(unmatchedStyles[i]);
        }
      });

      var generator = util.endlessGenerator('abcdefghijklmnopqrstuvwxyz');
      var sortedCounter = counter.sortByMostFrequent();

      var classes = {};
      for(var i=0; i < sortedCounter.length; i++){
        var key = sortedCounter[i][0];
        var val = sortedCounter[i][1];
        if(val <= 1){
          break;
        }
        classes[key] = generator();
      }
      return classes;
    }()
  };
};

var Formatter = module.exports.Formatter = function(aggregate){
  var self = {
    defaultTag: function(){
      var tag;
      for(var t in aggregate.tags){
        if(!tag || t.length < tag.length){
          tag = t;
        }
      }
      return tag;
    }(),

    styles: function(prepend){
      var ret = [];
      for(var t in aggregate.tags){
        ret.push(util.format('{0} {1} { {2} }', prepend, t, aggregate.tags[t].join('; ')));
      }

      for(var c in aggregate.classes){
        ret.push(util.format('{0} .{1} { {2} }', prepend, aggregate.classes[c], c));
      }
      return ret;
    },

    valuesFor: function(searchStyles){
      var match = bestMatch(aggregate.tags, searchStyles);
      var tag = match.tag || self.defaultTag;

      var classes = [];
      var styles = [];
      for(var i=0; i < match.unmatchedStyles.length; i++){
        var style = match.unmatchedStyles[i];
        if(aggregate.classes[style]){
          classes.push(aggregate.classes[style]);
        } else {
          styles.push(style);
        }
      }

      return {
        tag: tag,
        classes: classes.join(' '),
        styles: styles.join('; ')
      };
    },

    elementFor: function(searchStyles){
      var values = self.valuesFor(searchStyles);
      var attrs = '';
      if(values.classes){
        attrs += util.format(' class="{0}"', values.classes);
      }
      if(values.styles){
        attrs += util.format(' style="{0}"', values.styles);
      }
      return util.format('<{0}{1}></{0}\n>', values.tag, attrs);
    }
  };
  return self;
};

Formatter.fromStylesElements = function(stylesElements){
  var agg = Aggregator(stylesElements);
  return Formatter(agg);
};


text:
package com.example.eachother;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MyDoTaskActivity extends AppCompatActivity implements View.OnClickListener {

    public Button receivedFinished;
    public Button receivedUnFinished;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_do_task);

        receivedFinished = (Button)findViewById(R.id.my_received_finished);
        receivedUnFinished=(Button)findViewById(R.id.my_received_unfinished);

        receivedFinished.setOnClickListener(this);
        receivedUnFinished.setOnClickListener(this);

        replaceFragment(new MyReceivedTaskFinishedFragment());

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.my_received_finished:
                replaceFragment(new MyReceivedTaskFinishedFragment());
                break;
            case R.id.my_received_unfinished:
                replaceFragment(new MyReceivedTaskUnFinishedFragment());
                break;
            default:
                break;
        }
    }

    private void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.my_received_task_fragment,fragment);
        transaction.commit();
    }
}


text:
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Servicios

                        Nosotros

                        Equipo

                        Contacto

Tu empresa

Bajo TU Control

                Más informacion


text:
import { BaseDriver } from 'wix-ui-test-utils/driver-factory';

export interface RadioDriver extends BaseDriver {
  keyDown(key: string): void;
  click(): void;
  getValue(): string;
  getName(): string;
  getId(): string;
  iconExists(): boolean;
  labelExists(): boolean;
  isChecked(): boolean;
  isDisabled(): boolean;
}


text:
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

import re

from lib.core.enums import HTTP_HEADER
from lib.core.settings import WAF_ATTACK_VECTORS

__product__ = "BinarySEC Web Application Firewall (BinarySEC)"

def detect(get_page):
    retval = False

    for vector in WAF_ATTACK_VECTORS:
        page, headers, code = get_page(get=vector)
        retval = any(headers.get(_) for _ in ("x-binarysec-via", "x-binarysec-nocache"))
        retval |= re.search(r"BinarySec", headers.get(HTTP_HEADER.SERVER, ""), re.I) is not None
        if retval:
            break

    return retval


text:
"""
    sphinx.ext.coverage
    ~~~~~~~~~~~~~~~~~~~

    Check Python modules and C API for coverage.  Mostly written by Josip
    Dzolonga for the Google Highly Open Participation contest.

    :copyright: 2008 by Josip Dzolonga, Georg Brandl.
    :license: BSD.
"""

import re
import glob
import inspect
import cPickle as pickle
from os import path

from sphinx.builder import Builder

# utility
def write_header(f, text, char='-'):
    f.write(text + '\n')
    f.write(char * len(text) + '\n')

def compile_regex_list(name, exps, warnfunc):
    lst = []
    for exp in exps:
        try:
            lst.append(re.compile(exp))
        except Exception:
            warnfunc('invalid regex %r in %s' % (exp, name))
    return lst

class CoverageBuilder(Builder):

    name = 'coverage'

    def init(self):
        self.c_sourcefiles = []
        for pattern in self.config.coverage_c_path:
            pattern = path.join(self.srcdir, pattern)
            self.c_sourcefiles.extend(glob.glob(pattern))

        self.c_regexes = []
        for (name, exp) in self.config.coverage_c_regexes.items():
            try:
                self.c_regexes.append((name, re.compile(exp)))
            except Exception:
                self.warn('invalid regex %r in coverage_c_regexes' % exp)

        self.c_ignorexps = {}
        for (name, exps) in self.config.coverage_ignore_c_items.iteritems():
            self.c_ignorexps[name] = compile_regex_list('coverage_ignore_c_items',
                                                        exps, self.warn)
        self.mod_ignorexps = compile_regex_list('coverage_ignore_modules',
                                                self.config.coverage_ignore_modules,
                                                self.warn)
        self.cls_ignorexps = compile_regex_list('coverage_ignore_classes',
                                                self.config.coverage_ignore_classes,
                                                self.warn)
        self.fun_ignorexps = compile_regex_list('coverage_ignore_functions',
                                                self.config.coverage_ignore_functions,
                                                self.warn)

    def get_outdated_docs(self):
        return 'coverage overview'

    def write(self, *ignored):
        self.py_undoc = {}
        self.build_py_coverage()
        self.write_py_coverage()

        self.c_undoc = {}
        self.build_c_coverage()
        self.write_c_coverage()

    def build_c_coverage(self):
        # Fetch all the info from the header files
        for filename in self.c_sourcefiles:
            undoc = []
            f = open(filename, 'r')
            try:
                for line in f:
                    for key, regex in self.c_regexes:
                        match = regex.match(line)
                        if match:
                            name = match.groups()[0]
                            if name not in self.env.descrefs:
                                for exp in self.c_ignorexps.get(key, ()):
                                    if exp.match(name):
                                        break
                                else:
                                    undoc.append((key, name))
                            continue
            finally:
                f.close()
            if undoc:
                self.c_undoc[filename] = undoc

    def write_c_coverage(self):
        output_file = path.join(self.outdir, 'c.txt')
        op = open(output_file, 'w')
        try:
            write_header(op, 'Undocumented C API elements', '=')
            op.write('\n')

            for filename, undoc in self.c_undoc.iteritems():
                write_header(op, filename)
                for typ, name in undoc:
                    op.write(' * %-50s [%9s]\n' % (name, typ))
                op.write('\n')
        finally:
            op.close()

    def build_py_coverage(self):
        for mod_name in self.env.modules:
            ignore = False
            for exp in self.mod_ignorexps:
                if exp.match(mod_name):
                    ignore = True
                    break
            if ignore:
                continue

            try:
                mod = __import__(mod_name, fromlist=['foo'])
            except ImportError, err:
                self.warn('module %s could not be imported: %s' % (mod_name, err))
                self.py_undoc[mod_name] = {'error': err}
                continue

            funcs = []
            classes = {}

            for name, obj in inspect.getmembers(mod):
                # diverse module attributes are ignored:
                if name[0] == '_':
                    # begins in an underscore
                    continue
                if not hasattr(obj, '__module__'):
                    # cannot be attributed to a module
                    continue
                if obj.__module__ != mod_name:
                    # is not defined in this module
                    continue

                full_name = '%s.%s' % (mod_name, name)

                if inspect.isfunction(obj):
                    if full_name not in self.env.descrefs:
                        for exp in self.fun_ignorexps:
                            if exp.match(name):
                                break
                        else:
                            funcs.append(name)
                elif inspect.isclass(obj):
                    for exp in self.cls_ignorexps:
                        if exp.match(name):
                            break
                    else:
                        if full_name not in self.env.descrefs:
                            # not documented at all
                            classes[name] = []
                            continue

                        attrs = []

                        for attr_name, attr in inspect.getmembers(obj, inspect.ismethod):
                            if attr_name[0] == '_':
                                # starts with an underscore, ignore it
                                continue

                            full_attr_name = '%s.%s' % (full_name, attr_name)
                            if full_attr_name not in self.env.descrefs:
                                attrs.append(attr_name)

                        if attrs:
                            # some attributes are undocumented
                            classes[name] = attrs

            self.py_undoc[mod_name] = {'funcs': funcs, 'classes': classes}

    def write_py_coverage(self):
        output_file = path.join(self.outdir, 'python.txt')
        op = open(output_file, 'w')
        failed = []
        try:
            write_header(op, 'Undocumented Python objects', '=')

            keys = self.py_undoc.keys()
            keys.sort()
            for name in keys:
                undoc = self.py_undoc[name]
                if 'error' in undoc:
                    failed.append((name, undoc['error']))
                else:
                    if not undoc['classes'] and not undoc['funcs']:
                        continue

                    write_header(op, name)
                    if undoc['funcs']:
                        op.write('Functions:\n')
                        op.writelines(' * %s\n' % x for x in undoc['funcs'])
                        op.write('\n')
                    if undoc['classes']:
                        op.write('Classes:\n')
                        for name, methods in undoc['classes'].iteritems():
                            if not methods:
                                op.write(' * %s\n' % name)
                            else:
                                op.write(' * %s -- missing methods:\n' % name)
                                op.writelines('   - %s\n' % x for x in methods)
                        op.write('\n')

            if failed:
                write_header(op, 'Modules that failed to import')
                op.writelines(' * %s -- %s\n' % x for x in failed)
        finally:
            op.close()

    def finish(self):
        # dump the coverage data to a pickle file too
        picklepath = path.join(self.outdir, 'undoc.pickle')
        dumpfile = open(picklepath, 'wb')
        try:
            pickle.dump((self.py_undoc, self.c_undoc), dumpfile)
        finally:
            dumpfile.close()

def setup(app):
    app.add_builder(CoverageBuilder)
    app.add_config_value('coverage_ignore_modules', [], False)
    app.add_config_value('coverage_ignore_functions', [], False)
    app.add_config_value('coverage_ignore_classes', [], False)
    app.add_config_value('coverage_c_path', [], False)
    app.add_config_value('coverage_c_regexes', {}, False)
    app.add_config_value('coverage_ignore_c_items', {}, False)


text:
{% load comments %}

    {% for comment in comments %}

{{ comment.comment }}

            {{ comment.submit_date }}
            reply

    {% endfor %}


text:
package test.model;

import javastrava.model.StravaMap;
import test.utils.BeanTest;

/**
 * <p>
 * Tests for {@link StravaMap}
 * </p>
 *
 * @author Dan Shannon
 *
 */
public class StravaMapTest extends BeanTest<StravaMap> {

	@Override
	protected Class<StravaMap> getClassUnderTest() {
		return StravaMap.class;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="@dimen/default_16dp"
    android:paddingLeft="48dp"
    android:paddingRight="48dp"
    android:paddingTop="@dimen/default_16dp">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="80dp"
        android:layout_marginBottom="24dp"
        android:src="@drawable/odoo_small"
        android:tint="@color/colorWhite" />

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:textColorHint="#77FFFFFF">

        <EditText
            android:id="@+id/edit_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_name"
            android:inputType="textPersonName"
            android:textColor="@color/colorWhite"
            android:textColorHint="#77FFFFFF" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:textColorHint="#77FFFFFF">

        <EditText
            android:id="@+id/edit_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:textColor="@color/colorWhite"
            android:textColorHint="#77FFFFFF" />

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:textColorHint="#77FFFFFF">

        <EditText
            android:id="@+id/edit_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:textColor="@color/colorWhite"
            android:textColorHint="#77FFFFFF" />

    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/btnSignup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/default_16dp"
        android:paddingLeft="@dimen/default_16dp"
        android:paddingRight="@dimen/default_16dp"
        android:text="@string/label_sign_up"
        android:textAllCaps="true"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/colorPrimaryExtraDark" />
</LinearLayout>


text:
<?php

namespace App\Console\Commands;

use Illuminate\Foundation\Console\ServeCommand;
use Symfony\Component\Console\Input\InputOption;

class CustomServeCommand extends ServeCommand
{

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '0.0.0.0'],//default 127.0.0.1
            ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 80],
        ];
    }

}


text:
begin
  require 'rspec/expectations'
rescue LoadError
  require 'spec/expectations'
end

require 'cucumber/formatter/unicode'
$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/../../lib")
require 'basket'
require 'belly'


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::Bindings::ServiceWorkerBinding::ServiceWorkerState;
use dom::bindings::codegen::Bindings::ServiceWorkerRegistrationBinding::{ServiceWorkerRegistrationMethods, Wrap};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::USVString;
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::serviceworker::ServiceWorker;
use dom::workerglobalscope::prepare_workerscope_init;
use dom_struct::dom_struct;
use script_traits::{WorkerScriptLoadOrigin, ScopeThings};
use servo_url::ServoUrl;
use std::cell::Cell;

#[dom_struct]
pub struct ServiceWorkerRegistration {
    eventtarget: EventTarget,
    active: Option<Dom<ServiceWorker>>,
    installing: Option<Dom<ServiceWorker>>,
    waiting: Option<Dom<ServiceWorker>>,
    scope: ServoUrl,
    uninstalling: Cell<bool>
}

impl ServiceWorkerRegistration {
    fn new_inherited(active_sw: &ServiceWorker, scope: ServoUrl) -> ServiceWorkerRegistration {
        ServiceWorkerRegistration {
            eventtarget: EventTarget::new_inherited(),
            active: Some(Dom::from_ref(active_sw)),
            installing: None,
            waiting: None,
            scope: scope,
            uninstalling: Cell::new(false)
        }
    }
    #[allow(unrooted_must_root)]
    pub fn new(global: &GlobalScope,
               script_url: &ServoUrl,
               scope: ServoUrl) -> DomRoot<ServiceWorkerRegistration> {
        let active_worker = ServiceWorker::install_serviceworker(global, script_url.clone(), scope.clone(), true);
        active_worker.set_transition_state(ServiceWorkerState::Installed);
        reflect_dom_object(Box::new(ServiceWorkerRegistration::new_inherited(&*active_worker, scope)), global, Wrap)
    }

    pub fn get_installed(&self) -> &ServiceWorker {
        self.active.as_ref().unwrap()
    }

    pub fn get_uninstalling(&self) -> bool {
        self.uninstalling.get()
    }

    pub fn set_uninstalling(&self, flag: bool) {
        self.uninstalling.set(flag)
    }

    pub fn create_scope_things(global: &GlobalScope, script_url: ServoUrl) -> ScopeThings {
        let worker_load_origin = WorkerScriptLoadOrigin {
            referrer_url: None,
            referrer_policy: None,
            pipeline_id: Some(global.pipeline_id())
        };

        let worker_id = global.get_next_worker_id();
        let devtools_chan = global.devtools_chan().cloned();
        let init = prepare_workerscope_init(&global, None);
        ScopeThings {
            script_url: script_url,
            init: init,
            worker_load_origin: worker_load_origin,
            devtools_chan: devtools_chan,
            worker_id: worker_id
        }
    }

    // https://w3c.github.io/ServiceWorker/#get-newest-worker-algorithm
    pub fn get_newest_worker(&self) -> Option<DomRoot<ServiceWorker>> {
        if self.installing.as_ref().is_some() {
            self.installing.as_ref().map(|sw| DomRoot::from_ref(&**sw))
        } else if self.waiting.as_ref().is_some() {
            self.waiting.as_ref().map(|sw| DomRoot::from_ref(&**sw))
        } else {
            self.active.as_ref().map(|sw| DomRoot::from_ref(&**sw))
        }
    }
}

pub fn longest_prefix_match(stored_scope: &ServoUrl, potential_match: &ServoUrl) -> bool {
    if stored_scope.origin() != potential_match.origin() {
        return false;
    }
    let scope_chars = stored_scope.path().chars();
    let matching_chars = potential_match.path().chars();
    if scope_chars.count() > matching_chars.count() {
        return false;
    }

    stored_scope.path().chars().zip(potential_match.path().chars()).all(|(scope, matched)| scope == matched)
}

impl ServiceWorkerRegistrationMethods for ServiceWorkerRegistration {
    // https://w3c.github.io/ServiceWorker/#service-worker-registration-installing-attribute
    fn GetInstalling(&self) -> Option<DomRoot<ServiceWorker>> {
        self.installing.as_ref().map(|sw| DomRoot::from_ref(&**sw))
    }

    // https://w3c.github.io/ServiceWorker/#service-worker-registration-active-attribute
    fn GetActive(&self) -> Option<DomRoot<ServiceWorker>> {
        self.active.as_ref().map(|sw| DomRoot::from_ref(&**sw))
    }

    // https://w3c.github.io/ServiceWorker/#service-worker-registration-waiting-attribute
    fn GetWaiting(&self) -> Option<DomRoot<ServiceWorker>> {
        self.waiting.as_ref().map(|sw| DomRoot::from_ref(&**sw))
    }

    // https://w3c.github.io/ServiceWorker/#service-worker-registration-scope-attribute
    fn Scope(&self) -> USVString {
        USVString(self.scope.as_str().to_owned())
    }
}


text:
require "google/cloud/errors"
require "google/cloud/pubsub/subscription/list"
require "google/cloud/pubsub/received_message"

module Google
  module Cloud
    module Pubsub
      ##
      # # Subscription
      #
      # A named resource representing the stream of messages from a single,
      # specific {Topic}, to be delivered to the subscribing application.
      #
      # @example
      #   require "google/cloud/pubsub"
      #
      #   pubsub = Google::Cloud::Pubsub.new
      #
      #   sub = pubsub.subscription "my-topic-sub"
      #   msgs = sub.pull
      #   msgs.each { |msg| msg.acknowledge! }
      #
      class Subscription
        ##
        # @private The Service object.
        attr_accessor :service

        ##
        # @private The gRPC Google::Pubsub::V1::Subscription object.
        attr_accessor :grpc

        ##
        # @private Create an empty {Subscription} object.
        def initialize
          @service = nil
          @grpc = Google::Pubsub::V1::Subscription.new
          @name = nil
          @exists = nil
        end

        ##
        # @private New lazy {Topic} object without making an HTTP request.
        def self.new_lazy name, service, options = {}
          new.tap do |s|
            s.grpc = nil
            s.service = service
            s.instance_variable_set "@name",
                                    service.subscription_path(name, options)
          end
        end

        ##
        # The name of the subscription.
        def name
          @grpc ? @grpc.name : @name
        end

        ##
        # The {Topic} from which this subscription receives messages.
        #
        # @return [Topic]
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   sub.topic.name #=> "projects/my-project/topics/my-topic"
        #
        def topic
          ensure_grpc!
          Topic.new_lazy @grpc.topic, service
        end

        ##
        # This value is the maximum number of seconds after a subscriber
        # receives a message before the subscriber should acknowledge the
        # message.
        def deadline
          ensure_grpc!
          @grpc.ack_deadline_seconds
        end

        ##
        # Returns the URL locating the endpoint to which messages should be
        # pushed.
        def endpoint
          ensure_grpc!
          @grpc.push_config.push_endpoint if @grpc.push_config
        end

        ##
        # Sets the URL locating the endpoint to which messages should be pushed.
        def endpoint= new_endpoint
          ensure_service!
          service.modify_push_config name, new_endpoint, {}
          @grpc.push_config = Google::Pubsub::V1::PushConfig.new(
            push_endpoint: new_endpoint,
            attributes: {}
          ) if @grpc
        end

        ##
        # Determines whether the subscription exists in the Pub/Sub service.
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   sub.exists? #=> true
        #
        def exists?
          # Always true if we have a grpc object
          return true unless @grpc.nil?
          # If we have a value, return it
          return @exists unless @exists.nil?
          ensure_grpc!
          @exists = !@grpc.nil?
        rescue Google::Cloud::NotFoundError
          @exists = false
        end

        ##
        # @private
        # Determines whether the subscription object was created with an
        # HTTP call.
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.get_subscription "my-topic-sub"
        #   sub.lazy? #=> false
        #
        def lazy?
          @grpc.nil?
        end

        ##
        # Deletes an existing subscription.
        # All pending messages in the subscription are immediately dropped.
        #
        # @return [Boolean] Returns `true` if the subscription was deleted.
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   sub.delete
        #
        def delete
          ensure_service!
          service.delete_subscription name
          true
        end

        ##
        # Pulls messages from the server. Returns an empty list if there are no
        # messages available in the backlog. Raises an ApiError with status
        # `UNAVAILABLE` if there are too many concurrent pull requests pending
        # for the given subscription.
        #
        # @param [Boolean] immediate When `true` the system will respond
        #   immediately even if it is not able to return messages. When `false`
        #   the system is allowed to wait until it can return least one message.
        #   No messages are returned when a request times out. The default value
        #   is `true`.
        # @param [Integer] max The maximum number of messages to return for this
        #   request. The Pub/Sub system may return fewer than the number
        #   specified. The default value is `100`, the maximum value is `1000`.
        # @param [Boolean] autoack Automatically acknowledge the message as it
        #   is pulled. The default value is `false`.
        #
        # @return [Array<Google::Cloud::Pubsub::ReceivedMessage>]
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   sub.pull.each { |msg| msg.acknowledge! }
        #
        # @example A maximum number of messages returned can also be specified:
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub", max: 10
        #   sub.pull.each { |msg| msg.acknowledge! }
        #
        # @example The call can block until messages are available:
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   msgs = sub.pull immediate: false
        #   msgs.each { |msg| msg.acknowledge! }
        #
        def pull immediate: true, max: 100, autoack: false
          ensure_service!
          options = { immediate: immediate, max: max }
          list_grpc = service.pull name, options
          messages = Array(list_grpc.received_messages).map do |msg_grpc|
            ReceivedMessage.from_grpc msg_grpc, self
          end
          acknowledge messages if autoack
          messages
        rescue Google::Cloud::DeadlineExceededError
          []
        end

        ##
        # Pulls from the server while waiting for messages to become available.
        # This is the same as:
        #
        #   subscription.pull immediate: false
        #
        # @param [Integer] max The maximum number of messages to return for this
        #   request. The Pub/Sub system may return fewer than the number
        #   specified. The default value is `100`, the maximum value is `1000`.
        # @param [Boolean] autoack Automatically acknowledge the message as it
        #   is pulled. The default value is `false`.
        #
        # @return [Array<Google::Cloud::Pubsub::ReceivedMessage>]
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   msgs = sub.wait_for_messages
        #   msgs.each { |msg| msg.acknowledge! }
        #
        def wait_for_messages max: 100, autoack: false
          pull immediate: false, max: max, autoack: autoack
        end

        ##
        # Poll the backend for new messages. This runs a loop to ping the API,
        # blocking indefinitely, yielding retrieved messages as they are
        # received.
        #
        # @param [Integer] max The maximum number of messages to return for this
        #   request. The Pub/Sub system may return fewer than the number
        #   specified. The default value is `100`, the maximum value is `1000`.
        # @param [Boolean] autoack Automatically acknowledge the message as it
        #   is pulled. The default value is `false`.
        # @param [Number] delay The number of seconds to pause between requests
        #   when the Google Cloud service has no messages to return. The default
        #   value is `1`.
        # @yield [msg] a block for processing new messages
        # @yieldparam [ReceivedMessage] msg the newly received message
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   sub.listen do |msg|
        #     # process msg
        #   end
        #
        # @example Limit number of messages pulled per API request with `max`:
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   sub.listen max: 20 do |msg|
        #     # process msg
        #   end
        #
        # @example Automatically acknowledge messages with `autoack`:
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   sub.listen autoack: true do |msg|
        #     # process msg
        #   end
        #
        def listen max: 100, autoack: false, delay: 1
          loop do
            msgs = wait_for_messages max: max, autoack: autoack
            if msgs.any?
              msgs.each { |msg| yield msg }
            else
              sleep delay
            end
          end
        end

        ##
        # Acknowledges receipt of a message. After an ack,
        # the Pub/Sub system can remove the message from the subscription.
        # Acknowledging a message whose ack deadline has expired may succeed,
        # although the message may have been sent again.
        # Acknowledging a message more than once will not result in an error.
        # This is only used for messages received via pull.
        #
        # @param [ReceivedMessage, String] messages One or more
        #   {ReceivedMessage} objects or ack_id values.
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   messages = sub.pull
        #   sub.acknowledge messages
        #
        def acknowledge *messages
          ack_ids = coerce_ack_ids messages
          return true if ack_ids.empty?
          ensure_service!
          service.acknowledge name, *ack_ids
          true
        end
        alias_method :ack, :acknowledge

        ##
        # Modifies the acknowledge deadline for messages.
        #
        # This indicates that more time is needed to process the messages, or to
        # make the messages available for redelivery if the processing was
        # interrupted.
        #
        # @param [Integer] new_deadline The new ack deadline in seconds from the
        #   time this request is sent to the Pub/Sub system. Must be >= 0. For
        #   example, if the value is `10`, the new ack deadline will expire 10
        #   seconds after the call is made. Specifying `0` may immediately make
        #   the message available for another pull request.
        # @param [ReceivedMessage, String] messages One or more
        #   {ReceivedMessage} objects or ack_id values.
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #
        #   sub = pubsub.subscription "my-topic-sub"
        #   messages = sub.pull
        #   sub.delay 120, messages
        #
        def delay new_deadline, *messages
          ack_ids = coerce_ack_ids messages
          ensure_service!
          service.modify_ack_deadline name, ack_ids, new_deadline
          true
        end

        ##
        # Gets the [Cloud IAM](https://cloud.google.com/iam/) access control
        # policy for this subscription.
        #
        # @see https://cloud.google.com/pubsub/docs/reference/rpc/google.iam.v1#iampolicy
        #   google.iam.v1.IAMPolicy
        #
        # @param [Boolean] force Force the latest policy to be retrieved from
        #   the Pub/Sub service when `true`. Otherwise the policy will be
        #   memoized to reduce the number of API calls made to the Pub/Sub
        #   service. The default is `false`.
        #
        # @yield [policy] A block for updating the policy. The latest policy
        #   will be read from the Pub/Sub service and passed to the block. After
        #   the block completes, the modified policy will be written to the
        #   service.
        # @yieldparam [Policy] policy the current Cloud IAM Policy for this
        #   subscription
        #
        # @return [Policy] the current Cloud IAM Policy for this subscription
        #
        # @example Policy values are memoized to reduce the number of API calls:
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #   sub = pubsub.subscription "my-subscription"
        #
        #   policy = sub.policy # API call
        #   policy_2 = sub.policy # No API call
        #
        # @example Use `force` to retrieve the latest policy from the service:
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #   sub = pubsub.subscription "my-subscription"
        #
        #   policy = sub.policy force: true # API call
        #   policy_2 = sub.policy force: true # API call
        #
        # @example Update the policy by passing a block:
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #   sub = pubsub.subscription "my-subscription"
        #
        #   policy = sub.policy do |p|
        #     p.add "roles/owner", "user:owner@example.com"
        #   end # 2 API calls
        #
        def policy force: nil
          @policy = nil if force || block_given?
          @policy ||= begin
            ensure_service!
            grpc = service.get_subscription_policy name
            Policy.from_grpc grpc
          end
          return @policy unless block_given?
          p = @policy.deep_dup
          yield p
          self.policy = p
        end

        ##
        # Updates the [Cloud IAM](https://cloud.google.com/iam/) access control
        # policy for this subscription. The policy should be read from
        # {#policy}. See {Google::Cloud::Pubsub::Policy} for an explanation of
        # the policy `etag` property and how to modify policies.
        #
        # You can also update the policy by passing a block to {#policy}, which
        # will call this method internally after the block completes.
        #
        # @see https://cloud.google.com/pubsub/docs/reference/rpc/google.iam.v1#iampolicy
        #   google.iam.v1.IAMPolicy
        #
        # @param [Policy] new_policy a new or modified Cloud IAM Policy for this
        #   subscription
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #   sub = pubsub.subscription "my-subscription"
        #
        #   policy = sub.policy # API call
        #
        #   policy.add "roles/owner", "user:owner@example.com"
        #
        #   sub.policy = policy # API call
        #
        def policy= new_policy
          ensure_service!
          grpc = service.set_subscription_policy name, new_policy.to_grpc
          @policy = Policy.from_grpc grpc
        end

        ##
        # Tests the specified permissions against the [Cloud
        # IAM](https://cloud.google.com/iam/) access control policy.
        #
        # @see https://cloud.google.com/iam/docs/managing-policies Managing
        #   Policies
        #
        # @param [String, Array<String>] permissions The set of permissions to
        #   check access for. Permissions with wildcards (such as `*` or
        #   `storage.*`) are not allowed.
        #
        #   The permissions that can be checked on a subscription are:
        #
        #   * pubsub.subscriptions.consume
        #   * pubsub.subscriptions.get
        #   * pubsub.subscriptions.delete
        #   * pubsub.subscriptions.update
        #   * pubsub.subscriptions.getIamPolicy
        #   * pubsub.subscriptions.setIamPolicy
        #
        # @return [Array<String>] The permissions that have access.
        #
        # @example
        #   require "google/cloud/pubsub"
        #
        #   pubsub = Google::Cloud::Pubsub.new
        #   sub = pubsub.subscription "my-subscription"
        #   perms = sub.test_permissions "pubsub.subscriptions.get",
        #                                "pubsub.subscriptions.consume"
        #   perms.include? "pubsub.subscriptions.get" #=> true
        #   perms.include? "pubsub.subscriptions.consume" #=> false
        #
        def test_permissions *permissions
          permissions = Array(permissions).flatten
          ensure_service!
          grpc = service.test_subscription_permissions name, permissions
          grpc.permissions
        end

        ##
        # @private New Subscription from a Google::Pubsub::V1::Subscription
        # object.
        def self.from_grpc grpc, service
          new.tap do |f|
            f.grpc = grpc
            f.service = service
          end
        end

        protected

        ##
        # @private Raise an error unless an active connection to the service is
        # available.
        def ensure_service!
          fail "Must have active connection to service" unless service
        end

        ##
        # Ensures a Google::Pubsub::V1::Subscription object exists.
        def ensure_grpc!
          ensure_service!
          return @grpc if @grpc
          @grpc = service.get_subscription @name
        end

        ##
        # Makes sure the values are the `ack_id`. If given several
        # {ReceivedMessage} objects extract the `ack_id` values.
        def coerce_ack_ids messages
          Array(messages).flatten.map do |msg|
            msg.respond_to?(:ack_id) ? msg.ack_id : msg.to_s
          end
        end
      end
    end
  end
end


text:
using DragonSpark.Sources.Parameterized;
using System;
using System.Collections;
using System.Collections.Generic;

namespace DragonSpark.Composition
{
	public sealed class SingletonExports : ExportSourceBase<SingletonExport>, IEnumerable<SingletonExport>
	{
		readonly IDictionary<Type, SingletonExport> dictionary;
		public SingletonExports( IDictionary<Type, SingletonExport> dictionary ) : base( dictionary.Keys, new DictionarySource<Type, SingletonExport>( dictionary ) )
		{
			this.dictionary = dictionary;
		}

		public IEnumerator<SingletonExport> GetEnumerator() => dictionary.Values.GetEnumerator();

		IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
	}
}