text:
package org.ehcache.impl.internal.loaderwriter.writebehind;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration;
import org.ehcache.config.builders.WriteBehindConfigurationBuilder;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.ehcache.spi.loaderwriter.WriteBehindConfiguration;
import org.ehcache.spi.service.ServiceConfiguration;
import org.hamcrest.core.IsCollectionContaining;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Collection;
import java.util.Map;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.ehcache.config.builders.ResourcePoolsBuilder.heap;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author rism
 */
public class WriteBehindProviderFactoryTest {

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

  @SuppressWarnings("unchecked")
  @Test
  public void testAddingWriteBehindConfigurationAtCacheLevel() {
    CacheManagerBuilder<CacheManager> cacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
    WriteBehindConfiguration writeBehindConfiguration = WriteBehindConfigurationBuilder.newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 1)
        .concurrencyLevel(3)
        .queueSize(10)
        .build();
    Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (SampleLoaderWriter.class);
    CacheManager cacheManager = cacheManagerBuilder.build(true);
    final Cache<Long, String> cache = cacheManager.createCache("cache",
        CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(100))
            .add(writeBehindConfiguration)
            .add(new DefaultCacheLoaderWriterConfiguration(klazz))
            .build());
    Collection<ServiceConfiguration<?>> serviceConfiguration = cache.getRuntimeConfiguration()
        .getServiceConfigurations();
    assertThat(serviceConfiguration, IsCollectionContaining.<ServiceConfiguration<?>>hasItem(instanceOf(WriteBehindConfiguration.class)));
    cacheManager.close();
  }

  @Test
  public void testWriteBehindWithoutCacheLoaderWriter() {
    expectedEx.expect(NullPointerException.class);
    expectedEx.expectMessage("WriteBehind requires a non null CacheLoaderWriter");

    WriteBehindProviderFactory factory = new WriteBehindProviderFactory();
    factory.create(null).createWriteBehindLoaderWriter(null, null);
  }

  public static class SampleLoaderWriter<K, V> implements CacheLoaderWriter<K, V> {

    @Override
    public V load(K key) {
      throw new UnsupportedOperationException("Implement Me");
    }

    @Override
    public Map<K, V> loadAll(Iterable<? extends K> keys) {
      throw new UnsupportedOperationException("Implement me!");
    }

    @Override
    public void write(K key, V value) {
      throw new UnsupportedOperationException("Implement me!");
    }

    @Override
    public void writeAll(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
      throw new UnsupportedOperationException("Implement me!");
    }

    @Override
    public void delete(K key) {
      throw new UnsupportedOperationException("Implement me!");
    }

    @Override
    public void deleteAll(Iterable<? extends K> keys) {
      throw new UnsupportedOperationException("Implement me!");
    }
  }
}


text:
<?php

namespace Cupon\TiendaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DefaultController extends Controller
{

    public function portadaAction($ciudad, $tienda)
    {
        // obtiene entity manager
        $em = $this->getDoctrine()->getEntityManager();

        // obtiene ciudad
        $ciudad = $em->getRepository('CiudadBundle:Ciudad')->findOneBySlug($ciudad);

        // obtiene tienda
        $tienda = $em->getRepository('TiendaBundle:Tienda')->findOneBy(array('slug' => $tienda,
            'ciudad' => $ciudad->getId()
            ));

        // verifica si existe tienda
        if (!$tienda) {
            // lanza excepci�n en caso de que no exista
            throw $this->createNotFoundException('No existe esta tienda');
        }

        // obtiene ofertas para la tienda
        $ofertas = $em->getRepository('TiendaBundle:Tienda')->findUltimasOfertasPublicadas($tienda->getId());

        // obtiene otras ciudades
        $cercanas = $em->getRepository('TiendaBundle:Tienda')->findCercanas($tienda->getSlug(), $tienda->getCiudad()->getSlug());

        // obtiene el formato de la consulta
        $formato = $this->get('request')->getRequestFormat();

        // retorna respuesta
        return $this->render('TiendaBundle:Default:portada.'.$formato.'.twig', array(
            'tienda' => $tienda,
            'ofertas' => $ofertas,
            'cercanas' => $cercanas
            ));
    }
}

redpajama_set_name: RedPajamaGithub


text:
module JSS

  #####################################
  ### Module Variables
  #####################################

  #####################################
  ### Module Methods
  #####################################

  #####################################
  ### Classes
  #####################################

  ###
  ### A Parent class for Advanced Computer, MobileDevice, and User searchs
  ###
  ### Subclasses must define:
  ### * the constant RESULT_CLASS which is the JSS Module class of
  ###   the item returned by the search, e.g. JSS::Computer
  ### * the constant RESULT_ID_FIELDS, which is an Array of Symbols
  ###   that come from the API in the search_results along with the
  ###   symbolized display fields.
  ###   E.g. for AdvancedComputerSearches, :id, :name, and :udid are present along with
  ###   whatever display fields have been defined.
  ###
  ###
  ### @see JSS::AdvancedComputerSearch
  ### @see JSS::AdvancedMobileDeviceSearch
  ### @see JSS::AdvancedUserSearch
  ### @see JSS::APIObject
  ###
  class AdvancedSearch < JSS::APIObject

    #####################################
    ### Mix-Ins
    #####################################
    include JSS::Creatable
    include JSS::Updatable
    include JSS::Criteriable

    #####################################
    ### Class Constants
    #####################################

    EXPORT_FORMATS = [:csv, :tab, :xml]

    #####################################
    ### Attributes
    #####################################

    ###
    ### @return [Array<Hash>] the results of the search
    ###
    ### Each Hash is one object that matches the criteria.
    ### Within each hash there are variable keys, but always at least
    ### the keys defined in each subclasses RESULT_ID_FIELDS
    ###
    ### The other keys correspond to the {AdvancedSearch#display_fields} defined for this
    ### Advanced Search.
    ###
    attr_reader :search_results

    ### @return [Array<Symbol>]
    ###
    ### The search result Hash keys for the {#display_fields} of the search
    ###
    ### The field names in {#display_fields} are strings matching how the field is labeled
    ### in the web UI (including the names of Extension Attributes). They have to be that way
    ### when submitting them to the API, and thats mostly what {#display_fields} and related
    ### methods are for.
    ###
    ### However, when those names come back as the Hash Keys of the {#search_results}
    ### they (inconsistently) have spaces and/or dashes converted to underscores, and,
    ### the JSON module converts the keys to Symbols, so they don't match the {#display_fields}.
    ###
    ### For example, the display field "Last Check-in" might come back as any of these Symbols:
    ### - :"Last Check-in"
    ### - :Last_Check_in
    ### - :"Last_Check-in"
    ###
    ### Also, the data returned in the {#search_results} contains more keys than just the
    ### {#display_fields} - namely it comes with some standard identifiers for each found item.
    ### such as JSS id number and name.
    ###
    ### {#result_display_keys} will hold just the Hash keys corresponding to the
    ### {#display_fields} by taking the keys from the first result Hash, and removing the
    ### identifier keys as listed in each subclass's RESULT_ID_FIELDS constant.
    ###
    attr_reader :result_display_keys

    ### @return [String] the name of the site for this search
    attr_reader :site

    ### @return [String]  the SQL query generated by the JSS based on the critera
    attr_reader :sql_text

    #####################################
    ### Constructor
    #####################################

    ###
    ### @see APIObject#initialize
    ###
    def initialize(args = {})

      super args

      ### @init_data now has the raw data
      ### so fill in our attributes or set defaults

      @sql_text = @init_data[:sql_text]
      @site = JSS::APIObject.get_name(@init_data[:site])

      @display_fields = @init_data[:display_fields] ? @init_data[:display_fields].map{|f| f[:name]} : []

      @search_results =  @init_data[self.class::RESULT_CLASS::RSRC_LIST_KEY]
      @search_results ||= []
      if @search_results.empty?
        @result_display_keys =[]
      else
        @result_display_keys = @search_results[0].keys - self.class::RESULT_ID_FIELDS
      end

      # make sure each hash of the search results
      # has a key matching a standard key.
      #
      @search_results.each do |hash|
        hash.keys.each do |key|
          std_key = key.to_s.gsub(/ |-/,"_").to_sym
          next if hash[std_key]
          hash[std_key] = hash[key]
        end
      end

      parse_criteria

    end # init

    #####################################
    ### Public Instance Methods
    #####################################

    ###
    ### Create in the JSS
    ###
    ### If get_results is true, they'll be available in {#search_results}. This might be slow.
    ###
    ### @param get_results[Boolean] should the results of the search be queried immediately?
    ###
    ### @return [Integer] the id of the newly created search
    ###
    def create(get_results = false)
      raise JSS::InvalidDataError, "JSS::Criteriable::Criteria instance required" unless @criteria.kind_of? JSS::Criteriable::Criteria
      raise JSS::InvalidDataError, "display_fields must be an Array." unless @display_fields.kind_of? Array

      orig_timeout = JSS::API.cnx.options[:timeout]
      JSS::API.timeout = 1800
      super()
      requery_search_results if get_results
      JSS::API.timeout = orig_timeout

      @id # remember to return the id

    end

    ###
    ### Save any changes
    ###
    ### If get_results is true, they'll be available in {#search_results}. This might be slow.
    ###
    ### @param get_results[Boolean] should the results of the search be queried immediately?
    ###
    ### @return [Integer] the id of the updated search
    ###
    def update(get_results = false)
      orig_timeout = JSS::API.cnx.options[:timeout]
      JSS::API.timeout = 1800
      super()
      requery_search_results if get_results
      JSS::API.timeout = orig_timeout

      @id  # remember to return the id
    end

    ###
    ### Requery the API for the search results.
    ###
    ### This can be very slow, so temporarily reset the API timeout to 30 minutes
    ###
    ### @return [Array<Hash>] the new search results
    ###
    def requery_search_results
      orig_open_timeout = JSS::API.cnx.options[:open_timeout]
      orig_timeout = JSS::API.cnx.options[:timeout]
      JSS::API.timeout = 1800
      JSS::API.open_timeout = 1800
      begin
        requery = self.class.new(:id => @id)
        @search_results = requery.search_results
        @result_display_keys = requery.result_display_keys
      ensure
        JSS::API.timeout = orig_timeout
        JSS::API.open_timeout = orig_open_timeout
      end
    end

    ###
    ### @return [Array<String>] the fields to be returned with the search results
    ###
    ### The API delivers these as an array of Hashes,
    ### where each hash has only one key, :name => the name of the fields/ExtAttrib
    ### to display. It should probably not have the underlying Hashes, and just
    ### be an array of names. This class converts it to just an Array of field names
    ### (Strings) for internal use.
    ###
    ### These fields are returned in the @search_results
    ### data along with :id, :name, and other unique identifiers
    ### for each found item. In that data, their names have
    ### spaces and dashes converted to underscores, and they are
    ### symbolized.
    ###
    ###
    def display_fields
      @display_fields
    end

    ###
    ### Set the list of fields to be retrieved with the
    ### search results.
    ###
    ### @param new_val[Array<String>] the new field names
    ###
    def display_fields= (new_val)
      raise JSS::InvalidDataError, "display_fields must be an Array." unless new_val.kind_of? Array
      return if new_val.sort == @display_fields.sort
      @display_fields = new_val
      @need_to_update = true
    end

    ###
    ### @return [Integer] the number of items found by the search
    ###
    def count
      @search_results.count
    end

    ###
    ### Export the display fields of the search results to a file.
    ###
    ### @param output_file[String,Pathname] The file in which to store the exported results
    ###
    ### @param format[Symbol] one of :csv, :tab, or :xml, defaults to :csv
    ###
    ### @param overwrite[Boolean] should the output_file be overwrite if it exists? Defaults to false
    ###
    ### @return [Pathname] the path to the output file
    ###
    ### @note This method only exports the display fields defined in this advanced search for
    ### the search_result members (computers, mobile_devices, or users)
    ### It doesn't currently provide the ability to export subsets of info about those objects, as the
    ### Web UI does (e.g. group memberships, applications, receipts, etc)
    ###
    def export(output_file, format = :csv, overwrite = false)

      raise JSS::InvalidDataError, "Export format must be one of: :#{EXPORT_FORMATS.join ', :'}" unless EXPORT_FORMATS.include? format

      out = Pathname.new output_file

      unless overwrite
        raise JSS::AlreadyExistsError, "The output file already exists: #{out}" if out.exist?
      end

      case format
        when :csv
          require 'csv'
          CSV.open(out.to_s, 'wb') do |csv|
            csv << @result_display_keys
            @search_results.each do |row|
              csv << @result_display_keys.map {|key| row[key]}
            end # each do row
          end #CSV.open

        when :tab
          tabbed = @result_display_keys.join("\t") + "\n"
          @search_results.each do |row|
            tabbed << @result_display_keys.map {|key| row[key]}.join("\t") + "\n"
          end # each do row
          out.jss_save tabbed.chomp

        else # :xml
          doc = REXML::Document.new '<?xml version="1.0" encoding="ISO-8859-1"?>'
          members = doc.add_element self.class::RESULT_CLASS::RSRC_LIST_KEY.to_s
          @search_results.each do |row|
            member = members.add_element self.class::RESULT_CLASS::RSRC_OBJECT_KEY.to_s
            @result_display_keys.each do |field|
              member.add_element(field.to_s.gsub(' ',"_")).text = row[field].empty? ? nil : row[field]
            end # ech do field
          end #each do row
          out.jss_save doc.to_s.gsub('><', ">\n<")
      end # case

      return out
    end

    #####################################
    ### Private Instance Methods
    #####################################
    private

    ###
    ### Clean up the inconsistent "Display Field" keys in the search results.
    ###
    ### Sometimes spaces have been converted to underscores, sometimes not, sometimes both.
    ### Same for dashes.
    ### E.g  :"Last Check-in"/:Last_Check_in/:"Last_Check-in", :Computer_Name, and :"Display Name"/:Display_Name
    ###
    ### This ensures there's always the fully underscored version.
    ###
    ### Update an internally used array of the display field names, symbolized, with
    ### spaces and dashes converted to underscores. We use these
    ### to overcome inconsistencies in how the names come from the API
    ###
    ### @return [void]
    ###
    def standardize_display_field_keys
      spdash=
      us =
      @display_field_std_keys = @display_fields.map{|f| f.gsub(/ |-/,"_").to_sym }
    end

    def rest_xml
      doc = REXML::Document.new APIConnection::XML_HEADER
      acs = doc.add_element self.class::RSRC_OBJECT_KEY.to_s
      acs.add_element('name').text = @name
      acs.add_element('sort_1').text = @sort_1 if @sort_1
      acs.add_element('sort_2').text = @sort_2 if @sort_2
      acs.add_element('sort_3').text = @sort_3 if @sort_3

      acs << @criteria.rest_xml

      df = acs.add_element('display_fields')
      @display_fields.each{|f| df.add_element('display_field').add_element('name').text = f }

      return doc.to_s
    end # rest xml

  end # class AdvancedSearch

