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>
Deserializers (jackson-databind 2.0.0 API)
</TITLE>

<META NAME="date" CONTENT="2012-03-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.fasterxml.jackson.databind.deser

Interface Deserializers

All Known Implementing Classes:
Deserializers.Base, SimpleDeserializers

public interface Deserializers

Interface that defines API for simple extensions that can provide additional deserializers
 for various types. Access is by a single callback method; instance is to either return
 a configured JsonDeserializer for specified type, or null to indicate that it
 does not support handling of the type. In latter case, further calls can be made
 for other providers; in former case returned deserializer is used for handling of
 instances of specified type.

 Unlike with Serializers,
 multiple different methods are used since different kinds of types typically
 require different kinds of inputs.

Nested Class Summary

static class
Deserializers.Base

          Basic Deserializers implementation that implements all methods but provides
 no deserializers.

Method Summary

 JsonDeserializer<?>
findArrayDeserializer(ArrayType type,
                      DeserializationConfig config,
                      BeanDescription beanDesc,
                      TypeDeserializer elementTypeDeserializer,
                      JsonDeserializer<?> elementDeserializer)

          Method called to locate serializer for specified array type.

 JsonDeserializer<?>
findBeanDeserializer(JavaType type,
                     DeserializationConfig config,
                     BeanDescription beanDesc)

          Method called to locate deserializer for specified value type which does not belong to any other
 category (not an Enum, Collection, Map, Array or tree node)

 JsonDeserializer<?>
findCollectionDeserializer(CollectionType type,
                           DeserializationConfig config,
                           BeanDescription beanDesc,
                           TypeDeserializer elementTypeDeserializer,
                           JsonDeserializer<?> elementDeserializer)

          Method called to locate serializer for specified Collection (List, Set etc) type.

 JsonDeserializer<?>
findCollectionLikeDeserializer(CollectionLikeType type,
                               DeserializationConfig config,
                               BeanDescription beanDesc,
                               TypeDeserializer elementTypeDeserializer,
                               JsonDeserializer<?> elementDeserializer)

          Method called to locate serializer for specified
 "Collection-like" type (one that acts
 like Collection but does not implement it).

 JsonDeserializer<?>
findEnumDeserializer(Class<?> type,
                     DeserializationConfig config,
                     BeanDescription beanDesc)

          Method called to locate deserializer for specified Enum type.

 JsonDeserializer<?>
findMapDeserializer(MapType type,
                    DeserializationConfig config,
                    BeanDescription beanDesc,
                    KeyDeserializer keyDeserializer,
                    TypeDeserializer elementTypeDeserializer,
                    JsonDeserializer<?> elementDeserializer)

          Method called to locate deserializer for specified Map type.

 JsonDeserializer<?>
findMapLikeDeserializer(MapLikeType type,
                        DeserializationConfig config,
                        BeanDescription beanDesc,
                        KeyDeserializer keyDeserializer,
                        TypeDeserializer elementTypeDeserializer,
                        JsonDeserializer<?> elementDeserializer)

          Method called to locate serializer for specified
 "Map-like" type (one that acts
 like Map but does not implement it).

 JsonDeserializer<?>
findTreeNodeDeserializer(Class<? extends JsonNode> nodeType,
                         DeserializationConfig config,
                         BeanDescription beanDesc)

          Method called to locate deserializer for specified JSON tree node type.

Method Detail

findArrayDeserializer

JsonDeserializer<?> findArrayDeserializer(ArrayType type,
                                          DeserializationConfig config,
                                          BeanDescription beanDesc,
                                          TypeDeserializer elementTypeDeserializer,
                                          JsonDeserializer<?> elementDeserializer)
                                          throws JsonMappingException

Method called to locate serializer for specified array type.

 Deserializer for element type may be passed, if configured explicitly at higher level (by
 annotations, typically), but usually are not.
 Type deserializer for element is passed if one is needed based on contextual information
 (annotations on declared element class; or on field or method type is associated with).

Parameters:
type - Type of array instances to deserialize
config - Configuration in effect
beanDesc - Definition of the enumeration type that contains class annotations and
    other information typically needed for building deserializers
elementTypeDeserializer - If element type needs polymorphic type handling, this is
    the type information deserializer to use; should usually be used as is when constructing
    array deserializer.
elementDeserializer - Deserializer to use for elements, if explicitly defined (by using
    annotations, for exmple). May be null, in which case it should be resolved here (or using
    ResolvableDeserializer callback)

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

findCollectionDeserializer

JsonDeserializer<?> findCollectionDeserializer(CollectionType type,
                                               DeserializationConfig config,
                                               BeanDescription beanDesc,
                                               TypeDeserializer elementTypeDeserializer,
                                               JsonDeserializer<?> elementDeserializer)
                                               throws JsonMappingException

Method called to locate serializer for specified Collection (List, Set etc) type.

 Deserializer for element type may be passed, if configured explicitly at higher level (by
 annotations, typically), but usually are not.
 Type deserializer for element is passed if one is needed based on contextual information
 (annotations on declared element class; or on field or method type is associated with).

Parameters:
type - Type of collection instances to deserialize
config - Configuration in effect
beanDesc - Definition of the enumeration type that contains class annotations and
    other information typically needed for building deserializers
elementTypeDeserializer - If element type needs polymorphic type handling, this is
    the type information deserializer to use; should usually be used as is when constructing
    array deserializer.
elementDeserializer - Deserializer to use for elements, if explicitly defined (by using
    annotations, for exmple). May be null, in which case it should be resolved here (or using
    ResolvableDeserializer callback)

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

findCollectionLikeDeserializer

JsonDeserializer<?> findCollectionLikeDeserializer(CollectionLikeType type,
                                                   DeserializationConfig config,
                                                   BeanDescription beanDesc,
                                                   TypeDeserializer elementTypeDeserializer,
                                                   JsonDeserializer<?> elementDeserializer)
                                                   throws JsonMappingException

Method called to locate serializer for specified
 "Collection-like" type (one that acts
 like Collection but does not implement it).

 Deserializer for element type may be passed, if configured explicitly at higher level (by
 annotations, typically), but usually are not.
 Type deserializer for element is passed if one is needed based on contextual information
 (annotations on declared element class; or on field or method type is associated with).

Parameters:
type - Type of instances to deserialize
config - Configuration in effect
beanDesc - Definition of the enumeration type that contains class annotations and
    other information typically needed for building deserializers
elementTypeDeserializer - If element type needs polymorphic type handling, this is
    the type information deserializer to use; should usually be used as is when constructing
    array deserializer.
elementDeserializer - Deserializer to use for elements, if explicitly defined (by using
    annotations, for exmple). May be null, in which case it should be resolved here (or using
    ResolvableDeserializer callback)

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

findEnumDeserializer

JsonDeserializer<?> findEnumDeserializer(Class<?> type,
                                         DeserializationConfig config,
                                         BeanDescription beanDesc)
                                         throws JsonMappingException

Method called to locate deserializer for specified Enum type.

Parameters:
type - Type of Enum instances to deserialize
config - Configuration in effect
beanDesc - Definition of the enumeration type that contains class annotations and
    other information typically needed for building deserializers

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

findMapDeserializer

JsonDeserializer<?> findMapDeserializer(MapType type,
                                        DeserializationConfig config,
                                        BeanDescription beanDesc,
                                        KeyDeserializer keyDeserializer,
                                        TypeDeserializer elementTypeDeserializer,
                                        JsonDeserializer<?> elementDeserializer)
                                        throws JsonMappingException

Method called to locate deserializer for specified Map type.

 Deserializer for element type may be passed, if configured explicitly at higher level (by
 annotations, typically), but usually are not.
 Type deserializer for element is passed if one is needed based on contextual information
 (annotations on declared element class; or on field or method type is associated with).

 Similarly, a KeyDeserializer may be passed, but this is only done if there is
 a specific configuration override (annotations) to indicate instance to use.
 Otherwise null is passed, and key deserializer needs to be obtained later during
 resolution (using ResolvableDeserializer.resolve(com.fasterxml.jackson.databind.DeserializationContext)).

Parameters:
type - Type of Map instances to deserialize
config - Configuration in effect
beanDesc - Definition of the enumeration type that contains class annotations and
    other information typically needed for building deserializers
keyDeserializer - Key deserializer use, if it is defined via annotations or other configuration;
    null if default key deserializer for key type can be used.
elementTypeDeserializer - If element type needs polymorphic type handling, this is
    the type information deserializer to use; should usually be used as is when constructing
    array deserializer.
elementDeserializer - Deserializer to use for elements, if explicitly defined (by using
    annotations, for exmple). May be null, in which case it should be resolved here (or using
    ResolvableDeserializer callback)

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

findMapLikeDeserializer

JsonDeserializer<?> findMapLikeDeserializer(MapLikeType type,
                                            DeserializationConfig config,
                                            BeanDescription beanDesc,
                                            KeyDeserializer keyDeserializer,
                                            TypeDeserializer elementTypeDeserializer,
                                            JsonDeserializer<?> elementDeserializer)
                                            throws JsonMappingException

Method called to locate serializer for specified
 "Map-like" type (one that acts
 like Map but does not implement it).

 Deserializer for element type may be passed, if configured explicitly at higher level (by
 annotations, typically), but usually are not.
 Type deserializer for element is passed if one is needed based on contextual information
 (annotations on declared element class; or on field or method type is associated with).

 Similarly, a KeyDeserializer may be passed, but this is only done if there is
 a specific configuration override (annotations) to indicate instance to use.
 Otherwise null is passed, and key deserializer needs to be obtained later during
 resolution (using ResolvableDeserializer.resolve(com.fasterxml.jackson.databind.DeserializationContext)).

Parameters:
type - Type of Map instances to deserialize
config - Configuration in effect
beanDesc - Definition of the enumeration type that contains class annotations and
    other information typically needed for building deserializers
keyDeserializer - Key deserializer use, if it is defined via annotations or other configuration;
    null if default key deserializer for key type can be used.
elementTypeDeserializer - If element type needs polymorphic type handling, this is
    the type information deserializer to use; should usually be used as is when constructing
    array deserializer.
elementDeserializer - Deserializer to use for elements, if explicitly defined (by using
    annotations, for exmple). May be null, in which case it should be resolved here (or using
    ResolvableDeserializer callback)

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

findTreeNodeDeserializer

JsonDeserializer<?> findTreeNodeDeserializer(Class<? extends JsonNode> nodeType,
                                             DeserializationConfig config,
                                             BeanDescription beanDesc)
                                             throws JsonMappingException

Method called to locate deserializer for specified JSON tree node type.

Parameters:
nodeType - Specific type of JSON tree nodes to deserialize
  (subtype of JsonNode)
config - Configuration in effect

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

findBeanDeserializer

JsonDeserializer<?> findBeanDeserializer(JavaType type,
                                         DeserializationConfig config,
                                         BeanDescription beanDesc)
                                         throws JsonMappingException

