text:
package org.apache.camel.builder.endpoint.dsl;

import java.util.List;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;

/**
 * To integrate with a fully managed, high-performance message queuing service
 * on Huawei Cloud
 *
 * Generated by camel build tools - do NOT edit this file!
 */
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface DMSEndpointBuilderFactory {

    /**
     * Builder for endpoint for the Huawei Distributed Message Service (DMS)
     * component.
     */
    public interface DMSEndpointBuilder extends EndpointProducerBuilder {
        /**
         * Access key for the cloud user.
         *
         * The option is a: java.lang.String type.
         *
         * Required: true
         * Group: producer
         *
         * @param accessKey the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder accessKey(String accessKey) {
            doSetProperty("accessKey", accessKey);
            return this;
        }
        /**
         * The username of a RabbitMQ instance. This option is mandatory when
         * creating a RabbitMQ instance.
         *
         * The option is a: java.lang.String type.
         *
         * Group: producer
         *
         * @param accessUser the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder accessUser(String accessUser) {
            doSetProperty("accessUser", accessUser);
            return this;
        }
        /**
         * The ID of an available zone. This option is mandatory when creating
         * an instance and it cannot be an empty array.
         *
         * The option is a:
         * java.util.List<java.lang.String> type.
         *
         * Group: producer
         *
         * @param availableZones the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder availableZones(List<String> availableZones) {
            doSetProperty("availableZones", availableZones);
            return this;
        }
        /**
         * The ID of an available zone. This option is mandatory when creating
         * an instance and it cannot be an empty array.
         *
         * The option will be converted to a
         * <code>java.util.List&lt;java.lang.String&gt;</code> type.
         *
         * Group: producer
         *
         * @param availableZones the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder availableZones(String availableZones) {
            doSetProperty("availableZones", availableZones);
            return this;
        }
        /**
         * DMS url. Carries higher precedence than region parameter based client
         * initialization.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param endpoint the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder endpoint(String endpoint) {
            doSetProperty("endpoint", endpoint);
            return this;
        }
        /**
         * The message engine. Either kafka or rabbitmq. If the parameter is not
         * specified, all instances will be queried.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param engine the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder engine(String engine) {
            doSetProperty("engine", engine);
            return this;
        }
        /**
         * The version of the message engine. This option is mandatory when
         * creating an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param engineVersion the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder engineVersion(String engineVersion) {
            doSetProperty("engineVersion", engineVersion);
            return this;
        }
        /**
         * Ignore SSL verification.
         *
         * The option is a: <code>boolean</code> type.
         *
         * Default: false
         * Group: producer
         *
         * @param ignoreSslVerification the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder ignoreSslVerification(
                boolean ignoreSslVerification) {
            doSetProperty("ignoreSslVerification", ignoreSslVerification);
            return this;
        }
        /**
         * Ignore SSL verification.
         *
         * The option will be converted to a <code>boolean</code>
         * type.
         *
         * Default: false
         * Group: producer
         *
         * @param ignoreSslVerification the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder ignoreSslVerification(
                String ignoreSslVerification) {
            doSetProperty("ignoreSslVerification", ignoreSslVerification);
            return this;
        }
        /**
         * The id of the instance. This option is mandatory when deleting or
         * querying an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param instanceId the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder instanceId(String instanceId) {
            doSetProperty("instanceId", instanceId);
            return this;
        }
        /**
         * The password for logging in to the Kafka Manager. This option is
         * mandatory when creating a Kafka instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param kafkaManagerPassword the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder kafkaManagerPassword(
                String kafkaManagerPassword) {
            doSetProperty("kafkaManagerPassword", kafkaManagerPassword);
            return this;
        }
        /**
         * The username for logging in to the Kafka Manager. This option is
         * mandatory when creating a Kafka instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param kafkaManagerUser the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder kafkaManagerUser(String kafkaManagerUser) {
            doSetProperty("kafkaManagerUser", kafkaManagerUser);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option is a: <code>boolean</code> type.
         *
         * Default: false
         * Group: producer
         *
         * @param lazyStartProducer the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option will be converted to a <code>boolean</code>
         * type.
         *
         * Default: false
         * Group: producer
         *
         * @param lazyStartProducer the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder lazyStartProducer(String lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
        /**
         * The name of the instance for creating and updating an instance. This
         * option is mandatory when creating an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param name the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder name(String name) {
            doSetProperty("name", name);
            return this;
        }
        /**
         * The maximum number of partitions in a Kafka instance. This option is
         * mandatory when creating a Kafka instance.
         *
         * The option is a: <code>int</code> type.
         *
         * Group: producer
         *
         * @param partitionNum the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder partitionNum(int partitionNum) {
            doSetProperty("partitionNum", partitionNum);
            return this;
        }
        /**
         * The maximum number of partitions in a Kafka instance. This option is
         * mandatory when creating a Kafka instance.
         *
         * The option will be converted to a <code>int</code> type.
         *
         * Group: producer
         *
         * @param partitionNum the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder partitionNum(String partitionNum) {
            doSetProperty("partitionNum", partitionNum);
            return this;
        }
        /**
         * The password of a RabbitMQ instance. This option is mandatory when
         * creating a RabbitMQ instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param password the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder password(String password) {
            doSetProperty("password", password);
            return this;
        }
        /**
         * The product ID. This option is mandatory when creating an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param productId the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder productId(String productId) {
            doSetProperty("productId", productId);
            return this;
        }
        /**
         * Cloud project ID.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Required: true
         * Group: producer
         *
         * @param projectId the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder projectId(String projectId) {
            doSetProperty("projectId", projectId);
            return this;
        }
        /**
         * Proxy server ip/hostname.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param proxyHost the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder proxyHost(String proxyHost) {
            doSetProperty("proxyHost", proxyHost);
            return this;
        }
        /**
         * Proxy authentication password.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param proxyPassword the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder proxyPassword(String proxyPassword) {
            doSetProperty("proxyPassword", proxyPassword);
            return this;
        }
        /**
         * Proxy server port.
         *
         * The option is a: <code>int</code> type.
         *
         * Group: producer
         *
         * @param proxyPort the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder proxyPort(int proxyPort) {
            doSetProperty("proxyPort", proxyPort);
            return this;
        }
        /**
         * Proxy server port.
         *
         * The option will be converted to a <code>int</code> type.
         *
         * Group: producer
         *
         * @param proxyPort the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder proxyPort(String proxyPort) {
            doSetProperty("proxyPort", proxyPort);
            return this;
        }
        /**
         * Proxy authentication user.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param proxyUser the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder proxyUser(String proxyUser) {
            doSetProperty("proxyUser", proxyUser);
            return this;
        }
        /**
         * DMS service region.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Required: true
         * Group: producer
         *
         * @param region the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder region(String region) {
            doSetProperty("region", region);
            return this;
        }
        /**
         * Secret key for the cloud user.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Required: true
         * Group: producer
         *
         * @param secretKey the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder secretKey(String secretKey) {
            doSetProperty("secretKey", secretKey);
            return this;
        }
        /**
         * The security group which the instance belongs to. This option is
         * mandatory when creating an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param securityGroupId the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder securityGroupId(String securityGroupId) {
            doSetProperty("securityGroupId", securityGroupId);
            return this;
        }
        /**
         * Configuration object for cloud service authentication.
         *
         * The option is a:
         * <code>org.apache.camel.component.huaweicloud.common.models.ServiceKeys</code> type.
         *
         * Group: producer
         *
         * @param serviceKeys the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder serviceKeys(Object serviceKeys) {
            doSetProperty("serviceKeys", serviceKeys);
            return this;
        }
        /**
         * Configuration object for cloud service authentication.
         *
         * The option will be converted to a
         * <code>org.apache.camel.component.huaweicloud.common.models.ServiceKeys</code> type.
         *
         * Group: producer
         *
         * @param serviceKeys the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder serviceKeys(String serviceKeys) {
            doSetProperty("serviceKeys", serviceKeys);
            return this;
        }
        /**
         * The baseline bandwidth of a Kafka instance. This option is mandatory
         * when creating a Kafka instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param specification the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder specification(String specification) {
            doSetProperty("specification", specification);
            return this;
        }
        /**
         * The message storage space. This option is mandatory when creating an
         * instance.
         *
         * The option is a: <code>int</code> type.
         *
         * Group: producer
         *
         * @param storageSpace the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder storageSpace(int storageSpace) {
            doSetProperty("storageSpace", storageSpace);
            return this;
        }
        /**
         * The message storage space. This option is mandatory when creating an
         * instance.
         *
         * The option will be converted to a <code>int</code> type.
         *
         * Group: producer
         *
         * @param storageSpace the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder storageSpace(String storageSpace) {
            doSetProperty("storageSpace", storageSpace);
            return this;
        }
        /**
         * The storage I/O specification. This option is mandatory when creating
         * an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param storageSpecCode the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder storageSpecCode(String storageSpecCode) {
            doSetProperty("storageSpecCode", storageSpecCode);
            return this;
        }
        /**
         * The subnet ID. This option is mandatory when creating an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param subnetId the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder subnetId(String subnetId) {
            doSetProperty("subnetId", subnetId);
            return this;
        }
        /**
         * The VPC ID. This option is mandatory when creating an instance.
         *
         * The option is a: <code>java.lang.String</code> type.
         *
         * Group: producer
         *
         * @param vpcId the value to set
         * @return the dsl builder
         */
        default DMSEndpointBuilder vpcId(String vpcId) {
            doSetProperty("vpcId", vpcId);
            return this;
        }
    }

    public interface DMSBuilders {
        /**
         * Huawei Distributed Message Service (DMS) (camel-huaweicloud-dms)
         * To integrate with a fully managed, high-performance message queuing
         * service on Huawei Cloud
         *
         * Category: cloud
         * Since: 3.12
         * Maven coordinates: org.apache.camel:camel-huaweicloud-dms
         *
         * Syntax: hwcloud-dms:operation
         *
         * Path parameter: operation (required)
         * Operation to be performed
         *
         * @param path operation
         * @return the dsl builder
         */
        default DMSEndpointBuilder hwcloudDms(String path) {
            return DMSEndpointBuilderFactory.endpointBuilder("hwcloud-dms", path);
        }
        /**
         * Huawei Distributed Message Service (DMS) (camel-huaweicloud-dms)
         * To integrate with a fully managed, high-performance message queuing
         * service on Huawei Cloud
         *
         * Category: cloud
         * Since: 3.12
         * Maven coordinates: org.apache.camel:camel-huaweicloud-dms
         *
         * Syntax: hwcloud-dms:operation
         *
         * Path parameter: operation (required)
         * Operation to be performed
         *
         * @param componentName to use a custom component name for the endpoint
         * instead of the default name
         * @param path operation
         * @return the dsl builder
         */
        default DMSEndpointBuilder hwcloudDms(String componentName, String path) {
            return DMSEndpointBuilderFactory.endpointBuilder(componentName, path);
        }
    }
    static DMSEndpointBuilder endpointBuilder(String componentName, String path) {
        class DMSEndpointBuilderImpl extends AbstractEndpointBuilder implements DMSEndpointBuilder {
            public DMSEndpointBuilderImpl(String path) {
                super(componentName, path);
            }
        }
        return new DMSEndpointBuilderImpl(path);
    }
}