end # module JSS

require "jss-api/api_object/advanced_search/advanced_computer_search"
require "jss-api/api_object/advanced_search/advanced_mobile_device_search"
require "jss-api/api_object/advanced_search/advanced_user_search"


text:
package uk.co.CyniCode.CyniChat.Chatting;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import uk.co.CyniCode.CyniChat.CyniChat;
import uk.co.CyniCode.CyniChat.events.ChannelChatEvent;
import uk.co.CyniCode.CyniChat.objects.Channel;
import uk.co.CyniCode.CyniChat.objects.UserDetails;
import uk.co.CyniCode.CyniChat.routing.ChatRouter;
import uk.co.CyniCode.CyniChat.routing.IChatEndpoint;

/**
 * A class to do something
 */
public class OnChannelChatEvent implements IChatEndpoint {

	/**
	 * Make a method for returning formatted output for a chat event
	 * @param event : The event that we're taking our cues from
	 * @return the formatted string of [<channel>] <player> : <message>
	 */
	public static String getCompleteMessage( ChannelChatEvent event ) {
		//Make the format string
		return String.format( "%s %s%s %s ", event.getChannel().getColour() +
				"[" + event.getChannel().getNick() + "]",
				CyniChat.perms.getPlayerFull( event.getSender().getPlayer() ),
				event.getConnector(),
				event.getChannel().getColour() + event.getMessage() );
	}

	/**
	 * Catch our event and play it to the server
	 *
	 * @param event : The event we're listening to
	 */
	public static void hearMessage(ChannelChatEvent event) {

		if (!event.isCancelled()) {

			CyniChat.printDebug("Event heard...");

			//Since we're listening for our own event... take nothing for
			// granted and take all the values from this
			for ( Player forAllPlayers : event.getRecipients() ) {
				CyniChat.printDebug( "Sending message to "+forAllPlayers.getDisplayName() );
				forAllPlayers.sendMessage( getCompleteMessage( event ) );
				CyniChat.printDebug( "Message sent to "+forAllPlayers.getDisplayName() );
			}

			CyniChat.printDebug( "Sent messages..." );

			//Finally having done that... route the message according to any
			// given instructions
			ChatRouter.routeMessage(ChatRouter.EndpointType.PLAYER, event.getSenderName(),
					event.getChannel().getName(), event.getMessage());

		}

	}

	/**
	 * Let's handle the message in a way that it wants to be handled
	 * @param type : The endpoint that it wants to go to
	 * @param player : The player that sent it
	 * @param channel : The channel that they sent it on
	 * @param message : The message that they sent
	 */
	public void giveMessage(ChatRouter.EndpointType type, String player, String channel, String message) {

		//Has the message come from IRC?
		if (type == ChatRouter.EndpointType.IRC) {

			//Yes it does. Hand it over to the handler for IRC
			// messages
			CyniChat.printDebug( "Handling an IRC endtype" );
			_handleIRCMessage(player, channel, message);

		}

		//Does it want to go to bungee?
		if (type == ChatRouter.EndpointType.BUNGEE) {

			//Yep. Send it to the bungee handler
			CyniChat.printDebug( "Handling a bungee endtype" );
			_handleBungeeMessage(player, channel, message);
			return;

		}

		//We don't handle this type of message
		CyniChat.printDebug( type.name() + " endpoint not defined" );

	}

	/**
	 * Handle a message that came from IRC
	 * @param player : The nickname of the person who sent the message
	 * @param channel : The channel that they sent the message on
	 * @param message : The message that they actually sent
	 */
	private void _handleIRCMessage(String player, String channel, String message) {

		//Get all the online players for the server
		Player[] online = Bukkit.getServer().getOnlinePlayers();

		//And the channel object we're dealing with
		Channel chatChannel = CyniChat.data.getChannel(channel);

		//For each and every player on the server...
		for (Player online1 : online) {

			//Get their details
			UserDetails curPl = CyniChat.data.getOnlineDetails(online1);

			//Is the current player joined to this channel?
			if (curPl.getAllChannels().contains(channel)) {

				//Yep. Let's send them the message from IRC
				CyniChat.printDebug("Sending message to " + online1.getDisplayName());
				String outing = chatChannel.getColour() + "[IRC] [" + chatChannel.getNick() + "] ";
				outing += player + " : " + message;
				online1.sendMessage(outing);

			}

		}

	}

	/**
	 * Handle a message originating from bungee
	 * @param player : The player that sent the message
	 * @param channel : The channel they sent it on
	 * @param message : The actual message
	 */
	private void _handleBungeeMessage(String player, String channel, String message) {

		//Tell the console what's happening
		CyniChat.printDebug( "Handling a bungee message..." );

		//Get the channel details
		Channel chatChannel = CyniChat.data.getChannel(channel);

		//Then check if the channel exists on this server
		if ( chatChannel == null ){

			//If it doesn't, drop it and run
			CyniChat.printDebug("Dropped bungee message from unknown channel " + channel + ":: " + player + " said " + message);
			return;

		}

		//ChannelChatEvent newChat = new ChannelChatEvent(
		//		player,
		//		chatChannel,
		//		message,
		//		getRecipients( channel )
		//	);

		//Make the message
		String formattedMsg = chatChannel.getColour() + "[" + chatChannel.getNick() + "] "
				+ player + " : " + chatChannel.getColour() + message;

		//And show it in the debug along with the channel we're sending it in
		CyniChat.printDebug( "Message : " + formattedMsg );
		CyniChat.printDebug( "On : " + chatChannel.getName() );

		//For every player on the server...
		for (Player p : Bukkit.getOnlinePlayers()) {

			//Print some basic debug about the player
			CyniChat.printDebug( "Current Player: " + p.getDisplayName() );
			CyniChat.printDebug( "Checking channel: " + chatChannel.getName() );

			//Go and ask if they are in the channel
			if (CyniChat.data.getOnlineDetails(p).getAllChannels().contains( chatChannel.getName() )) {

				//They are... send them the message
				CyniChat.printDebug( "Player was in the channel... sending" );
				p.sendMessage(formattedMsg);

			} else {

				//They're not... move on
				CyniChat.printDebug( "Player was not in the channel..." );

			}

			//Finally, just print the debug about them
			CyniChat.data.getOnlineDetails(p).printAll();

		}

	}

}


text:
#include "TcpSocketWriter.h"
#include "CleanupSupport.h"
#include "TcpSocketEngine.h"
#include "TimeOutTimer.h"
#include "SocketUser.h"

#include "Log.h"
#define LOGPOINTER if(iLog)iLog
#include "LogMacros.h"

//
// CTcpSymbianWrite: active object wrapping comms write requests
//

// Construction functions
CTcpSymbianWrite::CTcpSymbianWrite(class RSocket& aSocket,
                                   class MTcpSymbianSocketUser& aConsole,
                                   class CTcpSymbianEngine& aEngine) :
   CActive(EPriorityStandard), iEchoSocket(aSocket), iConsole(aConsole),
   iEngine(aEngine), iTimeOut(KTimeOut), iWriteStatus(EWaiting)
{
}

class CTcpSymbianWrite*
CTcpSymbianWrite::NewL(class RSocket& aSocket,
                       class MTcpSymbianSocketUser& aConsole,
                       class CTcpSymbianEngine& aEngine,
                       class isab::LogMaster* aLogMaster)
{
   class CTcpSymbianWrite* self = NewLC(aSocket, aConsole, aEngine, aLogMaster);
   CleanupStack::Pop(self);
   return self;
}

class CTcpSymbianWrite*
CTcpSymbianWrite::NewLC(class RSocket& aSocket,
                        class MTcpSymbianSocketUser& aConsole,
                        class CTcpSymbianEngine& aEngine,
                        class isab::LogMaster* aLogMaster)
{
   class CTcpSymbianWrite* self =
      new (ELeave) CTcpSymbianWrite(aSocket, aConsole, aEngine);
   CleanupStack::PushL(self);
   self->ConstructL(aLogMaster);
   return self;
}