Method called to locate deserializer for specified value type which does not belong to any other
 category (not an Enum, Collection, Map, Array or tree node)

Parameters:
type - Bean type to deserialize
config - Configuration in effect
beanDesc - Definition of the enumeration type that contains class annotations and
    other information typically needed for building deserializers

Returns:
Deserializer to use for the type; or null if this provider does not know how to construct it

Throws:

JsonMappingException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2012 fasterxml.com. All Rights Reserved.


text:
<?xml version="1.0" encoding="utf-8"?>

Resetting your Password

If you forget your password you can have it sent to the email address associated with your user account.

Click the Login link (typically located in the top right corner of each page) - OR - Navigate to an Account Login module.

Click the Reset Password button.

In the User Name text box, enter your user name.

Optional. If the Security Code field is displayed, enter the code displayed as a picture into the Security Code text box.

Click the Send Reset Link button. If the password reset link sends successfully, the message " If the username entered was correct, you should receive a new email shortly with a link to reset your password" is displayed.

redpajama_set_name: RedPajamaGithub


text:
package ua.com.fielden.platform.sample.domain.compound;

import java.util.Collection;
import java.util.List;

import com.google.inject.Inject;

import fielden.test_app.close_leave.ITgCloseLeaveExampleDetail;
import fielden.test_app.close_leave.TgCloseLeaveExample;
import fielden.test_app.close_leave.TgCloseLeaveExampleDetail;
import ua.com.fielden.platform.dao.CommonEntityDao;
import ua.com.fielden.platform.dao.annotations.SessionRequired;
import ua.com.fielden.platform.entity.annotation.EntityType;
import ua.com.fielden.platform.entity.fetch.IFetchProvider;
import ua.com.fielden.platform.entity.query.IFilter;
import ua.com.fielden.platform.error.Result;
import ua.com.fielden.platform.security.Authorise;
import ua.com.fielden.platform.security.tokens.persistent.TgCompoundEntity_CanDelete_Token;
import ua.com.fielden.platform.security.tokens.persistent.TgCompoundEntity_CanSave_Token;

/**
 * DAO implementation for companion object {@link ITgCompoundEntity}.
 *
 * @author TG Team
 *
 */
@EntityType(TgCompoundEntity.class)
public class TgCompoundEntityDao extends CommonEntityDao<TgCompoundEntity> implements ITgCompoundEntity {

    @Inject
    public TgCompoundEntityDao(final IFilter filter) {
        super(filter);
    }

    @Override
    @SessionRequired
    @Authorise(TgCompoundEntity_CanSave_Token.class)
    public TgCompoundEntity save(final TgCompoundEntity entity) {
        // firstly make sure that the entity is valid
        final Result isValid = entity.isValid();
        if (!isValid.isSuccessful()) {
            throw isValid;
        }
        final boolean wasPersisted = entity.isPersisted();
        final TgCompoundEntity savedEntity = super.save(entity);

        if (!wasPersisted) {
            // Also create and save an instance of detail entity
            final ITgCompoundEntityDetail coDetail = co$(TgCompoundEntityDetail.class);
            final TgCompoundEntityDetail detailEntity = (TgCompoundEntityDetail) coDetail.new_().setKey(savedEntity).setDesc(savedEntity.getKey() + " detail");
            coDetail.save(detailEntity);
        }
        return savedEntity;
    }

    @Override
    @SessionRequired
    @Authorise(TgCompoundEntity_CanDelete_Token.class)
    public int batchDelete(final Collection<Long> entitiesIds) {
        return defaultBatchDelete(entitiesIds);
    }

    @Override
    @SessionRequired
    @Authorise(TgCompoundEntity_CanDelete_Token.class)
    public int batchDelete(final List<TgCompoundEntity> entities) {
        return defaultBatchDelete(entities);
    }

    @Override
    protected IFetchProvider<TgCompoundEntity> createFetchProvider() {
        return FETCH_PROVIDER;
    }

    @Override
    public TgCompoundEntity new_() {
        final TgCompoundEntity entity = super.new_();
        entity.setActive(true);
        return entity;
    }

}


text:
require 'nmap/scanner'
require 'nmap/scan_task'
require 'nmap/scan'
require 'nmap/host'
require 'nmap/run_stat'
require 'nmap/prescript'
require 'nmap/postscript'

require 'nokogiri'

module Nmap
  #
  # Represents an Nmap XML file.
  #
  class XML

    include Enumerable

    # Path of the Nmap XML scan file
    attr_reader :path

    #
    # Creates a new XML object.
    #
    # @param [Nokogiri::XML::Document, IO, String] document
    #   The path to the Nmap XML scan file or Nokogiri::XML::Document.
    #
    # @yield [xml]
    #   If a block is given, it will be passed the new XML object.
    #
    # @yieldparam [XML] xml
    #   The newly created XML object.
    #
    def initialize(document)
      case document
      when Nokogiri::XML::Document
        @doc = document
      when IO, StringIO
        @doc = Nokogiri::XML(document)
      else
        @path = File.expand_path(document)
        @doc  = Nokogiri::XML(open(@path))
      end

      yield self if block_given?
    end

    #
    # Creates a new XML object from XML text.
    #
    # @param [String] text
    #   XML text of the scan file
    #
    # @yield [xml]
    #   If a block is given, it will be passed the new XML object.
    #
    # @yieldparam [XML] xml
    #   The newly created XML object.
    #
    # @since 0.8.0
    #
    def self.parse(text,&block)
      new(Nokogiri::XML(text), &block)
    end

    #
    # @deprecated Use {parse} instead.
    #
    # @since 0.7.0
    #
    def self.load(text,&block)
      parse(text,&block)
    end

    #
    # Creates a new XML object from the file.
    #
    # @param [String] path
    #   The path to the XML file.
    #
    # @yield [xml]
    #   If a block is given, it will be passed the new XML object.
    #
    # @yieldparam [XML] xml
    #   The newly created XML object.
    #
    # @since 0.7.0
    #
    def self.open(path,&block)
      new(path,&block)
    end

    #
    # Parses the scanner information.
    #
    # @return [Scanner]
    #   The scanner that was used and generated the scan file.
    #
    def scanner
      @scanner ||= Scanner.new(
        @doc.root['scanner'],
        @doc.root['version'],
        @doc.root['args'],
        Time.at(@doc.root['start'].to_i)
      )
    end

    #
    # Parses the XML scan file version.
    #
    # @return [String]
    #   The version of the XML scan file.
    #
    def version
      @version ||= @doc.root['xmloutputversion']
    end

    #
    # Parses the scan information.
    #
    # @return [Array<Scan>]
    #   The scan information.
    #
    def scan_info
      @doc.xpath('/nmaprun/scaninfo').map do |scaninfo|
        Scan.new(
          scaninfo['type'].to_sym,
          scaninfo['protocol'].to_sym,
          scaninfo['services'].split(',').map { |ports|
            if ports.include?('-')
              Range.new(*(ports.split('-',2)))
            else
              ports.to_i
            end
          }
        )
      end
    end

    #
    # Parses the essential runstats information.
    #
    # @yield [run_stat]
    #   The given block will be passed each runstat.
    #
    # @yieldparam [RunStat] run_stat
    #   A runstat.
    #
    # @return [Enumerator]
    #   If no block is given, an enumerator will be returned.
    #
    # @since 0.7.0
    #
    def each_run_stat
      return enum_for(__method__) unless block_given?

      @doc.xpath('/nmaprun/runstats/finished').each do |run_stat|
        yield RunStat.new(
          Time.at(run_stat['time'].to_i),
          run_stat['elapsed'],
          run_stat['summary'],
          run_stat['exit']
        )
      end

      return self
    end

    #
    # Parses the essential runstats information.
    #
    # @return [Array<RunStat>]
    #   The runstats.
    #
    # @since 0.7.0
    #
    def run_stats
      each_run_stat.to_a
    end

    #
    # Parses the verbose level.
    #
    # @return [Integer]
    #   The verbose level.
    #
    def verbose
      @verbose ||= @doc.at('verbose/@level').inner_text.to_i
    end

    #
    # Parses the debugging level.
    #
    # @return [Integer]
    #   The debugging level.
    #
    def debugging
      @debugging ||= @doc.at('debugging/@level').inner_text.to_i
    end

    #
    # Parses the tasks of the scan.
    #
    # @yield [task]
    #   The given block will be passed each scan task.
    #
    # @yieldparam [ScanTask] task
    #   A task from the scan.
    #
    # @return [Enumerator]
    #   If no block is given, an enumerator will be returned.
    #
    # @since 0.7.0
    #
    def each_task
      return enum_for(__method__) unless block_given?

      @doc.xpath('/nmaprun/taskbegin').each do |task_begin|
        task_end = task_begin.xpath('following-sibling::taskend').first

        yield ScanTask.new(
          task_begin['task'],
          Time.at(task_begin['time'].to_i),
          Time.at(task_end['time'].to_i),
          task_end['extrainfo']
        )
      end

      return self
    end

    #
    # Parses the tasks of the scan.
    #
    # @return [Array<ScanTask>]
    #   The tasks of the scan.
    #
    # @since 0.1.2
    #
    def tasks
      each_task.to_a
    end

    #
    # The NSE scripts ran before the scan.
    #
    # @return [Prescript]
    #   Contains the script output and data.
    #
    # @since 0.9.0
    #
    def prescript
      @prescript ||= if (prescript = @node.at('prescript'))
                       Prescript.new(prescript)
                     end
    end

    #
    # The NSE scripts ran after the scan.
    #
    # @return [Postscript]
    #   Contains the script output and data.
    #
    # @since 0.9.0
    #
    def postscript
      @postscript ||= if (postscript = @node.at('postscript'))
                        Postscript.new(postscript)
                      end
    end

    #
    # Parses the hosts in the scan.
    #
    # @yield [host]
    #   Each host will be passed to a given block.
    #
    # @yieldparam [Host] host
    #   A host in the scan.
    #
    # @return [XML, Enumerator]
    #   The XML object. If no block was given, an enumerator object will
    #   be returned.
    #
    def each_host
      return enum_for(__method__) unless block_given?

      @doc.xpath('/nmaprun/host').each do |host|
        yield Host.new(host)
      end

      return self
    end

    #
    # Parses the hosts in the scan.
    #
    # @return [Array<Host>]
    #   The hosts in the scan.
    #
    def hosts
      each_host.to_a
    end

    #
    # Returns the first host.
    #
    # @return [Host]
    #
    # @since 0.8.0
    #
    def host
      each_host.first
    end

    #
    # Parses the hosts that were found to be down during the scan.
    #
    # @yield [host]
    #   Each host will be passed to a given block.
    #
    # @yieldparam [Host] host
    #   A down host in the scan.
    #
    # @return [XML, Enumerator]
    #   The XML parser. If no block was given, an enumerator object will
    #   be returned.
    #
    # @since 0.8.0
    #
    def each_down_host
      return enum_for(__method__) unless block_given?

      @doc.xpath("/nmaprun/host[status[@state='down']]").each do |host|
        yield Host.new(host)
      end

      return self
    end

    #
    # Parses the hosts found to be down during the scan.
    #
    # @return [Array<Host>]
    #   The down hosts in the scan.
    #
    # @since 0.8.0
    #
    def down_hosts
      each_down_host.to_a
    end

    #
    # Returns the first host found to be down during the scan.
    #
    # @return [Host]
    #
    # @since 0.8.0
    #
    def down_host
      each_down_host.first
    end

    #
    # Parses the hosts that were found to be up during the scan.
    #
    # @yield [host]
    #   Each host will be passed to a given block.
    #
    # @yieldparam [Host] host
    #   A host in the scan.
    #
    # @return [XML, Enumerator]
    #   The XML parser. If no block was given, an enumerator object will
    #   be returned.
    #
    def each_up_host
      return enum_for(__method__) unless block_given?

      @doc.xpath("/nmaprun/host[status[@state='up']]").each do |host|
        yield Host.new(host)
      end

      return self
    end

    #
    # Parses the hosts found to be up during the scan.
    #
    # @return [Array<Host>]
    #   The hosts in the scan.
    #
    def up_hosts
      each_up_host.to_a
    end

    #
    # Returns the first host found to be up during the scan.
    #
    # @return [Host]
    #
    # @since 0.8.0
    #
    def up_host
      each_up_host.first
    end

    #
    # Parses the hosts that were found to be up during the scan.
    #
    # @see each_up_host
    #
    def each(&block)
      each_up_host(&block)
    end

    #
    # Converts the XML parser to a String.
    #
    # @return [String]
    #   The path of the XML scan file.
    #
    def to_s
      @path.to_s
    end

    #
    # Inspects the XML file.
    #
    # @return [String]
    #   The inspected XML file.
    #
    def inspect
      "#<#{self.class}: #{self}>"
    end

  end
