text:
package org.jboss.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import org.jboss.logging.Cause;
import org.jboss.logging.Message;
import org.jboss.logging.MessageBundle;
import org.jboss.logging.Messages;

/**
 * Logging IDs 1-1000
 * @author Remy Maucherat
 */
@MessageBundle(projectCode = "JBWEB")
public interface CatalinaMessages {

    /**
     * The messages
     */
    CatalinaMessages MESSAGES = Messages.getBundle(CatalinaMessages.class);

    @Message(id = 1, value = "Configuration error:  Must be attached to a Context")
    IllegalArgumentException authenticatorNeedsContext();

    @Message(id = 2, value = "Security Interceptor has already been started")
    String authenticatorAlreadyStarted();

    @Message(id = 3, value = "Security Interceptor has not yet been started")
    String authenticatorNotStarted();

    @Message(id = 4, value = "The request body was too large to be cached during the authentication process")
    String requestBodyTooLarge();

    @Message(id = 5, value = "The time allowed for the login process has been exceeded. If you wish to continue you must either click back twice and re-click the link you requested or close and re-open your browser")
    String sessionTimeoutDuringAuthentication();

    @Message(id = 6, value = "Invalid direct reference to form login page")
    String invalidFormLoginDirectReference();

    @Message(id = 7, value = "Unexpected error forwarding to error page")
    String errorForwardingToFormError();

    @Message(id = 8, value = "Unexpected error forwarding to login page")
    String errorForwardingToFormLogin();

    @Message(id = 9, value = "No client certificate chain in this request")
    String missingRequestCertificate();

    @Message(id = 10, value = "Cannot authenticate with the provided credentials")
    String certificateAuthenticationFailure();

    @Message(id = 11, value = "Valve has already been started")
    String valveAlreadyStarted();

    @Message(id = 12, value = "Valve has not yet been started")
    String valveNotStarted();

    @Message(id = 13, value = "Username [%s] NOT successfully authenticated")
    String userNotAuthenticated(String userName);

    @Message(id = 14, value = "Username [%s] successfully authenticated")
    String userAuthenticated(String userName);

    @Message(id = 15, value = "Access to the requested resource has been denied")
    String forbiddenAccess();

    @Message(id = 16, value = "User [%s] does not have role [%s]")
    String userDoesNotHaveRole(String user, String role);

    @Message(id = 17, value = "User [%s] has role [%s]")
    String userHasRole(String user, String role);

    @Message(id = 18, value = "Realm has already been started")
    String realmAlreadyStarted();

    @Message(id = 19, value = "Realm has not yet been started")
    String realmNotStarted();

    @Message(id = 20, value = "Invalid message digest algorithm %s specified")
    String invalidMessageDigest(String digest);

    @Message(id = 21, value = "Illegal digest encoding %s")
    IllegalArgumentException illegalDigestEncoding(String digest, @Cause UnsupportedEncodingException e);

    @Message(id = 22, value = "Missing MD5 digest")
    IllegalArgumentException noMD5Digest(@Cause NoSuchAlgorithmException e);

    @Message(id = 23, value = "Protocol handler initialization failed")
    String protocolHandlerInitFailed(@Cause Throwable t);

    @Message(id = 24, value = "Protocol handler start failed")
    String protocolHandlerStartFailed(@Cause Throwable t);

    @Message(id = 25, value = "Protocol handler destroy failed")
    String protocolHandlerDestroyFailed(@Cause Throwable t);

    @Message(id = 26, value = "Failed to instatiate protocol handler")
    IllegalArgumentException protocolHandlerInstantiationFailed(@Cause Throwable t);

    @Message(id = 27, value = "getWriter() has already been called for this response")
    IllegalStateException writerAlreadyUsed();

    @Message(id = 28, value = "getOutputStream() has already been called for this response")
    IllegalStateException outputStreamAlreadyUsed();

    @Message(id = 29, value = "Cannot reset buffer after response has been committed")
    IllegalStateException cannotResetBuffer();

    @Message(id = 30, value = "Cannot change buffer size after data has been written")
    IllegalStateException cannotChangeBufferSize();

    @Message(id = 31, value = "Cannot call sendError() after the response has been committed")
    IllegalStateException cannotSendError();

    @Message(id = 32, value = "Cannot call sendRedirect() after the response has been committed")
    IllegalStateException cannotSendRedirect();

    @Message(id = 33, value = "Cannot call sendUpgrade() after the response has been committed")
    IllegalStateException cannotSendUpgrade();

    @Message(id = 34, value = "Cannot upgrade from HTTP/1.1 without IO events")
    IllegalStateException cannotUpgradeWithoutEvents();

    @Message(id = 36, value = "Cannot call sendFile() after the response has been committed")
    IllegalStateException cannotSendFile();

    @Message(id = 37, value = "Sendfile is disabled")
    IllegalStateException noSendFile();

    @Message(id = 38, value = "Invalid path for sendfile %s")
    IllegalStateException invalidSendFilePath(String path);

    @Message(id = 39, value = "getReader() has already been called for this request")
    IllegalStateException readerAlreadyUsed();

    @Message(id = 40, value = "getInputStream() has already been called for this request")
    IllegalStateException inputStreamAlreadyUsed();

    @Message(id = 41, value = "Exception thrown by attributes event listener")
    String attributesEventListenerException();

    @Message(id = 42, value = "Cannot call setAttribute with a null name")
    IllegalStateException attributeNameNotSpecified();

    @Message(id = 43, value = "Cannot create a session after the response has been committed")
    IllegalStateException cannotCreateSession();

    @Message(id = 44, value = "Parameters were not parsed because the size of the posted data was too big. Use the maxPostSize attribute of the connector to resolve this if the application should accept large POSTs.")
    IllegalStateException postDataTooLarge();

    @Message(id = 45, value = "The request is not multipart content")
    String notMultipart();

    @Message(id = 46, value = "Exception thrown whilst processing multipart")
    IllegalStateException multipartProcessingFailed(@Cause Throwable t);

    @Message(id = 47, value = "Exception thrown whilst processing multipart")
    IOException multipartIoProcessingFailed(@Cause Throwable t);

    @Message(id = 48, value = "The servlet or filters that are being used by this request do not support async operation")
    IllegalStateException noAsync();

    @Message(id = 49, value = "Response has been closed already")
    IllegalStateException asyncClose();

    @Message(id = 50, value = "Cannot start async")
    IllegalStateException cannotStartAsync();

    @Message(id = 51, value = "Error invoking onStartAsync on listener of class %s")
    IllegalStateException errorStartingAsync(String listenerClassName, @Cause Throwable t);

    @Message(id = 52, value = "No authenticator available for programmatic login")
    String noAuthenticator();

    @Message(id = 53, value = "Failed to authenticate a principal")
    String authenticationFailure();

    @Message(id = 54, value = "Exception logging out user")
    String logoutFailure();

    @Message(id = 55, value = "Could not determine or access context for server absolute URI %s")
    IllegalStateException cannotFindDispatchContext(String uri);

    @Message(id = 56, value = "Failed to instantiate class %s")
    String listenerCreationFailed(String className);

    @Message(id = 57, value = "The request object has been recycled and is no longer associated with this facade")
    IllegalStateException nullRequestFacade();

    @Message(id = 58, value = "The response object has been recycled and is no longer associated with this facade")
    IllegalStateException nullResponseFacade();

    @Message(id = 59, value = "Stream closed")
    IOException streamClosed();

    @Message(id = 64, value = "Error report")
    String errorReport();

    @Message(id = 65, value = "HTTP Status %s - %s")
    String statusHeader(int statusCode, String message);

    @Message(id = 66, value = "Exception report")
    String exceptionReport();

    @Message(id = 67, value = "Status report")
    String statusReport();

    @Message(id = 68, value = "message")
    String statusMessage();

    @Message(id = 69, value = "description")
    String statusDescritpion();

    @Message(id = 70, value = "exception")
    String statusException();

    @Message(id = 71, value = "root cause")
    String statusRootCause();

    @Message(id = 72, value = "note")
    String statusNote();

    @Message(id = 73, value = "The full stack trace of the root cause is available in the %s logs.")
    String statusRootCauseInLogs(String log);

    @Message(id = 74, value = "Exception processing event.")
    String eventValveExceptionDuringEvent();

    @Message(id = 75, value = "Exception processing session listener event.")
    String eventValveSessionListenerException();

    @Message(id = 76, value = "Exception performing insert access entry.")
    String jdbcAccessLogValveInsertError();

    @Message(id = 77, value = "Exception closing database connection.")
    String jdbcAccessLogValveConnectionCloseError();

    @Message(id = 78, value = "Syntax error in request filter pattern %s")
    String requestFilterValvePatternError(String pattern);

    @Message(id = 79, value = "The property %s is not defined for filters of type %s")
    String propertyNotFound(String property, String className);

    @Message(id = 80, value = "Unable to create Random source using class %s")
    String cannotCreateRandom(String className);

    @Message(id = 81, value = "Unsupported startingPoint %s")
    IllegalStateException expiresUnsupportedStartingPoint(String startingPoint);

    @Message(id = 82, value = "Exception processing configuration parameter %s: %s")
    String expiresExceptionProcessingParameter(String name, String value);

    @Message(id = 83, value = "Starting point (access|now|modification|a<seconds>|m<seconds>) not found in directive %s")
    IllegalStateException expiresStartingPointNotFound(String line);

    @Message(id = 84, value = "Invalid starting point (access|now|modification|a<seconds>|m<seconds>) %s in directive %s")
    IllegalStateException expiresInvalidStartingPoint(String token, String line);

    @Message(id = 85, value = "Duration not found in directive %s")
    IllegalStateException expiresDurationNotFound(String line);

    @Message(id = 86, value = "Invalid duration (number) %s in directive %s")
    IllegalStateException expiresInvalidDuration(String token, String line);

    @Message(id = 87, value = "Duration unit not found after amount %s in directive %s")
    IllegalStateException expiresDurationUnitNotFound(int amount, String line);

    @Message(id = 88, value = "The requested resource (%s) is not available")
    String resourceNotAvailable(String resource);

    @Message(id = 89, value = "Directory Listing For %s")
    String listingDirectoryTitle(String directory);

    @Message(id = 90, value = "Up To %s")
    String listingDirectoryParent(String directory);

    @Message(id = 91, value = "Filename")
    String listingFilename();

    @Message(id = 92, value = "Size")
    String listingSize();

    @Message(id = 93, value = "Last Modified")
    String listingLastModified();

    @Message(id = 94, value = "JAXP initialization failed")
    String jaxpInitializationFailed();

    @Message(id = 95, value = "Ignored external entity %s %s")
    String ignoredExternalEntity(String publicId, String systemId);

    @Message(id = 96, value = "No modifications are allowed to a locked ParameterMap")
    IllegalStateException lockedParameterMap();

    @Message(id = 97, value = "No modifications are allowed to a locked ResourceSet")
    IllegalStateException lockedResourceSet();

    @Message(id = 98, value = "Bad hexadecimal digit")
    IllegalArgumentException badHexDigit();

    @Message(id = 99, value = "Odd number of hexadecimal digits")
    IllegalArgumentException oddNomberOfHexDigits();