void CTcpSymbianWrite::ConstructL(class isab::LogMaster* aLogMaster)
{
   if(aLogMaster){
      iLog = new (ELeave) isab::Log("TcpSymbianWrite", isab::Log::LOG_ALL, aLogMaster);
   }
   iTimer = CTimeOutTimer::NewL(10, *this);
   CActiveScheduler::Add(this);
   DBG("TcpSymbianWrite fully constructed.");
};

CTcpSymbianWrite::~CTcpSymbianWrite()
{
   delete iTimer;
   delete iBuffer;
   DBG("TcpSymbianWrite fully destroyed.");
   delete iLog;
}

void CTcpSymbianWrite::DoCancel()
   // Cancel asychronous write request
{
   DBG("DoCancel");
   iEchoSocket.CancelWrite();
   iTimer->Cancel();
   DBG("DoCancel complete");
};

void CTcpSymbianWrite::TimerExpired()
   // Implements MTimeOutNotify: called when timeout expired
{
   WARN("TimerExpired");
   Cancel();
   iWriteStatus = ETimedOut;
   class TRequestStatus* p = &iStatus;		// Signal RunL()
   SetActive();
   User::RequestComplete(p, KErrNone); //no system error
   DBG("Completeing self");
}

void CTcpSymbianWrite::RunL()
{
   DBG("RunL, iStatus: %d, iWriteStatus: %d", iStatus.Int(), iWriteStatus);
   if (iStatus == KErrNone){ //normal state handling
      switch(iWriteStatus){
      case ESending:// Buffer has been written to socket
         iTimer->Cancel(); // Cancel TimeOut timer
         iWriteStatus = EWaiting;
         break;
      case ETimedOut:// Request timed out
         WARN("Write timed out and was canceled.");
         iEngine.Stop(); //reason? XXX
         break;
      default:
         ERR("PANIC KEchoEngine EBadWriteState(%d)", EBadWriteState);
         User::Panic(KEchoEngine, EBadWriteState);
         break;
      };
   } else if(iStatus == KErrEof){
      WARN("Write with KErrEof, connection broken?");
      iEngine.Stop(CTcpSymbianEngine::EBroken);
   }else{
      ERR("PANIC KEchoEngine, EUnhandledWriteStatus(%d)",
          EUnhandledWriteStatus);
      User::Panic(KEchoEngine, EUnhandledWriteStatus);
      ///XXXX
   }
   iConsole.OperationComplete();
}

void CTcpSymbianWrite::IssueWrite(HBufC8* aData)
   // Write a data to a stream socket
{
   //replace buffer;
   delete iBuffer;
   iBuffer = NULL;
   iBuffer = aData;

   iEchoSocket.Write(*iBuffer, iStatus);
   // Request timeout
   iTimer->After(iTimeOut);
   SetActive();
   iWriteStatus = ESending;
   DBG("Async write has started.");
};


text:
clipsDir=$FLERE_IMSAHO/data/audio/clips

#numberOfRAWFilesBefore=$(ls -l $clipsDir/*.raw | wc -l)
#numberOfMP3FilesBefore=$(ls -l $clipsDir/*.mp3 | wc -l)
numberOfRAWClipsBefore=$(ls -l $clipDir | grep '^-.*.raw' | wc -l)
numberOfMP3ClipsBefore=$(ls -l $clipDir | grep '^-.*.mp3' | wc -l)

cd $clipsDir

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

FILES=$(find -name "*.raw")

for file in $FILES
do
  rm ${file}
done

IFS=$SAVEIFS

################################################################################
# echo stats
################################################################################

#numberOfRAWFilesAfter=$(ls -l $clipsDir/*.raw | wc -l)
#numberOfMP3FilesAfter=$(ls -l $clipsDir/*.mp3 | wc -l)
numberOfRAWClipsAfter=$(ls -l $clipDir | grep '^-.*.raw' | wc -l)
numberOfMP3ClipsAfter=$(ls -l $clipDir | grep '^-.*.mp3' | wc -l)

echo "numberOfRAWFilesBefore = $numberOfRAWFilesBefore"
echo "numberOfRAWFilesAfter  = $numberOfRAWFilesAfter"
echo "numberOfMP3FilesBefore = $numberOfMP3FilesBefore"
echo "numberOfMP3FilesAfter  = $numberOfMP3FilesAfter"


text:
package io.github.mathmaniac0.snek.sprite;

import io.github.mathmaniac0.snek.GameField;
import io.github.mathmaniac0.snek.VARIABLES;
import io.github.mathmaniac0.snek.sprite.behaviors.PermaDeath;

import java.awt.*;

public abstract class Boss extends NPC {

    public Boss(GameField gamefield, Point pos, int health) {
        super(gamefield, pos, health);
        setDeathBehavior(new PermaDeath(this));
    }

    public Boss(GameField gamefield, Point pos) {
        this(gamefield, pos, 10);
    }

    @Override
    public int priority() {
        return 1;
    }

    @Override
    protected void performDraw(Graphics g) {
        drawHealthbar(g);
    }