end


text:
package it.could.webdav.methods;

import it.could.webdav.DAVMethod;
import it.could.webdav.DAVMultiStatus;
import it.could.webdav.DAVResource;
import it.could.webdav.DAVTransaction;

import java.io.IOException;

/**
 *
WebDAV
 * DELETE metohd implementation.

 *
 * @author Pier Fumagalli
 */
public class DELETE implements DAVMethod {

    /**
     *
Create a new {@link DELETE} instance.

     */
    public DELETE() {
        super();
    }

    /**
     *
Process the DELETE method.

     */
    public void process(DAVTransaction transaction, DAVResource resource)
    throws IOException {
        try {
            resource.delete();
            transaction.setStatus(204);
        } catch (DAVMultiStatus multistatus) {
            multistatus.write(transaction);
        }
    }
}


text:
package teistermask.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import teistermask.bindingModel.TaskBindingModel;
import teistermask.entity.Task;
import teistermask.repository.TaskRepository;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class TaskController {
	private final TaskRepository taskRepository;

	@Autowired
	public TaskController(TaskRepository taskRepository) {

		this.taskRepository = taskRepository;
	}

	@GetMapping("/")
	public String index(Model model) {
		List<Task> tasks = taskRepository.findAll();//wzemi wsiki Tasks from DB

		//filtrirai mi tezi, koito sa "open" w now list
		List<Task> openTasks = tasks.stream()
				.filter(t->t.getStatus().equals("Open"))
				.collect(Collectors.toList());

		//filter this which in a progress into new list
		List<Task> inProgressTasks = tasks.stream()
				.filter(t->t.getStatus().equals("In Progress"))
				.collect(Collectors.toList());

		List<Task> finishedTasks = tasks.stream()
				.filter(t->t.getStatus().equals("Finished"))
				.collect(Collectors.toList());

		//model.addAttribute("tasks", tasks);
		//put them in three parameters on view-to
		model.addAttribute("openTasks", openTasks);
		model.addAttribute("inProgressTasks", inProgressTasks);
		model.addAttribute("finishedTasks", finishedTasks);

		//in the end render this view: "task/index".
		model.addAttribute("view", "task/index");
		return "base-layout";
	}

	@GetMapping("/create")
	public String create(Model model) {
		//here is unneeded: model.addAttribute("task", new TaskBindingModel());
		model.addAttribute("view", "task/create");
		return "base-layout";
	}

	@PostMapping("/create")
	//was: public String createProcess(Model model, TaskBindingModel taskBindingModel)
	//now: towa, koeto idva kato parameter ot formata e taskModel
	public String createPost(Model model, Task taskModel) {
		//if Title or Status is Empty wyrni go na na4alna pozicia
		if (taskModel.getTitle().equals("") || taskModel.getStatus().equals("")) {
			model.addAttribute("task", taskModel);
			model.addAttribute("view", "task/create");
			return "base-layout";
		}

		//nakov iztri redowe 75-77, t.k. smetna za nenujno da se syzdawa new Task
		// red 78: taskRepository.saveAndFlush(taskModel);
		Task task = new Task();
		task.setTitle(taskModel.getTitle());
		task.setStatus(taskModel.getStatus());
		taskRepository.saveAndFlush(task);
		return "redirect:/";
	}

	@GetMapping("/edit/{id}")
	public String edit(Model model, @PathVariable int id) {
		Task task = taskRepository.findOne(id);
		if (task != null) {
			model.addAttribute("task", task);
			model.addAttribute("view", "task/edit");
			return "base-layout";
		}
		return "redirect:/";
	}

	@PostMapping("/edit/{id}")
	public String editProcess(Model model, @PathVariable int id, Task taskModel) {
		if (taskModel.getTitle().equals("") ||
				taskModel.getStatus().equals("")) {

			taskModel.setId(id);
			model.addAttribute("task", taskModel);
			model.addAttribute("view", "task/edit");
			return "base-layout";
		}

		Task taskFromDB = taskRepository.findOne(id);
		if (taskFromDB != null) {
			taskFromDB.setTitle(taskModel.getTitle());
			taskFromDB.setStatus(taskModel.getStatus());
			taskRepository.saveAndFlush(taskFromDB);
		}

		return "redirect:/";
	}
}


text:
package alluxio.client.file;

import alluxio.AlluxioURI;
import alluxio.client.file.options.OutStreamOptions;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Mock implementation of {@link FileOutStream} which delegates to a {@link ByteArrayOutputStream}.
 */
public final class MockFileOutStream extends FileOutStream {
  private final ByteArrayOutputStream mStream;

  /**
   * Creates a mock {@link FileOutputStream} which will store any bytes written to it for later
   * inspection during tests.
   */
  public MockFileOutStream() throws IOException {
    super(new AlluxioURI("/"), OutStreamOptions.defaults(), FileSystemContext.INSTANCE);
    mStream = new ByteArrayOutputStream();
  }

  @Override
  public void cancel() {}

  @Override
  public void close() throws IOException {
    mStream.close();
  }

  @Override
  public void flush() throws IOException {
    mStream.flush();
  }

  @Override
  public void write(int b) {
    mStream.write(b);
  }

  @Override
  public void write(byte[] b) throws IOException {
    mStream.write(b);
  }

  @Override
  public void write(byte[] b, int off, int len) {
    mStream.write(b, off, len);
  }

  /**
   * @return the bytes that have been written to the output stream
   */
  public byte[] toByteArray() {
    return mStream.toByteArray();
  }
}


text:
package main

import (
	_ "expvar"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"path"
	"strings"
	"text/template"

	"github.com/gorilla/mux"
)

// Page .
type Page struct {
	Title string
}

var (
	templates     = template.New("tpl")
	registeredTpl = map[string]struct{}{}
)

func init() {
	tpls, err := ioutil.ReadDir("tpl")
	if err != nil {
		log.Fatalf("Error reading template dir: %s", err)
	}
	for _, fi := range tpls {
		registeredTpl[fi.Name()] = struct{}{}
		template.Must(templates.ParseFiles(path.Join("tpl", fi.Name())))
	}
}

// RootHandler parses and serve content in ./tpl.
func RootHandler(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-type", "text/html")
	if err := req.ParseForm(); err != nil {
		http.Error(w, fmt.Sprintf("error parsing url %s", err), http.StatusInternalServerError)
	}
	path := mux.Vars(req)["path"]
	if path == "" || path == "/" {
		path = "index.tpl"
	}
	if !strings.HasSuffix(path, ".tpl") {
		path += ".tpl"
	}
	if _, ok := registeredTpl[path]; !ok {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Not found")
		return
	}
	if err := templates.ExecuteTemplate(w, path, Page{
		Title: "Home",
	}); err != nil {
		log.Printf("Error executing template: %s", err)
		http.Error(w, fmt.Sprintf("error parsing template: %s", err), http.StatusInternalServerError)
	}
}

func main() {
	println("Ready on :80")
	router := mux.NewRouter()
	router.Methods("GET").Path("/static/{path:.*}").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		http.ServeFile(w, req, path.Join(".", "static", mux.Vars(req)["path"]))
	})
	router.Methods("GET").Path("/{path:.*}").HandlerFunc(RootHandler)
	log.Fatal(http.ListenAndServe(":80", router))
}


text:
db.cars.ensureIndex({"make" : 1});
db.testuser.ensureIndex({"lastName" : 1});
db.testuser.ensureIndex({"firstName" : 1, "lastName" : 1});
db.testuser.ensureIndex({"firstName" : 1, "info.dob" : 1});

db.cars.ensureIndex({"VIN" : 1}, {"unique" : true});
db.testuser.ensureIndex({"userId" : 1}, {"unique" : true});
db.testuser.ensureIndex({"firstName" : 1, "info.phone" : 1}, {"unique" : true});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Rhus viminalis Aiton . gerrardii Engl.

### Remarks
null


text:
import logging

from entrypoint2 import entrypoint

VERSION = "1.2"

@entrypoint
def f(x, y):
    logging.debug(x)
    return x + y


text:
package de.uni_hildesheim.sse.monitoring.runtime.recordingStrategies;

import java.io.PrintStream;

/**
 * A formatter for emitting out monitoring results. First method of using this
 * interface should be {@link #configure} and
 * {@link #setProcessData(ProcessData)}.
 *
 * @author Holger Eichelberger
 * @since 1.00
 * @version 1.00
 */
public interface ResultFormatter {

    /**
     * Defines the basic data for output.
     *
     * @param out the target output stream
     * @param total the recorder element representing the entire program
     * @param showPercentages should percentages be printed or absolute values
     *     instead
     *
     * @since 1.00
     */
    public void configure(PrintStream out, RecorderElement total,
        boolean showPercentages);

    /**
     * Returns if this instance was configured by calling
     * {@link #configure(PrintStream, RecorderElement, boolean)}.
     *
     * @return true if it was configured, false else
     *
     * @since 1.00
     */
    public boolean isConfigured();