    @Message(id = 100, value = "The client may continue.")
    String http100();

    @Message(id = 101, value = "The server is switching protocols according to the 'Upgrade' header.")
    String http101();

    @Message(id = 102, value = "The server has accepted the complete request, but has not yet completed it.")
    String http102();

    @Message(id = 103, value = "The request succeeded and a new resource has been created on the server.")
    String http201();

    @Message(id = 104, value = "This request was accepted for processing, but has not been completed.")
    String http202();

    @Message(id = 105, value = "The meta information presented by the client did not originate from the server.")
    String http203();

    @Message(id = 106, value = "The request succeeded but there is no information to return.")
    String http204();

    @Message(id = 107, value = "The client should reset the document view which caused this request to be sent.")
    String http205();

    @Message(id = 108, value = "The server has fulfilled a partial GET request for this resource.")
    String http206();

    @Message(id = 109, value = "Multiple status values have been returned.")
    String http207();

    @Message(id = 110, value = "This collection binding was already reported.")
    String http208();

    @Message(id = 111, value = "The response is a representation of the result of one or more instance-manipulations applied to the current instance.")
    String http226();

    @Message(id = 112, value = "The requested resource corresponds to any one of a set of representations, each with its own specific location.")
    String http300();

    @Message(id = 113, value = "The requested resource has moved permanently to a new location.")
    String http301();

    @Message(id = 114, value = "The requested resource has moved temporarily to a new location.")
    String http302();

    @Message(id = 115, value = "The response to this request can be found under a different URI.")
    String http303();

    @Message(id = 116, value = "The requested resource is available and has not been modified.")
    String http304();

    @Message(id = 117, value = "The requested resource must be accessed through the proxy given by the 'Location' header.")
    String http305();

    @Message(id = 118, value = "The requested resource resides temporarily under a different URI.")
    String http307();

    @Message(id = 119, value = "The target resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs.")
    String http308();

    @Message(id = 120, value = "The request sent by the client was syntactically incorrect.")
    String http400();

    @Message(id = 121, value = "This request requires HTTP authentication.")
    String http401();

    @Message(id = 122, value = "Payment is required for access to this resource.")
    String http402();

    @Message(id = 123, value = "Access to the specified resource has been forbidden.")
    String http403();

    @Message(id = 124, value = "The requested resource is not available.")
    String http404();

    @Message(id = 125, value = "The specified HTTP method is not allowed for the requested resource.")
    String http405();

    @Message(id = 126, value = "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request 'Accept' headers.")
    String http406();

    @Message(id = 127, value = "The client must first authenticate itself with the proxy.")
    String http407();

    @Message(id = 128, value = "The client did not produce a request within the time that the server was prepared to wait.")
    String http408();

    @Message(id = 129, value = "The request could not be completed due to a conflict with the current state of the resource.")
    String http409();

    @Message(id = 130, value = "The requested resource is no longer available, and no forwarding address is known.")
    String http410();

    @Message(id = 131, value = "This request cannot be handled without a defined content length.")
    String http411();

    @Message(id = 132, value = "A specified precondition has failed for this request.")
    String http412();

    @Message(id = 133, value = "The request entity is larger than the server is willing or able to process.")
    String http413();

    @Message(id = 134, value = "The server refused this request because the request URI was too long.")
    String http414();

    @Message(id = 135, value = "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.")
    String http415();

    @Message(id = 136, value = "The requested byte range cannot be satisfied.")
    String http416();

    @Message(id = 137, value = "The expectation given in the 'Expect' request header could not be fulfilled.")
    String http417();

    @Message(id = 138, value = "The server understood the content type and syntax of the request but was unable to process the contained instructions.")
    String http422();

    @Message(id = 139, value = "The source or destination resource of a method is locked.")
    String http423();

    @Message(id = 140, value = "The method could not be performed on the resource because the requested action depended on another action and that action failed.")
    String http424();

    @Message(id = 141, value = "The request can only be completed after a protocol upgrade.")
    String http426();

    @Message(id = 142, value = "The request is required to be conditional.")
    String http428();

    @Message(id = 143, value = "The user has sent too many requests in a given amount of time.")
    String http429();

    @Message(id = 144, value = "The server refused this request because the request header fields are too large.")
    String http431();

    @Message(id = 145, value = "The server encountered an internal error that prevented it from fulfilling this request.")
    String http500();

    @Message(id = 146, value = "The server does not support the functionality needed to fulfill this request.")
    String http501();

    @Message(id = 147, value = "This server received an invalid response from a server it consulted when acting as a proxy or gateway.")
    String http502();

    @Message(id = 148, value = "The requested service is not currently available.")
    String http503();

    @Message(id = 149, value = "The server received a timeout from an upstream server while acting as a gateway or proxy.")
    String http504();

    @Message(id = 150, value = "The server does not support the requested HTTP protocol version.")
    String http505();

    @Message(id = 151, value = "The chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.")
    String http506();

    @Message(id = 152, value = "The resource does not have sufficient space to record the state of the resource after execution of this method.")
    String http507();

    @Message(id = 153, value = "The server terminated an operation because it encountered an infinite loop.")
    String http508();

    @Message(id = 154, value = "The policy for accessing the resource has not been met in the request.")
    String http510();

    @Message(id = 155, value = "The client needs to authenticate to gain network access.")
    String http511();

    @Message(id = 200, value = "Store has already been started")
    String storeAlreadyStarted();

    @Message(id = 201, value = "Store has not yet been started")
    String storeNotStarted();

    @Message(id = 202, value = "Loading Session %s from file %s")
    String fileStoreSessionLoad(String sessionId, String file);

    @Message(id = 203, value = "Saving Session %s to file %s")
    String fileStoreSessionSave(String sessionId, String file);

    @Message(id = 204, value = "Removing Session %s at file %s")
    String fileStoreSessionRemove(String sessionId, String file);

    @Message(id = 205, value = "No persisted data file found")
    String fileStoreFileNotFound();

    @Message(id = 206, value = "Parent Container is not a Context")
    IllegalArgumentException parentNotContext();

    @Message(id = 207, value = "JDBC Store SQL exception")
    String jdbcStoreDatabaseError();

    @Message(id = 208, value = "JDBC driver class not found %s")
    String jdbcStoreDriverFailure(String className);

    @Message(id = 209, value = "Session creation failed due to too many active sessions")
    IllegalStateException managerMaxActiveSessions();

    @Message(id = 210, value = "Error deserializing Session %s")
    IllegalStateException persistentManagerDeserializeError(String sessionId, @Cause Throwable t);

    @Message(id = 211, value = "Session event listener threw exception")
    String sessionEventListenerException();

    @Message(id = 212, value = "Session already invalidated")
    IllegalStateException invalidSession();

    @Message(id = 213, value = "Exception logging out user when expiring session")
    String sessionLogoutException();

    @Message(id = 214, value = "Session attribute event listener threw exception")
    String sessionAttributeEventListenerException();

    @Message(id = 215, value = "Session attribute name cannot be null")
    IllegalArgumentException sessionAttributeNameIsNull();

    @Message(id = 216, value = "Non-serializable attribute %s")
    IllegalArgumentException sessionAttributeIsNotSerializable(String name);

    @Message(id = 217, value = "Session binding event listener threw exception")
    String sessionBindingEventListenerException();

    @Message(id = 218, value = "Cannot serialize session attribute %s for session %s")
    String sessionAttributeSerializationException(Object attribute, String sessionId);

    @Message(id = 219, value = "Path %s does not start with a '/' character")
    IllegalArgumentException invalidDispatcherPath(String path);

    @Message(id = 220, value = "Dispatcher mapping error")
    String dispatcherMappingError();

    @Message(id = 221, value = "Path %s does not start with a '/' character")
    String invalidDispatcherPathString(String path);

    @Message(id = 222, value = "Exception thrown by attributes event listener")
    String servletContextAttributeListenerException();

    @Message(id = 223, value = "Attribute name cannot be null")
    String servletContextAttributeNameIsNull();

    @Message(id = 224, value = "The listener that attempted to call this method is restricted")
    UnsupportedOperationException restrictedListenerCannotCallMethod();

    @Message(id = 225, value = "Context %s is already initialized")
    IllegalStateException contextAlreadyInitialized(String context);

    @Message(id = 226, value = "Error creating instance")
    String contextObjectCreationError();

    @Message(id = 227, value = "Bad listener class %s for context %s")
    IllegalArgumentException invalidContextListener(String className, String path);

    @Message(id = 228, value = "Bad listener class %s for context %s")
    IllegalArgumentException invalidContextListenerWithException(String className, String path, @Cause Throwable t);

    @Message(id = 229, value = "The session tracking mode %s requested for context %s is not supported by that context")
    IllegalArgumentException unsupportedSessionTrackingMode(String sessionTracking, String path);

    @Message(id = 230, value = "The session tracking mode SSL requested for context %s cannot be combined with other tracking modes")
    IllegalArgumentException sslSessionTrackingModeIsExclusive(String path);

    @Message(id = 231, value = "Invalid empty role specified for context %s")
    IllegalArgumentException invalidEmptyRole(String path);

    @Message(id = 232, value = "Cannot forward after response has been committed")
    IllegalStateException cannotForwardAfterCommit();

    @Message(id = 233, value = "Exception sending request initialized lifecycle event to listener instance of class %s")
    String requestListenerInitException(String className);

    @Message(id = 234, value = "Servlet %s is currently unavailable")
    String servletIsUnavailable(String wrapperName);

    @Message(id = 235, value = "Allocate exception for servlet %s")
    String servletAllocateException(String wrapperName);

    @Message(id = 236, value = "Servlet.service() for servlet %s threw exception")
    String servletServiceException(String wrapperName);

    @Message(id = 237, value = "Deallocate exception for servlet %s")
    String servletDeallocateException(String wrapperName);

    @Message(id = 238, value = "Exception sending request destroyed lifecycle event to listener instance of class %s")
    String requestListenerDestroyException(String className);

    @Message(id = 239, value = "Original SevletRequest or wrapped original ServletRequest not passed to RequestDispatcher in violation of SRV.8.2 and SRV.14.2.5.1")
    String notOriginalRequestInDispatcher();

    @Message(id = 240, value = "Original SevletResponse or wrapped original ServletResponse not passed to RequestDispatcher in violation of SRV.8.2 and SRV.14.2.5.1")
    String notOriginalResponseInDispatcher();

    @Message(id = 241, value = "Context %s has already been initialized")
    IllegalStateException cannotAddFilterRegistrationAfterInit(String contextName);

    @Message(id = 242, value = "Illegal null or empty argument specified")
    IllegalArgumentException invalidFilterRegistrationArguments();

    @Message(id = 243, value = "Context %s has already been initialized")
    IllegalStateException cannotAddServletRegistrationAfterInit(String contextName);

    @Message(id = 244, value = "Illegal null or empty argument specified")
    IllegalArgumentException invalidServletRegistrationArguments();

    @Message(id = 245, value = "Error destroying filter %s")
    String errorDestroyingFilter(String filterName);

    @Message(id = 246, value = "Exception processing component pre destroy")
    String preDestroyException();

    @Message(id = 247, value = "Filter execution threw an exception")
    String filterException();