text:
function getUpcomingEvents() {
    Date.prototype.MMMM_dd_AT = function() {
    var monthNames = new Array("January", "February", "March",
        "April", "May", "June", "July", "August", "September",
        "October", "November", "December");
       var mm = this.getMonth();
       var dd = this.getDate().toString();
       var hours = this.getHours();
       var mins = this.getMinutes();
       var ampm = hours >= 12 ? 'pm' : 'am';
       hours = hours % 12 || 12;
       mins = mins < 10 ? '0' + minutes : mins;
       return (monthNames[mm]) + " " + (dd[1]?dd:"0"+dd[0]) + " @ " + hours + ':' + mins + ' ' + ampm;
    };

    var config = {
      'apiKey': 'AIzaSyBFeb_6ac2FhIRk1XqCrfqIAAA5UpVPqKM',
      'userEmail': "codeforhawaii.org_hhtbaa6tsmucnl1abvfpb0f2j8@group.calendar.google.com",
      'userTimeZone': "Honolulu",
      'maxEvents': 2,
    };

    gapi.client.setApiKey(config.apiKey);
    gapi.client.load('calendar', 'v3').then(function() {
      var request = gapi.client.calendar.events.list({
        'calendarId' : config.userEmail,
        'timeZone' : config.userTimeZone,
        'singleEvents': true,
        'timeMin': new Date().toISOString(),
        'maxResults': config.maxEvents,
        'orderBy': 'startTime'});

      request.execute(function (resp) {
        document.querySelector('.featured-event')
          .classList.add('active');
        for (var i = 0; i < resp.items.length; i++) {
          var event = resp.items[i];
          var start = new Date(Date.parse(event.start.dateTime));
          var end = new Date(Date.parse(event.end.dateTime));
          var htmlLink = event.htmlLink;
          var hangoutLink = event.hangoutLink;
          var description = event.description;
          var location = event.location;

          if (description.indexOf("Hangout") > -1)
          {
            $('div.featured-event--wrap').append('
Our next video call on Google Hangouts is ' +
                '' + start.MMMM_dd_AT() + '
');
          }
          else
          {
            $('div.featured-event--wrap').append('
Our next meetup at ' + location.split(',')[0] + ' is ' +
                '' + start.MMMM_dd_AT() + '
');
          }
        }
      });
    });
}

redpajama_set_name: RedPajamaGithub


text:
class ServiceDoesNotExists(Exception):
    """Service doesn't exists"""

class ServiceError(Exception):
    """Service error"""


text:
class ClassificurationBridge

  attr_accessor :curation
  attr_reader   :bridger

  delegate :bridge, :to => :bridger

  def self.bridge(curation)
    c = ClassificurationBridge.new(curation)
    c.bridge
    c
  end

  def initialize(curation)
    @curation = curation
    @bridger  = BridgeFactory.for(curation)
  end

end

# Builds the correct strategy for bridging classification curations to PHP
class BridgeFactory
  def self.for(curation)
    if curation.split?
      BridgeSplit.new(curation)
    elsif curation.merge?
      BridgeMerge.new(curation)
    elsif curation.move?
      BridgeMove.new(curation)
    end
  end
end

# Classic Stratgey Pattern for bridging classification curations to PHP
class Bridge

  attr_accessor :curation

  def initialize(curation)
    @curation = curation
  end

  def bridge
    raise "Unimplemented abstract method called"
  end

end

class BridgeSplit < Bridge
  def bridge
    curation.hierarchy_entries.each do |he|
      CodeBridge.split_entry(:hierarchy_entry_id => he.id, :exemplar_id => curation.exemplar_id,
                             :notify => curation.user_id, :classification_curation_id => curation.id)
    end
  end
end

class BridgeMerge < Bridge
  def bridge
    CodeBridge.merge_taxa(curation.source_id, curation.target_id, :notify => curation.user_id,
                          :classification_curation_id => curation.id)
  end
end

class BridgeMove < Bridge
  def bridge
    curation.hierarchy_entries.each do |he|
      CodeBridge.move_entry(:from_taxon_concept_id => curation.source_id, :to_taxon_concept_id => curation.target_id,
                            :hierarchy_entry_id => he.id, :exemplar_id => curation.exemplar_id,
                            :notify => curation.user_id, :classification_curation_id => curation.id)
    end
  end
end

class ClassificationCuration < ActiveRecord::Base

  # For convenience, these are the non-relationship fields:
  # :completed_at => When it was finished PROCESSING. This does NOT mean it worked! (Check #failed? for that.)
  # :forced       => boolean. ...Whether the move was (had to be) forced due to conflicts in CP assertions.
  # :error        => merges don't have hierarchy_entry_moves, so the errors cannot be stored there. Here it is!

  has_many :hierarchy_entry_moves
  has_many :hierarchy_entries, :through => :hierarchy_entry_moves

  # If this is null, it was a merge:
  belongs_to :exemplar, :class_name => 'HierarchyEntry', :foreign_key => 'exemplar_id'
  # If this has a superceded_id after the operation, it was a merge:
  belongs_to :moved_from, :class_name => 'TaxonConcept', :foreign_key => 'source_id'
  # If this is null, it's a split:
  belongs_to :moved_to, :class_name => 'TaxonConcept', :foreign_key => 'target_id'
  # This is the curator that requested the move/merge/split:
  belongs_to :user

  after_create :bridge

  def bridge
    ClassificurationBridge.bridge(self)
  end

  def split?
    moved_to.nil?
  end

  def merge?
    exemplar.nil?
  end

  def move?
    moved_to && exemplar
  end

  def check_status_and_notify
    if ready_to_complete? && ! already_complete?
      mark_as_complete # Nothing else should pick this up for work, now...
      if failed?
        compile_errors_into_log
      else
        reindex_taxa
        log_completion
      end
    end
  end

  def reindex_taxa
    # Allowing large trees, here, since you shouldn't have gotten here unless it was okay.
    TaxonConceptReindexing.reindex(moved_from, :allow_large_tree => true) if source_id
    if target_id
      TaxonConceptReindexing.reindex(moved_to, :allow_large_tree => true)
    elsif hierarchy_entry_moves
      taxon_concepts = hierarchy_entry_moves.collect{ |m| m.hierarchy_entry.taxon_concept }.compact.uniq
      taxon_concepts.each do |taxon_concept|
        TaxonConceptReindexing.reindex(taxon_concept, :allow_large_tree => true)
      end
    end
  end

  def log_completion
    log_activity_on(moved_from || moved_to)
    log_unlock_and_notify(Activity.unlock)
  end

  def already_complete?
    completed_at && hierarchy_entry_moves.all? {|move| move.complete?}
  end

  def ready_to_complete?
    if merge?
      # This is slightly expensive... but not THAT bad... and running in the background. The "magic" is NOT using the
      # direct association, but using #find, so that supercedure is followed.
      TaxonConcept.find(moved_from) == TaxonConcept.find(moved_to)
    else
      hierarchy_entry_moves.all? {|move| move.complete?}
    end
  end

  def failed?
    !(error.blank? && hierarchy_entry_moves.all? {|move| move.error.blank? })
  end

  def to_s
    "ClassificationCuration ##{self.id} (moved_from #{source_id}, moved_to #{target_id})"
  end

  # A split doesn't specify a target (it creates one), so we look to see where it went (for logging):
  def split_to
    hierarchy_entry_moves.first.hierarchy_entry.taxon_concept
  end

private

  def compile_errors_into_log
    # Yes, english. This is a comment and cannot be internationalized:
    comment = "The following error(s) occured during the curation of classifications: "
    comment += ([error] +
                hierarchy_entry_moves.with_errors.map do |m|
                  "\"#{m.error}\" on the classification from #{m.hierarchy_entry.hierarchy.display_title}"
                end
               ).to_sentence
    log_unlock_and_notify(Activity.unlock_with_error, :comment => comment)
  end

  # The ugliness of this method is born of the need (or desire) to create only ONE notification (but to leave two
  # logs if required).
  def log_unlock_and_notify(activity, options = {})
    activity_log = nil
    if moved_from
      activity_log = leave_log_on_taxon(moved_from, activity, options)
    end
    if moved_to && activity_log.nil?
      activity_log = leave_log_on_taxon(moved_to, activity, options)
    end
    if activity_log
      force_immediate_notification_of(activity_log)
    else
      logger.error "** ERROR: #{self} not reported; no activity log was created."
    end
  end

  def leave_log_on_taxon(parent, activity, options = {})
    comment = nil
    log = nil
    begin
      if options[:comment]
        comment = Comment.create!(:user_id => $BACKGROUND_TASK_USER_ID, :body => options[:comment], :parent => parent)
      end
      log = CuratorActivityLog.create!(:user_id => user_id,
                                       :changeable_object_type_id => comment ?
                                          ChangeableObjectType.comment.id :
                                          ChangeableObjectType.classification_curation.id,
                                       :target_id => options[:comment] ? comment.id : id,
                                       :activity => activity,
                                       :taxon_concept_id => parent.id)
    rescue => e
      logger.error "** ERROR: Could not create CuratorActivityLog for #{self}: #{e.message}"
    end
    log
  end

  def force_immediate_notification_of(moved_to)
    begin
      PendingNotification.create!(:user_id => user_id,
                                  :notification_frequency_id => NotificationFrequency.immediately.id,
                                  :target => moved_to,
                                  :reason => 'auto_email_after_curation')
      Resque.enqueue(PrepareAndSendNotifications)
    rescue => e
      # Do nothing (for now)...
    end
  end

  def log_activity_on(taxon_concept)
    CuratorActivityLog.create(
      :user => user,
      :taxon_concept => taxon_concept,
      :changeable_object_type => ChangeableObjectType.classification_curation,
      :target_id => id,
      :activity => Activity.curate_classifications
    )
  end

  # This method makes sure we don't process a ClassificationCuration twice, and makes sure that classifications don't
  # show up as "pending curation" on the names tab anymore.
  def mark_as_complete
    hierarchy_entry_moves.each do |move|
      move.update_column(:completed_at, Time.now)
    end
    update_column(:completed_at, Time.now)
  end

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.taverna.scufl2.api.common.AbstractCloneable.Cloning (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)</title>
<meta name="date" content="2016-03-14">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.taverna.scufl2.api.common.AbstractCloneable.Cloning

Packages that use AbstractCloneable.Cloning

Package
Description

org.apache.taverna.scufl2.api.activity

org.apache.taverna.scufl2.api.annotation

Common annotations

org.apache.taverna.scufl2.api.common

org.apache.taverna.scufl2.api.configurations

org.apache.taverna.scufl2.api.container

org.apache.taverna.scufl2.api.core

org.apache.taverna.scufl2.api.iterationstrategy

org.apache.taverna.scufl2.api.port

org.apache.taverna.scufl2.api.profiles

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.activity

Methods in org.apache.taverna.scufl2.api.activity with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
Activity.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.annotation

Methods in org.apache.taverna.scufl2.api.annotation with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
Revision.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

protected void
Annotation.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.common

Methods in org.apache.taverna.scufl2.api.common with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
AbstractNamed.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

protected abstract void
AbstractCloneable.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Constructors in org.apache.taverna.scufl2.api.common with parameters of type AbstractCloneable.Cloning

Constructor and Description

CopyVisitor(AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.configurations

Methods in org.apache.taverna.scufl2.api.configurations with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
Configuration.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.container

Methods in org.apache.taverna.scufl2.api.container with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
WorkflowBundle.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.core

Methods in org.apache.taverna.scufl2.api.core with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
Workflow.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

protected void
DataLink.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

protected void
BlockingControlLink.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.iterationstrategy

Methods in org.apache.taverna.scufl2.api.iterationstrategy with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
PortNode.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.port

Methods in org.apache.taverna.scufl2.api.port with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
AbstractGranularDepthPort.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

protected void
AbstractDepthPort.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Uses of AbstractCloneable.Cloning in org.apache.taverna.scufl2.api.profiles

Methods in org.apache.taverna.scufl2.api.profiles with parameters of type AbstractCloneable.Cloning

Modifier and Type
Method and Description

protected void
Profile.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

protected void
ProcessorPortBinding.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

protected void
ProcessorBinding.cloneInto(WorkflowBean clone,
         AbstractCloneable.Cloning cloning)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015–2016 The Apache Software Foundation. All rights reserved.


text:
+++
date = "2016-03-03T16:27:00+01:00"
draft = false
title = "Uploading CoreOS to Openstack Glance"
slug = "uploading-coreos-to-openstack-glance"
tags = [ "coreos", "glance", "openstack", ]
categories = [ "openstack", ]
+++

How to upload CoreOS to an Openstack provider.

<!--more-->

Run the following commands to download the latest CoreOS image and upload it
to the Openstack provider.

```
$ curl \
    -o coreos_production_openstack_image.img.bz2 \
    http://stable.release.core-os.net/amd64-usr/current/coreos_production_openstack_image.img.bz2

$ bunzip2 coreos_production_openstack_image.img.bz2

$ glance image-create \
    --architecture x86_64 \
    --name "coreos" \
    --min-disk 10 \
    --disk-format qcow2 \
    --min-ram 1024 \
    --container-format bare \
    --file coreos_production_openstack_image.img \
    --progress
```

The instructions assume you have a properly configured Openstack environment
running on the computer where you run the above commands.


text:
layout: post
title: Toy VS. Usage
filePath: 20180810-toyVSusage.jpg
tags: [hubblemonster]
description: What are some cat toys you have bought that your cat(s) love?
---


text:
layout: page
title: "MATH 3430: Ordinary Differential Equations Statistics"
comments: true
description: "blanks"
keywords: "MATH,3430,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 8.33%

**Percent incomplete**: 0.57%

**Average grade** (4.0 scale): 3.14

**Standard deviation in grades** (4.0 scale): 0.42

**Average workload** (raw): 2.93

**Standard deviation in workload** (raw): 0.33

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 4.63

**Standard deviation in course rating** (6 point scale): 0.67

**Average instructor rating** (6 point scale): 4.85

**Standard deviation in instructor rating** (6 point scale): 0.89

**Instructors**: Jeffrey Fox, David Grant, Judith Packer Jesudason, Gerard Misiolek, Bahram Rangipour, Alejandro Sarria, Alejandro Spina, Divya Vernerey, Jordan Watts

#### GENERAL CLASS INFORMATION

**Years provided**: Fall 2014, Spring 2015, Fall 2015, Spring 2016, Fall 2016, Spring 2017

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 16

**Department**: MATH

**College**: College of Arts and Sciences

**A&S Division**: Natural Sciences

**Level**: Upper

**Activity**: LEC - Lecture


text:
The project is described [here](http://dev.crantastic.org/about). Some other
links of interests are:

- [Crantastic](http://crantastic.org/)
- [Development blog](http://blog.crantastic.org/)
- [User Voice](http://crantastic.uservoice.com/)

The rest of this document contains various pieces of information relevant for
developers/contributors.

## Coding conventions

The [YARD](http://github.com/lsegal/yard/tree/master) meta-tag formatting format
is used for documentation, whenever it feels necessary.

## Development

Ruby 1.8.7 is recommended (we use the latest Ruby Enterprise version on the live
site). 1.9.x will not work (yet).

Copy `config/database.sample.yml` to `config/database.yml`. It defaults to
SQLite, so no additional configuration of this file is necessary unless you want
to use MySQL (which the site runs on in production). It's important that the
encoding flag is set to utf8, or you'll run into subtle bugs.

We use bundler to manage gems, so simply run `bundle install` to install all
required gem dependencies.

Using `autospec` while doing changes to the source code is highly recommended,
as this is very helpful for catching accidental regressions.

Note that you should only add/edit stylesheets in the `app/stylesheets` folder.
`public/stylesheets` should only contain compiled Sass stylesheets.

### Solr

A connection to a Solr server is required for running the site. Note that the
version of `acts_as_solr` that is included in the repository is stripped down,
so it does not include the server part. Setting up a Solr server on your
development machine is simple, though:

* Install the Java runtime environment (not necessary on OSX). On Debian or
  Ubuntu this can be done with: sudo apt-get install sun-java6-jre
* git clone git://github.com/mattmatt/acts_as_solr.git
* cd acts_as_solr/solr && java -jar start.jar

Then you can run `rake solr:reindex` from the folder where you have the
crantastic source code.

#### Solr on Production

If you need to restart solr on production, ssh in as crantastic to crantastic.org and do this:

    cd ~/acts_as_solr/solr
    nohup java -jar start.jar &

After that, you can exit the ssh session.

### R package

There is a R package for crantastic that lives in its own branch in the Git
repository. Use the following steps to check out the source:

    git fetch origin R-package
    git checkout --track -b R-package origin/R-package

## Updating packages from CRAN

Run `rake crantastic:cron` or `rake crantastic:update_packages`. Look in the
`lib/scripts` folder for scripts and cron tasks.

## License

The crantastic source code is released under the MIT license, consult the
accompanying MIT-LICENSE file for details.


text:
package org.javalite.activejdbc.test_models;

import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.BelongsToPolymorphic;

/**
 * @author Igor Polevoy on 10/24/14.
 */
@BelongsToPolymorphic(parents = {Article.class, Post.class})
public class Tag extends Model {
}


text:
<TITLE>Review for Shakespeare in Love (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Shakespeare in Love (1998)

reviewed by
David N. Butterworth

SHAKESPEARE IN LOVE
A film review by David N. Butterworth
Copyright 1999 David N. Butterworth

***1/2 stars (out of ****)

With hundreds of sonnets, comedies, tragedies, and patriotic histories
to his name, William Shakespeare seems an unlikely candidate for
writer's block.  But that's the conundrum facing the illustrious Bard at
the outset of "Shakespeare in Love," a deliciously witty and inventive
comedy drama that reminds us once again of the true genius of England's
greatest writer.

London, 1593, and Will Shakespeare (Joseph Fiennes, no doubt sick of
being referred to as "Ralph's little brother") is struggling with his
latest play.  He needs inspiration in the form of a muse and finds it in
Viola De Lesseps (a radiant Gwyneth Paltrow), who auditions for the male
lead (since women weren't allowed on stage in Elizabethan England).  It
isn't long before Viola, still in drag, starts canoodling in the wings
with the smitten playwright.

Unfortunately Viola is to be wed this fortnight to the odious Lord
Wessex (Colin Firth), which puts a bit of a crimp in our heroes'
romantic future.

It goes without saying that this is a purely invented account of what
inspired Will to write "Romeo and Juliet" (working title: "Romeo and
Ethel, the Pirate's Daughter"), but it's absolutely credible and great
fun in what it supposes.  Like any good Shakespearean work, "Shakespeare
in Love" is filled with love, sex, villainy, despair, tears, sword
fights, men dressed as women, women dressed as men, buffoonery, ribald
humor, intimidating penmanship...and a dog!

Writers Marc Norman and Tom Stoppard (who's been down a similar road
before with "Rosencrantz and Guildenstern Are Dead") take great delight
in mirroring the diction, the meter, and the sentiment of Shakespeare's
English.  Their screenplay is punctuated with earnest soliloquies,
anachronistic asides and, most effectively, the kind of adult humor
missing from so many mainstream scripts.  Where else but in "Shakespeare
in Love" might you find "But, soft! what light through yonder window
breaks?" within spitting distance of "for sixpence a line I'd cause a
riot in a nunnery."

As sophisticated as the writing is, it's not the be all and end all of
the piece.  "Shakespeare in Love" is a real team effort, from the fine
direction of John Madden ("Mrs. Brown") to a superlative cast.
"Shine"'s Geoffrey Rush plays the fool, Judi Dench plays the Queen, and
Tom ("The Full Monty") Wilkinson, Ben ("Armageddon") Affleck, and Rupert
("My Best Friend's Wedding") Everett all give fine accountings, with
Everett brief but fun as Will's rival playwright, the ill-fated
Christopher Marlowe.

Fiennes and Paltrow, of course, are terrific and make a handsomely
engaging couple, even if the latter's nude scenes do seem cheap and
somewhat distracting in this otherwise high-class production.

That said, "Shakespeare in Love" remains a wicked and wonderfully
mature period romance, one with which the Bard himself, no doubt, would
have been proud to be associated.

--
David N. Butterworth
dnb61@hotmail.com

Get Your Private, Free Email at http://www.hotmail.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package org.argus.jawa.core.codegen

import java.util

import org.stringtemplate.v4.STGroupString
import org.argus.jawa.core.util._
import org.stringtemplate.v4.ST
import org.argus.jawa.core._
import org.argus.jawa.core.elements.{JavaKnowledge, JawaType, Signature}

/**
 * @author Fengguo Wei
 */
abstract class MethodGenerator(global: Global) {

  private final val TITLE = "MethodGenerator"

  protected var currentComponent: JawaType = _
  protected var classes: ISet[JawaType] = isetEmpty
  /**
   * Map from class (i.e. container class) to list of callback method
   */
  protected var callbackFunctions: IMap[JawaType, ISet[Signature]] = imapEmpty
  protected var conditionCounter: Int = 0
  protected var codeCounter: Int = 0
  protected val template = new STGroupString(JawaModelProvider.jawaModel)
  protected val procDeclTemplate: ST = template.getInstanceOf("ProcedureDecl")
  protected val localVarsTemplate: ST = template.getInstanceOf("LocalVars")
  protected val bodyTemplate: ST = template.getInstanceOf("Body")
  protected val varGen = new VariableGenerator()
  protected val localVars = new util.ArrayList[String]
  protected val codeFragments = new util.ArrayList[CodeFragmentGenerator]

  /**
   * map from a clazz to it's substitute clazz
   */
  protected var substituteClassMap: IMap[JawaType, JawaType] = imapEmpty

  /**
   * Map of it's local variables
   */
  protected var localVarsForClasses: IMap[JawaType, String] = imapEmpty

  /**
   * Set of param's clazz name
   */
  protected var paramClasses: ISet[JawaType] = isetEmpty

  /**
   * set the substituteClassMap
   */
  def setSubstituteClassMap(map: IMap[JawaType, JawaType]): Unit = this.substituteClassMap = map

  /**
   * Registers a list of classes to be automatically scanned for Android
   * lifecycle methods
   * @param classes The list of classes to be automatically scanned for
   * Android lifecycle methods
   */
  def setEntryPointClasses(classes: ISet[JawaType]): Unit = {
    this.classes = classes
  }

  def setCurrentComponent(clazz: JawaType): Unit = {
    this.currentComponent = clazz
  }

  def setCodeCounter(codeCtr: Int): Unit = {
    this.codeCounter = codeCtr
  }

   def getCodeCounter: Int = {
    this.codeCounter
  }

  /**
   * Sets the list of callback functions to be integrated into the Android
   * lifecycle
   * @param callbackFunctions The list of callback functions to be integrated
   * into the Android lifecycle. This is a mapping from the Android element
   * class (activity, service, etc.) to the list of callback methods for that
   * element.
   */
  def setCallbackFunctions(callbackFunctions: IMap[JawaType, ISet[Signature]]) {
    if(this.callbackFunctions.isEmpty)
      this.callbackFunctions = callbackFunctions
    else {
      val funcs: MMap[JawaType, MSet[Signature]] = mmapEmpty
      this.callbackFunctions.foreach {
        case (k, v) => funcs.getOrElseUpdate(k, msetEmpty) ++= v
      }
      callbackFunctions.foreach {
        case (k, v) => funcs.getOrElseUpdate(k, msetEmpty) ++= v
      }
      this.callbackFunctions = funcs.map{case (k, v) => k -> v.toSet}.toMap
    }
  }

  def generate(name: String): (JawaMethod, String) = {
    generate(List(), name)
  }

  /**
   * generate environment with predefined methods list
   */
  def generate(methods: List[Signature], name: String): (JawaMethod, String) = {
    val className = this.currentComponent.jawaName
    val methodName = name
//    val annotations = new util.ArrayList[ST]
    val signature = JavaKnowledge.genSignature(JavaKnowledge.formatTypeToSignature(this.currentComponent), name, "()V")
    initMethodHead("void", methodName, className, signature, "STATIC")
    val code = generateInternal(methods)
    global.reporter.echo(TITLE, "Environment code:\n" + code)
    (global.resolveMethodCode(signature, code), code)
  }

  def generateWithParam(params: List[(JawaType, String)], methods: List[Signature], name: String, kind: String): (JawaMethod, String) = {
    val className = this.currentComponent.jawaName
    val methodName = name
//    val annotations = new util.ArrayList[ST]
    var parSigStr: String = ""
    params.foreach{param => if(param._2 != "this") parSigStr += JavaKnowledge.formatTypeToSignature(param._1)}
    val signature = JavaKnowledge.genSignature(JavaKnowledge.formatTypeToSignature(this.currentComponent), name, "(" + parSigStr+ ")V")

    initMethodHead("void", methodName, className, signature, kind)
    val paramArray = new util.ArrayList[ST]
    params.indices.foreach{ i =>
      val paramVar = template.getInstanceOf("ParamVar")
      val (param, kind) = params(i)
      val p = varGen.generate(param)
      localVarsForClasses += (param -> p)
      this.paramClasses += param
      val typStr = JawaModelProvider.generateType(param, template)
      paramVar.add("typ", typStr)
      paramVar.add("name", p)
      val annot = JawaModelProvider.generateAnnotation("kind", kind, template)
      paramVar.add("annotations", new util.ArrayList[ST](util.Arrays.asList(annot)))
      paramArray.add(i, paramVar)
    }
    procDeclTemplate.add("params", paramArray)
    val code = generateInternal(methods)
    global.reporter.echo(TITLE, "Environment code:\n" + code)
    (global.resolveMethodCode(signature, code), code)
  }

  protected def initMethodHead(retTyp: String, methodName: String, owner: String, signature: Signature, access: String): ST = {
    procDeclTemplate.add("retTyp", retTyp)
    procDeclTemplate.add("procedureName", methodName)
    val annotations = new util.ArrayList[ST]
    annotations.add(JawaModelProvider.generateAnnotation("signature", "`" + signature.signature + "`", template))
    annotations.add(JawaModelProvider.generateAnnotation("AccessFlag", access, template))
    procDeclTemplate.add("annotations", annotations)
  }

  def generateInternal(methods: List[Signature]): String

  protected def generateBody(): util.ArrayList[String] = {
    val body: util.ArrayList[String] = new util.ArrayList[String]
    for(i <- 0 until codeFragments.size()){
      body.add(i, codeFragments.get(i).generate())
    }
    body
  }

  protected def generateInstanceCreation(classType: JawaType, codefg: CodeFragmentGenerator): String = {
    val rhs = if(classType.jawaName == "java.lang.String"){
      val stringAnnot = JawaModelProvider.generateAnnotation("kind", "object", template)
      "\"\" " + stringAnnot.render()
    } else {
      val newExp = template.getInstanceOf("NewExp")
      newExp.add("name", JawaModelProvider.generateType(classType, template))
      newExp.render()
    }
    val va = varGen.generate(classType)
    val variable = template.getInstanceOf("LocalVar")
    val typStr = JawaModelProvider.generateType(classType, template)
    variable.add("typ", typStr)
    variable.add("name", va)
    localVars.add(variable.render())
    val asmt = template.getInstanceOf("AssignmentStmt")
    asmt.add("lhs", va)
    asmt.add("rhs", rhs)
    codefg.setCode(asmt)
    va
  }

  def generateClassConstructor(r: JawaClass, constructionStack: MSet[JawaType], codefg: CodeFragmentGenerator): Signature = {
    constructionStack.add(r.getType)
    val ps = r.getDeclaredMethods
    var cons: Signature = null
    val conMethods = ps.filter(p => p.isConstructor && !p.isStatic && !p.getParamTypes.contains(new JawaType("java.lang.Class")))
    if(conMethods.nonEmpty){
      val p = conMethods.minBy(_.getParamTypes.size)
      cons = p.getSignature
    }
    if(cons != null){
      generateMethodCall(cons, "direct", localVarsForClasses(r.getType), constructionStack, codefg)
    } else {
      global.reporter.warning(TITLE, "Cannot find constructor for " + r)
    }
    cons
  }

  protected def generateMethodCall(pSig: Signature, typ: String, localClassVar: String, constructionStack: MSet[JawaType], codefg: CodeFragmentGenerator): Unit = {
    val paramNum = pSig.getParameterNum
    val params = pSig.getObjectParameters
    var paramVars: Map[Int, String] = Map()
    params.foreach{ case(i, param) =>
      var r = global.getClassOrResolve(param)
      if(!r.isConcrete){
        val substClassName = this.substituteClassMap.getOrElse(r.getType, null)
        if(substClassName != null) r = global.getClassOrResolve(substClassName)
        else if(r.isInterface) global.getClassHierarchy.getAllImplementersOf(r).foreach(i => if(constructionStack.contains(i.getType)) r = i)
        else if(r.isAbstract) global.getClassHierarchy.getAllSubClassesOf(r).foreach(s => if(s.isConcrete && constructionStack.contains(s.getType)) r = s)
      }
      // to protect from going into dead constructor create loop
      if(localVarsForClasses.contains(r.getType)) paramVars += (i -> localVarsForClasses(r.getType))
      else if(!r.isConcrete){
        val va = varGen.generate(r.getType)
        localVarsForClasses += (r.getType -> va)
        paramVars += (i -> va)
        global.reporter.warning(TITLE, "Cannot create valid constructor for " + r + ", because it is " + r.getAccessFlagsStr + " and cannot find substitute.")
      } else if(!constructionStack.contains(r.getType)){
        val va = generateInstanceCreation(r.getType, codefg)
        localVarsForClasses += (r.getType -> va)
        paramVars += (i -> va)
        generateClassConstructor(r, constructionStack, codefg)
      } else {
        paramVars += (i -> localVarsForClasses(r.getType))
      }
    }
    val invokeStmt = template.getInstanceOf("InvokeStmtWithoutReturn")
    invokeStmt.add("funcName", pSig.methodName)
    val finalParamVars: util.ArrayList[String] = new util.ArrayList[String]
    finalParamVars.add(0, localClassVar)
    var index = 0
    for(i <- 0 until paramNum){
      if(paramVars.contains(i)){
        finalParamVars.add(index + 1, paramVars(i))
      } else {
        finalParamVars.add(index + 1, "x")
      }
      index += 1
    }
    invokeStmt.add("params", finalParamVars)
    val annotations = new util.ArrayList[ST]
    annotations.add(JawaModelProvider.generateAnnotation("signature", "`" + pSig.signature + "`", template))
    annotations.add(JawaModelProvider.generateAnnotation("kind", typ, template))
    invokeStmt.add("annotations", annotations)
    codefg.setCode(invokeStmt)
  }

  protected def generateCallToAllCallbacks(callbackClass: JawaClass, callbackMethods: Set[JawaMethod], classLocalVar: String, codefg: CodeFragmentGenerator): Unit = {
    var oneCallBackFragment = codefg
    callbackMethods.foreach{ callbackMethod =>
      val pSig = callbackMethod.getSignature
      val thenStmtFragment = new CodeFragmentGenerator
      createIfStmt(thenStmtFragment, oneCallBackFragment)
      val elseStmtFragment = new CodeFragmentGenerator
      createGotoStmt(elseStmtFragment, oneCallBackFragment)
      thenStmtFragment.addLabel()
      codeFragments.add(thenStmtFragment)
      generateMethodCall(pSig, "virtual", classLocalVar, msetEmpty + callbackClass.getType, thenStmtFragment)
      elseStmtFragment.addLabel()
      codeFragments.add(elseStmtFragment)
      oneCallBackFragment = new CodeFragmentGenerator
      oneCallBackFragment.addLabel()
      codeFragments.add(oneCallBackFragment)
    }
  }

  protected def searchAndBuildMethodCall(subsignature: String, clazz: JawaClass, entryPoints: MList[Signature], constructionStack: MSet[JawaType], codefg: CodeFragmentGenerator): Any = {
    val apopt = findMethod(clazz, subsignature)
    apopt match{
      case Some(ap) =>
        if(ap.getDeclaringClass.isApplicationClass) {
          entryPoints -= ap.getSignature
          assert(ap.isStatic || localVarsForClasses(clazz.getType) != null)
          generateMethodCall(ap.getSignature, "virtual", localVarsForClasses(clazz.getType), constructionStack, codefg)
        }
      case None =>
        global.reporter.warning(TITLE, "Could not find entry point method " + subsignature + " for " + clazz)
        null
    }
  }

  protected def addCallbackMethods(clazz: JawaClass, parentClassLocalVar: String, codefg: CodeFragmentGenerator): Unit = {
    if(!this.callbackFunctions.contains(clazz.getType)) return
    var callbackClasses: Map[JawaClass, ISet[JawaMethod]] = Map()
    this.callbackFunctions(clazz.getType).foreach{
      case pSig =>
        val theClass = global.getClassOrResolve(pSig.getClassType)
        val theMethod = findMethod(theClass, pSig.getSubSignature)
        theMethod match {
          case Some(method) =>
            callbackClasses += (theClass -> (callbackClasses.getOrElse(theClass, isetEmpty) + method))
          case None =>
            global.reporter.warning(TITLE, "Could not find callback method " + pSig)
        }
    }
    var oneCallBackFragment = codefg
    callbackClasses.foreach{
      case(callbackClass, callbackMethods) =>
        val classLocalVar: String = if(isCompatible(clazz, callbackClass)) {
          parentClassLocalVar
        }
        // create a new instance of this class
        else if(callbackClass.isConcrete){
          val va = generateInstanceCreation(callbackClass.getType, oneCallBackFragment)
          this.localVarsForClasses += (callbackClass.getType -> va)
          generateClassConstructor(callbackClass, msetEmpty + clazz.getType, oneCallBackFragment)
          va
        } else null
        if(classLocalVar != null){
          // build the calls to all callback methods in this clazz
          generateCallToAllCallbacks(callbackClass, callbackMethods, classLocalVar, oneCallBackFragment)
        } else {
          global.reporter.warning(TITLE, "Constructor cannot be generated for callback class " + callbackClass)
        }
        oneCallBackFragment = new CodeFragmentGenerator
        oneCallBackFragment.addLabel()
        codeFragments.add(oneCallBackFragment)
    }
  }

  protected def isCompatible(actual: JawaClass, expected: JawaClass): Boolean = {
    expected.isAssignableFrom(actual)
  }

  protected def createIfStmt(targetfg: CodeFragmentGenerator, codefg: CodeFragmentGenerator): AnyVal = {
    val target = targetfg.getLabel
    if(target != null){
      val condExp = template.getInstanceOf("CondExp")
      condExp.add("lhs", "RandomCoinToss")
      condExp.add("rhs", "head")
      val ifStmt = template.getInstanceOf("IfStmt")
      ifStmt.add("cond", condExp)
      ifStmt.add("label", target)
      codefg.setCode(ifStmt)
    }
  }

  protected def createGotoStmt(targetfg: CodeFragmentGenerator, codefg: CodeFragmentGenerator): AnyVal = {
    val target = targetfg.getLabel
    if(target != null){
      val gotoStmt = template.getInstanceOf("GotoStmt")
      gotoStmt.add("label", target)
      codefg.setCode(gotoStmt)
    }
  }

  protected def createReturnStmt(variable: String, codefg: CodeFragmentGenerator): Boolean = {
    val returnStmt = template.getInstanceOf("ReturnStmt")
    returnStmt.add("variable", variable)
    codefg.setCode(returnStmt)
  }

  protected def createFieldSetStmt(base: String, field: String, rhs: String, annoTyp: String, fieldType: JawaType, codefg: CodeFragmentGenerator): Boolean = {
    val mBaseField = template.getInstanceOf("FieldAccessExp")
    mBaseField.add("base", base)
    mBaseField.add("field", field)
    mBaseField.add("typ", JawaModelProvider.generateType(fieldType, template))
    val asmt = template.getInstanceOf("AssignmentStmt")
    asmt.add("lhs", mBaseField)
    asmt.add("rhs", rhs)
    val annotations = new util.ArrayList[ST]
    annotations.add(JawaModelProvider.generateAnnotation("kind", annoTyp, template))
    asmt.add("annotations", annotations)
    codefg.setCode(asmt)
  }

  protected class CodeFragmentGenerator {
    protected val codeFragment: ST = template.getInstanceOf("CodeFragment")
    protected val codes: util.ArrayList[ST] = new util.ArrayList[ST]
    protected var label: ST = template.getInstanceOf("Label")

    def addLabel(): Unit = {
      label.add("num", conditionCounter)
      codeFragment.add("label", label)
      conditionCounter += 1
    }
    def getLabel: ST = label
    def setCode(code: ST): Boolean = {
      codes.add(code)
    }
    def generate(): String = {
      val finalCodes = new util.ArrayList[ST]
      for(i <- 0 until codes.size){
        val code = template.getInstanceOf("Code")
        code.add("num", codeCounter)
        codeCounter += 1
        code.add("code", codes.get(i))
        finalCodes.add(i, code)
      }
      codeFragment.add("codes", finalCodes)
      codeFragment.render()
    }
  }

  protected def findMethod(currentClass: JawaClass, subSig: String): Option[JawaMethod] = {
    if(currentClass.declaresMethod(subSig)) currentClass.getMethod(subSig)
    else if(currentClass.hasSuperClass) findMethod(currentClass.getSuperClass, subSig)
    else None
  }
}


text:
title: Gibraltar - miasto tysiąca i jednej armaty
layout: post
category: relacje
keywords: rejs, kurs, Gibraltar
desc: Co warto zobaczyć na Gibraltarze.
img: /img/old/gibraltar/meczet.jpg
---
![lotnisko](/img/old/gibraltar/lotnisko.jpg)

W zeszłą niedzielę wróciłem z Gibraltaru.
Miasto zaskakuje, ale głównie mieszaniną ludzi i kultur. Już pierwszego dnia usłyszałem "Adios. Take care".

![armata](/img/old/gibraltar/armata.jpg)

Gibraltar to jednak nie tylko mieszanka angielsko-hiszpańska. Na ławce przed kościołem zupełnie naturalnie wyglądały
dwie kobiety ubrane w tradycyjne marokańskie stroje. Od dawna istnieją tu społeczności włoska, hinduska i żydowska.
Społeczności ukraińska i polska pojawiły zapewne całkiem niedawno, ale w jakimś sensie stanowią kontynuację pewnej tradycji.

Różnorodności kulturowe zdumiewająco zacierają się wśród młodzieży. Językiem, ubiorem i zachowaniem nastolatkowie
wydają się być typowymi anglikami. W pewnym momencie zastanawiałem się nawet skąd tam tyle młodzieży brytyjskiej :)

Nie byli to jednak młodzi turyści. Miasto ma kilka miejsc wartych odwiedzenia, raczej nie zostanie jednak mekką turystyczną.

![jaskinia](/img/old/gibraltar/jaskinia.jpg)

Warto odwiedzić jaskinię Św. Michała. Stalaktyty i stalagmity odpowiednio oświetlone tworzą znakomity nastrój.
Dodatkowo tajemniczości groty dodaje fakt, że było to ostatnie miejsce zamieszkiwania neandertalczyka.
W czasach, gdy cała ziemia była już opanowana przez naszych przodków, na Gibraltarze, żyło jeszcze kilka ostatnich rodzin naszych "kuzynów".

![tunel](/img/old/gibraltar/tunel.jpg)

Na drugiej stronie Skały "groty" wykuli już współcześni ludzie. Tunele z umieszczonymi w nich działami robią wrażenie.
Zwłaszcza, że większość powstała w XVIII wieku.

Generał hiszpański, któremu nie udało się zdobyć fortyfikacji w czasie oblężenia w latach 1779-1783, stwierdził,
że jest to dzieło inżynierskie godne starożytnych rzymian.
Armaty, działa, forty widoczne są w Gibraltarze na każdym kroku. Takiego nagromadzenia militariów z przeróżnych wieków
nie widziałem nigdy w jednym mieście. Zapewne zostały wystawione na widok publiczny by przypominać Hiszpanom, robiącym tu zakupy, kto tu rządzi... :-)

![malpa](/img/old/gibraltar/malpa.jpg)

Największą atrakcją Gibraltaru jest oczywiście sam Rock, czyli skała i zamieszkujące ją małpy. Góra, będąca geologicznie częścią Afryki,
wyrasta pionowo z morza i robi wrażenie. Nie dziwne, że starożytni nazywali ją słupami herkulesa (obok widocznym gołym okiem masywu górskiego w Maroku).
Natomiast występowanie tu dziko żyjących małp jest współczesnym, europejskim ewenementem.
Co prawda co do ich dzikości można mieć uzasadnione wątpliwości. Nie wydają się zbyt podekscytowane obecności ludzi na swoim terenie
- tylko nieliczne rewidują torby turystów. Większość pozuje do zdjęć drzemiąc.

![telefon](/img/old/gibraltar/telefon.jpg)

Ogród botaniczny jest miłym zakątkiem wartym odwiedzenia. Natomiast zamek muzułmański nie zrobił na mnie specjalnego wrażenia.
Porównywałem, go z Cuba z Palermo. Powstały mniej więcej w tym samym czasie i reprezentują podobny styl architektoniczny.
Mimo mniejszego zniszczenia, ten w Gibraltarze robi znacznie mniejsze wrażenie.

![pasy](/img/old/gibraltar/pasy.jpg)

Dużo większą atrakcją jest lotnisko. Wybudowane na mokradłach, które oddzielały kiedyś Gibraltar od Hiszpanii,
znajduje się dosłownie na granicy. Pas startowy przecina jedyna droga biegnąca do miasta.
Największym zaskoczeniem jest jednak bliskość mariny. Oddzielona jest od pasa startowego jedynie... no w zasadzie niczym,
nie jest oddzielona. Samoloty startują i lądują mniej niż 100 metrów od manewrujących jachtów.
Gdy na całym świecie nawet 10 metrów dzielące samolot od terminala, trzeba pokonać specjalnym autobusem,
to w Gibraltarze idąc z lotniska do miasta przechodzi się środkiem pasa startowego.

![zatoka](/img/old/gibraltar/zatoka.jpg)

Wysoka zabudowa mieszkalna (a nie hotelowa) i ceny nieruchomości świadczą, ż turystyka nie stanowi tu priorytetu.
Gibraltar wydaje się miastem skoncentrowanym na handlu i obsłudze wielkich statków przepływających cieśninę i tankujących tutaj,
nieobciążone podatkiem VAT, paliwo.

![meczet](/img/old/gibraltar/meczet.jpg)

Pewna pradawna tradycja morska, wydaje się jednak zamierać. Jeszcze 20 lat temu, dość otwarcie, działały tu silne grupy
zajmujące się przemytem narkotyków z Maroka do Hiszpanii. Podobno w latach 90-tych młodzi Gibraltarczycy po wygranej
w zawodach łodzi motorowych w Szkocji oświadczyli w wywiadzie w TV, że pływać uczyli się pędząc na swych super szybkich,
nieoświetlonych pontonach, pomiędzy tankowcami, uciekając przed helikopterami hiszpańskiej Guardia Civil.
Ta "piracka" przeszłość stanowi już chyba jedynie wspomnienie. Dziś Gibraltar wydaje się bardzo bezpiecznym,
a nawet sennym miejscem. Fakt, że marina i znajdujące się w niej jachty są całkowicie otwarte, jest rzadkością w UK, czy Hiszpanii.

Mimo całej swojej odmienności kulturowej i odmiennego klimatu, Gibraltarowi udaje się w jakiś sposób pozostać
prowincjonalnym brytyjskim miastem usytuowanym na krańcu Hiszpanii i Europy.

![samochodem](/img/old/gibraltar/samochodem.jpg)

Oby tak zostało.

----------------

O tym po co tam byłem można przeczytać tutaj: [Yachtmaster - egzamin i kurs przygotowawczy](/yachtmaster-egzamin-kurs).

Zapraszam również do galerii:

* [z samolotu](https://plus.google.com/photos/+ArekStryjski/albums/5310908063223525857)
* [miasto](https://plus.google.com/photos/+ArekStryjski/albums/5310922392627095057)
* [The Rock](https://plus.google.com/photos/+ArekStryjski/albums/5310904612295812353)
* [grota świętego Michała](https://plus.google.com/photos/+ArekStryjski/albums/5310833966162623649)
* [tunele, koszary, zamek](https://plus.google.com/photos/+ArekStryjski/albums/5310926315115263825)
* [ogród botaniczny](https://plus.google.com/photos/+ArekStryjski/albums/5310912664801617313)
* [marina](https://plus.google.com/photos/+ArekStryjski/albums/5310915271695513569)
* [nocą](https://plus.google.com/photos/+ArekStryjski/albums/5310909573738053137)


text:
package com.cognizant.cognizantits.qcconnection.qcupdation;

import com4j.Com4jObject;
import com4j.DISPID;
import com4j.DefaultValue;
import com4j.IID;
import com4j.MarshalAs;
import com4j.NativeType;
import com4j.Optional;
import com4j.ReturnValue;
import com4j.VTID;

@IID("{4BA5615F-21D7-49B3-94C8-12A29485E6F7}")
public abstract interface IComponentFactory3
  extends IComponentFactory2
{
  @DISPID(77)
  @VTID(21)
  @ReturnValue(type=NativeType.Dispatch)
  public abstract Com4jObject buildMultiProjectSummaryGraph(@Optional @DefaultValue("") String paramString1, @Optional @DefaultValue("") String paramString2, @Optional @DefaultValue("") String paramString3, @Optional @DefaultValue("") String paramString4, @Optional @DefaultValue("0") int paramInt, @Optional @MarshalAs(NativeType.VARIANT) Object paramObject, @Optional @DefaultValue("0") boolean paramBoolean1, @Optional @DefaultValue("0") boolean paramBoolean2);

  @DISPID(78)
  @VTID(22)
  @ReturnValue(type=NativeType.Dispatch)
  public abstract Com4jObject buildMultiProjectTrendGraph(@Optional @DefaultValue("") String paramString1, @Optional @DefaultValue("") String paramString2, @Optional @DefaultValue("") String paramString3, @Optional @DefaultValue("0") int paramInt, @Optional @MarshalAs(NativeType.VARIANT) Object paramObject1, @Optional @MarshalAs(NativeType.VARIANT) Object paramObject2, @Optional @DefaultValue("0") boolean paramBoolean1, @Optional @DefaultValue("0") boolean paramBoolean2);

  @DISPID(79)
  @VTID(23)
  @ReturnValue(type=NativeType.Dispatch)
  public abstract Com4jObject buildMultiProjectProgressGraph(@Optional @DefaultValue("") String paramString1, @Optional @DefaultValue("") String paramString2, @Optional @DefaultValue("") String paramString3, @Optional @DefaultValue("-1") boolean paramBoolean1, @Optional @DefaultValue("0") int paramInt1, @Optional @DefaultValue("1") int paramInt2, @Optional @DefaultValue("0") int paramInt3, @Optional @MarshalAs(NativeType.VARIANT) Object paramObject1, @Optional @MarshalAs(NativeType.VARIANT) Object paramObject2, @Optional @DefaultValue("0") boolean paramBoolean2, @Optional @DefaultValue("0") boolean paramBoolean3);
}

/* Location:           D:\Prabu\jars\QC.jar
 * Qualified Name:     qcupdation.IComponentFactory3
 * JD-Core Version:    0.7.0.1
 */


text:
//
// Copyright © 2014, David Tesler (https://github.com/protobufel)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

package com.github.protobufel.grammar;

import static com.github.protobufel.grammar.ParserUtils.getEndPositionInLine;
import static com.github.protobufel.grammar.ParserUtils.getLineCount;
import static com.github.protobufel.grammar.ParserUtils.getTrimmedBlockCommentContent;
import static com.github.protobufel.grammar.ProtoParser.LINE_COMMENT;
import static com.github.protobufel.grammar.ProtoParser.RBRACE;
import static com.github.protobufel.grammar.ProtoParser.SEMI;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;

import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;

import com.github.protobufel.grammar.ParserUtils.CommonTokenStreamEx;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.SourceCodeInfo;
import com.google.protobuf.DescriptorProtos.SourceCodeInfo.Location;
import com.google.protobuf.DescriptorProtos.UninterpretedOption;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.JavaType;

// ********************* LocationBuilder START ****************************************************

// FIXME implement and enable
class LocationBuilder {
  private static final String NEW_LINE = "\n";
  private static final Set<Integer> COMMENT_SKIPPERS;
  private Location.Builder location;
  private final Path path;
  // private ScopeManager scopeManager;
  private final SourceCodeInfo.Builder sourceBuilder;
  private final IdentityHashMap<Token, String> leadingComments;
  private final CommonTokenStreamEx tokens;

  private Scope currentScope;

  // Because Location path requires the repeated element to know its index
  // within its parent,
  // we need either to use the current parent builder, or scopes with type
  // element counters, or
  // as a fake FileDescriptorProto only for repeated fields within it with empty
  // elements.

  static {
    COMMENT_SKIPPERS = new HashSet<Integer>();
    COMMENT_SKIPPERS.add(RBRACE);
    COMMENT_SKIPPERS.add(SEMI);
  }

  public LocationBuilder(final SourceCodeInfo.Builder sourceBuilder,
      final CommonTokenStreamEx tokens) {
    location = null;
    path = new Path();
    currentScope = new FileScope();
    this.sourceBuilder = sourceBuilder;
    leadingComments = new IdentityHashMap<Token, String>();
    this.tokens = tokens;
  }

  public LocationBuilder addMessageLocation() {
    final int elementIndex = currentScope.addMessage();
    return addLocation();
  }

  public LocationBuilder addEnumLocation() {
    final int elementIndex = currentScope.addEnum();
    return addLocation();
  }

  public LocationBuilder addFieldLocation() {
    final int elementIndex = currentScope.addField();
    return addLocation();
  }

  public LocationBuilder addOptionLocation(final ParserRuleContext parentCtx) {
    final int optionsFieldNumber = currentScope.getOptionsFieldNumber();
    addLocation().addPath(optionsFieldNumber).setAllSpan(parentCtx);
    final int elementIndex = currentScope.addOption(optionsFieldNumber);
    return addLocation();
  }

  public LocationBuilder addOptionLocation() {
    final int optionsFieldNumber = currentScope.getOptionsFieldNumber();
    addLocation().addPath(optionsFieldNumber);
    final int elementIndex = currentScope.addOption(optionsFieldNumber);
    return addLocation();
  }

  public LocationBuilder addOptionNameLocation() {
    final int elementIndex = currentScope.addOptionName();
    return addLocation();
  }

  public LocationBuilder addLocationForPrimitive(final int fieldNumber) {
    final int elementIndex = currentScope.addElement(fieldNumber);
    addLocation();

    if (elementIndex >= 0) {
      addAllPath(Arrays.asList(fieldNumber, elementIndex));
    } else {
      addAllPath(Arrays.asList(fieldNumber));
    }

    return this;
  }

  public LocationBuilder popScope() {
    currentScope = currentScope.popScope();
    return this;
  }

  public LocationBuilder addLocation(final int index) {
    location = path.setAllPath(sourceBuilder.addLocationBuilder(index));
    return this;
  }

  public LocationBuilder addLocation() {
    location = path.setAllPath(sourceBuilder.addLocationBuilder());
    return this;
  }

  public LocationBuilder addLocationClone() {
    location =
        location == null ? sourceBuilder.getLocationBuilder(sourceBuilder.getLocationCount() - 1)
            : location;
    location = sourceBuilder.addLocationBuilder().addAllPath(location.getPathList());
    return this;
  }

  // ******************************* Path stuff START

  public LocationBuilder addAllPath(final ParserRuleContext ctx, final ParseTree... parts) {
    location.addAllSpan(getSpan(ctx));

    // FIXME
    if (parts != null && parts.length > 0) {
      for (final ParseTree parseTree : parts) {
        location
            .addAllSpan(parseTree instanceof ParserRuleContext ? getSpan((ParserRuleContext) parseTree)
                : getSpan((TerminalNode) parseTree));
      }
    }

    return this;
  }

  public LocationBuilder addAllPath(final Iterable<? extends Integer> values) {
    location.addAllPath(values);
    return this;
  }

  public LocationBuilder addPath(final int value) {
    location.addPath(value);
    return this;
  }

  // ******************************* Span stuff START

  public LocationBuilder setAllSpan(final ParserRuleContext ctx) {
    return setAllSpan(getSpan(ctx));
  }

  public LocationBuilder setAllSpan(final TerminalNode ctx) {
    return setAllSpan(getSpan(ctx));
  }

  public LocationBuilder setAllSpan(final ParseTree ctx) {
    if (ctx instanceof ParserRuleContext) {
      setAllSpan((ParserRuleContext) ctx);
    } else {
      setAllSpan((TerminalNode) ctx);
    }

    return this;
  }

  private LocationBuilder setAllSpan(final Iterable<? extends Integer> values) {
    if (location.getSpanCount() > 0) {
      location.clearSpan();
    }

    location.addAllSpan(values);
    return this;
  }

  private Iterable<Integer> getSpan(final ParserRuleContext ctx) {
    final Token startToken = ctx.getStart();
    final Token stopToken = ctx.getStop();

    if (stopToken.getLine() == startToken.getLine()) {
      return Arrays.asList(startToken.getLine() - 1, startToken.getCharPositionInLine(),
          getEndPositionInLine(stopToken));

    } else {
      return Arrays.asList(startToken.getLine() - 1, startToken.getCharPositionInLine(),
          stopToken.getLine() - 1, getEndPositionInLine(stopToken));
    }
  }

  private Iterable<Integer> getSpan(final TerminalNode ctx) {
    final Token startToken = ctx.getSymbol();
    return Arrays.asList(startToken.getLine() - 1, startToken.getCharPositionInLine(),
        getEndPositionInLine(startToken));
  }

  // ***************************** Comments stuff START

  public LocationBuilder clearComments() {
    location.clearLeadingComments().clearTrailingComments();
    return this;
  }

  public LocationBuilder comments(final ParserRuleContext ctx) {
    String comments = getLeadingComments(ctx);

    if (!comments.isEmpty()) {
      location.setLeadingComments(comments);
    }

    comments = getTrailingComments(ctx);

    if (!comments.isEmpty()) {
      location.setTrailingComments(comments);
    }

    return this;
  }

  private String getLeadingComments(final ParserRuleContext ctx) {
    final Token startToken = ctx.getStart();
    final String result = leadingComments.remove(startToken);

    if (result != null) {
      return result;
    }

    final List<Token> comments =
        tokens.getHiddenTokensToLeft(startToken.getTokenIndex(), Token.HIDDEN_CHANNEL);

    if (comments == null) {
      return "";
    }

    // process all comments as the previousToken is not a comments magnet!
    final StringBuilder builder = new StringBuilder();
    int currentLine = startToken.getLine();

    for (final ListIterator<Token> iterator = comments.listIterator(comments.size()); iterator
        .hasPrevious();) {
      final Token token = iterator.previous();
      final String text = token.getText();

      // FIXME deal with in beetwen comments intervals and endings!

      if (token.getType() == LINE_COMMENT) {
        if (currentLine - token.getLine() > 1) {
          break;
        }

        builder.append(text, 2, text.length()).append(NEW_LINE);
      } else { // this must be COMMENT!
        if (currentLine - (token.getLine() + getLineCount(text)) > 1) {
          break;
        }

        builder.append(getTrimmedBlockCommentContent(text));
      }

      currentLine = token.getLine();
    }

    return builder.toString();
  }

  private String getTrailingComments(final ParserRuleContext ctx) {
    final Token stopToken = ctx.getStop();
    final List<Token> comments =
        tokens.getHiddenTokensToRight(stopToken.getTokenIndex(), Token.HIDDEN_CHANNEL);

    if (comments == null) {
      return "";
    }

    final Token nextToken =
        tokens.nextToken(comments.get(comments.size() - 1).getTokenIndex(), Token.DEFAULT_CHANNEL);
    int toIndex;

    if (nextToken == null || isCommentSkipper(nextToken)) {
      toIndex = comments.size();
    } else {
      toIndex = setLeadingComments(stopToken, nextToken, comments);
    }

    int currentLine = stopToken.getLine();
    final StringBuilder builder = new StringBuilder();

    // FIXME deal with in beetwen comments intervals and endings!

    for (final Token token : comments.subList(0, toIndex)) {
      if (token.getLine() - currentLine > 1) {
        break;
      }

      final String text = token.getText();

      if (token.getType() == LINE_COMMENT) {
        builder.append(text, 2, text.length()).append(NEW_LINE);
        currentLine = token.getLine();
      } else { // this must be COMMENT!
        builder.append(getTrimmedBlockCommentContent(text));
        currentLine = token.getLine() + getLineCount(text);
      }
    }

    return builder.toString();
  }

  private boolean isCommentSkipper(final Token nextToken) {
    return COMMENT_SKIPPERS.contains(nextToken);
  }

  private int setLeadingComments(final Token previousToken, final Token startToken,
      final List<Token> comments) {
    final int skipLine = previousToken.getLine();
    final StringBuilder builder = new StringBuilder();
    int currentLine = startToken.getLine();
    int index = comments.size();

    for (final ListIterator<Token> iterator = comments.listIterator(comments.size()); iterator
        .hasPrevious();) {
      final Token token = iterator.previous();

      if (token.getLine() == skipLine) {
        break;
      }

      final String text = token.getText();

      // FIXME deal with in beetwen comments intervals and endings!

      if (token.getType() == LINE_COMMENT) {
        if (currentLine - token.getLine() > 1) {
          break;
        }

        builder.append(text, 2, text.length()).append(NEW_LINE);
      } else { // this must be COMMENT!
        if (currentLine - (token.getLine() + getLineCount(text)) > 1) {
          break;
        }

        builder.append(getTrimmedBlockCommentContent(text));
      }

      index--;
      currentLine = token.getLine();
    }

    leadingComments.put(startToken, builder.toString());
    return index;
  }

  // *************************** Comments END **********************************

  // ************************* Path START ***********************

  private static final class Path {
    private final List<Integer> path;

    private Path() {
      path = new ArrayList<Integer>();
    }

    public boolean isEmpty() {
      return path.isEmpty();
    }

    public void pushPath(final Collection<Integer> elementPath) {
      path.addAll(elementPath);
    }

    public boolean popPath(final int subPathSize) {
      path.subList(path.size() - subPathSize, path.size()).clear();
      return !path.isEmpty();
    }

    public Location.Builder setAllPath(final Location.Builder builder) {
      if (builder.getPathCount() > 0) {
        builder.clearPath();
      }

      return builder.addAllPath(path);
    }

    public Location.Builder newLocationBuilder() {
      return Location.newBuilder().addAllPath(path);
    }
  }

  // ************************* Path END ***********************
  // ************************* Scope Management START ****************

  private abstract class Scope {
    /*
     * private static final Set<Descriptor> SCOPE_TYPES = new HashSet<Descriptor>(Arrays.asList(
     * FileDescriptorProto.getDescriptor(), DescriptorProto.getDescriptor(),
     * EnumDescriptorProto.getDescriptor(), ServiceDescriptorProto.getDescriptor(),
     * FileOptions.getDescriptor(), MessageOptions.getDescriptor(), FieldOptions.getDescriptor(),
     * EnumOptions.getDescriptor(), EnumValueOptions.getDescriptor(),
     * ServiceOptions.getDescriptor(), MethodOptions.getDescriptor(),
     * UninterpretedOption.getDescriptor()));
     */
    private final Descriptor protoDescriptor;
    private final Map<Integer, Integer> counters;
    private Scope parent;
    private final int pathSize;

    public Scope(final Descriptor protoDescriptor, final Scope parent,
        final Collection<Integer> scopePath) {
      this.protoDescriptor = protoDescriptor;
      counters = new HashMap<Integer, Integer>();
      this.parent = parent;
      path.pushPath(scopePath);
      pathSize = scopePath.size();
    }

    public Scope popScope() {
      if (parent == null) {
        throw new RuntimeException("cannot pop the root scope");
      }

      path.popPath(pathSize);
      final Scope result = parent;
      parent = null;
      return result;
    }

    public Scope popScope(final Descriptor protoDescriptor) {
      Scope scope = this;

      while (!scope.protoDescriptor.equals(protoDescriptor)) {
        scope = scope.popScope();
      }

      return scope;
    }

    public int addElement(final int fieldNumber) {
      final Integer counter = counters.get(fieldNumber);

      if (counter != null) {
        counters.put(fieldNumber, counter + 1);
        return counter;
      }

      if (protoDescriptor.findFieldByNumber(fieldNumber).isRepeated()) {
        counters.put(fieldNumber, 1);
        return 0;
      }

      return -1;
    }

    public Descriptor getElementType(final int fieldNumber) {
      final FieldDescriptor field = protoDescriptor.findFieldByNumber(fieldNumber);
      return field.getJavaType() == JavaType.MESSAGE ? field.getMessageType() : null;
    }

    public Descriptor getProtoDescriptor() {
      return protoDescriptor;
    }

    public int getElementCount(final int fieldNumber) {
      final Integer count = counters.get(fieldNumber);
      return count == null ? 0 : count;
    }

    public int addEnum() {
      throw new RuntimeException("not applicable in current scope!");
    }

    public int addMessage() {
      throw new RuntimeException("not applicable in current scope!");
    }

    public int addField() {
      throw new RuntimeException("not applicable in current scope!");
    }

    public int addOption(final int optionsFieldNumber) {
      final int index = addElement(optionsFieldNumber);
      currentScope = new OptionScope(this, Arrays.asList(optionsFieldNumber, index));
      return index;
    }

    public int getOptionsFieldNumber() {
      final int optionsFieldNumber = protoDescriptor.findFieldByName("options").getNumber();
      return optionsFieldNumber;
    }

    public int addOptionName() {
      throw new RuntimeException("not applicable in current scope!");
    }
  }

  private class FileScope extends Scope {

    public FileScope() {
      super(FileDescriptorProto.getDescriptor(), null, Collections.<Integer>emptyList());
    }

    @Override
    public int addEnum() {
      return addElement(FileDescriptorProto.ENUM_TYPE_FIELD_NUMBER);
    }

    @Override
    public int addMessage() {
      final int index = addElement(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER);
      currentScope =
          new MessageScope(this,
              Arrays.asList(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER, index));
      return index;
    }

    @Override
    public int addField() {
      return addElement(FileDescriptorProto.EXTENSION_FIELD_NUMBER);
    }
  }

  private class MessageScope extends Scope {

    public MessageScope(final Scope parent, final Collection<Integer> scopePath) {
      super(DescriptorProto.getDescriptor(), parent, scopePath);
    }

    @Override
    public int addEnum() {
      return addElement(DescriptorProto.ENUM_TYPE_FIELD_NUMBER);
    }

    @Override
    public int addMessage() {
      final int index = addElement(DescriptorProto.NESTED_TYPE_FIELD_NUMBER);
      currentScope =
          new MessageScope(this, Arrays.asList(DescriptorProto.NESTED_TYPE_FIELD_NUMBER, index));
      return index;
    }

    @Override
    public int addField() {
      return addElement(DescriptorProto.FIELD_FIELD_NUMBER);
    }
  }

  private class OptionScope extends Scope {

    public OptionScope(final Scope parent, final Collection<Integer> scopePath) {
      super(UninterpretedOption.getDescriptor(), parent, scopePath);
    }

    @Override
    public int addOptionName() {
      final int index = addElement(UninterpretedOption.NAME_FIELD_NUMBER);
      currentScope =
          new GeneralScope(UninterpretedOption.NamePart.getDescriptor(), this, Arrays.asList(
              UninterpretedOption.NAME_FIELD_NUMBER, index));
      return index;
    }
  }

  private class GeneralScope extends Scope {

    public GeneralScope(final Descriptor protoDescriptor, final Scope parent,
        final Collection<Integer> scopePath) {
      super(protoDescriptor, parent, scopePath);
    }
  }

  // ************************* Scope Management END ******************

}