    /**
     * Sets the current process data object for comparisons.
     *
     * @param data the process data object with system and JVM measurements (may be null)
     *
     * @since 1.00
     */
    public void setProcessData(ProcessData data);

    /**
     * Prints the information for an individual thread.
     *
     * @param description an additional description to be printed
     * @param thread the thread information to be printed
     *
     * @since 1.00
     */
    public void printThreadData(String description, ThreadData thread);

    /**
     * Prints out the min/avg/max statistics for the
     * system and the virtual machine.
     */
    public void printProcessStatistics();

    /**
     * Prints out an individual recorder element.
     *
     * @param description a description of the element to be printed out
     * @param individual the individual element to be emitted
     *
     * @since 1.00
     */
    public void printIndividual(String description, RecorderElement individual);

    /**
     * Prints out the headline describing the data columns.
     */
    public void printHeadline();

    /**
     * Prints a comparison among the individual element and the
     * total element defined in {@link #setProcessData}.
     *
     * @param description a description on the elements being compared
     * @param individual the individual element to be compared with the
     *     total element
     * @param system true if a comparison to system level
     *     properties, false if a comparison to JVM level
     *     properties should be done
     *
     * @since 1.00
     */
    public void printCompare(String description, RecorderElement individual,
        boolean system);

    /**
     * Prints some additional information categorizing the printout.
     *
     * @param info the category to be printed
     *
     * @since 1.00
     */
    public void printInfo(InfoCategory info);

    /**
     * Defines some information categories to be printed as additional
     * information.
     *
     * @author Holger Eichelberger
     * @since 1.00
     * @version 1.00
     */
    public enum InfoCategory {

        /**
         * Marks the program as explicitly threaded and headlines the threads
         * to be emitted.
         */
        THREADED,

        /**
         * Marks the breakdown section, i.e. where global system measurements
         * are related to group / variability measurements.
         */
        BREAKDOWN,

        /**
         * Marks the configurations section, i.e. where measurements for
         * compositions of monitoring groups are emitted.
         */
        CONFIGURATIONS;
    }

    /**
     * Clears all basic data for reuse of this instance.
     */
    public void clear();

    /**
     * Prints the current (aggregated) state. This method needs an appropriate
     * call of {@link #setProcessData(ProcessData)} before.
     *
     * @param elements all (current) elements
     * @param programRecord the program record
     * @param overheadRecord the overhead record
     *
     * @since 1.00
     */
    public void printCurrentStateStatistics(RecorderElementMap elements,
        RecorderElement programRecord, RecorderElement overheadRecord);

    /**
     * Prints a footer for the runtime statistics section. This method needs an
     * appropriate call of {@link #setProcessData(ProcessData)} before.
     *
     * @param elements all (current) elements
     * @param programRecord the program record
     * @param overheadRecord the overhead record
     *
     * @since 1.00
     */
    public void printCurrentStateStatisticsFooter(RecorderElementMap elements,
        RecorderElement programRecord, RecorderElement overheadRecord);

}


text:
package com.pedro.romannumerals.translator;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Direct translation table created to contains all the basic translations between arabic and roman format.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
class ArabicToRomanTranslationTable extends DirectTranslationTable {

    ArabicToRomanTranslationTable() {
        this(new LinkedHashSet<DirectTranslation>());
    }

    ArabicToRomanTranslationTable(Set<DirectTranslation> directTranslations) {
        super(directTranslations);
        initializeDirectTranslationsTrable(directTranslations);
    }

    private void initializeDirectTranslationsTrable(Set<DirectTranslation> directTranslations) {

        directTranslations.add(new DirectTranslation("1000", "M"));
        directTranslations.add(new DirectTranslation("900", "CM"));
        directTranslations.add(new DirectTranslation("500", "D"));
        directTranslations.add(new DirectTranslation("100", "C"));
        directTranslations.add(new DirectTranslation("90", "XC"));
        directTranslations.add(new DirectTranslation("50", "L"));
        directTranslations.add(new DirectTranslation("10", "X"));
        directTranslations.add(new DirectTranslation("9", "IX"));
        directTranslations.add(new DirectTranslation("5", "V"));
        directTranslations.add(new DirectTranslation("1", "I"));
    }

    int getBetterTranslation(String arabicNumber) {
        int number = Integer.parseInt(arabicNumber);
        for (DirectTranslation translation : getDirectTranslations()) {
            if (number - Integer.parseInt(translation.getFromValue()) >= 0) {
                return Integer.parseInt(translation.getFromValue());
            }
        }
        return 0;
    }

}


text:
package com.coolweather.app.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coolweather.app.R;
import com.coolweather.app.service.AutoUpdateService;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

/**
 * Created by Chai on 2016/9/15.
 */
public class WeatherActivity extends Activity implements View.OnClickListener {
    private LinearLayout weatherInfoLayout;
    private TextView cityNameText;
    private TextView publishText;
    private TextView weatherDespText;
    private TextView temp1Text;
    private TextView temp2Text;
    private TextView currentDateText;
    private TextView windDirection;
    private TextView windSpeed;

    /**
     * Switch city button
     */
    private Button switchCity;
    /**
     * Refresh weather info button
     */
    private Button refreshWeather;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.weather_layout);
        // Initializing all widgets
        weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout);
        cityNameText = (TextView) findViewById(R.id.city_name);
        publishText = (TextView) findViewById(R.id.publish_text);
        weatherDespText = (TextView) findViewById(R.id.weather_desp);
        temp1Text = (TextView) findViewById(R.id.temp1);
        temp2Text = (TextView) findViewById(R.id.temp2);
        currentDateText = (TextView) findViewById(R.id.current_data);
        switchCity = (Button) findViewById(R.id.switch_city);
        refreshWeather = (Button) findViewById(R.id.refresh_weather);
        windDirection = (TextView) findViewById(R.id.WD);
        windSpeed = (TextView) findViewById(R.id.WS);
        switchCity.setOnClickListener(this);
        refreshWeather.setOnClickListener(this);
        String countyCode = getIntent().getStringExtra("county_code");
        if (!TextUtils.isEmpty(countyCode)) {
            // go for weather data with county code
            publishText.setText("Loading");
            weatherInfoLayout.setVisibility(View.INVISIBLE);
            cityNameText.setVisibility(View.INVISIBLE);
            queryWeatherCode(countyCode);
        } else {
            // show local weather info without county code
            showWeather();
        }

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * Check weather data according to county code
     */
    private void queryWeatherCode(String countyCode) {
        String address = "http://www.weather.com.cn/data/list3/city"+countyCode+".xml";
        queryFromServer(address, "countyCode");
    }

    /**
     * Check weather data according to weather code
     */
    private void queryWeatherInfo(String weatherCode) {
        String address = "http://apis.baidu.com/apistore/weatherservice/cityid?cityid="+weatherCode;
        queryFromServer(address, "weatherCode");
    }

    /**
     * Find data from server according to address and code
     */
    private void queryFromServer(final String address, final String type) {
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                if ("countyCode".equals(type)) {
                    if (!TextUtils.isEmpty(response)) {
                        //get weather code (citycode) from server
                        String[] array = response.split("\\|");
                        if(array != null && array.length == 2){
                            String weatherCode = array[1];
                            queryWeatherInfo(weatherCode);
                        }
                    }
                }else if("weatherCode".equals(type)){
                    //handle weather info from server
                    Utility.handleWeatherResponse(WeatherActivity.this, response);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showWeather();
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        publishText.setText("Failed to load weather info");
                    }
                });
            }
        });
    }

    /**
     * read weather info from SharedPreferences and show which on screen
     */
    private void showWeather() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        cityNameText.setText(prefs.getString("city_name", ""));
        temp1Text.setText(prefs.getString("temp1", ""));
        temp2Text.setText(prefs.getString("temp2", ""));
        weatherDespText.setText(prefs.getString("weather_desp", ""));
        publishText.setText("Today" + prefs.getString("publish_time", "") + "publish");
        currentDateText.setText(prefs.getString("current_date", ""));
        windDirection.setText(prefs.getString("wind_direction",""));
        windSpeed.setText(prefs.getString("wind_speed",""));
        weatherInfoLayout.setVisibility(View.VISIBLE);
        cityNameText.setVisibility(View.VISIBLE);
        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.switch_city:
                Intent intent = new Intent(this, ChooseAreaActivity.class);
                intent.putExtra("from_weather_activity", true);
                startActivity(intent);
                finish();
                break;
            case R.id.refresh_weather:
                publishText.setText("Loading");
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                String weatherCode = prefs.getString("city_code", "");
                if (!TextUtils.isEmpty(weatherCode)) {
                    queryWeatherInfo(weatherCode);
                }
                break;
            default:
                break;
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Weather Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}


text:
package io.kubernetes.client.openapi.models;

import io.kubernetes.client.fluent.VisitableBuilder;

public class V1SubjectBuilder extends V1SubjectFluentImpl<V1SubjectBuilder>
    implements VisitableBuilder<V1Subject, V1SubjectBuilder> {
  public V1SubjectBuilder() {
    this(false);
  }

  public V1SubjectBuilder(Boolean validationEnabled) {
    this(new V1Subject(), validationEnabled);
  }

  public V1SubjectBuilder(V1SubjectFluent<?> fluent) {
    this(fluent, false);
  }

  public V1SubjectBuilder(V1SubjectFluent<?> fluent, Boolean validationEnabled) {
    this(fluent, new V1Subject(), validationEnabled);
  }

  public V1SubjectBuilder(V1SubjectFluent<?> fluent, V1Subject instance) {
    this(fluent, instance, false);
  }

  public V1SubjectBuilder(
      V1SubjectFluent<?> fluent, V1Subject instance, Boolean validationEnabled) {
    this.fluent = fluent;
    fluent.withApiGroup(instance.getApiGroup());

    fluent.withKind(instance.getKind());

    fluent.withName(instance.getName());

    fluent.withNamespace(instance.getNamespace());

    this.validationEnabled = validationEnabled;
  }

  public V1SubjectBuilder(V1Subject instance) {
    this(instance, false);
  }

  public V1SubjectBuilder(V1Subject instance, Boolean validationEnabled) {
    this.fluent = this;
    this.withApiGroup(instance.getApiGroup());

    this.withKind(instance.getKind());

    this.withName(instance.getName());

    this.withNamespace(instance.getNamespace());

    this.validationEnabled = validationEnabled;
  }

  V1SubjectFluent<?> fluent;
  Boolean validationEnabled;

  public V1Subject build() {
    V1Subject buildable = new V1Subject();
    buildable.setApiGroup(fluent.getApiGroup());
    buildable.setKind(fluent.getKind());
    buildable.setName(fluent.getName());
    buildable.setNamespace(fluent.getNamespace());
    return buildable;
  }
}


text:
require "ipaddresslabs/version"
require "httparty"