    @Message(id = 248, value = "Servlet execution threw an exception")
    String servletException();

    @Message(id = 249, value = "Child container name cannot be null")
    IllegalArgumentException containerChildWithNullName();

    @Message(id = 250, value = "Child container with name %s already exists")
    IllegalArgumentException containerChildNameNotUnique(String name);

    @Message(id = 251, value = "Failed to start child container %s")
    IllegalStateException containerChildStartFailed(String name, @Cause Throwable t);

    @Message(id = 252, value = "Child of an Engine must be a Host")
    IllegalArgumentException engineChildMustBeHost();

    @Message(id = 253, value = "Engine cannot have a parent Container")
    IllegalArgumentException engineHasNoParent();

    @Message(id = 254, value = "Host name is required")
    IllegalArgumentException hostNameIsNull();

    @Message(id = 255, value = "Child of a Host must be a Context")
    IllegalArgumentException hostChildMustBeContext();

    @Message(id = 256, value = "Parent of a Wrapper must be a Context")
    IllegalArgumentException wrapperParentMustBeContext();

    @Message(id = 257, value = "A Wrapper cannot have a child container")
    IllegalArgumentException wrapperHasNoChild();

    @Message(id = 258, value = "Cannot allocate servlet %s because it is being unloaded")
    String cannotAllocateServletWhileUnloading(String name);

    @Message(id = 259, value = "Error allocating a servlet instance")
    String cannotAllocateServletInstance();

    @Message(id = 260, value = "No servlet class has been specified for servlet %s")
    String noClassSpecifiedForServlet(String name);

    @Message(id = 261, value = "Class %s is not a Servlet")
    String specifiedClassIsNotServlet(String className);

    @Message(id = 262, value = "Error instantiating servlet class %s")
    String errorInstantiatingServletClass(String className);

    @Message(id = 263, value = "Servlet.init() for servlet %s threw exception")
    String errorInitializingServlet(String name);

    @Message(id = 264, value = "Marking servlet %s as unavailable")
    String markingServletUnavailable(String name);

    @Message(id = 265, value = "Servlet.destroy() for servlet %s threw exception")
    String errorDestroyingServlet(String name);

    @Message(id = 266, value = "Servlet %s threw unload exception")
    String errorUnloadingServlet(String name);

    @Message(id = 267, value = "LoginConfig cannot be null")
    IllegalArgumentException nullLoginConfig();

    @Message(id = 268, value = "Form login page %s must start with a ''/'")
    IllegalArgumentException loginPageMustStartWithSlash(String loginPage);

    @Message(id = 269, value = "Error page location %s must start with a ''/''")
    IllegalArgumentException errorPageMustStartWithSlash(String errorPage);

    @Message(id = 270, value = "%s is not a subclass of StandardWrapper")
    IllegalArgumentException invalidWrapperClass(String wrapperClass);

    @Message(id = 271, value = "Cannot set resources after Context startup")
    IllegalStateException cannotSetResourcesAfterStart();

    @Message(id = 272, value = "Child of a Context must be a Wrapper")
    IllegalArgumentException contextChildMustBeWrapper();

    @Message(id = 273, value = "JSP file %s must start with a ''/''")
    IllegalArgumentException jspFileMustStartWithSlash(String jspFile);

    @Message(id = 274, value = "Invalid <url-pattern> %s in security constraint")
    IllegalArgumentException invalidSecurityConstraintUrlPattern(String urlPattern);

    @Message(id = 275, value = "ErrorPage cannot be null")
    IllegalArgumentException nullErrorPage();

    @Message(id = 276, value = "Filter mapping specifies an unknown filter name %s")
    IllegalArgumentException unknownFilterNameInMapping(String filterName);

    @Message(id = 277, value = "Filter mapping must specify either a <url-pattern> or a <servlet-name>")
    IllegalArgumentException missingFilterMapping();

    @Message(id = 278, value = "Invalid <url-pattern> %s in filter mapping")
    IllegalArgumentException invalidFilterMappingUrlPattern(String urlPattern);

    @Message(id = 279, value = "Both parameter name and parameter value are required")
    IllegalArgumentException missingParameterNameOrValue();

    @Message(id = 280, value = "Duplicate context initialization parameter %s")
    IllegalArgumentException duplicateContextParameters(String name);

    @Message(id = 281, value = "Servlet mapping specifies an unknown Servlet name %s")
    IllegalArgumentException unknownServletNameInMapping(String servletName);

    @Message(id = 282, value = "Invalid <url-pattern> %s in Servlet mapping")
    IllegalArgumentException invalidServletMappingUrlPattern(String urlPattern);

    @Message(id = 283, value = "Create wrapper failed")
    IllegalStateException errorCreatingWrapper(@Cause Throwable t);

    @Message(id = 284, value = "Exception starting filter %s")
    String errorStartingFilter(String filterName);

    @Message(id = 285, value = "Error configuring application listener of class %s")
    String errorInstatiatingApplicationListener(String listenerClass);

    @Message(id = 286, value = "Skipped installing application listeners due to previous error(s)")
    String skippingApplicationListener();

    @Message(id = 287, value = "Exception sending context initialized event to listener instance of class %s")
    String errorSendingContextInitializedEvent(String listenerClass);

    @Message(id = 288, value = "Error destroying application listener of class %s")
    String errorDestroyingApplicationListener(String listenerClass);

    @Message(id = 289, value = "Servlet %s threw load() exception")
    String errorLoadingServlet(String servletName);

    @Message(id = 290, value = "Error initializing context")
    String errorInitializingContext();

    @Message(id = 291, value = "No Context was mapped to process this request")
    String noContext();

    @Message(id = 292, value = "Syntax error in IP filter pattern %s")
    IllegalArgumentException remoteIpValvePatternError(String pattern, @Cause Throwable t);

    @Message(id = 293, value = "No host [%s] mapped")
    String noHost(String host);

    @Message(id = 294, value = "Servlet %s does not have any instance support")
    IllegalStateException missingInstanceSupport(String servletName);

    @Message(id = 295, value = "This application is not currently available")
    String unavailable();

    @Message(id = 296, value = "Error acknowledging request for Servlet %s")
    String errorAcknowledgingRequest(String servletName);

    @Message(id = 297, value = "Async listener processing for servlet %s threw exception")
    String asyncListenerError(String servletName);

    @Message(id = 298, value = "Async runnable processing for servlet %s threw exception")
    String asyncRunnableError(String servletName);

    @Message(id = 299, value = "Async dispatch processing for servlet %s threw exception")
    String asyncDispatchError(String servletName);

    @Message(id = 300, value = "Loading Session %s from file %s")
    String jdbcStoreSessionLoad(String sessionId, String table);

    @Message(id = 301, value = "Saving Session %s to file %s")
    String jdbcStoreSessionSave(String sessionId, String table);

    @Message(id = 302, value = "Removing Session %s at file %s")
    String jdbcStoreSessionRemove(String sessionId, String table);

    @Message(id = 303, value = "No persisted data object found")
    String jdbcStoreIdNotFound();

    @Message(id = 304, value = "The database connection is null or was found to be closed. Trying to re-open it.")
    String jdbcStoreConnectionWasClosed();

    @Message(id = 305, value = "The re-open on the database failed. The database could be down.")
    String jdbcStoreConnectionReopenFailed();

    @Message(id = 306, value = "Exception sending context destroyed event to listener instance of class %s")
    String errorSendingContextDestroyedEvent(String listenerClass);

    @Message(id = 307, value = "Invalid duration unit (years|months|weeks|days|hours|minutes|seconds) %s in directive %s")
    IllegalStateException expiresInvalidDurationUnit(String token, String line);

    @Message(id = 308, value = "Request filter invalid pattern %s")
    IllegalArgumentException requestFilterInvalidPattern(String pattern, @Cause Throwable t);

    @Message(id = 309, value = "type")
    String statusType();

    @Message(id = 310, value = "Null attribute name")
    IllegalArgumentException invalidNullAttributeName();

    @Message(id = 311, value = "Null attribute")
    IllegalArgumentException invalidNullAttribute();

    @Message(id = 312, value = "Invalid negative read ahead %s specified")
    IllegalArgumentException invalidReadAhead(int readAhead);

    @Message(id = 313, value = "Exception processing error page %s")
    String errorProcessingErrorPage(String location);

    @Message(id = 314, value = "Exception parsing number %s (zero based) of comma delimited list %s")
    IllegalArgumentException invalidNumberInList(int number, String list);

    @Message(id = 315, value = "Invalid HTTP port number specified %s")
    IllegalArgumentException invalidHttpPortNumber(String port);

    @Message(id = 316, value = "Invalid HTTPS port number specified %s")
    IllegalArgumentException invalidHttpsPortNumber(String port);

    @Message(id = 317, value = "WebDAV client problem: XP-x64-SP2 clients only work with the root context")
    String webDavClientProblemXpRootOnly();

    @Message(id = 318, value = "WebDAV client problem: XP-x64-SP2 is known not to work with WebDAV Servlet")
    String webDavClientProblemXp();

    @Message(id = 319, value = "Unknown mode %s, must be one of: strict, authOnly, strictAuthOnly")
    IllegalArgumentException unknownAuthMode(String authMode);

    @Message(id = 320, value = "Running CGI: bad header line: %s")
    String cgiInvalidHeader(String header);

    @Message(id = 321, value = "Error running CGI: %s")
    String cgiException(String errorMessage);

    @Message(id = 322, value = "Error closing header reader: %s")
    String cgiExceptionClosingHeaderReader(String errorMessage);

    @Message(id = 323, value = "Error closing output stream: %s")
    String cgiExceptionClosingOutputStream(String errorMessage);

    @Message(id = 324, value = "Interrupted waiting for stderr reader thread")
    String cgiInterrupted();

    @Message(id = 325, value = "Invalid HTTP status line: %s")
    String cgiInvalidStatusLine(String line);

    @Message(id = 326, value = "Invalid status code: %s")
    String cgiInvalidStatusCode(String code);

    @Message(id = 327, value = "Invalid status value: %s")
    String cgiInvalidStatusValue(String value);

    @Message(id = 328, value = "CGI stderr: %s")
    String cgiErrorLogPrefix(String line);

    @Message(id = 329, value = "Error reading error reader")
    String cgiStderrErrror();

    @Message(id = 330, value = "XSL transformer error")
    String xslTransformerError();

    @Message(id = 331, value = "Session %s expires processing failed")
    String errorProcessingSessionExpires(String sessionId);

    @Message(id = 332, value = "Error removing key %s")
    String errorRemovingKey(String sessionId);

    @Message(id = 333, value = "No nodes created")
    String ssiParseNoNodes();

    @Message(id = 334, value = "Extra nodes created")
    String ssiParseExtraNodes();

    @Message(id = 335, value = "Unused opp nodes exist")
    String ssiParseUnusedNodes();

    @Message(id = 336, value = "Couldn't exec file: %s")
    String ssiExecFailed(String file);

    @Message(id = 337, value = "#%s--Invalid attribute: %s")
    String ssiInvalidAttribute(String directive, String attribute);

    @Message(id = 338, value = "#flastmod--Couldn't get last modified for file: %s")
    String ssiFlastmodFailed(String file);