    protected void drawHealthbar(Graphics g) {
        int CELL = VARIABLES.CELL_SIZE;
        int marginX = 1; // By cells
        int marginY = 1; // By cells
        int marginHealth = 2; // By pixels

        int VERT_SPACE_USED = (gamefield.getGameArea().height + gamefield.getOffset().y) * CELL;
        int HEALTHBAR_WIDTH = (VARIABLES.CELL_NUM_X - marginX * 2) * CELL;
        int HEALTHBAR_HEIGHT = CELL;

        Rectangle HEALTHBAR = new Rectangle(marginX * CELL, VERT_SPACE_USED + marginY * CELL,
                HEALTHBAR_WIDTH, HEALTHBAR_HEIGHT);

        int HEALTH_WIDTH = HEALTHBAR_WIDTH * getHealth() / getMaxHealth() - marginHealth * 2;

        g.setColor(Color.WHITE);
        g.drawRect(HEALTHBAR.x, HEALTHBAR.y, HEALTHBAR.width, HEALTHBAR.height);
        g.setColor(Color.RED);
        g.fillRect(HEALTHBAR.x + marginHealth, HEALTHBAR.y + marginHealth,
                HEALTH_WIDTH, HEALTHBAR_HEIGHT - marginHealth * 2);

    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CircuitBreaker.Test
{
    [TestClass]
    public class CircuitBreakerExtensionTests
    {
        [TestMethod]
        public void Retry_Failure()
        {
            AggregateException exceptions = new AggregateException();

            try
            {
                var func = new Func<int>(() => { throw new Exception(); });
                var cb = new CircuitBreaker(500, 1);
                cb.Retry<int>(func, 2);
            }
            catch (AggregateException ex)
            {
                exceptions = ex;
            }

            Assert.AreEqual("The operation terminated after 2 retries.", exceptions.Message);
            Assert.AreEqual(2 , exceptions.InnerExceptions.Count);
        }

        [TestMethod]
        public void Retry_WithZeroAttempts_Failure()
        {
            AggregateException exceptions = new AggregateException();

            try
            {
                var func = new Func<int>(() => { throw new Exception(); });
                var cb = new CircuitBreaker(500, 1);
                cb.Retry<int>(func, 0);
            }
            catch (AggregateException ex)
            {
                exceptions = ex;
            }

            Assert.AreEqual("The operation terminated after 0 retries.", exceptions.Message);
            Assert.AreEqual(0, exceptions.InnerExceptions.Count);
        }
    }
}


text:
The API method being called.

```csharp
public string? Method { get; set; }
```

## See Also

* class [ConformanceTestInfo](../ConformanceTestInfo.md)
* namespace [Facility.ConformanceApi.Testing](../../Facility.ConformanceApi.md)

<!-- DO NOT EDIT: generated by xmldocmd for Facility.ConformanceApi.dll -->


text:
	<title>Gisela Stuart's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Gisela Stuart's panel show appearances

Gisela Stuart (born 1955-11-26[ref]) has appeared in 1 episodes between 2017-2017.  Gisela Stuart on Wikipedia.

2017

2017-01-12 / Question Time


text:
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.simpleframework.http.Query;
import org.simpleframework.http.Request;

public class CampanhaService extends SQLConnection {

	CampanhaService(String hostName, String dbName, String user, String pwd) {
		super(hostName, dbName, user, pwd);
	}

	CampanhaService() {
		super();
	}

	public Boolean cadastrar(Request request) throws Exception {
		setConnection(DriverManager.getConnection(getUrl()));
		Boolean adicionado = true;
		String insertSql = "INSERT INTO CAMPANHA (DSCAMPANHA, DTINICIO, DTFIM, CIDADECAMPANHA, NMCAMPANHA, VLRINVESTIMENTO, QTDMINVOUCHER, IMGPATH) "
				+ "VALUES (?,?,?,?,?,?,?,?);";
		try (PreparedStatement prep = getConnection().prepareStatement(insertSql)) {
			Query query = request.getQuery();
			prep.setString(1, query.get("dsCampanha"));
			prep.setDate(2, java.sql.Date.valueOf(query.get("dtInicio")));
			prep.setDate(3, java.sql.Date.valueOf(query.get("dtFim")));
			prep.setString(4, query.get("cidadeCampanha"));
			prep.setString(5, query.get("nmCampanha"));
			prep.setDouble(6, query.getFloat("vlrInvestimento"));
			prep.setInt(7, query.getInteger("qtdMinVoucher"));
			prep.setString(8, query.get("imgPath"));
			int count = prep.executeUpdate();
			System.out.println("Inserida: " + count + " linha(s)");
		} catch (Exception e) {
			adicionado = false;
			e.printStackTrace();
		}
		return adicionado;
	}
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ActivityLoaderActivity" >

    <Button
        android:id="@+id/start_bookmarks_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/main_button3" />

</LinearLayout>


text:
struct Record
{
    double quizOne;
    double quizTwo;
    double midterm;
    double final;
    double avg;
    char grade;
};

void calculateAvg(Record& record);
void writeRecord(Record record);
char getGrade(double score);

int main(int argc, char *argv[]) {
    Record record;
    if (argc != 5) {
        std::cout << "Enter your grades." << std::endl;
        std::cout << "Quiz Score One: ";
        std::cin >> record.quizOne;
        std::cout << "Quiz Score Two: ";
        std::cin >> record.quizTwo;
        std::cout << "Midterm Exam Score: ";
        std::cin >> record.midterm;
        std::cout << "Final Exam Score: ";
        std::cin >> record.final;
    }
    else {
        record.quizOne = atof(argv[1]);
        record.quizTwo = atof(argv[2]);
        record.midterm = atof(argv[3]);
        record.final = atof(argv[4]);
    }
        calculateAvg(record);
        record.grade = getGrade(record.avg);
        writeRecord(record);
}

char getGrade(double score) {
    char letterGrade;
    if (score < 60) {
    letterGrade = 'F';
    }
    else if (score < 70) {
    letterGrade = 'D';
    }
    else if (score < 80) {
    letterGrade = 'C';
    }
    else if (score < 90) {
    letterGrade = 'B';
    }
    else {
    letterGrade = 'A';
    }
    return letterGrade;
}

void writeRecord(Record record)
{
    std::cout << "***************************" << std::endl;
    std::cout << "Quiz One Score: " << record.quizOne << std::endl;
    std::cout << "Quiz Two Score: " << record.quizTwo << std::endl;
    std::cout << "Midterm Score: " << record.midterm << std::endl;
    std::cout << "Final Score: " << record.final << std::endl;
    std::cout << "Course Average: " << record.avg << std::endl;
    std::cout << "***************************" << std::endl;
    std::cout << "Final Grade: " << record.grade << std::endl;
}

void calculateAvg(Record& record)
{
    const double EXAM_WEIGHT = 0.5;
    const double MIDTERM_WEIGHT = 0.25;
    const double QUIZ_WEIGHT = 0.25;
    double quizOneGrade = 100 * record.quizOne / 10.0;
    double quizTwoGrade = 100 * record.quizTwo / 10.0;
    double quizAvg = (quizOneGrade + quizTwoGrade) / 2;
    record.avg = quizAvg * QUIZ_WEIGHT + record.midterm * MIDTERM_WEIGHT +
    record.final * EXAM_WEIGHT;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <com.sincsmart.attendance.view.FlippingImageView
        android:id="@+id/loadingdialog_fiv_icon"
        android:layout_width="@dimen/loading_img"
        android:layout_height="@dimen/loading_img"
        android:src="@drawable/logo_ing" />

    <com.sincsmart.attendance.view.HandyTextView
        android:id="@+id/loadingdialog_htv_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="left|center"
        android:textColor="@color/white"
        android:textSize="@dimen/loading_tv"
        android:layout_marginLeft="@dimen/loading_tv" />

</LinearLayout>


text:
Package.describe({summary: "Telescope tags package"});

Package.onUse(function (api) {

  api.use([
    'telescope-lib',
    'telescope-base',
    'aldeed:simple-schema',
    'tap:i18n',
    'fourseven:scss'
  ], ['client', 'server']);

  api.use([
    'jquery',
    'underscore',
    'iron:router',
    'templating'
  ], 'client');

  api.add_files([
    'lib/tags.js',
    'package-tap.i18n'
  ], ['client', 'server']);

  api.add_files([
    'lib/client/routes.js',
    'lib/client/scss/categories.scss',
    'lib/client/views/categories.html',
    'lib/client/views/categories.js',
    'lib/client/views/category_item.html',
    'lib/client/views/category_item.js',
    'lib/client/views/categories_menu.html',
    'lib/client/views/categories_menu.js',
    'lib/client/views/post_categories.html',
    'lib/client/views/post_categories.js'
    ], ['client']);

  api.add_files(['lib/server/publications.js'], ['server']);

  api.add_files([
    "i18n/de.i18n.json",
    "i18n/en.i18n.json",
    "i18n/es.i18n.json",
    "i18n/fr.i18n.json",
    "i18n/it.i18n.json",
    "i18n/zh-CN.i18n.json",
  ], ["client", "server"]);

  api.export(['preloadSubscriptions', 'adminNav', 'Categories', 'addToPostSchema', 'primaryNav', 'postModules']);
});


text:
package net.fai.daems;

public abstract class MessageListenActivity extends DaemsActivity {

	@Override
	public boolean subscribeMessage() {
		return true;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="AuthAutherRole">
	<resultMap id="AuthAutherRole" type="com.foreveross.qdp.domain.system.auth.AuthAutherRole">
        <id     property="id"         column="ID"/>
        <result property="autherId"   column="AUTHER_ID"/>
        <result property="roleId"     column="ROLE_ID"/>
        <result property="type"       column="TYPE"/>
        <result property="createTime" column="CREATE_TIME"/>
        <result property="updateTime" column="UPDATE_TIME"/>

	</resultMap>
	<sql id="orderBy">
		<if test="page !=null and page.orderBy!=null">
			<bind name="fieldColMap" value="#{
           'ID'          : 'ID'         ,
           'AUTHERID'    : 'AUTHER_ID'  ,
           'AUTHER_ID'   : 'AUTHER_ID'  ,
           'ROLEID'      : 'ROLE_ID'    ,
           'ROLE_ID'     : 'ROLE_ID'    ,
           'TYPE'        : 'TYPE'       ,
           'CREATETIME'  : 'CREATE_TIME',
           'CREATE_TIME' : 'CREATE_TIME',
           'UPDATETIME'  : 'UPDATE_TIME',
           'UPDATE_TIME' : 'UPDATE_TIME'

			}"/>
			<bind name="orderMap" value="#{'ASC':'ASC', 'DESC':'DESC'}"/>
			<trim prefix="order by " suffixOverrides=",">
				<foreach item="item" index="index" collection="page.orderBy" separator=",">
					<if test="item != null and item.name !=null and (fieldColMap[item.name.toUpperCase()] != null or orderMap[item.order.toUpperCase()]!=null)">${aliasDot}${fieldColMap[item.name.toUpperCase()]} ${orderMap[item.order.toUpperCase()]}</if>
				</foreach>
			</trim>
		</if>
	</sql>
	<select id="getAuthAutherRoleById" parameterType="com.foreveross.qdp.domain.system.auth.AuthAutherRole" resultMap="AuthAutherRole">
		SELECT *
		FROM AUTH_AUTHER_ROLE
		<where>
				AND ID = #{id,jdbcType=VARCHAR}
		</where>
	</select>
	<select id="getAuthAutherRoleMapById" parameterType="com.foreveross.qdp.domain.system.auth.AuthAutherRole" resultType="hashmap">
		SELECT
           AuthAutherRole.ID           AS  id                        ,
           AuthAutherRole.AUTHER_ID    AS  autherId                  ,
           AuthAutherRole.ROLE_ID      AS  roleId                    ,
           AuthAutherRole.TYPE         AS  type                      ,
           AuthAutherRole.CREATE_TIME  AS  createTime                ,
           AuthAutherRole.UPDATE_TIME  AS  updateTime                ,
           roleIdAuthRole.NAME         AS  roleIdName

		FROM AUTH_AUTHER_ROLE AuthAutherRole
		LEFT JOIN AUTH_ROLE roleIdAuthRole ON AuthAutherRole.ROLE_ID = roleIdAuthRole.ID

		<where>
				AND authAutherRole.ID = #{id,jdbcType=VARCHAR}
		</where>
	</select>
	<select id="pageFindAuthAutherRole" resultMap="AuthAutherRole">
		SELECT *
		FROM AUTH_AUTHER_ROLE
		<where>
           <if test="vo!=null and vo.id != null and vo.id != ''                 "> AND ID = #{vo.id,jdbcType=VARCHAR} </if>
           <if test="vo!=null and vo.autherId != null and vo.autherId != ''     "> AND AUTHER_ID LIKE CONCAT('%',#{vo.autherId,jdbcType=VARCHAR},'%') </if>
           <if test="vo!=null and vo.roleId != null and vo.roleId != ''         "> AND ROLE_ID LIKE CONCAT('%',#{vo.roleId,jdbcType=VARCHAR},'%') </if>
           <if test="vo!=null and vo.type != null and vo.type != ''             "> AND TYPE LIKE CONCAT('%',#{vo.type,jdbcType=VARCHAR},'%') </if>
           <if test="vo!=null and vo.createTime != null and vo.createTime != '' "> AND CREATE_TIME = #{vo.createTime,jdbcType=VARCHAR} </if>
           <if test="vo!=null and vo.updateTime != null and vo.updateTime != '' "> AND UPDATE_TIME = #{vo.updateTime,jdbcType=VARCHAR} </if>

		</where>
		<bind name="aliasDot" value="''"/><include refid="orderBy"/>
	</select>
	<select id="pageFindAuthAutherRoleMap" resultType="hashmap">
		SELECT
           AuthAutherRole.ID           AS  id                        ,
           AuthAutherRole.AUTHER_ID    AS  autherId                  ,
           AuthAutherRole.ROLE_ID      AS  roleId                    ,
           AuthAutherRole.TYPE         AS  type                      ,
           AuthAutherRole.CREATE_TIME  AS  createTime                ,
           AuthAutherRole.UPDATE_TIME  AS  updateTime                ,
           roleIdAuthRole.NAME         AS  roleIdName

		FROM AUTH_AUTHER_ROLE AuthAutherRole
		LEFT JOIN AUTH_ROLE roleIdAuthRole ON AuthAutherRole.ROLE_ID = roleIdAuthRole.ID

		<where>
           <if test="vo!=null and vo.id != null and vo.id != ''                 "> AND AuthAutherRole.ID = #{vo.id,jdbcType=VARCHAR} </if>
           <if test="vo!=null and vo.autherId != null and vo.autherId != ''     "> AND AuthAutherRole.AUTHER_ID LIKE CONCAT('%',#{vo.autherId,jdbcType=VARCHAR},'%') </if>
           <if test="vo!=null and vo.roleId != null and vo.roleId != ''         "> AND AuthAutherRole.ROLE_ID LIKE CONCAT('%',#{vo.roleId,jdbcType=VARCHAR},'%') </if>
           <if test="vo!=null and vo.type != null and vo.type != ''             "> AND AuthAutherRole.TYPE LIKE CONCAT('%',#{vo.type,jdbcType=VARCHAR},'%') </if>
           <if test="vo!=null and vo.createTime != null and vo.createTime != '' "> AND AuthAutherRole.CREATE_TIME = #{vo.createTime,jdbcType=VARCHAR} </if>
           <if test="vo!=null and vo.updateTime != null and vo.updateTime != '' "> AND AuthAutherRole.UPDATE_TIME = #{vo.updateTime,jdbcType=VARCHAR} </if>

		</where>
		<bind name="aliasDot" value="'AuthAutherRole.'"/><include refid="orderBy"/>
	</select>
	<insert id="insertAuthAutherRole" parameterType="com.foreveross.qdp.domain.system.auth.AuthAutherRole"  useGeneratedKeys="true" keyProperty="id" >
		INSERT INTO AUTH_AUTHER_ROLE
			( ID, AUTHER_ID, ROLE_ID, TYPE, CREATE_TIME, UPDATE_TIME )
		VALUES
			(
           #{id,jdbcType=VARCHAR},
           #{autherId,jdbcType=VARCHAR},
           #{roleId,jdbcType=VARCHAR},
           #{type,jdbcType=VARCHAR},
           #{createTime,jdbcType=VARCHAR},
           #{updateTime,jdbcType=VARCHAR}

			)
	</insert>
	<update id="updateAuthAutherRole" parameterType="com.foreveross.qdp.domain.system.auth.AuthAutherRole">
		UPDATE AUTH_AUTHER_ROLE
		<set>
           <if test="id != null         "> ID = #{id,jdbcType=VARCHAR},</if>
           <if test="autherId != null   "> AUTHER_ID = #{autherId,jdbcType=VARCHAR},</if>
           <if test="roleId != null     "> ROLE_ID = #{roleId,jdbcType=VARCHAR},</if>
           <if test="type != null       "> TYPE = #{type,jdbcType=VARCHAR},</if>
           <if test="createTime != null "> CREATE_TIME = #{createTime,jdbcType=VARCHAR},</if>
           <if test="updateTime != null "> UPDATE_TIME = #{updateTime,jdbcType=VARCHAR},</if>

		</set>
		<where>
				AND ID = #{id,jdbcType=VARCHAR}
		</where>
	</update>
	<delete id="deleteAuthAutherRole" parameterType="com.foreveross.qdp.domain.system.auth.AuthAutherRole">
		DELETE FROM AUTH_AUTHER_ROLE
		<where>
				AND ID = #{id,jdbcType=VARCHAR}
		</where>
	</delete>
</mapper>


text:
package org.jbpm.bpmn2.xml;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.drools.core.xml.BaseAbstractHandler;
import org.drools.core.xml.ExtensibleXmlParser;
import org.drools.core.xml.Handler;
import org.jbpm.bpmn2.core.Association;
import org.jbpm.bpmn2.core.IntermediateLink;
import org.jbpm.bpmn2.core.Lane;
import org.jbpm.bpmn2.core.SequenceFlow;
import org.jbpm.process.core.context.variable.Variable;
import org.jbpm.ruleflow.core.RuleFlowProcess;
import org.jbpm.workflow.core.Node;
import org.jbpm.workflow.core.NodeContainer;
import org.jbpm.workflow.core.node.CompositeNode;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

public class SequenceFlowHandler extends BaseAbstractHandler implements Handler {

	public SequenceFlowHandler() {
		initValidParents();
		initValidPeers();
		this.allowNesting = false;
	}

	protected void initValidParents() {
		this.validParents = new HashSet<Class<?>>();
		this.validParents.add(NodeContainer.class);
	}

	protected void initValidPeers() {
		this.validPeers = new HashSet<Class<?>>();
		this.validPeers.add(null);
		this.validPeers.add(Lane.class);
		this.validPeers.add(Variable.class);
		this.validPeers.add(Node.class);
		this.validPeers.add(SequenceFlow.class);
		this.validPeers.add(Lane.class);
		this.validPeers.add(Association.class);
		// TODO: this is right?
		this.validPeers.add(IntermediateLink.class);

	}

	@SuppressWarnings("unchecked")
	public Object start(final String uri, final String localName,
			final Attributes attrs, final ExtensibleXmlParser parser)
			throws SAXException {
		parser.startElementBuilder(localName, attrs);

		final String id = attrs.getValue("id");
		final String sourceRef = attrs.getValue("sourceRef");
		final String targetRef = attrs.getValue("targetRef");
		final String bendpoints = attrs.getValue("g:bendpoints");
		final String name = attrs.getValue("name");
		final String priority = attrs.getValue("http://www.jboss.org/drools",
				"priority");

		NodeContainer nodeContainer = (NodeContainer) parser.getParent();

		List<SequenceFlow> connections = null;
		if (nodeContainer instanceof RuleFlowProcess) {
			RuleFlowProcess process = (RuleFlowProcess) nodeContainer;
			connections = (List<SequenceFlow>) process
					.getMetaData(ProcessHandler.CONNECTIONS);
			if (connections == null) {
				connections = new ArrayList<SequenceFlow>();
				process.setMetaData(ProcessHandler.CONNECTIONS, connections);
			}
		}

		else if (nodeContainer instanceof CompositeNode) {

			CompositeNode compositeNode = (CompositeNode) nodeContainer;
			connections = (List<SequenceFlow>) compositeNode
					.getMetaData(ProcessHandler.CONNECTIONS);
			if (connections == null) {
				connections = new ArrayList<SequenceFlow>();
				compositeNode.setMetaData(ProcessHandler.CONNECTIONS,
						connections);
			}
		}

		SequenceFlow connection = new SequenceFlow(id, sourceRef, targetRef);
		connection.setBendpoints(bendpoints);
		connection.setName(name);
		if (priority != null) {
			connection.setPriority(Integer.parseInt(priority));
		}

		connections.add(connection);

		return connection;
	}

	public Object end(final String uri, final String localName,
			final ExtensibleXmlParser parser) throws SAXException {
		final Element element = parser.endElementBuilder();
		SequenceFlow sequenceFlow = (SequenceFlow) parser.getCurrent();

		org.w3c.dom.Node xmlNode = element.getFirstChild();
		while (xmlNode != null) {
			String nodeName = xmlNode.getNodeName();
			if ("conditionExpression".equals(nodeName)) {
				String expression = xmlNode.getTextContent();
				org.w3c.dom.Node languageNode = xmlNode.getAttributes()
						.getNamedItem("language");
				if (languageNode != null) {
					String language = languageNode.getNodeValue();
					if (XmlBPMNProcessDumper.JAVA_LANGUAGE.equals(language)) {
						sequenceFlow.setLanguage("java");
					} else if (XmlBPMNProcessDumper.MVEL_LANGUAGE
							.equals(language)) {
						sequenceFlow.setLanguage("mvel");
					} else if (XmlBPMNProcessDumper.RULE_LANGUAGE
							.equals(language)) {
						sequenceFlow.setType("rule");
					} else if (XmlBPMNProcessDumper.XPATH_LANGUAGE
							.equals(language)) {
						sequenceFlow.setLanguage("XPath");
					} else if (XmlBPMNProcessDumper.JAVASCRIPT_LANGUAGE
                            .equals(language)) {
                        sequenceFlow.setLanguage("JavaScript");
                    } else {
						throw new IllegalArgumentException("Unknown language "
								+ language);
					}
				}
				sequenceFlow.setExpression(expression);
			}
			xmlNode = xmlNode.getNextSibling();
		}
		return sequenceFlow;
	}

	public Class<?> generateNodeFor() {
		return SequenceFlow.class;
	}

}


text:
local MISS = missing
local editor_prod = producer(181, "SMARTMET")

editor_prod:SetCentre(86)
editor_prod:SetProcess(181)

local editor_origintime = raw_time(radon:GetLatestTime(editor_prod, "", 0))
local editor_time = forecast_time(editor_origintime, current_time:GetValidDateTime())

local H0 = level(HPLevelType.kHeight, 0)
local CC = luatool:FetchWithType(current_time, H0, param("N-0TO1"), current_forecast_type)
local CH = luatool:FetchWithType(current_time, H0, param("NH-0TO1"), current_forecast_type)
local CM = luatool:FetchWithType(current_time, H0, param("NM-0TO1"), current_forecast_type)
local CL = luatool:FetchWithType(current_time, H0, param("NL-0TO1"), current_forecast_type)

if not CC or not CH or not CM or not CL then
  return
end

local _CH = {}
local _CM = {}
local _CL = {}

for i=1, #CC do
  local cc = CC[i]
  local ch = CH[i]
  local cm = CM[i]
  local cl = CL[i]

  _CH[i] = ch
  _CM[i] = cm
  _CL[i] = cl

  -- From 'DBChecker'

  -- Lisätään ala-, keski- tai yläpilviä niin että jokin kerroksista on sama kuin kokonaispilvisyys.
  -- Valinta tehdään sen mukaan mitä on jo alunperin enemmän.
  -- Tehdään ensin alapilville

  if (cl < cc and cl >= cm and cl >= ch) then
    _CL[i] = cc
  end

  -- ja keskipilville

  if (cm < cc and cl < cm and ch < cm) then
    _CM[i] = cc
  end

  -- lopuksi lisätään yläpilviä

  if (cm < cc and cl < ch and cm < ch) then
    _CH[i] = cc
  end

  -- Vähennetään ala- ja keskipilviä, jos ne ovat suurempia kuin kokonaispilvisyys.

  _CL[i] = math.min(cl, cc)
  _CM[i] = math.min(cm, cc)

end

result:SetParam(param("NH-0TO1"))
result:SetValues(_CH)
luatool:WriteToFile(result)
result:SetParam(param("NM-0TO1"))
result:SetValues(_CM)
luatool:WriteToFile(result)
result:SetParam(param("NL-0TO1"))
result:SetValues(_CL)
luatool:WriteToFile(result)


text:
package com.orientechnologies.orient.test.database.speed;

import com.orientechnologies.orient.core.db.record.ODatabaseFlat;
import com.orientechnologies.orient.core.record.impl.ORecordFlat;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE;
import com.orientechnologies.orient.test.database.base.OrientMultiThreadTest;
import com.orientechnologies.orient.test.database.base.OrientThreadTest;

public class TxRemoteCreateObjectsMultiThreadSpeedTest extends OrientMultiThreadTest {
  protected ODatabaseFlat database;
  protected long          foundObjects;

  public static void main(String[] iArgs) throws InstantiationException, IllegalAccessException {
    TxRemoteCreateObjectsMultiThreadSpeedTest test = new TxRemoteCreateObjectsMultiThreadSpeedTest();
    test.data.go(test);
  }

  public TxRemoteCreateObjectsMultiThreadSpeedTest() {
    super(1000000, 10, CreateObjectsThread.class);
  }

  @Override
  public void init() {
    database = new ODatabaseFlat(System.getProperty("url")).open("admin", "admin");

    if (!database.getStorage().getClusterNames().contains("Animal"))
      database.addCluster("Animal", OStorage.CLUSTER_TYPE.PHYSICAL);

    foundObjects = database.countClusterElements("Animal");
    System.out.println("\nTotal objects in Animal cluster before the test: " + foundObjects);
  }

  public static class CreateObjectsThread extends OrientThreadTest {
    protected ODatabaseFlat database;
    protected ORecordFlat   record = new ORecordFlat();

    @Override
    public void init() {
      database = new ODatabaseFlat(System.getProperty("url")).open("admin", "admin");
      record = database.newInstance();

      database.begin(TXTYPE.NOTX);
    }

    public void cycle() {
      record.reset();
      record.value(data.getCyclesDone() + "|Gipsy|Cat|European|Italy|" + (data.getCyclesDone() + 300) + ".00").save("csv");

      if (data.getCyclesDone() >= data.getCycles() - 1)
        database.commit();
    }

    @Override
    public void deinit() throws Exception {
      database.close();
      super.deinit();
    }
  }

  @Override
  public void deinit() {
    System.out.println("\nTotal objects in Animal cluster after the test: " + (database.countClusterElements("Animal")));

    System.out.println("Created " + (database.countClusterElements("Animal") - foundObjects));

    assert threadCycles == database.countClusterElements("Animal") - foundObjects;

    if (database != null)
      database.close();
  }
}


text:
#include "../../SDL_internal.h"

#ifndef _SDL_cocoamousetap_h
#define _SDL_cocoamousetap_h

#include "SDL_cocoamouse.h"

extern void Cocoa_InitMouseEventTap(SDL_MouseData *driverdata);
extern void Cocoa_EnableMouseEventTap(SDL_MouseData *driverdata, SDL_bool enabled);
extern void Cocoa_QuitMouseEventTap(SDL_MouseData *driverdata);

#endif /* _SDL_cocoamousetap_h */

/* vi: set ts=4 sw=4 expandtab: */


text:
<?php

/* dummy file - for testing purposes */

?>


text:
import { assert, expect } from 'chai';
import * as Lint from 'tslint';
import * as fs from 'fs';
import * as path from 'path';
import * as BenchMark from 'benchmark';

const dedent = Lint.Utils.dedent;
const empty = '░';

class Position {
  private line: number | undefined;
  private character: number | undefined;
  private position: number | undefined;

  constructor(line?: number, character?: number, position?: number) {
    this.line = line;
    this.character = character;
    this.position = position;
  }

  /**
   * Returns the string representation of a Position in the form of `[line:char|pos]`. If
   * any of its properties is undefined an empty block will appear. For instance, if we only
   * provide only the line then the result will be `[line:░|░]`.
   * @returns {string}
   */
  public toString(): string {
    const line = this.line === undefined ? empty : this.line;
    const char = this.character === undefined ? empty : this.character;
    const pos = this.position === undefined ? empty : this.position;
    return `[${line}:${char}|${pos}]`;
  }

  /**
   * A comparable Position to the calling object is a Position that has the same undefined
   * properties. For instance, `new Position(1)` and `new Position(10, 2)` are not comparable
   * since the second position defines its character location.
   *
   * Returns a copy of the Position parameter object with some properties set to undefined. Those
   * properties are set to undefined only in the case the calling object has them to set to
   * undefined. Thus, the returned object will be comparable to the calling object.
   *
   * @param pos The object we wish to compare.
   * @returns {Position} A comparable position.
   */
  public getComparablePosition(obj: Position): Position {
    const line = this.line === undefined ? undefined : obj.line;
    const char = this.character === undefined ? undefined : obj.character;
    const pos = this.position === undefined ? undefined : obj.position;
    return new Position(line, char, pos);
  }
}

interface Failure {
  failure: string;
  startPosition: Position;
  endPosition: Position;
}

class LintFailure {
  private name: string;
  private ruleName: string;
  private failure: string;
  private startPosition: Position;
  private endPosition: Position;

  constructor(name: string, ruleName: string, failure: string, start?: Position, end?: Position) {
    this.name = name;
    this.ruleName = ruleName;
    this.failure = failure;
    this.startPosition = start || new Position();
    this.endPosition = end || new Position();
  }

  /**
   * Returns the string representation of the Failure object in the following form:
   *
   * ```
   * [name@{startPos -> endPos}] ruleName: failure
   * ```
   *
   * @returns {string}
   */
  public toString(): string {
    const pos = `${this.name}@{${this.startPosition} -> ${this.endPosition}}`;
    return `[${pos}] ${this.ruleName}: ${this.failure}`;
  }

  /**
   * Return a clone of the Failure where the start and end positions are comparable to the
   * ones of the calling Failure.
   * @param obj The Failure to compare.
   * @returns {Failure} A comparable Failure.
   */
  public getComparableFailure(obj: LintFailure): LintFailure {
    return new LintFailure(
      obj.name,
      obj.ruleName,
      obj.failure,
      this.startPosition.getComparablePosition(obj.startPosition),
      this.endPosition.getComparablePosition(obj.endPosition)
    );
  }
}

interface ITest {
  code: string;
  output?: string;
  options?: any;
  errors?: Failure[];
}

class Test {
  private name: string;
  private testFixer: boolean;
  public code: string;
  public output: string;
  public options: Lint.Configuration.IConfigurationFile;
  public errors: LintFailure[];

  constructor(
    name: string,
    code: string,
    output: string,
    options: Lint.Configuration.IConfigurationFile,
    errors: LintFailure[],
    testFixer: boolean = false
  ) {
    this.name = name;
    this.code = code;
    this.output = output;
    this.options = options;
    this.errors = errors;
    this.testFixer = testFixer;
  }

  public runTest(skipErrorCheck: boolean = false): void {
    const options: Lint.ILinterOptions = {
      fix: false,
      formatter: 'json',
      formattersDirectory: 'dist/formatters/',
      rulesDirectory: 'dist/rules/'
    };

    const linter = new Lint.Linter(options);
    linter.lint(this.name, this.code, this.options);

    // May need to exit early when doing benchmarks since we only care about the linting process.
    if (skipErrorCheck) return;

    const failures = JSON.parse(linter.getResult().output);
    this.compareErrors(
      this.errors || [],
      failures.map((error: any) => {
        const start = error.startPosition;
        const end = error.endPosition;
        return new LintFailure(
          error.name,
          error.ruleName,
          error.failure,
          new Position(start.line, start.character, start.position),
          new Position(end.line, end.character, end.position)
        );
      }),
      linter
    );
  }

  private compareErrors(
    expectedErrors: LintFailure[],
    foundErrors: LintFailure[],
    linter: Lint.Linter
  ): void {
    const expected = this.arrayDiff(expectedErrors, foundErrors);
    const found = this.arrayDiff(foundErrors, expectedErrors, false);

    const codeLines = this.code.split('\n');
    const total = codeLines.length.toString().length;
    const codeStr = codeLines.map((x, i) => `     ${this.pad(i, total)}| ${x}`).join('\n');
    const expectedStr = expected.length ? `Expected:\n       ${expected.join('\n       ')}` : '';
    const foundStr = found.length ? `Found:\n       ${found.join('\n       ')}` : '';
    const msg = [
      `Error mismatch in ${this.name}:`,
      '',
      codeStr,
      '',
      `     ${expectedStr}`,
      '',
      `     ${foundStr}`,
      ''
    ].join('\n');
    assert(expected.length === 0 && found.length === 0, msg);
    if (this.testFixer && this.output) {
      const fixes = linter.getResult().failures.filter(f => f.hasFix()).map(f => f.getFix()!);
      const fixedCode = Lint.Replacement.applyFixes(this.code, fixes);
      const fixerMsg = [
        `Fixer output mismatch in ${this.name}:`,
        '',
        codeStr,
        '',
        '      '
      ].join('\n');
      expect(fixedCode).to.equal(this.output, fixerMsg);
    }
  }

  private arrayDiff(source: LintFailure[], target: LintFailure[], compareToTarget: boolean = true) {
    return source
      .filter(item => this.findIndex(target, item, compareToTarget) === -1)
      .map((x) => {
        if (compareToTarget) {
          return x.toString();
        } else {
          return target.length ? target[0].getComparableFailure(x).toString() : x.toString();
        }
      });
  }

  private findIndex(source: LintFailure[], error: LintFailure, compareToError: boolean = true) {
    const len = source.length;
    let k = 0;
    while (k < len) {
      if (compareToError && `${error}` === `${error.getComparableFailure(source[k])}`) {
        return k;
      } else if (`${source[k]}` === `${source[k].getComparableFailure(error)}`) {
        return k;
      }
      k++;
    }
    return -1;
  }

  private pad(n: number, width: number) {
    const numStr: string = n.toString();
    const padding: string = new Array(width - numStr.length + 1).join(' ');
    return numStr.length >= width ? numStr : padding + numStr;
  }
}

class TestGroup {
  public name: string;
  public ruleName: string;
  public description: string;
  public tests: Test[];

  constructor(
    name: string,
    description: string,
    ruleName: string,
    tests: (ITest | string)[],
    testFixer: boolean = false,
    groupConfig: any = null
  ) {
    this.name = name;
    this.ruleName = ruleName;
    this.description = description;
    this.tests = tests.map((test: ITest | string, index) => {
      const config: any = { rules: { [ruleName]: true } };
      const codeFileName = `${name}-${index}.ts`;
      if (typeof test === 'string') {
        if (groupConfig) {
          config.rules[ruleName] = [true, ...groupConfig];
        }
        const configuration = Lint.Configuration.parseConfigFile(config);
        return new Test(codeFileName, test, '', configuration, []);
      }
      if (test.options) {
        config.rules[ruleName] = [true, ...test.options];
      } else if (groupConfig) {
        config.rules[ruleName] = [true, ...groupConfig];
      }
      const configFile = Lint.Configuration.parseConfigFile(config);
      const failures: LintFailure[] = (test.errors || []).map((error) => {
        return new LintFailure(
          codeFileName,
          ruleName,
          error.failure,
          error.startPosition,
          error.endPosition
        );
      });
      return new Test(codeFileName, test.code, test.output || '', configFile, failures, testFixer);
    });
  }
}

class RuleTester {
  private ruleName: string;
  private testFixer: boolean;
  private groups: TestGroup[] = [];

  constructor(ruleName: string, testFixer: boolean = false) {
    this.ruleName = ruleName;
    this.testFixer = testFixer;
  }

  public addTestGroup(name: string, description: string, tests: (ITest | string)[]): this {
    this.groups.push(new TestGroup(name, description, this.ruleName, tests, this.testFixer));
    return this;
  }

  /**
   * Appends a test group to run under a configuration. This configuration can be overwritten
   * by providing a configuration in the test.
   *
   * @param name Test identifier
   * @param description Test description
   * @param groupConfig The configuration for the group
   * @param tests A list of string or ITest objects.
   * @return {RuleTester}
   */
  public addTestGroupWithConfig(
    name: string,
    description: string,
    groupConfig: any,
    tests: (ITest | string)[]
  ): this {
    this.groups.push(new TestGroup(name, description, this.ruleName, tests, this.testFixer, groupConfig));
    return this;
  }

  public runTests(): void {
    const singleTest = JSON.parse(process.env.SINGLE_TEST || 'null');
    const runGroup = singleTest === null || singleTest.group === null;
    const runIndex = singleTest === null || singleTest.num === null;
    const benchmark = process.env.BENCHMARK !== 'undefined';
    describe(this.ruleName, () => {
      this.groups.forEach((group) => {
        if (runGroup || group.name === singleTest.group) {
          it(`${group.name} - ${group.description}`, () => {
            if (benchmark) {
              console.log('');
            }
            group.tests.forEach((test, index) => {
              if (runIndex || singleTest.num === index) {
                test.runTest();
                if (benchmark) {
                  const suite = new BenchMark.Suite();
                  suite
                    .add(`      [${index}]:`, () => test.runTest(true))
                    .on('cycle', (event: any) => console.log(String(event.target)))
                    .run({ async: false });
                }
              }
            });
          });
        }
      });
    });
  }
}

function readFixture(name: string): string {
  return fs.readFileSync(path.join(__dirname, `../../../src/test/fixtures/${name}`), 'utf8');
}

export {
  dedent,
  Position,
  Failure,
  TestGroup,
  RuleTester,
  readFixture
};


text:
//
//  TJSConstKeyForNotificaitonDefine.h
//  TianJiCloud
//
//  Created by 朱鹏 on 17/7/21.
//  Copyright © 2017年 TianJiMoney. All rights reserved.
//

#ifndef TJSConstKeyForNotificaitonDefine_h
#define TJSConstKeyForNotificaitonDefine_h

#pragma mark - NSNotification
static NSString *const kNotificationLoginSuccess    = @"kNotificationLoginSuccess";        // 登录注册成功
static NSString *const kNotificationLoginOutSuccess = @"kNotificationLoginOutSuccess";    //退出登录成功
static NSString *const kNotificationLoginCancel     = @"kNotificationLoginCancel";        // 取消登录

#endif /* TJSConstKeyForNotificaitonDefine_h */


text:
const MicroEvent = require('../vendor/MicroEvent');

var UserStore = {
    user: {
        loggedIn: false,
        nick: '',
        email: '',
        gravatar: './dist/svg/avatar.svg'
    },

    getUser: function () {
        return this.user;
    }
};

MicroEvent.mixin(UserStore);

module.exports = UserStore;


text:
% See: `first_function.m`.

[hello, world] = first_function();

hello_world = sprintf('%s, %s!', hello, world);

disp hello_world;


text:
<?php

namespace Symfony\Component\ErrorRenderer\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ErrorRenderer\ErrorRenderer\ErrorRendererInterface;

/**
 * @author Yonel Ceruto <yonelceruto@gmail.com>
 */
class ErrorRendererPass implements CompilerPassInterface
{
    private $rendererService;
    private $rendererTag;

    public function __construct(string $rendererService = 'error_renderer', string $rendererTag = 'error_renderer.renderer')
    {
        $this->rendererService = $rendererService;
        $this->rendererTag = $rendererTag;
    }

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition($this->rendererService)) {
            return;
        }

        $renderers = [];
        foreach ($container->findTaggedServiceIds($this->rendererTag, true) as $serviceId => $tags) {
            /** @var ErrorRendererInterface $class */
            $class = $container->getDefinition($serviceId)->getClass();

            foreach ($tags as $tag) {
                $format = $tag['format'] ?? $class::getFormat();
                $priority = $tag['priority'] ?? 0;
                if (!isset($renderers[$priority][$format])) {
                    $renderers[$priority][$format] = new Reference($serviceId);
                }
            }
        }

        if ($renderers) {
            ksort($renderers);
            $renderers = array_merge(...$renderers);
        }

        $definition = $container->getDefinition($this->rendererService);
        $definition->replaceArgument(0, ServiceLocatorTagPass::register($container, $renderers));
    }
}


text:
package com.piaopiao.android.taqu.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.piaopiao.android.taqu.CustomAppl;
import com.piaopiao.android.taqu.R;
import com.piaopiao.android.taqu.adapter.HomeAdapter;
import com.piaopiao.android.taqu.utils.SizeUtils;
import com.piaopiao.android.taqu.utils.LogUtil;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author:Create by guojam on 2017/2/26.
 * @email: guojam@outlook.com
 */

public class HomeFragment extends Fragment {

    ArrayList<String> data = new ArrayList<>();
    ArrayList<String> pics = new ArrayList<>();
    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.home_title_text)
    TextView home_title_text;
    private View view;
    /**
     * recyclerview 滑动监听
     */
    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        int totalDistance;
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            totalDistance += dy;
            rlTitleTransparentAnimation(totalDistance);
            LogUtil.d("%s这次是滑动距离了吧",totalDistance);
        }
    };

    /**
     * 标题透明动画
     * @param scrollDistance
     */
    private void rlTitleTransparentAnimation(int scrollDistance) {
        if(scrollDistance == 0){
            if(rlTitle != null){
                rlTitle.setVisibility(View.GONE);
            }

        }else if(scrollDistance > 0 && scrollDistance < 400){
            rlTitle.setVisibility(View.VISIBLE);
            float scale = (float) scrollDistance / 400;
            float alpha = (255 * scale);
            // 背景透明度
            rlTitle.getBackground().setAlpha((int) alpha);
            // 文字透明度
            home_title_text.setTextColor(Color.argb((int) alpha,0,0,0));
        } else {
            rlTitle.getBackground().setAlpha(255);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            initData();
            view = inflater.inflate(R.layout.home_fragment_layout, null);
            ButterKnife.bind(this, view);
            recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
            HomeAdapter homeAdapter = new HomeAdapter(data);
            // 自动轮播图
            RollPagerView rollViewpager = new RollPagerView(getContext());
            //设置播放时间间隔
            rollViewpager.setPlayDelay(2500);
            //设置透明度
            rollViewpager.setAnimationDurtion(500);
            rollViewpager.setAdapter(new TestNomalAdapter());

            FrameLayout frameLayout = new FrameLayout(getContext());
            frameLayout.addView(rollViewpager, new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dip2px(180)));

            homeAdapter.setHeaderView(frameLayout);
            recyclerview.setAdapter(homeAdapter);
            // recyclerview的滑动监听
            recyclerview.addOnScrollListener(onScrollListener);
        } else {
            ButterKnife.bind(this, view);
        }
        return view;
    }

    private void initData() {
        for (int i = 0; i < 50; i++) {
            data.add("test" + i);
        }
        pics.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488856151&di=0a23ceb6a5c9bc1f52874a0ef9872cad&imgtype=jpg&er=1&src=http%3A%2F%2Fimg.90sjimg.com%2Finspiration%2F04%2F01%2F72%2F36%2F63%2Fs_236_Z0FnBbejEF9Uo505MLAv.jpg");
        pics.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488856173&di=2dfe263dbc822e489e5bbac75ded6726&imgtype=jpg&er=1&src=http%3A%2F%2Fsc.jb51.net%2Fuploads%2Fallimg%2F140629%2F10-14062Z404070-L.jpg");
        pics.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488856193&di=211d71dc710e42080594243b18a2435b&imgtype=jpg&er=1&src=http%3A%2F%2Fpic.vjshi.com%2F2016-03-23%2F2015-ab86c87cce8283fb86b7ee1facbaa29b.jpg");
        pics.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488856213&di=1ffb53e3f8bbc5eb4d7f2fc33bcc01d0&imgtype=jpg&er=1&src=http%3A%2F%2Fimg2.ooopic.com%2F13%2F05%2F20%2F93bOOOPIC74_202.jpg");
        pics.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488856237&di=0b7eaedb6b8fc72a5c2a9d54e5b000b9&imgtype=jpg&er=1&src=http%3A%2F%2Fimg05.tooopen.com%2Fimages%2F20150818%2Ftooopen_sl_138750037934.jpg");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ViewParent parent = view.getParent();
        if (parent instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) parent;
            viewGroup.removeView(view);
        }
        ButterKnife.unbind(this);
    }

    private class TestNomalAdapter extends StaticPagerAdapter {

        @Override
        public View getView(ViewGroup container, int position) {
            ImageView view = new ImageView(CustomAppl.getCtx());
            Glide.with(getContext())
                    .load(pics.get(position))
                    .into(view);
            view.setScaleType(ImageView.ScaleType.FIT_XY);
            return view;
        }

        @Override
        public int getCount() {
            return pics.size();
        }
    }
}


text:
import six
from six.moves import queue

class Forum:
    """
    Manages a messaging system that allows messages to be published for any
    interested subscriber to receive.  If desired, published messages will even
    be delivered across a network.  Furthermore, since the system was designed
    to work with concurrent applications, messages can be safely published at
    any time from any thread.
    """

    def __init__(self, *pipes, **options):
        """
        Create and prepare a new forum object.  If any network connections are
        passed into the constructor, the forum will presume that other forums
        are listening and will attempt to communicate with them.
        """
        self.pipes = []
        self.locked = False

        self.subscriptions = {}
        self.publications = queue.Queue()

        safety_flag = options.get('safe', True)

        self.incoming_limit = 1 if safety_flag else float('inf')
        self.incoming_publications = []

        class Publisher:
            publish = self.publish

        class Subscriber:
            subscribe = self.subscribe

        class Member:
            publish = self.publish
            subscribe = self.subscribe

        self.publisher = Publisher()
        self.subscriber = Subscriber()
        self.member = Member()

        self.setup(*pipes)

    def subscribe(self, flavor, callback):
        """
        Attach a callback to a particular flavor of message.  For simplicity,
        the message's flavor is always the message's class.  This requires that
        all messages be instances of new-style classes.  Once the forum is
        locked, new subscriptions can no longer be made.
        """
        assert not self.locked

        try:
            self.subscriptions[flavor].append(callback)
        except KeyError:
            self.subscriptions[flavor] = [callback]

    def publish(self, message, callback=lambda: None):
        """
        Publish the given message so subscribers to that class of message can
        react to it.  If any remote forums are connected, the underlying
        network connection must be capable of serializing the message.
        """

        publication = Publication(message, receipt=callback)
        self.publications.put(publication)

    def setup(self, *pipes):
        """
        Connect this forum to another forum on a remote machine.  Any message
        published by either forum will be relayed to the other.  This method
        must be called before the forum is locked.
        """

        assert not self.locked
        self.pipes.extend(pipes)

    def update(self):
        """
        Deliver any messages that have been published since the last call to
        this function.  For local messages, this requires executing the proper
        callback for each subscriber.  For remote messages, this involves both
        checking for incoming packets and relaying new publications across the
        network.  No publications can be delivered before the forum is locked.
        """

        assert self.locked

        # Accept any messages that came in over the network since the last
        # update.  Not all of these messages will necessarily delivered this
        # time.  Those that aren't will be stored and delivered later.

        for pipe in self.pipes:
            for message in pipe.receive():
                publication = Publication(message, origin=pipe)
                self.incoming_publications.append(publication)

        # Decide how many messages to deliver.  It is safer to deliver only
        # one, because this eliminates some potential race conditions.
        # However, sometimes this performance hit is unacceptable.

        iteration = 0
        while True:
            iteration += 1

            if iteration > self.incoming_limit:
                break
            if not self.incoming_publications:
                break

            publication = self.incoming_publications.pop(0)
            self.publications.put(publication)

        # Pop messages off the publication queue one at a time.

        while True:
            try:
                publication = self.publications.get(False)

                # Deliver the message to local subscribers.

                message = publication.message
                flavor = type(message)

                for callback in self.subscriptions.get(flavor, []):
                    callback(message)

                # Deliver the message to any remote peers.

                for pipe in self.pipes:
                    if pipe is not publication.origin:
                        pipe.send(message, publication.receipt)

            except queue.Empty:
                break

        # Send any queued up outgoing messages.

        for pipe in self.pipes:
            for receipt in pipe.deliver():

                # Deliver returns a list of receipt objects for each message
                # that is successfully sent.  The forum makes sure that all of
                # these receipts are callbacks.

                receipt()

    def teardown(self):
        """
        Prevent the forum from being used anymore.  This is exactly equivalent
        to calling unlock.
        """
        self.unlock()

    def lock(self):
        """
        Prevent the forum from making any more subscriptions and allow it to
        begin delivering publications.
        """

        self.locked = True

        for pipe in self.pipes:
            pipe.lock()

    def unlock(self):
        """
        Prevent the forum from delivering messages and allow it to make new
        subscriptions.  All existing subscriptions are cleared.
        """

        self.locked = False

        self.subscriptions = {}
        self.publications = queue.Queue()

        for pipe in self.pipes:
            pipe.unlock()

    def get_member(self):
        return self.member

    def get_publisher(self):
        return self.publisher

    def get_subscriber(self):
        return self.subscriber

class Publication:
    """
    Represents messages that are waiting to be delivered within a forum.
    Outside of the forum, this class should never be used.
    """

    # The origin argument specifies the pipe that delivered this publication.
    # It is used to avoid returning a incoming message to the forum that
    # originally sent it.  For new publications, this field isn't important and
    # should not be specified.
    #
    # The receipt argument specifies a callback which will be executed
    # once the message in question is delivered.  This is only meaningful for
    # messages that originated in this forum.

    def __init__(self, message, origin=None, receipt=lambda: None):
        self.message = message
        self.origin = origin
        self.receipt = receipt


text:
This folder contains resources used to test that Emblem is correctly provisioned on top of a (somewhat pre-configured) Google Cloud project.

**Notes:**
> This is an _optional_ sub-component of the Emblem project. You do **not** need to configure this component to use the application.

> These tests must be run against a Google Cloud Project. We recommend creating a **separate project** for this instead of reusing the ones created for the core Emblem application.

## Prerequisites

Make sure you've [set up an Emblem instance](/docs/tutorials/setup-quickstart.md) **before** following this tutorial.

## Setup
Follow the steps below to set up these tests.

1. Enable Terraform components:
```
export TF_VAR_setup_cd_system=true
```

2. Set required variables:
```
# Common regions include `us-central1`, `europe-west6` and `asia-east1`.
# See the page below for a full list:
#   https://cloud.google.com/about/locations
export REGION=<YOUR GCP REGION>

export TESTING_PROJECT=<YOUR GCP PROJECT>

# Expose testing project ID to Terraform
export TF_VAR_project_id=$TESTING_PROJECT

# Use the same project for "ops" and "staging"
export TF_VAR_ops_project_id=$TESTING_PROJECT

# Configure GitHub {user, repository} name
export TF_VAR_repo_owner=<YOUR GITHUB USER/ORG NAME>
export TF_VAR_repo_name=emblem
```

3. Run Terraform from the `installation-testing` directory:
```
terraform -chdir="installation-testing/terraform/modules/emblem-app" init
terraform -chdir="installation-testing/terraform/modules/emblem-app" apply

terraform -chdir="installation-testing/terraform/modules/ops" init
terraform -chdir="installation-testing/terraform/modules/ops" apply
```

4. Build the testing container:
```
gcloud builds submit \
    --config=installation-testing/builds/e2e-deployer.cloudbuild.yaml \
    --project="$TESTING_PROJECT" \
    --substitutions=_REGION="$REGION",_IMAGE_TAG="latest"
```

## Useful links

See [Emblem's testing documentation](/docs/testing.md) for more information about testing.


text:
// FileTable Component
/**
 * Table to render files and their information.
 * Opens a new page with file contents on row click
 * @packageDocumentation
 */
import React, { useRef } from 'react';
import { ColumnProps, AutoSizer } from 'react-virtualized';
import clsx from 'clsx';
import styled from 'styled-components';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import BaseTable from '../../../InfiniteTable/BaseTable';
import * as file_pb from '../../../../api/file_pb';

const TableContainer = styled.div`
    width: 100%;
    height: 100%;
    flex: 1;
`;

const useStyles = makeStyles((theme: Theme) =>
    createStyles({
        flexContainer: {
            display: 'flex',
            alignItems: 'center',
            boxSizing: 'border-box',
        },
        tableRow: {
            cursor: 'pointer',
            outline: 'none',
            minWidth: '0px',
            flexGrow: 1,
        },
        tableRowHover: {
            '&:hover': {
                backgroundColor: theme.palette.grey[200],
            },
        },
        tableCell: {
            flexGrow: 1,
        },
        tableHeader: {
            fontWeight: 550,
            fontSize: 16,
        },
    })
);

const columns: ColumnProps[] = [
    { dataKey: 'name', label: 'Artifact Name', width: 400 },
    { dataKey: 'type', label: 'Type', width: 100 },
    { dataKey: 'size', label: 'File Size', width: 100 },
];

/** Data rendered by the file table */
export interface Data {
    name: string;
    type: string;
    size: number;
}

/** FileTable Props */
interface Props {
    /** Currently selected resource's name whose files are viewable*/
    selectedName: string;
    /** Currently selected resource's type whose files are viewable*/
    selectedType: string;
    /** Array of files to be rendered in the table */
    files: Array<file_pb.File>;
    /** Table rows are being loaded if true */
    isLoadingTableRows: boolean;
}

/**
 *
 * @param file File whose information will be parsed into table readable data
 */
const parseFileTableData = (file: file_pb.File): Data => {
    const name = file.getUid();
    const type = file.getContentType();
    const size = file.getLength().getValue();
    return { name, type, size };
};

/** FileTable Component */
export const FileTable: React.FC<Props> = ({
    files,
    selectedName,
    isLoadingTableRows,
}) => {
    const classes = useStyles();
    const rows = files
        .filter((file) => !file.getHidden())
        .map((file) => parseFileTableData(file));
    const ref = useRef<HTMLDivElement>();

    const cellClass = clsx(classes.tableCell, classes.flexContainer);
    const headerClass = clsx(
        classes.tableCell,
        classes.flexContainer,
        classes.tableHeader
    );
    const getRowClassName = ({ index }) => {
        return clsx(classes.tableRow, classes.flexContainer, {
            [classes.tableRowHover]: index !== -1,
        });
    };

    const getFileURL = (fileUid: string) => {
        return (
            window.location.origin +
            `/file?prefix=${selectedName}&fileName=${fileUid}`
        );
    };

    return (
        <TableContainer ref={ref} id={'FileTable'}>
            <AutoSizer>
                {({ height, width }) => (
                    <BaseTable
                        columns={columns}
                        width={width}
                        height={height}
                        rowHeight={48}
                        headerHeight={48}
                        rowCount={files.length}
                        onRowsRendered={() => {}}
                        registerChild={null}
                        rowGetter={({ index }) => rows[index]}
                        onRowClick={({ index }) => {
                            window.open(
                                getFileURL(files[index].getUid()),
                                '_blank'
                            );
                        }}
                        headerClass={headerClass}
                        cellClass={cellClass}
                        rowClassName={getRowClassName}
                        isNextPageLoading={isLoadingTableRows}
                    />
                )}
            </AutoSizer>
        </TableContainer>
    );
};

export default FileTable;


text:
using System;

namespace De.Osthus.Ambeth.Privilege.Factory
{
    public interface IEntityPrivilegeFactoryProvider
    {
        IEntityPrivilegeFactory GetEntityPrivilegeFactory(Type entityType, bool create, bool read, bool update, bool delete, bool execute);
    }
}


text:
puls3
=====

Mejorando.la project for web design course.


text:
const rollupConfBase = require("./rollup.base");
const merge = require("lodash/merge");
module.exports = merge(rollupConfBase, {plugins: []});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Seatown.Data.Validation.Rules
{
    public enum ComparisonOperators
    {
        None = 0,
        Contains = 1,
        DoesNotEqual = 2,
        EndsWith = 4,
        Equals = 8,
        GreaterThan = 16,
        GreaterThanOrEqual = 32,
        LessThan = 64,
        LessThanOrEqual = 128,
        StartsWith = 256
    }
}


text:
SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/ugstudents/Git/Paul/ocv_kinect/plugins/KeyboardController")
SET(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/ugstudents/Git/Paul/ocv_kinect/plugins/KeyboardController")

# Force unix paths in dependencies.
SET(CMAKE_FORCE_UNIX_PATHS 1)

# The C and CXX include file search paths:
SET(CMAKE_C_INCLUDE_PATH
  "/usr/include/gazebo-1.9"
  "/usr/include/gazebo-1.9/gazebo"
  "/usr/include/sdformat-1.4"
  "/usr/include/OGRE"
  "/usr/include/OGRE/Terrain"
  "/usr/include/OGRE/Paging"
  )
SET(CMAKE_CXX_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})
SET(CMAKE_Fortran_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})
SET(CMAKE_ASM_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})

# The C and CXX include file regular expressions for this directory.
SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$")
SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$")
SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})
SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})