module Ipaddresslabs
  def self.locate ip
    key = Rails.application.secrets.ipaddresslabs_key || ENV["IPADDRESSLABS_KEY"]
    result = HTTParty.get("http://api.ipaddresslabs.com/iplocation/v1.8/locateip?key=#{key}&ip=#{ip}&format=JSON&compact=Y")
    JSON.parse(result.body)
  end
end


text:
package org.zstack.test.compute.vm;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.compute.host.HostGlobalConfig;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.config.GlobalConfigFacade;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.header.allocator.HostCapacityVO;
import org.zstack.header.host.HostInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmInstanceState;
import org.zstack.header.vm.VmInstanceVO;
import org.zstack.header.vm.VmInstanceVO_;
import org.zstack.simulator.SimulatorController;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.deployer.Deployer;

import java.util.concurrent.TimeUnit;

/**
 * 1. create a vm
 * 2. migrate the vm
 *
 * confirm the vm migrated successfully
 * confirm the src/dst host capacity correct
 *
 */
public class TestVmStateTracer5 {
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    GlobalConfigFacade gcf;
    SimulatorController sctrl;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        deployer = new Deployer("deployerXml/vm/TestVmStateTracer.xml");
        loader = deployer.getComponentLoader();
        gcf = loader.getComponent(GlobalConfigFacade.class);
        sctrl = loader.getComponent(SimulatorController.class);
        HostGlobalConfig.PING_HOST_INTERVAL.updateValue(1);
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);

        deployer.build();
        api = deployer.getApi();
    }

    @Test
    public void test() throws InterruptedException, ApiSenderException {
        HostInventory host1 = deployer.hosts.get("TestHost1");
        HostInventory host2 = deployer.hosts.get("TestHost2");
        VmInstanceInventory vm1 = deployer.vms.get("TestVm1");

        HostCapacityVO cap1 = dbf.findByUuid(host1.getUuid(), HostCapacityVO.class);
        HostCapacityVO cap2 = dbf.findByUuid(host2.getUuid(), HostCapacityVO.class);
        api.migrateVmInstance(vm1.getUuid(), host2.getUuid());
        TimeUnit.SECONDS.sleep(3);
        VmInstanceVO vmvo = dbf.findByUuid(vm1.getUuid(), VmInstanceVO.class);
        Assert.assertEquals(VmInstanceState.Running, vmvo.getState());
        Assert.assertEquals(host2.getUuid(), vmvo.getHostUuid());

        HostCapacityVO cap11 = dbf.findByUuid(host1.getUuid(), HostCapacityVO.class);
        HostCapacityVO cap22 = dbf.findByUuid(host2.getUuid(), HostCapacityVO.class);
        long cpu = vm1.getCpuNum() * vm1.getCpuSpeed();
        Assert.assertEquals(cap11.getAvailableCpu(), cap1.getAvailableCpu() + cpu);
        Assert.assertEquals(cap11.getAvailableMemory(), cap1.getAvailableMemory() + vm1.getMemorySize());
        Assert.assertEquals(cap22.getAvailableCpu(), cap2.getAvailableCpu() - cpu);
        Assert.assertEquals(cap22.getAvailableMemory(), cap2.getAvailableMemory() - vm1.getMemorySize());
    }
}


text:
#pragma once

#include <string>
#include <vector>

#include "Vector3.h"
#include "Attributes.h"
#include "Monitor.h"

using std::string;
using std::vector;

class Source;
class State;

namespace chunker_countsort_laszip {

	void doChunking(vector<Source> sources, string targetDir, Vector3 min, Vector3 max, State& state, Attributes outputAttributes, Monitor* monitor);

}


text:
#ifndef MOLEC_TIMER_H
#define MOLEC_TIMER_H

#include <molec/Common.h>

#ifdef MOLEC_PLATFORM_WINDOWS
#include <intrin.h>
#else /* MOLEC_PLATFORM_POSIX */
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#endif

/**
 * Time stamp counter (TSC)
 */
typedef union {
    molec_uint64_t int64;
    struct
    {
        molec_uint32_t lo, hi;
    } int32;
} molec_TSC;
#define MOLEC_TSC_VAL(a) ((a).int64)

/**
 *
 */
typedef struct molec_Measurement_Node
{
    molec_uint64_t value;
    struct molec_Measurement_Node* next;
} molec_Measurement_Node_t;

/**
 * @brief Count the number of cycles since last reset
 * @param cpu_c     molec_TSC to store the current tsc
 */
#ifdef MOLEC_PLATFORM_WINDOWS
#define MOLEC_RDTSC(cpu_c) (cpu_c).int64 = __rdtsc()
#else /* MOLEC_PLATFORM_POSIX */
#define MOLEC_RDTSC(cpu_c)                                                                         \
    MOLEC_ASM MOLEC_VOLATILE("rdtsc" : "=a"((cpu_c).int32.lo), "=d"((cpu_c).int32.hi))
#endif

/**
 * Query cpu-id (this is used to serialize the pipeline)
 */
#ifdef MOLEC_PLATFORM_WINDOWS
#define MOLEC_CPUID()                                                                              \
    {                                                                                \
        int __cpuInfo__[4];                                                                        \
        __cpuid(__cpuInfo__, 0x0);                                                                 \
    }
#else /* MOLEC_PLATFORM_POSIX */
#define MOLEC_CPUID() MOLEC_ASM MOLEC_VOLATILE("cpuid" : : "a"(0) : "bx", "cx", "dx")
#endif

/**
 * Serialize the pipeline and query the TSC
 * @return 64-bit unsigned integer representing a tick count
 */
molec_uint64_t molec_start_tsc();

/**
 * @brief Stop the RDTSC timer and return diffrence from start (in cycles)
 *
 * @param start     64-bit unsigned integer representing a tick count
 * @return number of elapsed cycles since start
 */
molec_uint64_t molec_stop_tsc(molec_uint64_t start);

/**
 * Infrastructure to measure runtime using the Time Stamp Counter (TSC)
 *
 * To time an exection:
 * @code{.c}
 *     molec_measurement_init(2); // Number of independent timers
 *
 *     molec_measurement_start(0); // Start timer 0
 *
 *     for(int i = 0; i < 100; ++i)
 *     {
 *         molec_measurement_start(1); // Start timer 1
 *
 *         // Do something intresting ...
 *
 *         molec_measurement_stop(1); // Stop timer 1
 *     }
 *
 *     molec_measurement_start(0); // Stop timer 0
 *
 *
 *     printf("Meadian of elapsed cycles of 0: %llu\n", molec_measurement_get_median(0));
 *
 *     molec_measurement_finish();
 *
 * @endcode
 */
typedef struct molec_Measurement
{
    /** Measured runtimes (in cycles) */
    molec_Measurement_Node_t** value_list_heads;
    molec_Measurement_Node_t** value_list_tails;

    /** Number of concurrent timers */
    int num_timers;

    /** Number of measurements */
    int* num_measurements;

    /** Current tick count returned by molec_start_tsc() */
    molec_uint64_t* start;

} molec_Measurement_t;

/**
 * Start the measurement by allocating the molec_Measurement_t struct
 *
 * @param num_timers        Number of timers
 */
void molec_measurement_init(const int num_timers);

/**
 * Start the TSC
 *
 * @param timer_index   Index of the timer to start
 */
void molec_measurement_start(int timer_index);

/**
 * Stop the TSC and register the value
 *
 * @param timer_index   Index of the timer to stop
 */
void molec_measurement_stop(int timer_index);

/**
 * @brief Compute the median of all measurements (in cycles) for timer Index
 *
 * @param timer_index   Index of the timer
 * @return meadian of all measurement of timer timer_index
 */
molec_uint64_t molec_measurement_get_median(int timer_index);

/**
 * @brief Prints the measured timers in readeable format to the command line
 */
void molec_measurement_print();

/**
 * @brief cleans the timing infrastructure
 */
void molec_measurement_finish();

/**********************************************************************************/
/*                                   R E A D M E                                  */
/**********************************************************************************/
/*
 *  When adding a new timer, check the following:
 *
 *   = MOLEC_MAX_NUM_TIMERS has to be at least as large as the total number of timers
 *
 *   = add the following lines to this file (assuming name of timer to be "POTATO":
 *
 *      "  #ifndef MOLEC_TIME_POTATO
 *          MOLEC_INTERNAL_IGNORE_TIMER(POTATO, <next-number-of-the-sequence>)
 *         #else
 *          MOLEC_INTERNAL_MAKE_TIMER(POTATO, <same-number-as-above>)
 *         #endif
 *      "
 *
 *   = add a line of code in the function "MOLEC_MEASUREMENT_GET_TIMER" corresponding
 *     to the timer you added
 *
 *   = modify the CMakeLists file according to the other examples
 */

#define MOLEC_MAX_NUM_TIMERS 10

#ifdef MOLEC_TIME
#define MOLEC_MEASUREMENT_INIT molec_measurement_init(MOLEC_MAX_NUM_TIMERS)
#define MOLEC_MEASUREMENT_FINISH molec_measurement_finish()
#define MOLEC_MEASUREMENT_PRINT molec_measurement_print()
#define MOLEC_INTERNAL_START_MEASUREMENT(id) molec_measurement_start((id))
#define MOLEC_INTERNAL_STOP_MEASUREMENT(id) molec_measurement_stop((id))
#define MOLEC_INTERNAL_GET_MEDIAN(id) molec_measurement_get_median((id))
#else // MOLEC_TIME
#define MOLEC_MEASUREMENT_INIT (void) 0
#define MOLEC_MEASUREMENT_FINISH (void) 0
#define MOLEC_MEASUREMENT_PRINT (void) 0
#define MOLEC_INTERNAL_START_MEASUREMENT(id) (void) 0
#define MOLEC_INTERNAL_STOP_MEASUREMENT(id) (void) 0
#endif // MOLEC_TIME

#define xstr(s) str(s)
     #define str(s) #s

#define MOLEC_INTERNAL_MAKE_TIMER(name, id)                                                        \
    MOLEC_INLINE void MOLEC_MEASUREMENT_##name##_START() { MOLEC_INTERNAL_START_MEASUREMENT(id); } \
    MOLEC_INLINE void MOLEC_MEASUREMENT_##name##_STOP() { MOLEC_INTERNAL_STOP_MEASUREMENT(id); }   \
    MOLEC_INLINE molec_uint64_t MOLEC_MEASUREMENT_##name##_GET_MEDIAN()                            \
        { return MOLEC_INTERNAL_GET_MEDIAN(id); }                                                  \
    MOLEC_INLINE char* MOLEC_MEASUREMENT_GET_TIMER_##id##_() { return xstr(name); }