    @Message(id = 339, value = "#fsize--Couldn't get size for file: %s")
    String ssiFsizeFailed(String file);

    @Message(id = 340, value = "Num chars can't be negative")
    IllegalArgumentException invalidNumChars();

    @Message(id = 341, value = "#include--Couldn't include file: %s")
    String ssiIncludeFailed(String file);

    @Message(id = 342, value = "#echo--Invalid encoding: %s")
    String ssiEchoInvlidEncoding(String encoding);

    @Message(id = 343, value = "[an error occurred while processing this directive]")
    String ssiDirectiveError();

    @Message(id = 344, value = "Unknown encoding: %s")
    String ssiUnknownEncoding(String encoding);

    @Message(id = 345, value = "Unknown command: %s")
    String ssiUnknownCommand(String command);

    @Message(id = 346, value = "Error parsing command %s parameters")
    String ssiParsingErrorNoParameters(String directive);

    @Message(id = 347, value = "Parameter names count does not match parameter values count on command %s")
    String ssiParsingErrorBadParameterCount(String directive);

    @Message(id = 348, value = "#set--no variable specified")
    String ssiSetFailed();

    @Message(id = 349, value = "Couldn't remove filename from path: %s")
    String ssiFailedRemovingFilename(String path);

    @Message(id = 350, value = "Normalization yielded null on path: %s")
    String ssiFailedNormalization(String path);

    @Message(id = 351, value = "A non-virtual path can't be absolute: %s")
    String ssiInvalidNonVirtualPath(String path);

    @Message(id = 352, value = "A non-virtual path can't contain '../': %s")
    String ssiInvalidNonVirtualPathWithTraversal(String path);

    @Message(id = 353, value = "Couldn't get context for path: %s")
    String ssiCannotGetContext(String path);

    @Message(id = 354, value = "Couldn't remove context from path: %s")
    String ssiCannotRemoveContext(String path);

    @Message(id = 355, value = "Couldn't get request dispatcher for path: %s")
    String ssiCannotGetRequestDispatcher(String path);

    @Message(id = 356, value = "Couldn't find file: %s")
    String ssiCannotFindFile(String path);

    @Message(id = 357, value = "Couldn't include file: %s")
    String ssiServletIncludeFailed(String path);

    @Message(id = 358, value = "Message digest non initialized")
    IllegalStateException uninitializedMessageDigest();

    @Message(id = 359, value = "Exception releasing filter %s")
    String errorStoppingFilter(String filterName);

    @Message(id = 360, value = "Unable to cast to the internal request class in order to complete HTTP upgrade")
    String errorUpgrading();

    @Message(id = 361, value = "The buffer is not big enough to contain the message currently being processed")
    String bufferTooSmall();

    @Message(id = 362, value = "The client frame was not masked but all client frames must be masked")
    String frameNotMasked();

    @Message(id = 363, value = "A sequence of bytes was received that did not represent valid UTF-8")
    String frameInvalidUtf8();

    @Message(id = 364, value = "The end of the stream was reached when trying to read the first byte of a new WebSocket frame")
    String frameEos();

    @Message(id = 365, value = "Failed to read the first byte of the next WebSocket frame. The return value from the read was [%s]")
    String frameFailedRead(int value);

    @Message(id = 366, value = "An attempt was made to access the request object passed to WebSocketServlet.createWebSocketInbound() outside of that method")
    IllegalStateException invalidWrapper();

    @Message(id = 367, value = "A frame with the unrecognized OpCode [%s] was received")
    String frameUnknownOpcode(byte opcode);

    @Message(id = 368, value = "A frame with the OpCode [%s] was received when a continuation frame was expected")
    String frameNotContinuation(byte opcode);

    @Message(id = 369, value = "The WebSocket connection has been closed")
    String outboundClosed();

    @Message(id = 370, value = "Read listener already set")
    IllegalStateException readListenerAlreadySet();

    @Message(id = 371, value = "Write listener already set")
    IllegalStateException writeListenerAlreadySet();

    @Message(id = 372, value = "Upgrade error")
    String upgradeError();

    @Message(id = 373, value = "Upgrade destroy processing for servlet %s threw exception")
    String upgradeHandlerDestroyError(String servletName);

    @Message(id = 374, value = "IO listener processing for servlet %s threw exception")
    String ioListenerError(String servletName);

    @Message(id = 375, value = "Null read or write listener")
    NullPointerException nullListener();

    @Message(id = 376, value = "Cannot use a read or write listener without upgrading or starting async")
    IllegalStateException cannotSetListenerWithoutUpgradeOrAsync();

    @Message(id = 377, value = "Error getting keys")
    String errorGettingKeys();

    @Message(id = 378, value = "Ignored external entity %s %s %s %s")
    String ignoredExternalEntity(String name, String publicId, String baseUri, String systemId);

    @Message(id = 379, value = "Ignored external subset %s %s")
    String ignoredExternalSubset(String publicId, String systemId);

}


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

from __future__ import absolute_import
from __future__ import print_function

import datetime
import doctest
import os
import re
import unittest
from dsub.lib import job_util
from dsub.lib import param_util
import parameterized

PL = param_util.P_LOCAL
PG = param_util.P_GCS

class ParamUtilTest(unittest.TestCase):

  def testEnvParam(self):
    env_param = param_util.EnvParam('my_name', 'my_value')
    self.assertEqual('my_name', env_param.name)
    self.assertEqual('my_value', env_param.value)

  @parameterized.parameterized.expand([
      ('gl1', 'genre', 'jazz'),
      ('gl2', 'underscores_are', 'totally_ok'),
      ('gl3', 'dashes-are', 'also-ok'),
      ('gl4', 'num_123', 'good_456'),
      ('gl5', 'final_underscore_', 'ok_too_'),
      ('gl6', 'final-dash', 'no-problem-'),
      ('gl7', 'optional_value', ''),
      ('gl8', 'optional_value_2', None),
      ('gl9', 'a' * 63, 'not_too_long'),
      ('gl10', 'numbers-are-now-okay', '1'),
      ('gl11', 'zero-is-okay', '0'),
      ('gl12', 'initial_dash', '-abc'),
      ('gl13', 'initial_underscore', '_abc'),
  ])
  def test_good_labels(self, unused_name, name, value):
    label_param = param_util.LabelParam(name, value)
    self.assertEqual(name, label_param.name)
    self.assertEqual(value, label_param.value)

  @parameterized.parameterized.expand(
      [('bl1', 'WHATS', 'updog'),
       ('bl2', '1', 'initial_number'),
       ('bl4', '-', 'initial_dash'),
       ('bl6', 'spaces bad', ''),
       ('bl7', 'midCaps', 'bad'),
       ('bl8', 'bad', 'midCaps'),
       ('bl9', 'a' * 64, 'too_long'),
       ('bl10', '', 'name_required'),
       ('bl11', 'too_long', 'a' * 64)])  # pyformat: disable
  def test_bad_labels(self, unused_name, name, value):
    with self.assertRaises(ValueError):
      param_util.LabelParam(name, value)

  def testFileParam(self):
    file_param = param_util.FileParam(
        'my_name',
        'my_value',
        'my_docker_path',
        'my_remote_uri',
        recursive=True,
        file_provider=param_util.P_GCS)
    self.assertEqual('my_name', file_param.name)
    self.assertEqual('my_docker_path', file_param.docker_path)
    self.assertEqual('my_remote_uri', file_param.uri)
    self.assertTrue(file_param.recursive)

  def testParseTasksFileHeader(self):
    header = '--env SAMPLE_ID\t--input VCF_FILE\t--output-recursive OUTPUT_PATH'
    header = header.split('\t')
    input_file_param_util = param_util.InputFileParamUtil('input')
    output_file_param_util = param_util.OutputFileParamUtil('output')
    job_params = param_util.parse_tasks_file_header(
        header, input_file_param_util, output_file_param_util)
    self.assertEqual(3, len(job_params))

    # The first one is the SAMPLE env param.
    self.assertTrue(isinstance(job_params[0], param_util.EnvParam))
    self.assertEqual('SAMPLE_ID', job_params[0].name)

    self.assertTrue(isinstance(job_params[1], param_util.InputFileParam))
    self.assertEqual('VCF_FILE', job_params[1].name)
    self.assertFalse(job_params[1].recursive)

    self.assertTrue(isinstance(job_params[2], param_util.OutputFileParam))
    self.assertEqual('OUTPUT_PATH', job_params[2].name)
    self.assertTrue(job_params[2].recursive)

  def testTasksFileToJobData(self):
    expected_tsv_file = 'test/testdata/params_tasks.tsv'
    input_file_param_util = param_util.InputFileParamUtil('input')
    output_file_param_util = param_util.OutputFileParamUtil('output')
    all_job_data = param_util.tasks_file_to_job_data({
        'path': expected_tsv_file
    }, input_file_param_util, output_file_param_util)
    self.assertEqual(4, len(all_job_data))

    for i in range(4):
      job_data = all_job_data[i]
      self.assertEqual('SAMPLE_ID', job_data['envs'][0].name)
      self.assertEqual('sid-00%d' % i, job_data['envs'][0].value)
      self.assertEqual('VCF_FILE', job_data['inputs'][0].name)
      self.assertEqual('input/gs/inputs/sid-00%d.vcf' % i,
                       job_data['inputs'][0].docker_path)
      self.assertEqual('OUTPUT_PATH', job_data['outputs'][0].name)
      self.assertEqual('output/gs/outputs/results-00%d/' % i,
                       job_data['outputs'][0].docker_path)

  # Fixed values for age_to_create_time
  fixed_time = datetime.datetime(2017, 1, 1)
  fixed_time_utc = int(
      (fixed_time - datetime.datetime.utcfromtimestamp(0)).total_seconds())

  @parameterized.parameterized.expand([
      ('simple_second', '1s', fixed_time_utc - 1),
      ('simple_minute', '1m', fixed_time_utc - (1 * 60)),
      ('simple_hour', '1h', fixed_time_utc - (1 * 60 * 60)),
      ('simple_day', '1d', fixed_time_utc - (24 * 60 * 60)),
      ('simple_week', '1w', fixed_time_utc - (7 * 24 * 60 * 60)),
      ('simple_now', str(fixed_time_utc), fixed_time_utc),
  ])
  def test_compute_create_time(self, unused_name, age, expected):
    result = param_util.age_to_create_time(age, self.fixed_time)
    self.assertEqual(expected, result)

  @parameterized.parameterized.expand([
      ('bad_units', '1second'),
      ('overflow', '100000000w'),
  ])
  def test_compute_create_time_fail(self, unused_name, age):
    with self.assertRaisesRegexp(ValueError, 'Unable to parse age string'):
      _ = param_util.age_to_create_time(age)