text:
package cz.metacentrum.perun.webgui.tabs;

import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.tabs.servicestabs.*;

import java.util.Map;

/**
 * Services tabs
 *
 * @author Vaclav Mach <374430@mail.muni.cz>
 */
public class ServicesTabs {

	private PerunWebSession session = PerunWebSession.getInstance();

	static public final String URL = "srv";

	/**
	 * Creates a new instance of pages
	 */
	public ServicesTabs(){}

	/**
	 * Loads the page
	 *
	 * @return true on success / false otherwise
	 */
	public boolean loadTab(final String tab, final Map<String, String> parameters) {

		if(tab == null){
			return false;
		}
		// if active
		boolean open = ("1".equals(parameters.get("active")));

		if (tab.equals(ServiceDestinationsTabItem.URL)) {
			session.getTabManager().addTab(ServiceDestinationsTabItem.load(parameters), open);
			return true;
		}
		if (tab.equals(ServiceDetailTabItem.URL)) {
			session.getTabManager().addTab(ServiceDetailTabItem.load(parameters), open);
			return true;
		}
		if (tab.equals(ServiceRequiredAttributesTabItem.URL)) {
			session.getTabManager().addTab(ServiceRequiredAttributesTabItem.load(parameters), open);
			return true;
		}
		if (tab.equals(ServicesTabItem.URL)) {
			session.getTabManager().addTab(ServicesTabItem.load(parameters), open);
			return true;
		}
		if (tab.equals(ServicePackagesTabItem.URL)) {
			session.getTabManager().addTab(ServicePackagesTabItem.load(parameters), open);
			return true;
		}

		return false;

	}

}