#define MOLEC_INTERNAL_IGNORE_TIMER(name, id)                                                      \
    MOLEC_INLINE void MOLEC_MEASUREMENT_##name##_START() { (void) 0; }                             \
    MOLEC_INLINE void MOLEC_MEASUREMENT_##name##_STOP() { (void) 0; }                              \
    MOLEC_INLINE molec_uint64_t MOLEC_MEASUREMENT_##name##_GET_MEDIAN()                            \
        { return 1ul; }                                                                            \
    MOLEC_INLINE char* MOLEC_MEASUREMENT_GET_TIMER_##id##_() { return ""; }

#ifndef MOLEC_TIME_FORCE
MOLEC_INTERNAL_IGNORE_TIMER(FORCE, 0)
#else
MOLEC_INTERNAL_MAKE_TIMER(FORCE, 0)
#endif

#ifndef MOLEC_TIME_INTEGRATOR
MOLEC_INTERNAL_IGNORE_TIMER(INTEGRATOR, 1)
#else
MOLEC_INTERNAL_MAKE_TIMER(INTEGRATOR, 1)
#endif

#ifndef MOLEC_TIME_PERIODIC
MOLEC_INTERNAL_IGNORE_TIMER(PERIODIC, 2)
#else
MOLEC_INTERNAL_MAKE_TIMER(PERIODIC, 2)
#endif

#ifndef MOLEC_TIME_SIMULATION
MOLEC_INTERNAL_IGNORE_TIMER(SIMULATION, 3)
#else
MOLEC_INTERNAL_MAKE_TIMER(SIMULATION, 3)
#endif

#ifndef MOLEC_TIME_CELL_CONSTRUCTION
MOLEC_INTERNAL_IGNORE_TIMER(CELL_CONSTRUCTION, 4)
#else
MOLEC_INTERNAL_MAKE_TIMER(CELL_CONSTRUCTION, 4)
#endif

MOLEC_INLINE char* MOLEC_MEASUREMENT_GET_TIMER(int id)
{
    switch(id){
        case 0: return MOLEC_MEASUREMENT_GET_TIMER_0_();
        case 1: return MOLEC_MEASUREMENT_GET_TIMER_1_();
        case 2: return MOLEC_MEASUREMENT_GET_TIMER_2_();
        case 3: return MOLEC_MEASUREMENT_GET_TIMER_3_();
        case 4: return MOLEC_MEASUREMENT_GET_TIMER_4_();
        default: molec_error("Index %d does not correspond to any timer\n", id);
    }
    molec_error("Index %d does not correspond to any timer\n", id);
    return "ERROR";
}

#endif


text:
<?php

require 'AsyncTask.php';

class TestTask extends AsyncTask
{
    protected function onPreExecute()
    {
        self::setProperty("count", 0);
    }

    protected function doInBackground($parameters)
    {
        sleep(2);
        $count = self::getProperty("count") + $parameters;
        sleep(1);
        return $count;
    }

    protected function onPostExecute($result)
    {
        echo $result;
    }
}

$task = new TestTask();
$task->execute(100);
echo $task->getStatus();
sleep(10);
if ($task->getStatus() == 'RUNNING') {
    $task->cancel();
}
echo $task->getStatus();


text:
import sys
import logging
import gitlab
import mongoengine
import collections
import requests

from models.team import Team
from sheep import Shepherd
from dateutil import parser

from vitrine import __version__, config
from vitrine.models.commit import Commit

requests.packages.urllib3.disable_warnings()

IGNORE = {
    'conf',
    'config',
    'txt',
    'lock',
    'project',
    'wiki',
    'properties',
    'gems',
    'gemspec',
    'rspec',
    'patch',
    'globo',
    'ico',
    'jpeg',
    'gif',
    'jpg',
    'png',
    'hosts',
    'empty',
    'localhost',
    'loopback',
    'base',
    'apt',
    'ca',
    'unfiltered',
    'setup',
    'init',
    'class',
    'jar',
    'swf',
    'bz2',
    'zip',
    'sqlite',
    'bkp',
    'war',
    'pyc',
    'db',
    'example',
    'egg',
    'vcproj',
    'psd',
    'svg',
    'rdf',
}

GROUP_IDS = [46, 13, 11, 65, 302, 80, 9, 33, 88, 15, 14, 102]

def _get_projects(gl):
    projects = []
    for group_id in GROUP_IDS:
        projects.extend(gl.Group(group_id).projects)
    return projects

class LangStatsWorker(Shepherd):

    def initialize(self):
        self.gl = gitlab.Gitlab(
            self.config.GITLAB_BASE_URL, self.config.GITLAB_TOKEN)
        mongoengine.connect(host=self.config.DBAAS_MONGODB_ENDPOINT)
        self.gl.auth()
        self.runs = 0
        self.teams_seen = set()

    def get_description(self):
        return 'LangStats worker {}'.format(__version__)

    def _get_lines(self, project, path):
        try:
            return 1  # project.blob('master', filepath=path).count('\n')
        except:
            print project.id, path
            return 1

    def _walk(self, current_node, project, extensions, path):
        for file_ in current_node:
            if path:
                new_path = '/'.join([path, file_['name']])
            else:
                new_path = file_['name']
            if file_['type'] == 'tree':
                self._walk(
                    project.tree(path=new_path, ref_name='master'), project, extensions, new_path)
            else:
                exts = file_['name'].split('.')
                if len(exts) > 1 and exts[0] and exts[-1].lower() not in IGNORE:
                    extensions[
                        exts[-1].lower()] += self._get_lines(project, new_path)

    def _lang_stats(self, project):
        extensions = collections.defaultdict(lambda: 0)
        try:
            current_node = project.tree(ref_name='master')
        except gitlab.GitlabGetError:
            return {}
        else:
            self._walk(current_node, project, extensions, '')
            return extensions

    def _process_project(self, project):
        team = Team.objects(team_id=project.namespace.id).first()
        # We reset team statistics when we first encounter it
        if team and project.namespace.id not in self.teams_seen:
            team.delete()
            team = None
            self.teams_seen.add(project.namespace.id)
        if not team:
            team = Team(team_id=project.namespace.id)
        for (lang, total) in self._lang_stats(project).items():
            if lang in team.languages:
                team.languages[lang] += total
            else:
                team.languages[lang] = total
        team.save()

    def do_work(self):
        logging.debug('Started doing work...')
        for project in _get_projects(self.gl):
            self._process_project(project)
        logging.debug('Work done!')
        self.teams_seen = set()

class CommitsWorker(Shepherd):

    def initialize(self):

        self.gl = gitlab.Gitlab(
            self.config.GITLAB_BASE_URL, self.config.GITLAB_TOKEN)
        mongoengine.connect(host=self.config.DBAAS_MONGODB_ENDPOINT)

    def get_description(self):
        return 'Commits worker {}'.format(__version__)

    def do_work(self):

        logging.info('Loading projects from Gitlab...')

        for project in _get_projects(self.gl):
            for page in range(1, 20):  # Missing total commits...
                try:
                    commits = project.Commit(page=page, per_page=100)
                except gitlab.GitlabListError as e:
                    logging.error(
                        'Error reading commit for project %s (%d), page %d: %s',
                        project.namespace.name,
                        project.id,
                        page,
                        e
                    )
                    continue
                for cmt in commits:

                    try:
                        commit = Commit.objects.get(commit_id=cmt.id)

                    except:

                        # Object commit does not exists.
                        commit = Commit()
                        commit.commit_id = cmt.id
                        commit.short_id = cmt.short_id
                        commit.title = cmt.title
                        commit.author_name = cmt.author_name
                        commit.author_email = cmt.author_email
                        commit.created_at = parser.parse(cmt.created_at)
                        commit.owner = project.namespace.name
                        commit.project_id = cmt.project_id
                        commit.project_name = project.name
                        commit.save()

def commits():
    worker = CommitsWorker(sys.argv[1:])
    worker.run()

def langstats():
    worker = LangStatsWorker(sys.argv[1:])
    worker.run()


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="users">
ftpserver.user.admin.userpassword=21232F297A57A5A743894A0E4A801FC3\r\n

ftpserver.user.admin.homedirectory=/mnt/sdcard/ftp/\r\n

ftpserver.user.admin.enableflag=true\r\n

ftpserver.user.admin.writepermission=true\r\n

ftpserver.user.admin.maxloginnumber=0\r\n

ftpserver.user.admin.maxloginperip=0\r\n

ftpserver.user.admin.idletime=0\r\n

ftpserver.user.admin.uploadrate=0\r\n

ftpserver.user.admin.downloadrate=0\r\n

ftpserver.user.anonymous.userpassword=anonymous\r\n

ftpserver.user.anonymous.homedirectory=/mnt/sdcard/ftp/\r\n

ftpserver.user.anonymous.enableflag=true\r\n

ftpserver.user.anonymous.writepermission=false\r\n

ftpserver.user.anonymous.maxloginnumber=20\r\n

ftpserver.user.anonymous.maxloginperip=2\r\n

ftpserver.user.anonymous.idletime=300\r\n

ftpserver.user.anonymous.uploadrate=480000\r\n

ftpserver.user.anonymous.downloadrate=480000\r\n

</string>
</resources>


text:
//
//  YHKVOController.h
//  Test123
//
//  Created by yahua on 16/3/2.
//  Copyright © 2016年 wangsw. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef void (^YAHKVONotificationBlock)(id observer, id object, NSDictionary *change);

@interface YAHKVOController : NSObject

/// The observer notified on key-value change. Specified on initialization.
@property (atomic, weak, readonly) id observer;

/**
 @abstract Registers observer for key-value change notification.
 @param object The object to observe.
 @param keyPath The key path to observe.
 @param block The block to execute on notification.
 @discussion On key-value change, the specified block is called. Inorder to avoid retain loops, the block must avoid referencing the KVO controller or an owner thereof. Observing an already observed object key path or nil results in no operation.
 */
- (void)observe:(id)object keyPath:(NSString *)keyPath block:(YAHKVONotificationBlock)block;

/**
 @abstract Registers observer for key-value change notification.
 @param object The object to observe.
 @param keyPaths The key paths to observe.
 @param block The block to execute on notification.
 @discussion On key-value change, the specified block is called. Inorder to avoid retain loops, the block must avoid referencing the KVO controller or an owner thereof. Observing an already observed object key path or nil results in no operation.
 */
- (void)observe:(id)object keyPaths:(NSArray *)keyPaths block:(YAHKVONotificationBlock)block;

/**
 @abstract Unobserve object key path.
 @param object The object to unobserve.
 @param keyPath The key path to observe.
 @discussion If not observing object key path, or unobserving nil, this method results in no operation.
 */
- (void)unobserve:(id)object keyPath:(NSString *)keyPath;

/**
 @abstract Unobserve all object key paths.
 @param object The object to unobserve.
 @discussion If not observing object, or unobserving nil, this method results in no operation.
 */
- (void)unobserve:(id)object;

/**
 @abstract Unobserve all objects.
 @discussion If not observing any objects, this method results in no operation.
 */
- (void)unobserveAll;

@end

@interface NSObject (YAHKVOController)