class FileParamUtilTest(unittest.TestCase):

  @parameterized.parameterized.expand([
      ('lf', False, 'file:///tmp/myfile', 'file/tmp/myfile', PL),
      ('lf', False, '/tmp/myfile', 'file/tmp/myfile', PL),
      ('lf', False, '../../myfile', 'file/_dotdot_/_dotdot_/myfile', PL),
      ('lf', False, '~/tmp/myfile', 'file/_home_/tmp/myfile', PL),
      ('gf', False, 'gs://tmp/myfile', 'gs/tmp/myfile', PG),
      ('gf', False, 'gs://tmp/myfile', 'gs/tmp/myfile', PG),
      ('gf', False, 'gs://bucket/../myfile', 'gs/bucket/../myfile', PG),
      # Recursive tests for local and google
      ('lr', True, 'file:///tmp/myfile/', 'file/tmp/myfile/', PL),
      ('lr', True, '/tmp/myfile', 'file/tmp/myfile/', PL),
      ('lr', True, '../../myfile/', 'file/_dotdot_/_dotdot_/myfile/', PL),
      ('lr', True, '~/tmp/myfile', 'file/_home_/tmp/myfile/', PL),
      ('gr', True, 'gs://tmp/myfile/', 'gs/tmp/myfile/', PG),
      ('gr', True, 'gs://tmp/myfile', 'gs/tmp/myfile/', PG),
      ('gr', True, 'gs://bucket/../myfile', 'gs/bucket/../myfile/', PG),
      # wildcard tests for local and google.
      ('wc', False, 'gs://bucket/f/*.txt', 'gs/bucket/f/*.txt', PG),
      ('wc', False, 'gs://bucket/f/*', 'gs/bucket/f/*', PG),
      ('wc', False, '*.bam', 'file/*.bam', PL),
      ('wc', False, '../*', 'file/_dotdot_/*', PL),
  ])
  def test_input_file_docker_rewrite(self, _, recursive, uri, docker, provider):
    docker = os.path.join('input', docker)
    file_param_util = param_util.InputFileParamUtil('input')
    param = file_param_util.make_param('TEST', uri, recursive)
    self.assertIsInstance(param, param_util.InputFileParam)
    self.assertEqual('TEST', param.name)
    self.assertEqual(docker, param.docker_path)
    self.assertEqual(provider, param.file_provider)

  @parameterized.parameterized.expand([
      # Non-recursive tests for local and google
      ('lf', False, 'file:///tmp/myfile', 'file/tmp/myfile', PL),
      ('lf', False, '/tmp/myfile', 'file/tmp/myfile', PL),
      ('lf', False, '../../myfile', 'file/_dotdot_/_dotdot_/myfile', PL),
      ('lf', False, '~/tmp/myfile', 'file/_home_/tmp/myfile', PL),
      ('lf', False, '/a../myfile', 'file/a../myfile', PL),
      ('lf', False, '../myfile', 'file/_dotdot_/myfile', PL),
      ('gf', False, 'gs://tmp/myfile', 'gs/tmp/myfile', PG),
      ('gf', False, 'gs://tmp/myfile', 'gs/tmp/myfile', PG),
      ('gf', False, 'gs://bucket/../myfile', 'gs/bucket/../myfile', PG),
      # Recursive tests for local and google
      ('lr', True, 'file:///tmp/myfile/', 'file/tmp/myfile/', PL),
      ('lr', True, '/tmp/myfile', 'file/tmp/myfile/', PL),
      ('lr', True, '../../myfile/', 'file/_dotdot_/_dotdot_/myfile/', PL),
      ('lr', True, '~/tmp/myfile', 'file/_home_/tmp/myfile/', PL),
      ('gr', True, 'gs://tmp/myfile/', 'gs/tmp/myfile/', PG),
      ('gr', True, 'gs://tmp/myfile', 'gs/tmp/myfile/', PG),
      ('gr', True, 'gs://bucket/../myfile', 'gs/bucket/../myfile/', PG),
      # wildcard tests for local and google.
      ('wc', False, 'gs://bucket/f/*.txt', 'gs/bucket/f/*.txt', PG),
      ('wc', False, 'gs://bucket/f/*', 'gs/bucket/f/*', PG),
      ('wc', False, '*.bam', 'file/*.bam', PL),
      ('wc', False, '../*', 'file/_dotdot_/*', PL),
  ])
  def test_out_file_docker_rewrite(self, _, recursive, uri, docker, provider):
    docker = os.path.join('output', docker)
    file_param_util = param_util.OutputFileParamUtil('output')
    param = file_param_util.make_param('TEST', uri, recursive)
    self.assertIsInstance(param, param_util.OutputFileParam)
    self.assertEqual('TEST', param.name)
    self.assertEqual(docker, param.docker_path)
    self.assertEqual(provider, param.file_provider)

  @parameterized.parameterized.expand([
      # Non-recursive tests for local and google
      ('gf', False, 'gs://tmp/myfile', 'gs://tmp/', 'myfile', PG),
      ('gf', False, 'gs://buc/../myfile', 'gs://buc/../', 'myfile', PG),
      ('lf', False, 'file:///tmp/myfile', '/tmp/', 'myfile', PL),
      ('lf', False, '../myfile', '../', 'myfile', PL),
      # Tests with wildcards.
      ('gfwc', False, 'gs://tmp/*.bam', 'gs://tmp/', '*.bam', PG),
      ('gfwc', False, 'gs://tmp/*', 'gs://tmp/', '*', PG),
      ('gfwc', False, 'gs://bucket/../*', 'gs://bucket/../', '*', PG),
      ('lfwc', False, '../tmp/*.bam', '../tmp/', '*.bam', PL),
      ('lfwc', False, './*', './', '*', PL),
      ('localroot', False, '/*', '/', '*', PL),
      ('lfwc', False, '/tmp/*', '/tmp/', '*', PL),
      ('lfwc', False, '/bucket/*', '/bucket/', '*', PL),
      # Recursive tests for local and google
      ('lr', True, '/tmp/myfile/', '/tmp/myfile/', '', PL),
      ('lr', True, '../myfile', '../myfile/', '', PL),
      ('lr', True, './', './', '', PL),
      ('gr', True, 'gs://t/myfile/', 'gs://t/myfile/', '', PG),
      ('gr', True, 'gs://t/myfile', 'gs://t/myfile/', '', PG),
      ('gr', True, 'gs://buc/../myfile', 'gs://buc/../myfile/', '', PG),
  ])
  def test_uri_rewrite_out(self, _, recursive, raw_uri, path, bn, provider):
    # perpare the path if local.
    if provider == PL:
      path = os.path.abspath(path).rstrip('/') + '/'
    out_util = param_util.OutputFileParamUtil('')
    out_param = out_util.make_param('TEST', raw_uri, recursive=recursive)
    self.assertEqual(path, out_param.uri.path)
    self.assertEqual(bn, out_param.uri.basename)
    self.assertEqual(path + bn, out_param.uri)
    self.assertEqual(provider, out_param.file_provider)

  @parameterized.parameterized.expand([
      # Non-recursive tests for local and google
      ('gf', False, 'gs://tmp/myfile', 'gs://tmp/', 'myfile', PG),
      ('gf', False, 'gs://buc/../myfile', 'gs://buc/../', 'myfile', PG),
      ('lf', False, 'file:///tmp/myfile', '/tmp/', 'myfile', PL),
      ('lf', False, '../myfile', '../', 'myfile', PL),
      # Tests with wildcards.
      ('gfwc', False, 'gs://tmp/*.bam', 'gs://tmp/', '*.bam', PG),
      ('gfwc', False, 'gs://tmp/*', 'gs://tmp/', '*', PG),
      ('gfwc', False, 'gs://bucket/../*', 'gs://bucket/../', '*', PG),
      ('lfwc', False, '../tmp/*.bam', '../tmp/', '*.bam', PL),
      ('lfwc', False, './*', './', '*', PL),
      ('localroot', False, '/*', '/', '*', PL),
      ('lfwc', False, '/tmp/*', '/tmp/', '*', PL),
      ('lfwc', False, '/bucket/*', '/bucket/', '*', PL),
      # Recursive tests for local and google
      ('lr', True, '/tmp/myfile/', '/tmp/myfile/', '', PL),
      ('lr', True, '../myfile', '../myfile/', '', PL),
      ('lr', True, './', './', '', PL),
      ('gr', True, 'gs://t/myfile/', 'gs://t/myfile/', '', PG),
      ('gr', True, 'gs://t/myfile', 'gs://t/myfile/', '', PG),
      ('gr', True, 'gs://buc/../myfile', 'gs://buc/../myfile/', '', PG),
  ])
  def test_uri_rewrite_in(self, _, recursive, uri_raw, path, bn, provider):
    # perpare the path if local.
    if provider == PL:
      path = os.path.abspath(path).rstrip('/') + '/'
    in_util = param_util.InputFileParamUtil('')
    in_param = in_util.make_param('TEST', uri_raw, recursive=recursive)
    self.assertEqual(path, in_param.uri.path)
    self.assertEqual(bn, in_param.uri.basename)
    self.assertEqual(path + bn, in_param.uri)
    self.assertEqual(provider, in_param.file_provider)

  @parameterized.parameterized.expand([
      ('cant_use_wc', True, 'gs://tmp/myfile/*', 'only supported for files'),
      ('dir_wc', False, 'gs://b/yfile/*/*', 'only supported for files'),
      ('question', False, 'gs://b/myfile/?', 'Question mark'),
      ('recursive_wc', False, 'gs://b/myfile/**', 'Recursive'),
      ('no_filename_l', False, '../myfile/', 'not recursive must reference'),
      ('no_filename_g', False, 'gs://myfile/', 'not recursive must reference'),
  ])
  def test_output_val_err(self, unused_name, recursive, uri, regex):
    file_param_util = param_util.OutputFileParamUtil('output')
    with self.assertRaisesRegexp(ValueError, regex):
      file_param_util.parse_uri(uri, recursive)

  @parameterized.parameterized.expand([
      ('s3', 's3://b/myfile/', 'not supported: s3://'),
      ('gluster', 'gluster+tcp://myfile/', r'supported: gluster\+tcp://'),
      ('ftp', 'ftp://myfile/', 'not supported: ftp://'),
  ])
  def test_file_provider_err(self, unused_name, uri, regex):
    file_param_util = param_util.OutputFileParamUtil('output')
    with self.assertRaisesRegexp(ValueError, regex):
      file_param_util.parse_file_provider(uri)

  @parameterized.parameterized.expand([
      ('l', '/tmp/mydir/inner', '/tmp/mydir/inner/', PL),
      ('l_log', '/tmp/mydir/data.log', '/tmp/mydir/data.log', PL),
      ('l_indir', '/tmp/mydir/extra/../runner', '/tmp/mydir/runner/', PL),
      ('g', 'gs://bucket/mydir', 'gs://bucket/mydir/', PG),
      ('glog', 'gs://bucket/my.log', 'gs://bucket/my.log', PG),
  ])
  def test_logging_param_maker(self, unused_name, uri, expected_out, provider):
    param = param_util.build_logging_param(
        uri, util_class=param_util.OutputFileParamUtil)
    self.assertEqual(param.uri, expected_out)
    self.assertEqual(param.file_provider, provider)