text:
import os
import datetime

os.chdir("cache")
os.system("ln buildings_adjusted_for_jobs.csv buildings.csv")
os.system("ln parcels_geography.csv parcels.csv")
today = datetime.datetime.today().strftime('%Y-%m-%d')
fname = today + "_basis_microdata.zip"
os.system("zip %s buildings.csv buildings_geometry.csv households.csv "
          "jobs.csv parcels.csv" % fname)


text:
use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    #[error("XML parser error")]
    Xml {
        #[from]
        source: quick_xml::Error,
    },

    #[error("XML attribute parser error")]
    XmlAttr {
        #[from]
        source: quick_xml::events::attributes::AttrError,
    },

    #[error("UTF-8 encoding error")]
    Utf8 {
        #[from]
        source: std::str::Utf8Error,
    },

    #[error("Integer parsing error")]
    ParseIntError {
        #[from]
        source: std::num::ParseIntError,
    },

    #[error("XML dictionary parsing error: {0}")]
    Parsing(String),
}

pub type Result<R> = std::result::Result<R, Error>;


text:
package md2k.mcerebrum.cstress.autosense;

/**
 * Static enumerations and configurable constants for the AutoSense platform
 */
public class AUTOSENSE {

    //Autosense hardware-specific constants
    public static final int CHEST_ECG = 0;
    public static final int CHEST_ACCEL_X = 1;
    public static final int CHEST_ACCEL_Y = 2;
    public static final int CHEST_ACCEL_Z = 3;
    public static final int CHEST_GSR = 4;