/**
 @abstract Lazy-loaded YHKVOController for use with any object
 @return YHKVOController associated with this object, creating one if necessary
 @discussion This makes it convenient to simply create and forget a YHKVOController, and when this object gets dealloc'd, so will the associated controller and the observation info.
 */
@property (nonatomic, strong) YAHKVOController *yah_KVOController;

@end


text:
package org.semanticweb.elk.reasoner.taxonomy.model;

import java.util.Collection;
import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.semanticweb.elk.owl.interfaces.ElkObject;
import org.semanticweb.elk.owl.printers.OwlFunctionalStylePrinter;

public class SimpleNode<T extends ElkObject> implements Node<T> {

	final SortedSet<T> members;

	public SimpleNode(Collection<T> members, Comparator<T> cmp) {
		this.members = new TreeSet<T>(cmp);
		this.members.addAll(members);
	}

	@Override
	public Set<T> getMembers() {
		return members;
	}

	@Override
	public T getCanonicalMember() {
		return members.isEmpty() ? null : members.iterator().next();
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();

		for (T member : members) {
			builder.append(OwlFunctionalStylePrinter.toString(member) + ",");
		}

		return builder.toString();
	}
}


text:
<template name="apiCatalog">

      {{_ "catalogue_Title" }}

    {{> apiCatalogToolbar apis=apis }}

    {{# if gridViewMode }}
      {{# if Template.subscriptionsReady }}
        {{> apiCatalogGrid apis=apis }}
      {{ else }}
        {{> spinner }}
      {{/ if }}
    {{/ if }}

    {{# if tableViewMode }}
      {{# if Template.subscriptionsReady }}
        {{> apiCatalogTable apis=apis }}
      {{ else }}
        {{> spinner }}
      {{/ if }}
    {{/ if }}

    {{> defaultBootstrapPaginator pagination=templatePagination limit=10 containerClass="text-center" }}

</template>


text:
package sdb;

import java.util.List;

import jena.cmd.ArgDecl;

import org.apache.jena.rdf.model.Model ;
import org.apache.jena.sdb.SDB ;
import org.apache.jena.atlas.lib.Lib ;

import sdb.cmd.CmdArgsDB;
import sdb.cmd.ModGraph;

 /** Write out the data from an SDB model.  Only works for small models
  * because of JDBC limitations in default configurations.
  *
  *

  *  Usage:

  *  sdbdump [db spec]
  *  where [db spec] is:
  *    --spec file        Contains an RDF description of the model
  *    --db JDBC_url --dbUser userId --dbPassword password --dbType [--model modelName]
  *

  *

  */

public class sdbdump extends CmdArgsDB
{
    public static final String usage = "sdbdump --sdb <SPEC> [--out syntax]" ;

    private static ModGraph modGraph = new ModGraph() ;
    static ArgDecl argDeclSyntax = new ArgDecl(true, "out") ;

    public static void main(String ... argv)
    {
        SDB.init();
        new sdbdump(argv).mainRun() ;
    }

    protected sdbdump(String ... args)
    {
        super(args);
        addModule(modGraph) ;
        add(argDeclSyntax) ;
    }

    @Override
    protected String getCommandName() { return Lib.className(this) ; }

    @Override
    protected String getSummary()  { return Lib.className(this)+" --sdb <SPEC> [--out syntax]" ; }

    @Override
    protected void processModulesAndArgs()
    {
        if ( getNumPositional() > 0 )
            cmdError("No positional arguments allowed", true) ;
    }

    @Override
    protected void execCmd(List<String> args)
    {
        // This is a streamable syntax.
        String syntax = "N-TRIPLES" ;
        if ( contains(argDeclSyntax) )
            syntax = getArg(argDeclSyntax).getValue() ;
        if ( isDebug() )
            System.out.println("Debug: syntax is "+syntax) ;

        try {
            Model model = modGraph.getModel(getStore()) ;
            model.write(System.out, syntax) ;
        } catch (Exception ex)
        {
            System.err.println("Exception: "+ex+" :: "+ex.getMessage()) ;
            ex.printStackTrace(System.err) ;
        }
    }

}


text:
package types

import (
	"github.com/pkg/errors"
	"github.com/tendermint/go-crypto"
	ctypes "github.com/tendermint/tendermint/rpc/core/types"
	. "github.com/zballs/comit/util"
	"gx/ipfs/QmcEcrBAMrwMyhSjXt4yfyPpzgSuV8HLHavnfmiKCSRqZU/go-cid"
)

type Message struct {
	Action string      `json:"action"`
	Data   interface{} `json:"data, omitempty"`
	Error  error       `json:"error, omitempty"`
}

type Keypair struct {
	PrivKeystr string `json:"priv_key"`
	PubKeystr  string `json:"pub_key"`
}

type Idpair struct {
	FormID    string `json:"form_id"`
	ContentID string `json:"content_id"`
}

func ResultToError(result interface{}) error {
	switch result.(type) {
	case *ctypes.ResultTMSPQuery:
		tmResult := result.(*ctypes.ResultTMSPQuery).Result
		if tmResult.Code == 0 {
			return nil
		}
		return errors.New(tmResult.Error())
	case *ctypes.ResultBroadcastTx:
		_result := result.(*ctypes.ResultBroadcastTx)
		if _result.Code == 0 {
			return nil
		}
		return errors.New(_result.Log)
	default:
		return errors.New("Unrecognized result type")
	}
}

func NewKeypair(pubKey crypto.PubKey, privKey crypto.PrivKey) *Keypair {
	return &Keypair{PrivKeytoHexstr(privKey), PubKeytoHexstr(pubKey)}
}

func NewIdpair(form Form, cid *cid.Cid) *Idpair {
	return &Idpair{BytesToHexstr(form.ID()), cid.String()}
}

func MessageChainID(err error) *Message {
	return &Message{
		Action: "chain_id",
		Error:  err,
	}
}

func MessageIssues(data []string, err error) *Message {
	return &Message{
		Action: "issues",
		Data:   data,
		Error:  err,
	}
}

func MessageLogin(err error) *Message {
	return &Message{
		Action: "login",
		Error:  err,
	}
}

func MessageCreateAccount(data *Keypair, err error) *Message {
	return &Message{
		Action: "create_account",
		Data:   data,
		Error:  err,
	}
}

func MessageRemoveAccount(err error) *Message {
	return &Message{
		Action: "remove_account",
		Error:  err,
	}
}

func MessageSubmitForm(data *Idpair, err error) *Message {
	return &Message{
		Action: "submit_form",
		Data:   data,
		Error:  err,
	}
}

func MessageFindForm(data *Form, err error) *Message {
	return &Message{
		Action: "find_form",
		Data:   data,
		Error:  err,
	}
}


text:
package com.indexoutofbounds.util;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 *
Simple class which allows other objects to extend in order to take advantage of
 * Commons-Lang's reflection toString(), equals(), and hashCode().

 *
 *
Debugging statements on POJO subclasses should probablly be wrapped in and if
 * statement to avoid the performance cost associated with the reflective toString().

 *
 * @author Travis Meisenheimer
 * @version $Id$
 */
public class ReflectionObject {

	/**
	 * Default (empty) constructor.
	 */
	public ReflectionObject() {
		super();
	}

	/**
	 * toString() which uses Jakarta-Commons ReflecttionToStringBuilder.
	 *
	 * @return String reprensentation.
	 */
	public String toString() {
		return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
	}

	/**
	 * equals() which uses Jakarta-Commons EqualsBuilder.
	 *
	 * @return boolean representing equality.
	 */
	public boolean equals(Object o) {
		return EqualsBuilder.reflectionEquals(this, o);
	}

	/**
	 * hashCode() which uses Jakarta-Commons HashCodeBuilder.
	 *
	 * @return int containing object's hash code.
	 */
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

}


text:
package com.acme.util.jms;

import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TemporaryQueue;

public class QueueRequestor {

   QueueSession session; // The queue session the queue belongs to.
   Queue queue; // The queue to perform the request/reply on.
   TemporaryQueue tempQueue;
   QueueSender sender;
   QueueReceiver receiver;

   /**
    * Constructor for the QueueRequestor class.
    *
    *

    * This implementation assumes the session parameter to be non-transacted,
    * with a delivery mode of either AUTO_ACKNOWLEDGE or
    * DUPS_OK_ACKNOWLEDGE.
    *
    * @param session
    *           the QueueSession the queue belongs to
    * @param queue
    *           the queue to perform the request/reply call on
    *
    * @exception JMSException
    *               if the JMS provider fails to create the
    *               QueueRequestor due to some internal error.
    * @exception InvalidDestinationException
    *               if an invalid queue is specified.
    */

   public QueueRequestor(QueueSession session, Queue queue) throws JMSException
   {
      this.session = session;
      this.queue = queue;
      tempQueue = session.createTemporaryQueue();
      sender = session.createSender(queue);
      receiver = session.createReceiver(tempQueue);
   }

   /**
    * Sends a request and waits for a reply. The temporary queue is used for the
    * JMSReplyTo destination, and only one reply per request is
    * expected.
    *
    * @param message
    *           the message to send
    *
    * @return the reply message
    *
    * @exception JMSException
    *               if the JMS provider fails to complete the request due to
    *               some internal error.
    */

   public Message request(Message message) throws JMSException
   {
      return request(message, 0);
   }

   public Message request(Message message, int wait) throws JMSException
   {
      message.setJMSReplyTo(tempQueue);
      sender.send(message);
      return (receiver.receive(wait));
   }

   /**
    * Closes the QueueRequestor and its session.
    *
    *

    * Since a provider may allocate some resources on behalf of a
    * QueueRequestor outside the Java virtual machine, clients
    * should close them when they are not needed. Relying on garbage collection
    * to eventually reclaim these resources may not be timely enough.
    *
    *

    * Note that this method closes the QueueSession object passed
    * to the QueueRequestor constructor.
    *
    * @exception JMSException
    *               if the JMS provider fails to close the
    *               QueueRequestor due to some internal error.
    */

   public void close() throws JMSException
   {

      // publisher and consumer created by constructor are implicitly closed.
      session.close();
      tempQueue.delete();
   }
 }


text:
package jdamvc.engine.core.authentication;

public class Credentials
{
    private String username; //Stored username
    private String password; //Stored password (hashed)
    private String dateSaved; //the last saved date of the credentials
    private String lastLogged; //the date the user last logged in

    public Credentials()
    {
        this(null, null, null, null);
    }

    public Credentials(String username, String password, String dateSaved, String lastLogged)
    {
        this.username   =   username;
        this.password   =   password;
        this.dateSaved  =   dateSaved;
        this.lastLogged =   lastLogged;
    }

    //Returns the stored username
    public String getUsername()
    {
        return username;
    }

    //Returns the stored password
    public String getPassword()
    {
        return password;
    }

    //Returns the stored saved date
    public String getDateSaved()
    {
        return dateSaved;
    }

    //Returns the stored last logged in date
    public String getLastLogged()
    {
        return lastLogged;
    }

    //Set the stored username
    public void setUsername(String username)
    {
        this.username   =   username;
    }

    //Set the stored password
    //Password should be hashed and not store plain-text
    public void setPassword(String password)
    {
        this.password   =   password;
    }

    //Set the stored last saved date
    public void setDateSaved(String dateSaved)
    {
       this.dateSaved   =   dateSaved;
    }

    //Set the stored last logged in date
    public void setLastLogged(String lastLogged)
    {
        this.lastLogged =   lastLogged;
    }
}


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Backpack Crud Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are used by the CRUD interface.
    | You are free to change them to anything
    | you want to customize your views to better match your application.
    |
    */

    // Forms
    'save_action_save_and_new' => 'Salva ed aggiungi un nuovo elemento',
    'save_action_save_and_edit' => 'Salva e modifica questo elemento',
    'save_action_save_and_back' => 'Salva e torna indietro',
    'save_action_changed_notification' => 'Azione predefinita cambiata',

    // Create form
    'add'                 => 'Aggiungi',
    'back_to_all'         => 'Torna a tutti i ',
    'cancel'              => 'Annulla',
    'add_a_new'           => 'Aggiungi un nuovo ',

    // Edit form
    'edit'                 => 'Modifica',
    'save'                 => 'Salva',

    // Revisions
    'revisions'            => 'Revisioni',
    'no_revisions'         => 'Nessuna revisione Trovato',
    'created_this'          => 'ha creato questo',
    'changed_the'          => 'cambiato il',
    'restore_this_value'   => 'ripristinare questo valore',
    'from'                 => 'de parte di',
    'to'                   => 'a',
    'undo'                 => 'Disfare',
    'revision_restored'    => 'Revisione successo restaurato',

    // CRUD table view
    'all'                       => 'Tutti i ',
    'in_the_database'           => 'nel database',
    'list'                      => 'Lista',
    'actions'                   => 'Azioni',
    'preview'                   => 'Anteprima',
    'delete'                    => 'Elimina',
    'admin'                     => 'Amministrazione',
    'details_row'               => 'Questa è la riga dei dettagli. Modificala a tuo piacimento.',
    'details_row_loading_error' => "C'è stato un errore caricando i dettagli. Riprova.",

        // Confirmation messages and bubbles
        'delete_confirm'                              => 'Sei sicuro di eliminare questo elemento?',
        'delete_confirmation_title'                   => 'Elemento eliminato',
        'delete_confirmation_message'                 => "L'elemento è stato eliminato con successo.",
        'delete_confirmation_not_title'               => 'NON eliminato',
        'delete_confirmation_not_message'             => "C'è stato un errore. L'elemento potrebbe non essere stato eliminato.",
        'delete_confirmation_not_deleted_title'       => 'Non eliminato',
        'delete_confirmation_not_deleted_message'     => "Non è successo niente. L'elemento è al sicuro.",

        // DataTables translation
        'emptyTable'     => 'Nessun record da visualizzare',
        'info'           => 'Visualizzando da _START_ a _END_ record di _TOTAL_',
        'infoEmpty'      => 'Visualizzando da 0 a 0 record di 0',
        'infoFiltered'   => '(filtrati da _MAX_ record totali)',
        'infoPostFix'    => '',
        'thousands'      => ',',
        'lengthMenu'     => '_MENU_ record per pagina',
        'loadingRecords' => 'Caricamento...',
        'processing'     => 'Elaborazione...',
        'search'         => 'Cerca: ',
        'zeroRecords'    => 'Nessun record corrispondente',
        'paginate'       => [
            'first'    => 'Primo',
            'last'     => 'Ultimo',
            'next'     => 'Prossimo',
            'previous' => 'Precedente',
        ],
        'aria' => [
            'sortAscending'  => ': attiva per ordinare la colonna ascendentemente',
            'sortDescending' => ': attiva per ordinare la colonna discendentemente',
        ],

    // global crud - errors
        'unauthorized_access' => 'Accesso non autorizzato - non hai i permessi necessari per vedere questa pagina.',
        'please_fix' => 'Per favore correggi i seguenti errori:',

    // global crud - success / error notification bubbles
        'insert_success' => "L'elemento è stato aggiunto correttamente.",
        'update_success' => "L'elemento è stato aggiornato correttamente.",

    // CRUD reorder view
        'reorder'                      => 'Riordina',
        'reorder_text'                 => 'Seleziona e trascina per riordinare.',
        'reorder_success_title'        => 'Fatto',
        'reorder_success_message'      => 'Il tuo ordinamento è stato salvato.',
        'reorder_error_title'          => 'Errore',
        'reorder_error_message'        => 'Il tuo ordinamento non è stato salvato.',

    // CRUD yes/no
        'yes' => 'Sì',
        'no' => 'No',

    // Fields
        'browse_uploads' => 'Sfoglia file caricati',
        'clear' => 'Pulisci',
        'page_link' => 'Link Pagina',
        'page_link_placeholder' => 'http://esempio.com/pagina-desiderata',
        'internal_link' => 'Link Interno',
        'internal_link_placeholder' => 'Slug interno. Es: \'admin/page\' (no quotes) for \':url\'',
        'external_link' => 'Link Esterno',

];


text:
package edu.indiana.lib.osid.base.repository;

public abstract class RecordStructureIterator
implements org.osid.repository.RecordStructureIterator
{
    public boolean hasNextRecordStructure()
    throws org.osid.repository.RepositoryException
    {
			throw new org.osid.repository.RepositoryException(org.osid.OsidException.UNIMPLEMENTED);
    }

    public org.osid.repository.RecordStructure nextRecordStructure()
    throws org.osid.repository.RepositoryException
    {
			throw new org.osid.repository.RepositoryException(org.osid.OsidException.UNIMPLEMENTED);
    }
}


text:
package gov.nasa.worldwind.awt;

import java.awt.event.*;

/**
 * @author jym
 * @version $Id: ViewInputActionHandler.java 1171 2013-02-11 21:45:02Z dcollins $
 */
public class ViewInputActionHandler implements KeyInputActionHandler, MouseInputActionHandler
{
    public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEventState keys, String target,
        ViewInputAttributes.ActionAttributes viewAction)
    {
        return false;
    }

    public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEvent event,
        ViewInputAttributes.ActionAttributes viewAction)
    {
        return false;
    }

    public boolean inputActionPerformed(KeyEventState keys, String target,
        ViewInputAttributes.ActionAttributes viewAction)
    {
        return false;
    }

    public boolean inputActionPerformed(AbstractViewInputHandler inputHandler,
        java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction)
    {
        return false;
    }

    public boolean inputActionPerformed(AbstractViewInputHandler inputHandler,
            java.awt.event.MouseWheelEvent mouseWheelEvent, ViewInputAttributes.ActionAttributes viewAction)
    {
        return false;
    }
}


text:
package org.nnsoft.trudeau.api;

public final class PathNotFoundException
    extends GraphException
{

    private static final long serialVersionUID = 2919520319054603708L;

    public PathNotFoundException( String messagePattern, Object...arguments )
    {
        super( messagePattern, arguments );
    }

}


text:
#include "cpu/testers/directedtest/RubyDirectedTester.hh"

#include "base/trace.hh"
#include "cpu/testers/directedtest/DirectedGenerator.hh"
#include "debug/DirectedTest.hh"
#include "sim/sim_exit.hh"

RubyDirectedTester::RubyDirectedTester(const Params *p)
  : MemObject(p),
    directedStartEvent([this]{ wakeup(); }, "Directed tick",
                       false, Event::CPU_Tick_Pri),
    m_requests_to_complete(p->requests_to_complete),
    generator(p->generator)
{
    m_requests_completed = 0;

    // create the ports
    for (int i = 0; i < p->port_cpuPort_connection_count; ++i) {
        ports.push_back(new CpuPort(csprintf("%s-port%d", name(), i),
                                    this, i));
    }

    // add the check start event to the event queue
    schedule(directedStartEvent, 1);
}

RubyDirectedTester::~RubyDirectedTester()
{
    for (int i = 0; i < ports.size(); i++)
        delete ports[i];
}

void
RubyDirectedTester::init()
{
    assert(ports.size() > 0);
    generator->setDirectedTester(this);
}

BaseMasterPort &
RubyDirectedTester::getMasterPort(const std::string &if_name, PortID idx)
{
    if (if_name != "cpuPort") {
        // pass it along to our super class
        return MemObject::getMasterPort(if_name, idx);
    } else {
        if (idx >= static_cast<int>(ports.size())) {
            panic("RubyDirectedTester::getMasterPort: unknown index %d\n", idx);
        }

        return *ports[idx];
    }
}

bool
RubyDirectedTester::CpuPort::recvTimingResp(PacketPtr pkt)
{
    tester->hitCallback(id, pkt->getAddr());

    //
    // Now that the tester has completed, delete the packet, then return
    //
    delete pkt;
    return true;
}

MasterPort*
RubyDirectedTester::getCpuPort(int idx)
{
    assert(idx >= 0 && idx < ports.size());

    return ports[idx];
}

void
RubyDirectedTester::hitCallback(NodeID proc, Addr addr)
{
    DPRINTF(DirectedTest,
            "completed request for proc: %d addr: 0x%x\n",
            proc,
            addr);

    generator->performCallback(proc, addr);
    schedule(directedStartEvent, curTick());
}

void
RubyDirectedTester::wakeup()
{
    if (m_requests_completed < m_requests_to_complete) {
        if (!generator->initiate()) {
            schedule(directedStartEvent, curTick() + 1);
        }
    } else {
        exitSimLoop("Ruby DirectedTester completed");
    }
}

RubyDirectedTester *
RubyDirectedTesterParams::create()
{
    return new RubyDirectedTester(this);
}


text:
'use strict';

var IDLFileContents = foam.lookup('org.chromium.webidl.IDLFileContents');
var GithubIDLFile = foam.lookup('org.chromium.webidl.GithubIDLFile');
var WebPlatformEngine = foam.lookup('org.chromium.webidl.WebPlatformEngine');
var Parser = foam.lookup('org.chromium.webidl.Parser');

var config = {
  source: WebPlatformEngine.WEBKIT,
  parserClass: Parser,
  repositoryURL: 'https://github.com/w3c/web-platform-tests.git',
  localRepositoryPath: require('path').resolve(__dirname, 'data/wpt/git'),
  sparsePath: 'WebIDL',
  findExcludePatterns: ['*/invalid/*'],
  extension: 'widl',
};
config.idlFileContentsFactory = function (path, contents, urls) {
  return IDLFileContents.create({
    metadata: GithubIDLFile.create({
      repository: this.repositoryURL,
      githubBaseURL: 'https://github.com/w3c/web-platform-tests',
      revision: this.commit,
      path: path,
    }),
    contents: contents,
    specUrls: urls,
  });
};
module.exports = { config };