class TestSubmitValidator(unittest.TestCase):

  def setUp(self):
    self.task_data = [
        {
            'inputs': [
                param_util.FileParam('IN', uri='gs://in/*', file_provider=PG)
            ],
            'outputs': []
        },
        {
            'inputs': [],
            'outputs': [
                param_util.FileParam('OUT', uri='gs://out/*', file_provider=PG)
            ]
        },
    ]

  def test_submit_validator_passes(self):
    resources = job_util.JobResources(logging=param_util.LoggingParam(
        'gs://buck/logs', PG))
    param_util.validate_submit_args_or_fail(
        job_resources=resources,
        job_data={'inputs': [],
                  'outputs': []},
        all_task_data=self.task_data,
        provider_name='MYPROVIDER',
        input_providers=[PG],
        output_providers=[PG],
        logging_providers=[PG])

  @parameterized.parameterized.expand([
      ('input', 'gs://in/*', [PL], [PG], [PG]),
      ('output', 'gs://out/*', [PG], [PL], [PG]),
      ('logging', 'gs://buck/logs', [PG], [PG], [PL]),
  ])
  def test_submit_validator_fails(self, name, path, inwl, outwl, logwl):
    resources = job_util.JobResources(logging=param_util.LoggingParam(
        'gs://buck/logs', PG))
    err_expected = 'Unsupported %s path (%s) for provider' % (name, path)
    with self.assertRaisesRegexp(ValueError, re.escape(err_expected)):
      param_util.validate_submit_args_or_fail(
          job_resources=resources,
          job_data={'inputs': [],
                    'outputs': []},
          all_task_data=self.task_data,
          provider_name='MYPROVIDER',
          input_providers=inwl,
          output_providers=outwl,
          logging_providers=logwl)

class TestParamUtilDocs(unittest.TestCase):

  def test_doctest(self):
    result = doctest.testmod(param_util, report=True)
    self.assertEqual(0, result.failed)

if __name__ == '__main__':
  unittest.main()

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Auth;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module implements AutoloaderProviderInterface {

    /**
     *
     * @return type
     */
    public function getConfig() {
        return include __DIR__ . '/config/module.config.php';
    }

    /**
     *
     * @return type
     */
    public function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    /**
     *
     * @return type
     */
    public function getViewHelperConfig() {
        return array(
            'factories' => array(
                'Auth' => function($sm) {
                    $auth = new \Auth\View\Helper\Auth();
                    $auth->setServiceManager($sm);
                    return $auth;
                }
            ),
        );
    }

    /**
     *
     * @return type
     */
    public function getServiceConfig() {
        return array(
            'factories' => [
                'Auth\Table\MyAuth' => function($sm) {

                    $sessionConfig = new \Zend\Session\Config\SessionConfig();
                    $sessionConfig->setOptions(array(
                        'cookie_lifetime' => 3600,
                        'gc_maxlifetime' => 3600,
                        'remember_me_seconds' => 3600,
                        'use_cookies' => true,
                    ));
                    $sessionManager = new \Zend\Session\SessionManager($sessionConfig);

                    return new \Auth\Table\MyAuth('auth', NULL, $sessionManager);
                },
                        'AuthService' => function($sm) {

                    $authService = new \Auth\Service\AuthService();
                    $authService->setServiceManager($sm);
                    return $authService->autenticar();
                }
                    ]
                );
            }

            /**
             *
             * @param \Zend\Mvc\MvcEvent $e
             */
            public function onBootstrap(MvcEvent $e) {
                $eventManager = $e->getApplication()->getEventManager();
                $moduleRouteListener = new ModuleRouteListener();
                $moduleRouteListener->attach($eventManager);

                $locale = 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3';

                if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {

                    $localeFromHttp = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

                    if (false === stripos($localeFromHttp, '-')) {

                        $locale = $localeFromHttp . '_' . strtoupper($localeFromHttp);
                    } else {

                        $locale = $localeFromHttp;
                    }
                }

                $translator = $e->getApplication()->getServiceManager()->get('translator');
                $translator->setLocale($locale)->setFallbackLocale('pt_BR');
            }

        }


text:
Santa's tor relay changes
#########################
:date: 2014-12-27 01:12
:author: kura
:category: tor
:tags: tor
:slug: santas-tor-relay-changes

.. contents::

Exiting relays
==============

Both `SpunkWeasel (865A408E2B1EA3E18C9A12E80A8D458F9C985C16) <https://globe.torproject.org/#/relay/865A408E2B1EA3E18C9A12E80A8D458F9C985C16>`_
and `AnorexicSquirrel (B8E6FFEB6F91FA3D26BC572836FB0ABBD142DC87) <https://globe.torproject.org/#/relay/B8E6FFEB6F91FA3D26BC572836FB0ABBD142DC87>`_
have been given additional horsepower in terms of CPU and memory and both have
been allowed to exit. Additionally, both are now capable of IPv6 connectivity
as guards, relays and exits.

New relays
==========

A new exit relay has been put online called `VivaciousAlpaca (24B1783665A9B0A4BF640A1CD02F685C0CA098ED)
<https://globe.torproject.org/#/relay/24B1783665A9B0A4BF640A1CD02F685C0CA098ED>`_.
It has the same CPU and memory as SpunkWeasel and AnorexicSquirrel and also
has full IPv6 capabilities.

A full list of my public Tor relays can be found on the `tor page
</tor/>`_.


text:
define([
    'underscore',
    'contrail-view'
], function (_, ContrailView) {
    var locationView = ContrailView.extend({
        el: $('#gohanGrid'),
        renderLocation: function (viewConfig) {
            this.renderView4Config(this.$el, null, getLocationViewConfig(viewConfig));
        }
    });

    function getLocationViewConfig(viewConfig) {
        return {
                elementId: cowu.formatElementId([ctwl.CFG_LOCATION_PAGE_ID]),
                view: "gcLocationListView",
                viewPathPrefix:
                    "config/gohanUi/location/ui/js/views/",
                app: cowc.APP_CONTRAIL_CONTROLLER,
                viewConfig: viewConfig
            }
    };
    return locationView;
});


text:
using System;
using System.Xml;
using MonoDevelop.Core;
using MonoDevelop.Projects;

namespace MonoDevelop.ATSBinding
{
    public class ATSLanguageBinding : IDotNetLanguageBinding
    {
        public string BlockCommentEndTag
        {
            get { return "*/"; }
        }

        public string BlockCommentStartTag
        {
            get { return "/*"; }
        }

        public string Language
        {
            get { return "ATS"; }
        }

        public string SingleLineCommentTag
        {
            get { return "//"; }
        }

        public FilePath GetFileName(FilePath fileNameWithoutExtension)
        {
            return fileNameWithoutExtension.ChangeExtension(".dats");
        }

        public static bool IsDATSFile(string fileName)
        {
            return fileName.EndsWith(".dats", System.StringComparison.OrdinalIgnoreCase);
        }
        public static bool IsSATSFile(string fileName)
        {
            return fileName.EndsWith(".sats", System.StringComparison.OrdinalIgnoreCase);
        }

        public bool IsSourceCodeFile(FilePath fileName)
        {
            return IsDATSFile(fileName) || IsSATSFile(fileName);
        }

        public BuildResult Compile(ProjectItemCollection items, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) {
            return new BuildResult("failed", 1, 1);
        }

        public ConfigurationParameters CreateCompilationParameters(XmlElement projectOptions) {
            return new UnknownCompilationParameters();
        }

        public ProjectParameters CreateProjectParameters(XmlElement projectOptions) {
            return new ProjectParameters();
        }

        public System.CodeDom.Compiler.CodeDomProvider GetCodeDomProvider() {
            return null;
        }

        public ClrVersion[] GetSupportedClrVersions() {
            return new[]{ ClrVersion.Net_4_0 };
        }

        public string ProjectStockIcon {
            get { return "md-project"; }
        }
    }
}


text:
#include "ui/UIEditBox/UIEditBoxImpl-win32.h"

#include "platform/CCPlatformConfig.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

#include "ui/UIEditBox/UIEditBox.h"
#include <tchar.h>
#include <stdio.h>
#include "2d/CCLabel.h"
#include "base/CCDirector.h"
#include "base/ccUTF8.h"
#include <Commctrl.h>
#include <windows.h>
#include "ui/UIHelper.h"

NS_CC_BEGIN

namespace ui {

    bool EditBoxImplWin::s_isInitialized = false;
    int EditBoxImplWin::s_editboxChildID = 100;
    HWND EditBoxImplWin::s_previousFocusWnd = 0;
    WNDPROC EditBoxImplWin::s_prevCocosWndProc = 0;
    HINSTANCE EditBoxImplWin::s_hInstance = 0;
    HWND EditBoxImplWin::s_hwndCocos = 0;

    void EditBoxImplWin::lazyInit()
    {
        s_hwndCocos = cocos2d::Director::getInstance()->getOpenGLView()->getWin32Window();
        LONG style = ::GetWindowLongW(s_hwndCocos, GWL_STYLE);
        ::SetWindowLongW(s_hwndCocos, GWL_STYLE, style | WS_CLIPCHILDREN);
        s_isInitialized = true;
        s_previousFocusWnd = s_hwndCocos;

        s_hInstance = ::GetModuleHandleW(nullptr);

        s_prevCocosWndProc = (WNDPROC)SetWindowLongPtrW(s_hwndCocos, GWL_WNDPROC, (LONG_PTR)hookGLFWWindowProc);
    }

    EditBoxImpl* __createSystemEditBox(EditBox* pEditBox)
    {
        return new (std::nothrow) EditBoxImplWin(pEditBox);
    }

    EditBoxImplWin::EditBoxImplWin(EditBox* pEditText)
        : EditBoxImplCommon(pEditText),
        _changedTextManually(false),
        _hasFocus(false),
        _endAction(EditBoxDelegate::EditBoxEndAction::UNKNOWN)
    {
        if (!s_isInitialized)
        {
            lazyInit();
        }

        s_editboxChildID++;
    }

    EditBoxImplWin::~EditBoxImplWin()
    {
        this->cleanupEditCtrl();
    }

    bool EditBoxImplWin::isEditing()
    {
        return false;
    }

    void EditBoxImplWin::cleanupEditCtrl()
    {
        if (_hwndEdit)
        {
            SetWindowLongPtrW(_hwndEdit, GWL_WNDPROC, (LONG_PTR)_prevWndProc);
            ::DestroyWindow(_hwndEdit);
            _hasFocus = false;
            _changedTextManually = false;
            _editingMode = false;
            _hwndEdit = NULL;
        }
    }

    void EditBoxImplWin::createEditCtrl(bool singleLine)
    {
        this->cleanupEditCtrl();
        if (!_hwndEdit)
        {
            _hwndEdit = ::CreateWindowExW(
                WS_EX_CLIENTEDGE, L"EDIT",   // predefined class
                NULL,         // no window title
                WS_CHILD | ES_LEFT | WS_BORDER | WS_EX_TRANSPARENT | WS_TABSTOP | ES_AUTOHSCROLL | (singleLine ? 0 : ES_MULTILINE),
                0,
                0,
                0,
                0,   // set size in WM_SIZE message
                s_hwndCocos,         // parent window
                (HMENU)s_editboxChildID,   // edit control ID
                s_hInstance,
                this);        // pointer not needed

            SetWindowLongPtrW(_hwndEdit, GWL_USERDATA, (LONG_PTR)this);
            _prevWndProc = (WNDPROC)SetWindowLongPtrW(_hwndEdit, GWL_WNDPROC, (LONG_PTR)WindowProc);

            ::SendMessageW(_hwndEdit, EM_LIMITTEXT, this->_maxLength, 0);
            s_previousFocusWnd = s_hwndCocos;
            this->setNativeFont(this->getNativeDefaultFontName(), this->_fontSize);
            this->setNativeText(this->_text.c_str());
        }
    }