    public static final int CHEST_RIP = 7;
    public static final int CHEST_BATTERY_SKINTEMP_AMBIENTTEMP = 8;

    public static final int QUALITY_GOOD = 0;
    public static final int QUALITY_NOISE = 1;
    public static final int QUALITY_BAD = 2;
    public static final int QUALITY_BAND_OFF = 3;
    public static final int QUALITY_MISSING = 4;
    public static final int QUALITY_BAND_LOOSE = 2;

    public static final double QUALITY_acceptableOutlierPercent = .34;
    public static final double QUALITY_outlierThresholdHigh = .9769;
    public static final double QUALITY_outlierThresholdLow = .004884;
    public static final int QUALITY_bufferLength = 3;
    public static final int ADC_range = 4095;

    public static final double QUALITY_ecgSlope = .02443;
    public static final int QUALITY_windowSizeEcg = 2000;
    public static final double QUALITY_ecgThresholdBandLoose = .01148;

    public static final double QUALITY_ripSlope = .0733;
    public static final int QUALITY_windowSizeRip = 4000;
    public static final double QUALITY_ripThresholdBandLoose = .0428;

    public static final int NOT_STRESSED = 0;
    public static final int STRESSED = 1;
    public static final int UNSURE = 2;

    //Library signal processing constants
    public static final double MED_CONSTANT = 4.5;
    public static final double MAD_CONSTANT = 2.8;
    public static final double CBD_THRESHOLD = 0.2;
    public static final double REF_MINIMUM = 0.3;
    public static final double REF_MAXIMUM = 2.0;
    public static final double THR1_INIT = 0.5;
    public static final int FL_INIT = 256;
    public static final double SIG_LEV_FACTOR = 4.0;
    public static final double NOISE_LEV_FACTOR = 0.1;
    public static final double EWMA_ALPHA = 0.125;
    public static final double RPEAK_BIN_FACTOR = 10.0;
    public static final int PEAK_INTERVAL_MINIMUM_SIZE = 8;
    public static final int PEAK_VALLEY_SMOOTHING_SIZE = 5;
    public static final double WINDOW_LENGTH_SECS = 8.0;
    public static final double INSPIRATION_EXPIRATION_AMPLITUDE_THRESHOLD_FACTOR = 0.15;
    public static final double RESPIRATION_MINIMUM = 8.0;
    public static final int RESPIRATION_MAXIMUM = 65;
    public static final double WINDOW_DIVIDER_FACTOR = 20.0;
    public static final double STRESS_PROBABILTY_THRESHOLD = 0.339329059788;

    public static final double RPEAK_INTERPEAK_MULTIPLIER = 0.5;
    public static final int RPEAK_INTERPEAK_LIMIT = 500;
    public static final int SAMPLE_LENGTH_SECS = 60;

    public static final double ACTIVITY_THRESHOLD = 0.21; //From Figure 3: http://www.cs.memphis.edu/~santosh/Papers/Timing-JIT-UbiComp-2014.pdf
    public static final int ACCEL_WINDOW_SIZE = 10000;
    public static final double AUTOSENSE_ECG_QUALITY = 0.67;
    public static final double AUTOSENSE_RIP_QUALITY = 0.67;

    //Data Quality
    public static int SEGMENT_GOOD = 0;
    public static int SEGMENT_BAD = 1;
}