    void EditBoxImplWin::createNativeControl(const Rect& frame)
    {
        this->createEditCtrl(false);
    }

    void EditBoxImplWin::setNativeFont(const char* pFontName, int fontSize)
    {
        auto glView = Director::getInstance()->getOpenGLView();
        HFONT hFont = ::CreateFontW(static_cast<int>(fontSize * glView->getScaleX()), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS,
            CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, L"Arial");

        ::SendMessageW(_hwndEdit,             // Handle of edit control
            WM_SETFONT,         // Message to change the font
            (WPARAM)hFont,     // handle of the font
            MAKELPARAM(TRUE, 0) // Redraw text
        );
    }

    void EditBoxImplWin::setNativeFontColor(const Color4B& color)
    {
        //not implemented yet
    }

    void EditBoxImplWin::setNativePlaceholderFont(const char* pFontName, int fontSize)
    {
        //not implemented yet
    }

    void EditBoxImplWin::setNativePlaceholderFontColor(const Color4B& color)
    {
        //not implemented yet
    }

    void EditBoxImplWin::setNativeInputMode(EditBox::InputMode inputMode)
    {
        if (_editBoxInputMode == cocos2d::ui::EditBox::InputMode::ANY)
        {
            this->createEditCtrl(false);
        }
        else if (_editBoxInputMode == cocos2d::ui::EditBox::InputMode::NUMERIC
            || _editBoxInputMode == cocos2d::ui::EditBox::InputMode::DECIMAL
            || _editBoxInputMode == cocos2d::ui::EditBox::InputMode::PHONE_NUMBER)
        {
            this->createEditCtrl(true);
            ::SetWindowLongW(_hwndEdit, GWL_STYLE, ::GetWindowLongW(_hwndEdit, GWL_STYLE) | ES_NUMBER);
        }
        else
        {
            this->createEditCtrl(true);
        }

        if (this->_editBoxInputFlag != cocos2d::ui::EditBox::InputFlag::PASSWORD)
        {
            ::PostMessageW(_hwndEdit, EM_SETPASSWORDCHAR, (WPARAM)0, (LPARAM)0);
        }
    }
    void EditBoxImplWin::setNativeInputFlag(EditBox::InputFlag inputFlag)
    {
        if (inputFlag == EditBox::InputFlag::PASSWORD)
        {
            this->createEditCtrl(true);
        }
        else
        {
            if (_editBoxInputMode != cocos2d::ui::EditBox::InputMode::ANY)
            {
                this->createEditCtrl(true);

                if (inputFlag == EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS)
                {
                    ::SetWindowLongW(_hwndEdit, GWL_STYLE, ::GetWindowLongW(_hwndEdit, GWL_STYLE) | ES_UPPERCASE);
                }
                // Clear the password style
                ::PostMessageW(_hwndEdit, EM_SETPASSWORDCHAR, (WPARAM)0, (LPARAM)0);
            }
        }
    }

    void EditBoxImplWin::setNativeReturnType(EditBox::KeyboardReturnType returnType)
    {
        //not implemented yet
    }

    void EditBoxImplWin::setNativeTextHorizontalAlignment(TextHAlignment alignment)
    {
        LONG style = ::GetWindowLongW(_hwndEdit, GWL_STYLE);
        switch (alignment)
        {
        case TextHAlignment::LEFT:
            style = (style & ~ES_CENTER & ~ES_RIGHT) | ES_LEFT;
            break;
        case TextHAlignment::CENTER:
            style = (style & ~ES_LEFT & ~ES_RIGHT) | ES_CENTER;
            break;
        case TextHAlignment::RIGHT:
            style = (style & ~ES_LEFT & ~ES_CENTER) | ES_RIGHT;
            break;
        }
        ::SetWindowLongW(_hwndEdit, GWL_STYLE, style);
    }

    void EditBoxImplWin::setNativeText(const char* pText)
    {
        std::u16string utf16Result;
        std::string text(pText);
        cocos2d::StringUtils::UTF8ToUTF16(text, utf16Result);
        this->_changedTextManually = true;
        ::SetWindowTextW(_hwndEdit, (LPCWSTR)utf16Result.c_str());
        int textLen = text.size();
        ::SendMessageW(_hwndEdit, EM_SETSEL, textLen, textLen);

        if (_editBoxInputMode == cocos2d::ui::EditBox::InputMode::ANY)
        {
            ::SendMessageW(_hwndEdit, EM_SCROLLCARET, 0, 0);
        }
    }

    void EditBoxImplWin::setNativePlaceHolder(const char* pText)
    {
        //not implemented yet
    }

    void EditBoxImplWin::setNativeVisible(bool visible)
    {
        if (visible)
        {
            ::ShowWindow(_hwndEdit, SW_SHOW);
        }
        else
        {
            ::ShowWindow(_hwndEdit, SW_HIDE);
        }
    }

    void EditBoxImplWin::updateNativeFrame(const Rect& rect)
    {
        ::SetWindowPos(
            _hwndEdit,
            HWND_NOTOPMOST,
            rect.origin.x,
            rect.origin.y,
            rect.size.width,
            rect.size.height,
            SWP_NOZORDER);
    }

    const char* EditBoxImplWin::getNativeDefaultFontName()
    {
        return "Arial";
    }

    void EditBoxImplWin::nativeOpenKeyboard()
    {
        ::PostMessageW(_hwndEdit, WM_SETFOCUS, (WPARAM)s_previousFocusWnd, 0);
//        s_previousFocusWnd = hwndEdit;
        this->editBoxEditingDidBegin();

        auto rect = ui::Helper::convertBoundingBoxToScreen(_editBox);
        this->updateNativeFrame(rect);
    }

    void EditBoxImplWin::nativeCloseKeyboard()
    {
        //don't need to implement
    }

    void EditBoxImplWin::setNativeMaxLength(int maxLength)
    {
        ::SendMessageW(_hwndEdit, EM_LIMITTEXT, maxLength, 0);
    }

    void EditBoxImplWin::_WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        switch (uMsg)
        {
        case WM_CHAR:
            if (wParam == VK_RETURN)
            {
                if (_editBoxInputMode != cocos2d::ui::EditBox::InputMode::ANY) {
                    if (s_previousFocusWnd != s_hwndCocos) {
                        switch (_keyboardReturnType)
                        {
                        case EditBox::KeyboardReturnType::DEFAULT:
                            _endAction = EditBoxDelegate::EditBoxEndAction::UNKNOWN;
                            break;
                        case EditBox::KeyboardReturnType::DONE:
                            _endAction = EditBoxDelegate::EditBoxEndAction::RETURN;
                            break;
                        case EditBox::KeyboardReturnType::SEND:
                            _endAction = EditBoxDelegate::EditBoxEndAction::RETURN;
                            break;
                        case EditBox::KeyboardReturnType::SEARCH:
                            _endAction = EditBoxDelegate::EditBoxEndAction::RETURN;
                            break;
                        case EditBox::KeyboardReturnType::GO:
                            _endAction = EditBoxDelegate::EditBoxEndAction::RETURN;
                            break;
                        case EditBox::KeyboardReturnType::NEXT:
                            _endAction = EditBoxDelegate::EditBoxEndAction::TAB_TO_NEXT;
                            break;
                        default:
                            _endAction = EditBoxDelegate::EditBoxEndAction::UNKNOWN;
                            break;
                        }
                        ::ShowWindow(s_previousFocusWnd, SW_HIDE);
                        ::SendMessageW(s_hwndCocos, WM_SETFOCUS, (WPARAM)s_previousFocusWnd, 0);
                        s_previousFocusWnd = s_hwndCocos;
                    }
                }
            }
            break;
        case WM_SETFOCUS:
            if (hwnd != s_previousFocusWnd)
            {
                ::PostMessageW(hwnd, WM_ACTIVATE, (WPARAM)s_previousFocusWnd, 0);
                ::PostMessageW(hwnd, WM_SETCURSOR, (WPARAM)s_previousFocusWnd, 0);
                s_previousFocusWnd = _hwndEdit;
                _hasFocus = true;
                this->_changedTextManually = false;
            }
            break;
        case WM_KILLFOCUS:
            _hasFocus = false;
            //when app enter background, this message also be called.
            if (this->_editingMode && !::IsWindowVisible(hwnd))
            {
                this->editBoxEditingDidEnd(this->getText(), _endAction);
            }
            break;
        default:
            break;
        }
    }

    std::string EditBoxImplWin::getText() const
    {
        std::u16string wstrResult;
        std::string utf8Result;

        int inputLength = ::GetWindowTextLengthW(_hwndEdit);
        wstrResult.resize(inputLength);

        ::GetWindowTextW(_hwndEdit, (LPWSTR)&wstrResult[0], inputLength + 1);
        bool conversionResult = cocos2d::StringUtils::UTF16ToUTF8(wstrResult, utf8Result);
        if (!conversionResult)
        {
            CCLOG("warning, editbox input text conversion error.");
        }
        return std::move(utf8Result);
    }

    LRESULT EditBoxImplWin::hookGLFWWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        switch (uMsg)
        {
        case WM_COMMAND:
            if (HIWORD(wParam) == EN_CHANGE) {
                EditBoxImplWin* pThis = (EditBoxImplWin*)GetWindowLongPtrW((HWND)lParam, GWLP_USERDATA);
                if (pThis && !pThis->_changedTextManually)
                {
                    pThis->editBoxEditingChanged(pThis->getText());
                    pThis->_changedTextManually = false;
                }

            }
            break;
        case WM_LBUTTONDOWN:
            if (s_previousFocusWnd != s_hwndCocos) {
                ::ShowWindow(s_previousFocusWnd, SW_HIDE);

                EditBoxImplWin* pThis = (EditBoxImplWin*)GetWindowLongPtrW(s_previousFocusWnd, GWLP_USERDATA);
                if (pThis!=nullptr && !pThis->_hasFocus)
                {
                    if (pThis->_editingMode && !IsWindowVisible(s_previousFocusWnd))
                    {
                        pThis->editBoxEditingDidEnd(pThis->getText());
                    }
                }
                else
                {
                    ::PostMessageW(s_hwndCocos, WM_SETFOCUS, (WPARAM)s_previousFocusWnd, 0);
                }
                s_previousFocusWnd = s_hwndCocos;
            }

            break;
        default:
            break;
        }

        return ::CallWindowProcW(s_prevCocosWndProc, hwnd, uMsg, wParam, lParam);
    }

    LRESULT EditBoxImplWin::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        EditBoxImplWin* pThis = (EditBoxImplWin*)GetWindowLongPtrW(hwnd, GWLP_USERDATA);
        if (pThis)
        {
            pThis->_WindowProc(hwnd, uMsg, wParam, lParam);
        }

        return ::CallWindowProcW(pThis->_prevWndProc, hwnd, uMsg, wParam, lParam);
    }
}

NS_CC_END

#endif /* (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) */


text:
from __future__ import division
from __future__ import unicode_literals

# look here for improvements...
# http://www.arnebrodowski.de/blog/write-your-own-restructuredtext-writer.html

import codecs
import os
import xml.etree.ElementTree as ET

from subprocess import Popen, PIPE

from django.utils.safestring import mark_safe

from docutils.core import publish_parts
from docutils.writers import latex2e

class MyLatexWriter(latex2e.Writer):

    def __init__(self, initial_header_level=1):
        latex2e.Writer.__init__(self)
        if initial_header_level == 2:
            self.translator_class = MyLatexTranslator2
        elif initial_header_level == 1:
            self.translator_class = MyLatexTranslator1
        else:
            self.translator_class = MyLatexTranslator0

class MyLatexTranslator2(latex2e.LaTeXTranslator):
    section_level = 2

    def __init__(self, node):
        latex2e.LaTeXTranslator.__init__(self, node)
        self._section_number = self.section_level*[0]

class MyLatexTranslator1(latex2e.LaTeXTranslator):
    section_level = 1

    def __init__(self, node):
        latex2e.LaTeXTranslator.__init__(self, node)
        self._section_number = self.section_level*[0]

class MyLatexTranslator0(latex2e.LaTeXTranslator):
    section_level = 0

    def __init__(self, node):
        latex2e.LaTeXTranslator.__init__(self, node)
        self._section_number = self.section_level*[0]

def rst2xml(source, part='whole'):
    source = '.. default-role:: math\n\n' + source
    writer_name = 'xml'
    settings_overrides = {}

    text = publish_parts(
        source=source,
        writer_name=writer_name,
        settings_overrides=settings_overrides,
    )[part].strip()

    root = ET.fromstring(text.encode('utf-8'))
    return root

def rst2html(source, initial_header_level=2, inline=False, part='body'):

    source = '.. default-role:: math\n\n' + source
    writer_name = 'html'
    settings_overrides = {
        'compact_lists' : True,
        'footnote_references' : 'superscript',
        'math_output' : 'MathJax',
        'stylesheet_path' : None,
        'initial_header_level' : initial_header_level,
        # 'doctitle_xform' : 0,
    }

    html = publish_parts(
        source=source,
        writer_name=writer_name,
        settings_overrides=settings_overrides,
    )[part].strip()

    if inline:
        if html[:3] == '<p>' and html[-4:] == '</p>':
            html = html[3:-4]

    html = html.replace('...','…')
    html = html.replace('---','—')
    html = html.replace('--','–')
    # oops ... need to reverse these back
    html = html.replace('<!–','<!--')
    html = html.replace('–>','-->')

    return mark_safe(html)

def rst2latex(source, initial_header_level=-1, part='body'):
    source = source.replace('\'"','\' "')
    source = '.. default-role:: math\n\n' + source
    writer = MyLatexWriter(initial_header_level)
    settings_overrides = {
        'use_latex_docinfo': True,
    }

    latex = publish_parts(
        source=source,
        writer=writer,
        settings_overrides=settings_overrides,
    )[part]
    latex = latex.replace('-{}','-') # unwind this manipulation from docutils
    latex = latex.replace("' ''","'\\,''")
    latex = latex.replace(" '"," `")

    return latex.strip()


text:
require File.expand_path('../../../spec_helper', __FILE__)

module Backup
describe 'Database::Redis' do

  specify 'No SAVE, no Compression' do
    create_model :my_backup, <<-EOS
      Backup::Model.new(:my_backup, 'a description') do
        database Redis do |db|
          db.path = '/var/lib/redis'
        end
        store_with Local
      end
    EOS

    job = backup_perform :my_backup

    expect( job.package.exist? ).to be_true
    expect( job.package ).to match_manifest(%q[
      5774  my_backup/databases/Redis.rdb
    ])
  end

  specify 'SAVE, no Compression' do
    create_model :my_backup, <<-EOS
      Backup::Model.new(:my_backup, 'a description') do
        database Redis do |db|
          db.path = '/var/lib/redis'
          db.invoke_save = true
        end
        store_with Local
      end
    EOS

    job = backup_perform :my_backup

    expect( job.package.exist? ).to be_true
    expect( job.package ).to match_manifest(%q[
      5774  my_backup/databases/Redis.rdb
    ])
  end

  specify 'SAVE, with Compression' do
    create_model :my_backup, <<-EOS
      Backup::Model.new(:my_backup, 'a description') do
        database Redis do |db|
          db.path = '/var/lib/redis'
          db.invoke_save = true
        end
        compress_with Gzip
        store_with Local
      end
    EOS

    job = backup_perform :my_backup

    expect( job.package.exist? ).to be_true
    expect( job.package ).to match_manifest(%q[
      1900..1950  my_backup/databases/Redis.rdb.gz
    ])
  end

  specify 'Multiple Dumps' do
    create_model :my_backup, <<-EOS
      Backup::Model.new(:my_backup, 'a description') do
        database Redis, :dump_01 do |db|
          db.path = '/var/lib/redis'
        end
        database Redis, 'Dump #2' do |db|
          db.path = '/var/lib/redis'
        end
        store_with Local
      end
    EOS

    job = backup_perform :my_backup

    expect( job.package.exist? ).to be_true
    expect( job.package ).to match_manifest(%q[
      5774  my_backup/databases/Redis-dump_01.rdb
      5774  my_backup/databases/Redis-Dump__2.rdb
    ])
  end

end
end


text:
import requests
from requests.compat import urljoin
from bs4 import BeautifulSoup

from util import sendmail

import time

URL_BASE = 'https://selfservice.mypurdue.purdue.edu/prod/bwckschd.p_disp_detail_sched?term_in=%s&crn_in=%s'
SENDER = 'the.agent.pete@gmail.com'

class Agent:
  headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}

  def __init__(self, sid, server, term, crn):
    self.sid = sid
    self.server = server
    self.term = term
    self.crn = crn

  def get_html(self, url):
    resp = requests.get(url, headers=self.headers)
    return resp.content

  def parse(self, html):
    soup = BeautifulSoup(html, 'html.parser')
    capacity = int(soup.select('tr td[class~=dddefault]')[1].text)
    remaining = int(soup.select('tr td[class~=dddefault]')[3].text)
    return remaining, capacity

  def report(self, remaining, capacity):
    url = urljoin(self.server, 'report')
    data = {
      'sid': self.sid,
      'term': self.term,
      'crn': self.crn,
      'remaining': remaining,
      'capacity': capacity
    }
    resp = requests.post(url, data=data)
    notis = resp.json()['notifications']
    for n in notis:
      self.notify(n)

  def notify(self, notification):
    sender = SENDER
    receiver = '%s@purdue.edu' % notification['username']
    subject, content = self.build_notification_body(notification)
    sendmail(sender, receiver, subject, content)

    crns = ','.join(map(lambda x: x['crn'], notification['sections']))
    print 'Sent mail to %s for %s' % (notification['username'], crns)

  def build_notification_body(self, notification):
    secs = notification['sections']
    coursename = secs[0]['coursename']

    title = '
%s
\n' % coursename
    body = title
    url = 'mypurdue.purdue.edu'

    hl = ''
    for s in secs:
      hl += '
%s	%s	%d/%d	' % (s['term'], s['crn'], s['remaining'], s['capacity'])
    title = '
Available Courses
\n'
    hl = '%s\n
\n%s
\n' % (title, hl)

    subject = '%s is available as of now' % coursename
    body = '
%s
\n\n\n%s\n%s' % (subject, hl, body)
    body += '\n\n\n%s\n' % (url, url)
    content = '\n%s\n\n' % body

    return subject, content

  def run(self):
    url = URL_BASE % (self.term, self.crn)
    html = self.get_html(url)
    rem, cap = self.parse(html)
    self.report(rem, cap)

if __name__ == '__main__':
  POOL_SIZE = 20
  REQUEST_COUNT = 100

  sid = '0'
  server = ''
  term = '201620'
  crns = ['10646', '12888', '14429', '12879', '12877', '14428']
  cnt = len(crns)
  crns = [crns[i % cnt] for i in xrange(REQUEST_COUNT)]

  def report(self, rem, cap):
    print '[crn %s] %d / %d' % (self.crn, rem, cap)
  Agent.report = report

  def spawn(crn):
    return Agent(sid, server, term, crn).run()

  from multiprocessing import Pool
  res = Pool(POOL_SIZE).map(spawn, crns)

  print 'Pool size: %d' % POOL_SIZE
  print 'CRNs: %d' % len(crns)


text:
from django.db import models

# Create your models here.

class User(models.Model):
	user_id = models.CharField(max_length=50)
	password = models.CharField(max_length=256)
	confirm_password = models.CharField(max_length=256)
	email = models.EmailField(max_length=100)
	is_active = models.BooleanField('Active?', default=True)

	def __unicode__(self):
		return self.user_id

	def get_absolute_url(self):
		return reverse('register_edit', kwargs={'pk': self.pk})


text:
<?php

namespace Omnipay\Mollie\Message\Response;

use Omnipay\Common\ItemBag;
use Omnipay\Mollie\Item;

/**
 * @see https://docs.mollie.com/reference/v2/payments-api/get-order
 */
class FetchOrderResponse extends FetchTransactionResponse
{
    public function getLines()
    {
        if (isset($this->data['lines'])) {
            return $this->data['lines'];
        }

        return null;
    }

    public function getItems()
    {

        if (isset($this->data['lines'])) {
            $items = [];

            foreach ($this->data['lines'] as $line) {
                $items[] = new Item($line);
            }

            return new ItemBag($items);
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__char_fscanf_square_84.h
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-84.tmpl.h
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: square
 *    GoodSink: Ensure there will not be an overflow before squaring data
 *    BadSink : Square data, which can lead to overflow
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */

#include "std_testcase.h"

namespace CWE190_Integer_Overflow__char_fscanf_square_84
{

#ifndef OMITBAD

class CWE190_Integer_Overflow__char_fscanf_square_84_bad
{
public:
    CWE190_Integer_Overflow__char_fscanf_square_84_bad(char dataCopy);
    ~CWE190_Integer_Overflow__char_fscanf_square_84_bad();

private:
    char data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE190_Integer_Overflow__char_fscanf_square_84_goodG2B
{
public:
    CWE190_Integer_Overflow__char_fscanf_square_84_goodG2B(char dataCopy);
    ~CWE190_Integer_Overflow__char_fscanf_square_84_goodG2B();

private:
    char data;
};

class CWE190_Integer_Overflow__char_fscanf_square_84_goodB2G
{
public:
    CWE190_Integer_Overflow__char_fscanf_square_84_goodB2G(char dataCopy);
    ~CWE190_Integer_Overflow__char_fscanf_square_84_goodB2G();

private:
    char data;
};

#endif /* OMITGOOD */

}


text:
import { isFunction, isNumber } from 'lodash-es';
import initialize from '../initialize';
export default function number(
  defaultValue?: number | ((x: any) => any),
  ...args: Array<(x: any) => any>): PropertyDecorator {
  if (isFunction(defaultValue)) {
    args.unshift(defaultValue);
    defaultValue = 0;
  } else if (!isNumber(defaultValue)) {
    defaultValue = 0;
  }
  args.unshift(function(value) {
    return isNumber(value) ? value : defaultValue;
  });
  return (initialize(...args) as PropertyDecorator);
}