text:
$(document).ready(function() {

     $.noConflict();
     $('#siblh_mantenimientobundle_blhdonacion_fechaDonacion').
        attr('data-bvalidator', 'required');

     $.datepicker.setDefaults($.datepicker.regional["es"]);
   $('input[id$="_fechaDonacion"]').datepicker({ dateFormat: 'yy-mm-dd',
                           changeMonth: true,
                           changeYear: true,
                           clearStatus: 'Borra fecha actual',
                           defaultDate: 'today',
                           minDate: 'today',
                           maxDate: 'today',
                          // yearRange: '2012:y',
                           dayNamesMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"],
                           monthNamesShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun",
                                             "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"]
                          });

    var optionsRed = {
        classNamePrefix: 'bvalidator_red_',
        lang: 'es'
    };

    //Validar el formulario
    $('form').bValidator(optionsRed);

$(function() {
    $( document ).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function( position, feedback ) {
          $( this ).css( position );
          $( "<div>" )
            .addClass( "arrow" )
            .addClass( feedback.vertical )
            .addClass( feedback.horizontal )
            .appendTo( this );
        }
      }
    });

           });

    $('#button').button();
   $('#boton1').button();

    $('#responsable').on ('click', function() {
    $('#siblh_mantenimientobundle_blhdonacion_responsableDonacion').val (this.value);
    ;
    });

});

redpajama_set_name: RedPajamaGithub


text:
class Api::V1::UsersController < Api::V1::BaseController
  def show
    respond_with current_user, serializer: Api::V1::UserSerializer
  end
end


text:
package org.xins.client;

import java.util.HashMap;
import org.xins.common.FormattedParameters;

import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.Utils;
import org.xins.common.collections.PropertyReader;
import org.xins.common.http.HTTPCallConfig;
import org.xins.common.http.HTTPCallException;
import org.xins.common.http.HTTPCallRequest;
import org.xins.common.http.HTTPCallResult;
import org.xins.common.http.HTTPServiceCaller;
import org.xins.common.http.StatusCodeHTTPCallException;
import org.xins.common.service.CallConfig;
import org.xins.common.service.CallException;
import org.xins.common.service.CallExceptionList;
import org.xins.common.service.CallRequest;
import org.xins.common.service.CallResult;
import org.xins.common.service.ConnectionTimeOutCallException;
import org.xins.common.service.ConnectionRefusedCallException;
import org.xins.common.service.Descriptor;
import org.xins.common.service.GenericCallException;
import org.xins.common.service.IOCallException;
import org.xins.common.service.ServiceCaller;
import org.xins.common.service.SocketTimeOutCallException;
import org.xins.common.service.TargetDescriptor;
import org.xins.common.service.TotalTimeOutCallException;
import org.xins.common.service.UnexpectedExceptionCallException;
import org.xins.common.service.UnknownHostCallException;
import org.xins.common.service.UnsupportedProtocolException;
import org.xins.common.spec.ErrorCodeSpec;
import org.xins.common.text.ParseException;
import org.xins.common.text.TextUtils;
import org.xins.common.xml.Element;

/**
 * XINS service caller. This class can be used to perform a call to a XINS
 * service, over HTTP, and fail-over to other XINS services if the first one
 * fails.
 *
 *
Supported protocols

 *
 *
This service caller currently only supports the HTTP protocol. If a
 * {@link TargetDescriptor} is passed to the constructor with a different
 * protocol, then an {@link UnsupportedProtocolException} is thrown. In the
 * future, HTTPS and other protocols are expected to be supported as well.
 *
 *
Load-balancing and fail-over

 *
 *
To perform a XINS call, use {@link #call(XINSCallRequest)}. Fail-over
 * and load-balancing can be performed automatically.
 *
 *
How load-balancing is done depends on the {@link Descriptor} passed to
 * the {@link #XINSServiceCaller(Descriptor)} constructor. If it is a
 * {@link TargetDescriptor}, then only this single target service is called
 * and no load-balancing is performed. If it is a
 * {@link org.xins.common.service.GroupDescriptor}, then the configuration of
 * the GroupDescriptor determines how the load-balancing is done.
 * A GroupDescriptor is a recursive data structure, which allows
 * for fairly advanced load-balancing algorithms.
 *
 *
If a call attempt fails and there are more available target services,
 * then the XINSServiceCaller may or may not fail-over to a next
 * target. If the request was not accepted by the target service, then
 * fail-over is considered acceptable and will be performed. This includes
 * the following situations:
 *
 *

 *
if the failOverAllowed property is set to true
 *        for the {@link XINSCallRequest};
 *
on connection refusal;
 *
if a connection attempt times out;
 *
if an HTTP status code other than 200-299 is returned;
 *
if the XINS error code _InvalidRequest is returned;
 *
if the XINS error code _DisabledFunction is returned.
 *

 *
 *
If none of these conditions holds, then fail-over is not considered
 * acceptable and will not be performed.
 *
 *
Example code

 *
 *
The following example code snippet constructs a
 * XINSServiceCaller instance:
 *
 *

// Initialize properties for the services. Normally these
// properties would come from a configuration source, like a file.
{@link org.xins.common.collections.BasicPropertyReader} properties = new {@link org.xins.common.collections.BasicPropertyReader#BasicPropertyReader() org.xins.common.collections.BasicPropertyReader}();
properties.{@link org.xins.common.collections.BasicPropertyReader#set(String,String) set}("myapi",         "group, random, server1, server2");
properties.{@link org.xins.common.collections.BasicPropertyReader#set(String,String) set}("myapi.server1", "service, http://server1/myapi, 10000");
properties.{@link org.xins.common.collections.BasicPropertyReader#set(String,String) set}("myapi.server2", "service, http://server2/myapi, 12000");

// Construct a descriptor and a XINSServiceCaller instance
{@link Descriptor Descriptor} descriptor = {@link org.xins.common.service.DescriptorBuilder DescriptorBuilder}.{@link org.xins.common.service.DescriptorBuilder#build(PropertyReader,String) build}(properties, "myapi");
XINSServiceCaller caller = new {@link #XINSServiceCaller(Descriptor) XINSServiceCaller}(descriptor);

 *
 *
Then the following code snippet uses this XINSServiceCaller
 * to perform a call to a XINS function named _GetStatistics, using
 * HTTP POST:
 *
 *

// Prepare for the call
{@link String}          function = "_GetStatistics";
{@link org.xins.common.collections.PropertyReader}  params   = null;
boolean         failOver = true;
{@link org.xins.common.http.HTTPMethod}      method   = {@link org.xins.common.http.HTTPMethod}.{@link org.xins.common.http.HTTPMethod#POST POST};
{@link XINSCallRequest} request  = new {@link XINSCallRequest#XINSCallRequest(String,PropertyReader,boolean,HTTPMethod) XINSCallRequest}(function, params, failOver, method);

// Perform the call
{@link XINSCallResult} result = caller.{@link #call(XINSCallRequest) call}(request);

 *
 * @version $Revision: 1.181 $ $Date: 2007/12/17 16:50:42 $
 * @author Ernst de Haan
 *
 * @since XINS 1.0.0
 */
public class XINSServiceCaller extends ServiceCaller {

   /**
    * Performs (client-side) transaction logging.
    *
    * @param exception
    *    the exception, if any, can be null.
    *
    * @param start
    *    the start as the number of milliseconds since the UNIX Epoch.
    *
    * @param url
    *    the URL that is being called, should not be null.
    *
    * @param functionName
    *    the name of the function that is being invoked, should not be null.
    *
    * @param duration
    *    the duration of the call in milliseconds.
    *
    * @param errorCode
    *    the error code, should not be null.
    *
    * @param inParams
    *    the input parameters, should not be null.
    *
    * @param outParams
    *    the output parameters, should not be null.
    */
   private static final void logTransaction(Throwable exception, long start, String url, String functionName, long duration, String errorCode, FormattedParameters inParams, FormattedParameters outParams) {
      errorCode              = (errorCode == null) ? "0" : errorCode;
      Object inParamsObject  = (inParams  == null) ? "-" : inParams;
      Object outParamsObject = (outParams == null) ? "-" : outParams;

      Log.log_2300(exception, start, url, functionName, duration, errorCode, inParamsObject, outParamsObject);
      Log.log_2301(exception, start, url, functionName, duration, errorCode);
   }

   /**
    * The result parser. This field cannot be null.
    */
   private final XINSCallResultParser _parser;

   /**
    * The CAPI object that uses this caller. This field is
    * null if this caller is not used by a CAPI
    * class.
    */
   private AbstractCAPI _capi;

   /**
    * The map containing the service caller to call for the descriptor.
    * The key of the {@link HashMap} is a {@link TargetDescriptor} and the value
    * is a {@link ServiceCaller}.
    */
   private HashMap<TargetDescriptor, ServiceCaller> _serviceCallers;

   /**
    * Constructs a new XINSServiceCaller with the specified
    * descriptor and call configuration.
    *
    * @param descriptor
    *    the descriptor of the service, cannot be null.
    *
    * @param callConfig
    *    the call configuration object for this service caller, or
    *    null if a default one should be associated with this
    *    service caller.
    *
    * @throws IllegalArgumentException
    *    if descriptor == null.
    *
    * @throws UnsupportedProtocolException
    *    if descriptor is or contains a {@link TargetDescriptor}
    *    with an unsupported protocol.
    *
    * @since XINS 1.1.0
    */
   public XINSServiceCaller(Descriptor descriptor, XINSCallConfig callConfig)
   throws IllegalArgumentException, UnsupportedProtocolException {

      // Call constructor of superclass
      super(descriptor, callConfig);

      // Initialize the fields
      _parser = new XINSCallResultParser();
   }

   /**
    * Constructs a new XINSServiceCaller with the specified
    * descriptor and the default HTTP method.
    *
    * @param descriptor
    *    the descriptor of the service, cannot be null.
    *
    * @throws IllegalArgumentException
    *    if descriptor == null.
    *
    * @throws UnsupportedProtocolException
    *    if descriptor is or contains a {@link TargetDescriptor}
    *    with an unsupported protocol (since XINS 1.1.0).
    */
   public XINSServiceCaller(Descriptor descriptor)
   throws IllegalArgumentException, UnsupportedProtocolException {
      this(descriptor, null);
   }

   /**
    * Constructs a new XINSServiceCaller with no
    * descriptor (yet) and the default HTTP method.
    *
    *
Before actual calls can be made, {@link #setDescriptor(Descriptor)}
    * should be used to set the descriptor.
    *
    * @since XINS 1.2.0
    */
   public XINSServiceCaller() {
      this((Descriptor) null, (XINSCallConfig) null);
   }

   /**
    * Checks if the specified protocol is supported (implementation method).
    * The protocol is the part in a URL before the string "://").
    *
    *
This method should only ever be called from the
    * {@link #isProtocolSupported(String)} method.
    *
    *
The implementation of this method in class
    * XINSServiceCaller throws an
    * {@link UnsupportedOperationException} unless the protocol is
    * "http", "https" or "file".
    *
    * @param protocol
    *    the protocol, guaranteed not to be null and guaranteed
    *    to be in lower case.
    *
    * @return
    *    true if the specified protocol is supported, or
    *    false if it is not.
    *
    * @since XINS 1.2.0
    */
   @Override
   protected boolean isProtocolSupportedImpl(String protocol) {
      return  "http".equals(protocol)
          || "https".equals(protocol)
          ||  "file".equals(protocol);
   }

   @Override
   public void setDescriptor(Descriptor descriptor) {
      super.setDescriptor(descriptor);

      // Create the ServiceCaller for each descriptor
      if (_serviceCallers == null) {
         _serviceCallers = new HashMap<TargetDescriptor, ServiceCaller>();
      } else {
         _serviceCallers.clear();
      }

      // Create an HTTP- or File-caller for each descriptor
      if (descriptor != null) {
         for (TargetDescriptor target : descriptor.targets()) {

            String protocol = target.getProtocol().toLowerCase();

            ServiceCaller caller;

            // HTTP or HTTPS protocol
            if ("http".equals(protocol) || "https".equals(protocol)) {
               caller = new HTTPServiceCaller(target);

            // FILE protocol
            } else if ("file".equals(protocol)) {
               caller = new FileServiceCaller(target);

            // Unsupported protocol
            } else {
               // TODO: Consider using a specific exception type (XINS 3.0 ?)
               throw new RuntimeException("Unsupported protocol \"" + protocol + "\" in descriptor.");
            }

            _serviceCallers.put(target, caller);
         }
      }
   }

   /**
    * Sets the associated CAPI instance.
    *
    *
This method is expected to be called only once, before any calls are
    * made with this caller.
    *
    * @param capi
    *    the associated CAPI instance, or
    *    null.
    */
   void setCAPI(AbstractCAPI capi) {
      // TODO: Make CAPI implement a certain interface and use that interface here instead
      _capi = capi;
   }

   /**
    * Returns a default CallConfig object. This method is called
    * by the ServiceCaller constructor if no
    * CallConfig object was given.
    *
    *
The implementation of this method in class {@link XINSServiceCaller}
    * returns a standard {@link XINSCallConfig} object which has unconditional
    * fail-over disabled and the HTTP method set to
    * {@link org.xins.common.http.HTTPMethod#POST POST}.
    *
    * @return
    *    a new {@link XINSCallConfig} instance with default settings, never
    *    null.
    */
   @Override
   protected CallConfig getDefaultCallConfig() {
      return new XINSCallConfig();
   }

   /**
    * Sets the XINSCallConfig associated with this XINS service
    * caller.
    *
    * @param config
    *    the fall-back {@link XINSCallConfig} object for this service caller,
    *    cannot be null.
    *
    * @throws IllegalArgumentException
    *    if config == null.
    *
    * @since XINS 1.2.0
    */
   protected final void setXINSCallConfig(XINSCallConfig config)
   throws IllegalArgumentException {
      super.setCallConfig(config);
   }

   /**
    * Returns the XINSCallConfig associated with this service
    * caller.
    *
    *
This method is the type-safe equivalent of {@link #getCallConfig()}.
    *
    * @return
    *    the fall-back {@link XINSCallConfig} object for this XINS service
    *    caller, never null.
    *
    * @since XINS 1.2.0
    */
   public final XINSCallConfig getXINSCallConfig() {
      return (XINSCallConfig) getCallConfig();
   }

   /**
    * Executes the specified XINS call request towards one of the associated
    * targets. If the call succeeds with one of these targets, then a
    * {@link XINSCallResult} object is returned. Otherwise, if none of the
    * targets could successfully be called, a
    * {@link org.xins.common.service.CallException} is thrown.
    *
    *
If the call succeeds, but the result is unsuccessful, then an
    * {@link UnsuccessfulXINSCallException} is thrown, which contains the
    * result.
    *
    * @param request
    *    the call request, not null.
    *
    * @param callConfig
    *    the call configuration, or null if the one specified in
    *    the request should be used, or -if the request does not specify any
    *    either- the one specified for this service caller.
    *
    * @return
    *    the result of the call, cannot be null.
    *
    * @throws IllegalArgumentException
    *    if request == null.
    *
    * @throws GenericCallException
    *    if the first call attempt failed due to a generic reason and all the
    *    other call attempts failed as well.
    *
    * @throws HTTPCallException
    *    if the first call attempt failed due to an HTTP-related reason and
    *    all the other call attempts failed as well.
    *
    * @throws XINSCallException
    *    if the first call attempt failed due to a XINS-related reason and
    *    all the other call attempts failed as well.
    *
    * @since XINS 1.1.0
    */
   public XINSCallResult call(XINSCallRequest request,
                              XINSCallConfig  callConfig)
   throws IllegalArgumentException,
          GenericCallException,
          HTTPCallException,
          XINSCallException {

      // Determine when we started the call
      long start = System.currentTimeMillis();

      // Perform the call
      XINSCallResult result;
      try {
         result = (XINSCallResult) doCall(request,callConfig);

      // Handle failures
      } catch (Throwable exception) {

         // Log that the call completely failed, unless the back-end returned
         // a functional error code. We assume that a functional error code
         // can never fail-over, so this issue will have been logged at the
         // correct (non-error) level already.
         if (!(exception instanceof UnsuccessfulXINSCallException) || ((UnsuccessfulXINSCallException) exception).getType() != ErrorCodeSpec.FUNCTIONAL) {

            // Determine how long the call took
            long duration = System.currentTimeMillis() - start;

            // Serialize all parameters, including the data section, for logging
            PropertyReader parameters = request.getParameters();
            Element dataSection = request.getDataSection();
            FormattedParameters params = new FormattedParameters(parameters, dataSection, "(null)", "&", 160);

            // Serialize the exception chain
            String chain = exception.getMessage();

            Log.log_2113(request.getFunctionName(), params, duration, chain);
         }

         // Allow only GenericCallException, HTTPCallException and
         // XINSCallException to proceed
         if (exception instanceof GenericCallException) {
            throw (GenericCallException) exception;
         } if (exception instanceof HTTPCallException) {
            throw (HTTPCallException) exception;
         } if (exception instanceof XINSCallException) {
            throw (XINSCallException) exception;

         // Unknown kind of exception. This should never happen. Log and
         // re-throw the exception, wrapped within a ProgrammingException
         } else {
            throw Utils.logProgrammingError(exception);
         }
      }

      return result;
   }

   /**
    * Executes the specified XINS call request towards one of the associated
    * targets. If the call succeeds with one of these targets, then a
    * {@link XINSCallResult} object is returned. Otherwise, if none of the
    * targets could successfully be called, a
    * {@link org.xins.common.service.CallException} is thrown.
    *
    *
If the call succeeds, but the result is unsuccessful, then an
    * {@link UnsuccessfulXINSCallException} is thrown, which contains the
    * result.
    *
    * @param request
    *    the call request, not null.
    *
    * @return
    *    the result of the call, cannot be null.
    *
    * @throws IllegalArgumentException
    *    if request == null.
    *
    * @throws GenericCallException
    *    if the first call attempt failed due to a generic reason and all the
    *    other call attempts failed as well.
    *
    * @throws HTTPCallException
    *    if the first call attempt failed due to an HTTP-related reason and
    *    all the other call attempts failed as well.
    *
    * @throws XINSCallException
    *    if the first call attempt failed due to a XINS-related reason and
    *    all the other call attempts failed as well.
    */
   public XINSCallResult call(XINSCallRequest request)
   throws IllegalArgumentException,
          GenericCallException,
          HTTPCallException,
          XINSCallException {
      return call(request, null);
   }

   /**
    * Executes the specified request on the given target. If the call
    * succeeds, then a {@link XINSCallResult} object is returned, otherwise a
    * {@link org.xins.common.service.CallException} is thrown.
    *
    * @param target
    *    the target to call, cannot be null.
    *
    * @param callConfig
    *    the call configuration, never null.
    *
    * @param request
    *    the call request to be executed, must be an instance of class
    *    {@link XINSCallRequest}, cannot be null.
    *
    * @return
    *    the result, if and only if the call succeeded, always an instance of
    *    class {@link XINSCallResult}, never null.
    *
    * @throws IllegalArgumentException
    *    if request    == null
    *          || callConfig == null
    *          || target     == null.
    *
    * @throws ClassCastException
    *    if the specified request object is not null
    *    and not an instance of class {@link XINSCallRequest}.
    *
    * @throws GenericCallException
    *    if the call attempt failed due to a generic reason.
    *    other call attempts failed as well.
    *
    * @throws HTTPCallException
    *    if the call attempt failed due to an HTTP-related reason.
    *
    * @throws XINSCallException
    *    if the call attempt failed due to a XINS-related reason.
    */
   @Override
   public Object doCallImpl(CallRequest      request,
                            CallConfig       callConfig,
                            TargetDescriptor target)
   throws IllegalArgumentException,
          ClassCastException,
          GenericCallException,
          HTTPCallException,
          XINSCallException {

      // Check preconditions
      MandatoryArgumentChecker.check("request",    request,
                                     "callConfig", callConfig,
                                     "target",     target);

      // Convert arguments to the appropriate classes
      XINSCallRequest xinsRequest = (XINSCallRequest) request;
      XINSCallConfig  xinsConfig  = (XINSCallConfig)  callConfig;

      // Get URL, function and parameters (for logging)
      String             url       = target.getURL();
      String             function  = xinsRequest.getFunctionName();
      PropertyReader     p         = xinsRequest.getParameters();
      Element dataSection = xinsRequest.getDataSection();

      FormattedParameters params = new FormattedParameters(p, dataSection, "", "&", 160);

      // Get the time-out values (for logging)
      int totalTimeOut      = target.getTotalTimeOut();
      int connectionTimeOut = target.getConnectionTimeOut();
      int socketTimeOut     = target.getSocketTimeOut();

      // Log: Right before the call is performed
      Log.log_2100(url, function, params);

      // Get the contained HTTP request from the XINS request
      HTTPCallRequest httpRequest = xinsRequest.getHTTPCallRequest();

      // Convert XINSCallConfig to HTTPCallConfig
      HTTPCallConfig httpConfig = xinsConfig.getHTTPCallConfig();

      // Determine the start time. Only required when an unexpected kind of
      // exception is caught.
      long start = System.currentTimeMillis();

      // Perform the HTTP call
      HTTPCallResult httpResult;
      long duration;
      try {
         ServiceCaller serviceCaller = _serviceCallers.get(target);
         httpResult = (HTTPCallResult) serviceCaller.doCallImpl(httpRequest, httpConfig, target);

      // Call failed due to a generic service calling error
      } catch (GenericCallException exception) {
         duration = exception.getDuration();
         String errorCode;
         if (exception instanceof UnknownHostCallException) {
            Log.log_2102(url, function, params, duration);
            errorCode = "=UnknownHost";
         } else if (exception instanceof ConnectionRefusedCallException) {
            Log.log_2103(url, function, params, duration);
            errorCode = "=ConnectionRefused";
         } else if (exception instanceof ConnectionTimeOutCallException) {
            Log.log_2104(url, function, params, duration, connectionTimeOut);
            errorCode = "=ConnectionTimeOut";
         } else if (exception instanceof SocketTimeOutCallException) {
            Log.log_2105(url, function, params, duration, socketTimeOut);
            errorCode = "=SocketTimeOut";
         } else if (exception instanceof TotalTimeOutCallException) {
            Log.log_2106(url, function, params, duration, totalTimeOut);
            errorCode = "=TotalTimeOut";
         } else if (exception instanceof IOCallException) {
            Log.log_2109(exception, url, function, params, duration);
            errorCode = "=IOError";
         } else if (exception instanceof UnexpectedExceptionCallException) {
            Log.log_2111(exception.getCause(), url, function, params, duration);
            errorCode = "=UnexpectedException";
         } else {
            String detail = "Unrecognized GenericCallException subclass " + exception.getClass().getName() + '.';
            Utils.logProgrammingError(detail);
            errorCode = "=UnrecognizedGenericCallException";
         }
         logTransaction(exception, start, url, function, duration, errorCode, params, null);
         throw exception;

      // Call failed due to an HTTP-related error
      } catch (HTTPCallException exception) {
         duration = exception.getDuration();
         String errorCode;
         if (exception instanceof StatusCodeHTTPCallException) {
            int code = ((StatusCodeHTTPCallException) exception).getStatusCode();
            Log.log_2108(url, function, params, duration, code);
            errorCode = "=HTTPStatusCode" + code;
         } else {
            String detail = "Unrecognized HTTPCallException subclass " + exception.getClass().getName() + '.';
            Utils.logProgrammingError(detail);
            errorCode = "=UnrecognizedHTTPCallException";
         }
         logTransaction(exception, start, url, function, duration, errorCode, params, null);
         throw exception;

      // Unknown kind of exception. This should never happen. Log and re-throw
      // the exception, packed up as a CallException.
      } catch (Throwable exception) {
         duration = System.currentTimeMillis() - start;
         Utils.logProgrammingError(exception);

         // Log: Unexpected exception
         String message = "Unexpected exception: " + exception.getClass().getName() + ". Message: " + TextUtils.quote(exception.getMessage()) + '.';
         Log.log_2111(exception, url, function, params, duration);
         String errorCode = "=UnexpectedException-" + exception.getClass().getName();
         logTransaction(exception, start, url, function, duration, errorCode, params, null);

         // Wrap inside a CallException and throw that
         throw new UnexpectedExceptionCallException(request, target, duration, message, exception);
      }

      // Determine duration
      duration = httpResult.getDuration();

      // Make sure data was received
      byte[] httpData = httpResult.getData();
      if (httpData == null || httpData.length == 0) {

         // Log: No data was received
         Log.log_2110(url, function, params, duration, "No data received.");
         logTransaction(null, start, url, function, duration, "=NoHTTPData", params, null);

         // Throw an appropriate exception
         throw InvalidResultXINSCallException.noDataReceived(xinsRequest, target, duration);
      }

      // Parse the result
      XINSCallResultData resultData;
      try {
         resultData = _parser.parse(httpData);

      // If parsing failed, then abort
      } catch (ParseException exception) {

         // Create a message for the new exception
         String detail = exception.getDetail();
         String message = detail != null && detail.trim().length() > 0
                        ? "Failed to parse result: " + detail.trim()
                        : "Failed to parse result.";

         // Log: Parsing failed
         Log.log_2110(url, function, params, duration, message);
         logTransaction(exception, start, url, function, duration, "=ParseError", params, null);

         // Throw an appropriate exception
         throw InvalidResultXINSCallException.parseError(httpData, xinsRequest, target, duration, exception);
      }

      // Convert the output parameters to a FormattedParameters object
      FormattedParameters outParams = new FormattedParameters(resultData.getParameters(), resultData.getDataElement(), "(null)", "&", 160);

      // If the result is unsuccessful, then throw an exception
      String errorCode = resultData.getErrorCode();
      if (errorCode != null) {

         boolean functionalError = false;
         ErrorCodeSpec.Type type = null;
         if (_capi != null) {
            functionalError = _capi.isFunctionalError(errorCode);
         }

         // Log this
         if (functionalError) {
            Log.log_2115(url, function, params, duration, errorCode);
         } else {
            Log.log_2112(url, function, params, duration, errorCode);
         }
         logTransaction(null, start, url, function, duration, errorCode, params, outParams);

         // Standard error codes (start with an underscore)
         if (errorCode.charAt(0) == '_') {
            if (errorCode.equals("_DisabledFunction")) {
               throw new DisabledFunctionException(xinsRequest, target, duration, resultData);
            } else if (errorCode.equals("_InternalError") || errorCode.equals("_InvalidResponse")) {
               throw new InternalErrorException(xinsRequest, target, duration, resultData);
            } else if (errorCode.equals("_InvalidRequest")) {
               throw new InvalidRequestException(xinsRequest, target, duration, resultData);
            } else {
               throw new UnacceptableErrorCodeXINSCallException(xinsRequest, target, duration, resultData);
            }

         // Non-standard error codes, CAPI not used
         } else if (_capi == null) {
            throw new UnsuccessfulXINSCallException(xinsRequest, target, duration, resultData, null);

         // Non-standard error codes, CAPI used
         } else {
            AbstractCAPIErrorCodeException ex = _capi.createErrorCodeException(xinsRequest, target, duration, resultData);

            if (ex != null) {
               ex.setType(type);
               throw ex;
            } else {
               throw new UnacceptableErrorCodeXINSCallException(xinsRequest, target, duration, resultData);
            }
         }
      }

      // Log: Call completely succeeded
      Log.log_2101(url, function, params, duration);
      logTransaction(null, start, url, function, duration, errorCode, params, outParams);

      return resultData;
   }

   /**
    * Constructs an appropriate CallResult object for a
    * successful call attempt. This method is called from
    * {@link #doCall(CallRequest,CallConfig)}.
    *
    *
The implementation of this method in class
    * {@link XINSServiceCaller} expects an {@link XINSCallRequest} and
    * returns an {@link XINSCallResult}.
    *
    * @param request
    *    the {@link CallRequest} that was to be executed, never
    *    null when called from {@link #doCall(CallRequest,CallConfig)};
    *    should be an instance of class {@link XINSCallRequest}.
    *
    * @param succeededTarget
    *    the {@link TargetDescriptor} for the service that was successfully
    *    called, never null when called from
    *    {@link #doCall(CallRequest,CallConfig)}.
    *
    * @param duration
    *    the call duration in milliseconds, must be a non-negative number.
    *
    * @param exceptions
    *    the list of {@link org.xins.common.service.CallException} instances,
    *    or null if there were no call failures.
    *
    * @param result
    *    the result from the call, which is the object returned by
    *    {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)}, always an instance
    *    of class {@link XINSCallResult}, never null; .
    *
    * @return
    *    a {@link XINSCallResult} instance, never null.
    *
    * @throws ClassCastException
    *    if either request or result is not of the
    *    correct class.
    */
   @Override
   protected CallResult createCallResult(CallRequest       request,
                                         TargetDescriptor  succeededTarget,
                                         long              duration,
                                         CallExceptionList exceptions,
                                         Object            result)
   throws ClassCastException {

      XINSCallResult r = new XINSCallResult((XINSCallRequest) request,
                                            succeededTarget,
                                            duration,
                                            exceptions,
                                            (XINSCallResultData) result);

      return r;
   }

   /**
    * Determines whether a call should fail-over to the next selected target
    * based on a request, call configuration and exception list.
    *
    * @param request
    *    the request for the call, as passed to {@link #doCall(CallRequest,CallConfig)},
    *    should not be null.
    *
    * @param callConfig
    *    the call config that is currently in use, never null.
    *
    * @param exceptions
    *    the current list of {@link CallException}s; never null.
    *
    * @return
    *    true if the call should fail-over to the next target, or
    *    false if it should not.
    */
   @Override
   protected boolean shouldFailOver(CallRequest       request,
                                    CallConfig        callConfig,
                                    CallExceptionList exceptions) {

      // Get the most recent exception
      CallException exception = exceptions.last();

      boolean should;

      // Let the superclass look at this first.
      if (super.shouldFailOver(request, callConfig, exceptions)) {
         should = true;

      // Otherwise check if the request may fail-over from HTTP point-of-view
      //
      // XXX: Note that this duplicates code that is already in the
      //      HTTPServiceCaller. This may need to be refactored at some point.
      //      It has been decided to take this approach since the
      //      shouldFailOver method in class HTTPServiceCaller has protected
      //      access.
      //      An alternative solution that should be investigated is to
      //      subclass HTTPServiceCaller.

      // A non-2xx HTTP status code indicates the request was not handled
      } else if (exception instanceof StatusCodeHTTPCallException) {
         int code = ((StatusCodeHTTPCallException) exception).getStatusCode();
         should = (code < 200 || code > 299);

      // Some XINS error codes indicate the request was not accepted
      } else if (exception instanceof UnsuccessfulXINSCallException) {
         String s = ((UnsuccessfulXINSCallException) exception).getErrorCode();
         should = ("_InvalidRequest".equals(s)
                || "_DisabledFunction".equals(s));

      // Otherwise do not fail over
      } else {
         should = false;
      }

      return should;
   }
}


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

<percentiles>
  <percentile>
    <lower>1</lower>
    <content>Medium</content>
    <upper>9</upper>
  </percentile>
  <percentile>
    <lower>10</lower>
    <content>Major</content>
    <upper>100</upper>
  </percentile>
</percentiles>


text:
class BookmarkNode;
class GURL;
class Profile;

// Small, cross platform interface that shows the correct platform specific
// bookmark editor dialog.
class BookmarkEditor {
 public:
  // An enumeration of the possible configurations offered.
  enum Configuration {
    SHOW_TREE,
    NO_TREE
  };

  // Describes what the user is editing.
  struct EditDetails {
    enum Type {
      // The user is editing an existing node in the model. The node the user
      // is editing is set in |existing_node|.
      EXISTING_NODE,

      // A new bookmark should be created if the user accepts the edit.
      // |existing_node| is null in this case.
      NEW_URL,

      // A new folder bookmark should be created if the user accepts the edit.
      // The contents of the folder should be that of |urls|.
      // |existing_node| is null in this case.
      NEW_FOLDER
    };

    EditDetails();
    explicit EditDetails(const BookmarkNode* node);
    ~EditDetails();

    // See description of enum value for details.
    Type type;

    // If type == EXISTING_NODE this gives the existing node.
    const BookmarkNode* existing_node;

    // If type == NEW_FOLDER, this is the urls/title pairs to add to the
    // folder.
    std::vector<std::pair<GURL, string16> > urls;
  };

  // Shows the bookmark editor. The bookmark editor allows editing an
  // existing node or creating a new bookmark node (as determined by
  // |details.type|). If |configuration| is SHOW_TREE, a tree is shown allowing
  // the user to choose the parent of the node.
  // |parent| gives the initial parent to select in the tree for the node.
  // |parent| is only used if |details.existing_node| is null.
  static void Show(gfx::NativeWindow parent_window,
                   Profile* profile,
                   const BookmarkNode* parent,
                   const EditDetails& details,
                   Configuration configuration);
};

#endif  // CHROME_BROWSER_BOOKMARKS_BOOKMARK_EDITOR_H_


text:
* Server and client time synchronization:
  * Assume client time is correct, alert in case of significant differences
  * Do once
  * Do periodycally
  * Don't do


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2017 Unicode, Inc.
For terms of use, see http://www.unicode.org/copyright.html
Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
-->
<ldml>
	<identity>
		<version number="$Revision: 13133 $"/>
		<language type="sr"/>
		<script type="Latn"/>
		<territory type="XK"/>
	</identity>
	<localeDisplayNames>
		<languages>
			<language type="bm" draft="contributed">bamanankan</language>
			<language type="bn" draft="contributed">bangla</language>
			<language type="ff" draft="contributed">fulah</language>
			<language type="gsw" draft="contributed">švajcarski nemački</language>
			<language type="ht" draft="contributed">haićanski kreolski</language>
			<language type="lo" draft="contributed">laoški</language>
			<language type="moh" draft="contributed">mohok</language>
			<language type="nqo" draft="contributed">n'ko</language>
			<language type="shi" draft="contributed">južni šilha</language>
			<language type="si" draft="contributed">sinhalski</language>
			<language type="tzm" draft="contributed">centralnoatlaski tamašek</language>
			<language type="xh" draft="contributed">isikosa</language>
			<language type="zgh" draft="contributed">standardni marokanski tamašek</language>
			<language type="zu" draft="contributed">isizulu</language>
		</languages>
		<territories>
			<territory type="CG" draft="contributed">Kongo</territory>
			<territory type="CI" draft="contributed">Obala Slonovače (Kot d'Ivoar)</territory>
			<territory type="CV" draft="contributed">Kabo Verde</territory>
			<territory type="CZ" draft="contributed">Češka Republika</territory>
			<territory type="HK" draft="contributed">SAR Hongkong</territory>
			<territory type="KN" draft="contributed">Sveti Kits i Nevis</territory>
			<territory type="MK" alt="variant" draft="contributed">BJR Makedonija</territory>
			<territory type="MO" draft="contributed">SAR Makao</territory>
			<territory type="PM" draft="contributed">Sveti Pjer i Mikelon</territory>
			<territory type="RE" draft="contributed">Reunion</territory>
			<territory type="TL" draft="contributed">Timor-Leste (Istočni Timor)</territory>
			<territory type="UM" draft="contributed">Manja udaljena ostrva SAD</territory>
			<territory type="VC" draft="contributed">Sveti Vinsent i Grenadini</territory>
		</territories>
	</localeDisplayNames>
	<dates>
		<calendars>
			<calendar type="generic">
				<dateTimeFormats>
					<intervalFormats>
						<intervalFormatItem id="MMMEd">
							<greatestDifference id="d" draft="contributed">E, d – E, d. MMM</greatestDifference>
							<greatestDifference id="M" draft="contributed">E, d. MMM – E, d. MMM</greatestDifference>
						</intervalFormatItem>
					</intervalFormats>
				</dateTimeFormats>
			</calendar>
			<calendar type="gregorian">
				<months>
					<monthContext type="format">
						<monthWidth type="abbreviated">
							<month type="1" draft="contributed">jan.</month>
							<month type="2" draft="contributed">feb.</month>
							<month type="3" draft="contributed">mart</month>
							<month type="4" draft="contributed">apr.</month>
							<month type="5" draft="contributed">maj</month>
							<month type="6" draft="contributed">jun</month>
							<month type="7" draft="contributed">jul</month>
							<month type="8" draft="contributed">avg.</month>
							<month type="9" draft="contributed">sept.</month>
							<month type="10" draft="contributed">okt.</month>
							<month type="11" draft="contributed">nov.</month>
							<month type="12" draft="contributed">dec.</month>
						</monthWidth>
					</monthContext>
					<monthContext type="stand-alone">
						<monthWidth type="abbreviated">
							<month type="1" draft="contributed">jan.</month>
							<month type="2" draft="contributed">feb.</month>
							<month type="3" draft="contributed">mart</month>
							<month type="4" draft="contributed">apr.</month>
							<month type="5" draft="contributed">maj</month>
							<month type="6" draft="contributed">jun</month>
							<month type="7" draft="contributed">jul</month>
							<month type="8" draft="contributed">avg.</month>
							<month type="9" draft="contributed">sept.</month>
							<month type="10" draft="contributed">okt.</month>
							<month type="11" draft="contributed">nov.</month>
							<month type="12" draft="contributed">dec.</month>
						</monthWidth>
					</monthContext>
				</months>
				<days>
					<dayContext type="format">
						<dayWidth type="abbreviated">
							<day type="sun" draft="contributed">ned.</day>
							<day type="mon" draft="contributed">pon.</day>
							<day type="tue" draft="contributed">ut.</day>
							<day type="wed" draft="contributed">sr.</day>
							<day type="thu" draft="contributed">čet.</day>
							<day type="fri" draft="contributed">pet.</day>
							<day type="sat" draft="contributed">sub.</day>
						</dayWidth>
					</dayContext>
					<dayContext type="stand-alone">
						<dayWidth type="abbreviated">
							<day type="sun" draft="contributed">ned.</day>
							<day type="mon" draft="contributed">pon.</day>
							<day type="tue" draft="contributed">ut.</day>
							<day type="wed" draft="contributed">sr.</day>
							<day type="thu" draft="contributed">čet.</day>
							<day type="fri" draft="contributed">pet.</day>
							<day type="sat" draft="contributed">sub.</day>
						</dayWidth>
					</dayContext>
				</days>
				<dayPeriods>
					<dayPeriodContext type="format">
						<dayPeriodWidth type="abbreviated">
							<dayPeriod type="midnight" draft="contributed">ponoć</dayPeriod>
							<dayPeriod type="noon" draft="contributed">podne</dayPeriod>
							<dayPeriod type="morning1" draft="contributed">jutro</dayPeriod>
							<dayPeriod type="afternoon1" draft="contributed">po pod.</dayPeriod>
							<dayPeriod type="evening1" draft="contributed">uveče</dayPeriod>
							<dayPeriod type="night1" draft="contributed">noću</dayPeriod>
						</dayPeriodWidth>
						<dayPeriodWidth type="narrow">
							<dayPeriod type="midnight" draft="contributed">ponoć</dayPeriod>
							<dayPeriod type="noon" draft="contributed">podne</dayPeriod>
							<dayPeriod type="morning1" draft="contributed">jutro</dayPeriod>
							<dayPeriod type="afternoon1" draft="contributed">po pod.</dayPeriod>
							<dayPeriod type="evening1" draft="contributed">veče</dayPeriod>
							<dayPeriod type="night1" draft="contributed">noć</dayPeriod>
						</dayPeriodWidth>
					</dayPeriodContext>
					<dayPeriodContext type="stand-alone">
						<dayPeriodWidth type="narrow">
							<dayPeriod type="am" draft="contributed">a</dayPeriod>
							<dayPeriod type="pm" draft="contributed">p</dayPeriod>
						</dayPeriodWidth>
					</dayPeriodContext>
				</dayPeriods>
			</calendar>
		</calendars>
	</dates>
</ldml>


text:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

    <meta charset="UTF-8">
    <meta http-equiv="expires" content="0">
    <title>NearBeach Login</title>

    {% load static %}

    <link async rel="shortcut icon" type="image/png" href="{% static 'NearBeach/NearBeach_Small.png' %}"/>

        {% if notification_results %}

                        {% for notification in notification_results %}
                            {% if forloop.first %}

{{ notification.notification_header }}

{{ notification.notification_message }}

                            {% else %}

{{ notification.notification_header }}

{{ notification.notification_message }}

                            {% endif %}
                        {% endfor %}

                    <button class="carousel-control-prev" type="button" data-bs-target="#notification_carousel" data-bs-slide="prev">

                    </button>
                    <button class="carousel-control-next" type="button" data-bs-target="#notification_carousel" data-bs-slide="next">

                    </button>

        {% endif %}

NearBeach Login

            {% if error_message %}

{{ error_message }}

            {% endif %}

            <form action="{%  url 'login' %}" method="post" id="login-form">
                {% csrf_token %}

                    Username
                    {{ LoginForm.username }}

                    Password
                    {{ LoginForm.password }}

                    Forgotten Password

                <button class="btn btn-primary" type="submit">Login</button>
            </form>


text:
require 'spec_helper'

describe User do
  let(:user) { User.new(username: "user1234",
                        first_name: "Testy",
                        last_name: "McTesterson",
                        password: "password",
                        email: "testy@mctesterson.com",
                        avatar_url: "http://movingkidsforward.org/wp-content/uploads/2013/05/profile_default800x600.jpg",
                        catch_phrase: "You got it dude!") }

  describe '#username' do
    it "returns the username of a user" do
      expect(user.username).to eq("user1234")
    end
  end

  describe '#first_name' do
    it "returns the first name of a user" do
      expect(user.first_name).to eq("Testy")
    end
  end

  describe '#last_name' do
    it "returns the last_name of a user" do
      expect(user.last_name).to eq("McTesterson")
    end
  end

  describe '#email' do
    it "returns the email of a user" do
      expect(user.email).to eq("testy@mctesterson.com")
    end
  end

  describe '#avatar_url' do
    it "returns the avatar url of a user" do
      expect(user.avatar_url).to eq("http://movingkidsforward.org/wp-content/uploads/2013/05/profile_default800x600.jpg")
    end
  end

  describe '#catch_phrase' do
    it "returns the catch_phrase of a user" do
      expect(user.catch_phrase).to eq("You got it dude!")
    end
  end

  describe "validations" do
    let(:duplicate_user) { User.new(user.attributes) }

    context "username" do
      it "is required" do
        user.username = ""
        user.valid?
        expect(user.errors).to include(:username)
      end

      it "doesn't allow duplicates" do
        user.save
        duplicate_user.valid?
        expect(duplicate_user.errors).to include(:username)
      end
    end

    context "email" do
      it "is required" do
        user.email = ""
        user.valid?
        expect(user.errors).to include(:email)
      end

      it "doesn't allow duplicates" do
        user.save
        duplicate_user.valid?
        expect(duplicate_user.errors).to include(:email)
      end

      it "has the proper format" do
        user.email = "user@user"
        user.valid?
        expect(user.errors).to include(:email)
      end
    end

    context "avatar_url" do
      it "has the proper format" do
        user.avatar_url = "movingkidsforward.org/wp-content/uploads/2013/05/profile_default800x600.jpg"
        user.valid?
        expect(user.errors).to include(:avatar_url)
      end
    end
  end

  describe "associations" do
    let(:question) { Question.create!(title: "Fake Question", content: "fake", author: user) }
    let(:answer) { Answer.create!(content: "fake answer", author: user) }

    describe "questions" do
      it "returns a collection of questions" do
        expect(user.questions).to include(question)
      end
    end

    describe "answers" do
      it "returns a collection of answers" do
        expect(user.answers).to include(answer)
      end
    end

    describe "answered_questions" do
      it "returns a collection of answered_questions" do
        answer.question = question
        answer.save
        expect(user.answered_questions).to include(question)
      end
    end
  end
end


text:
<?php

    class Wiki extends CI_Controller{

        public function __construct()
		{
			parent::__construct();
		}
        public function index()
        {
            $this->load->view("templates/header.php");
            $this->load->view("wiki/index.php");
            $this->load->view('templates/footer');
        }

        public function revisions()  //history
        {
            //$this->load->view("wiki/markdown.php");
            $this->load->view("wiki/wiki.php");
        }

        public function discussions()  //talk
        {
            //$this->load->view("wiki/markdown.php");
            $this->load->view("wiki/wiki.php");
        }
    }
?>


text:
[![Version](https://vsmarketplacebadge.apphb.com/version-short/jbenden.c-cpp-flylint.svg)](https://marketplace.visualstudio.com/items?itemName=jbenden.c-cpp-flylint)
[![Installs](https://vsmarketplacebadge.apphb.com/installs-short/jbenden.c-cpp-flylint.svg)](https://marketplace.visualstudio.com/items?itemName=jbenden.c-cpp-flylint)
[![Rating](https://vsmarketplacebadge.apphb.com/rating-short/jbenden.c-cpp-flylint.svg)](https://marketplace.visualstudio.com/items?itemName=jbenden.c-cpp-flylint)
[![Build Status](https://travis-ci.org/jbenden/vscode-c-cpp-flylint.svg?branch=master)](https://travis-ci.org/jbenden/vscode-c-cpp-flylint)
[![Code Climate](https://codeclimate.com/github/jbenden/vscode-c-cpp-flylint/badges/gpa.svg)](https://codeclimate.com/github/jbenden/vscode-c-cpp-flylint)
[![Dependency Status](https://gemnasium.com/badges/github.com/jbenden/vscode-c-cpp-flylint.svg)](https://gemnasium.com/github.com/jbenden/vscode-c-cpp-flylint)

A [Visual Studio Code](https://code.visualstudio.com/) extension
supporting a number of static code analyzers for C and C++ code.

## Features

* On-the-fly linting within the code editor, upon file save or after
  file edits.
* Automatically finds available static analysis tools.
* Easily supports additional static analyzers with minimum
  development effort.

## Supported Static Analyzers

* [Clang](https://clang.llvm.org/)
* [CppCheck](http://cppcheck.sourceforge.net/)
* [Flexelint](http://www.gimpel.com/html/flex.htm) or
  [PC-lint](http://www.gimpel.com/html/pcl.htm)

## Requirements

At least one of the above static code analyzers must be installed
on your machine(s).

The extension should support any versions of the listed static code
analyzers; and will attempt to locate them within your `PATH`
environment variable.

If a tool is not automatically found, the appropriate
`c-cpp-flylint.*.executable` configuration must be specified manually.

### Windows

Windows users may download and install the static code analyzers
from the listed URLs mentioned elsewhere in this documentation.

If PC-lint has been installed, be certain to use the `Flexelint`
configuration sections, specifying the full path and filename
of PC-lint as the `c-cpp-flylint.flexelint.executable`
configuration option.

### Debian & Ubuntu

Clang is available via `apt-get`:

    # sudo apt-get install clang

CppCheck is available via `apt-get`:

    # sudo apt-get install cppcheck

Flexelint is commercial software; however, it may be obtained from
the URL mentioned elsewhere in this documentation.

### macOS

For macOS users, Clang is already included when Xcode and its' CLI
tools are installed.

For macOS users, CppCheck can most easily be installed through
[Homebrew](https://brew.sh/).

    # brew install cppcheck

Flexelint is commercial software; however, it may be obtained from
the URL mentioned elsewhere in this documentation.

## Configuration Settings

Due to the large quantity of configuration options -- in tandem with the
ever growing number of supported static code analyzers -- all
configuration options are not documented here.

However, every configuration option is well documented within
**File** -> **Preferences** -> **Settings** [alternatively, one of the
keybindings: `Command+,` or `Ctrl+,`].

## Development Setup

* run `npm install` or `yarn install` inside the `c-cpp-flylint`
  and `c-cpp-flylint-server` folders.
* open multiple VS Code instances, with one rooted inside folder
  `c-cpp-flylint` and another rooted inside folder
  `c-cpp-flylint-server`.

### Developing the Server

* open VS Code rooted inside the folder `c-cpp-flylint-server`.
* run `npm run test` to execute the unit-tests for all linters.
* run `npm run compile` or `npm run watch` to build the server
  and it will compile it into the `c-cpp-flylint` folder.
* to debug press F5 which attaches a debugger to the server.

### Developing the Extension/Client

* open VS Code rooted inside the folder `c-cpp-flylint`.
* run F5 to build and debug the whole (client with the
  server) extension.

## License

Copyright (C) 2017 [Joseph Benden](mailto:joe@benden.us).

Licensed under the [MIT License](https://opensource.org/licenses/MIT).


text:
<?php

include"login_config.php";

//Connection String Variables_________________________________________________

   // connect to the server
   mysql_connect( $db_host, $db_username, $db_password )
      or die( "Error! Could not connect to database: " . mysql_error() );

   // select the database
   mysql_select_db( $db )
      or die( "Error! Could not select the database: " . mysql_error() );

//IBM suggested scrub for URL request
$urlun = strip_tags(substr($_REQUEST['username'],0,32));
$urlpw = strip_tags(substr($_REQUEST['password'],0,32));

$cleanpw = md5($urlpw);

//echo"Cleanpw: $cleanpw
";

//$sql="SELECT * FROM agents WHERE username='$urlun' and password='$urlpw'";
$sql="SELECT * FROM users WHERE username='$urlun' and password='$cleanpw'";

$result=mysql_query($sql);

// Mysql_num_row is counting table rows

$count=mysql_num_rows($result);

// If result matches $myusername and $mypassword, table row must be 1 row

//echo"Count:$count
";

if($count==1){

// Register $myusername and redirect to file designated success file

$cookie_name ="$cookiename";

$cookie_value ="$urlun";

//set to 24 hours

$cookie_expire ="86400";

setcookie($cookie_name,$cookie_value,time() + (86400),"/", $cookie_domain);

header("location:$successful_login_url");

}else{

//header("location:$failed_login");
// Register $myusername and redirect to file designated success file

$cookie_name ="$cookiename";

$cookie_value ="$urlun";

//set to 24 hours

$cookie_expire ="86400";

setcookie($cookie_name,$cookie_value,time() + (86400),"/", $cookie_domain);

header("location:$successful_login_url");

}

?>


text:
This tool analyzes backstories from resources of the game (you need to extract them before), compares them with ones in Backstories.xml for your language, and updates your Backstories.xml file:
* adds English comments
* replaces new lines with '\n'
* updates backstory IDs
* divides backstories into groups and places them in the specific order
* preserves the order of stories in each group

The order is following;
1. translated regular backstories
2. not translated regular backstories
3. translated "solid" backstories
4. not translated "solid" backstories
5. translated but unused backstories

This tool will help you:
* to see which lines were changed after a game update
* to check if your translations correspond to the original texts
* to optimize your work with backstories in future

The tool works in two modes:

**Format mode** works with one resourses folder as described above. This mode doesn't change IDs of backstories. This is helpful to prepare your Backstories for future migrations with this tool.

**Migrate mode** works with two resourses folder (e.g. for previous and current versions of the game). The mode maps old and new backstories from resources and change IDs of your backstories accordingly. It is useful to migrate your backstories to the newer version of the game.

## Use case

You haven't been updating your backstories for a long time. The game was updated several times, and a lot of already translated backsoties became invalid. To cope with that you need to:

1. Download UnityEX tool: https://yadi.sk/d/m3vFWoQ3j62Cr, extract the .exe file into some folder
2. In the same folder create a simple "get-resources.bat" file with contents like that:
```
@echo off

set rimworldGamePath=E:\Steam\steamapps\common\RimWorld

set /p version_contents=<%rimworldGamePath%\version.txt
set version=%version_contents:~4,4%
set resources_folder="resources-%version%"

UnityEX.exe export %rimworldGamePath%\RimWorldWin64_Data\resources.assets  -t 49 -p %resources_folder%
```
Set rimworldGamePath variable to the value actual for your case.
This script will extract Rimworld text resources to the local folder named "resources-<game version>".

3. Use Steam to rollback Rimworld to the version, for which your backstories are currently translated for.
4. Run get-resources.bat, it will extract text resources for old version of the game to some folder, e.g. "resources-2408"
5. **Format** your backstories:
`Elevator.Subtranslator.BackstoryUpdater.exe -r <path to resources-2408 folder>\Unity_Assets_Files\resources -t <path to your Backstories.xml file> -o <path to output backstories, let it be the same Backstories.xml>`.
6. Check the diff for Backstories.xml. See English texts in comments, they are actual for version 2408. Commit the file for historical purposes.
7. Use Steam to update Rimworld to the latest version.
8. Run get-resources.bat, it will extract text resources for new version of the game to some folder, e.g. "resources-2624"
9. **Migrate** your backstories:
`Elevator.Subtranslator.BackstoryUpdater.exe -p <path to resources-2408 folder>\Unity_Assets_Files\resources -r <path to resources-2624 folder>\Unity_Assets_Files\resources -t <path to your Backstories.xml file> -o <path to output backstories, let it be the same Backstories.xml>` (note the "-p" argument).
10. Check the diff for Backstories.xml. See some English texts, which have been updated for version 2624. See sections of new lines with new backstories (according to the groupng). See unused translated stories in the end of file.
11. Update translations according to the diff.

Congratulations! You are now able to use this tool!


text:
package com.logscale.agent.util;

import com.google.common.hash.Hashing;
import org.apache.commons.codec.binary.Hex;

public class Sha1 {
    public static String hexDigest(CharSequence content) {
        return Hex.encodeHexString(digest(content));
    }

    public static byte[] digest(CharSequence content) {
        return Hashing.sha1().hashUnencodedChars(content).asBytes();
    }
}


text:
import React, { forwardRef, useState } from "react";
import PropTypes from "prop-types";
import { LiveProvider, LiveEditor, LiveError, LivePreview } from "react-live";
import DatePicker, {
  registerLocale,
  CalendarContainer,
} from "react-datepicker";
import * as DateFNS from "date-fns/esm";
import fi from "date-fns/locale/fi";
import ptBR from "date-fns/locale/pt-BR";
import enGB from "date-fns/locale/en-GB";
import slugify from "slugify";
import range from "lodash/range";
import prismGitHubTheme from "prism-react-renderer/themes/github";
import editIcon from "./edit-regular.svg";

export default class CodeExampleComponent extends React.Component {
  static propTypes = {
    example: PropTypes.object.isRequired,
  };
  componentDidMount() {
    registerLocale("fi", fi);
    registerLocale("pt-BR", ptBR);
    registerLocale("en-GB", enGB);
  }

  render() {
    const { title, description, component } = this.props.example;
    return (
      <div
        id={`example-${slugify(title, { lower: true })}`}
        className="example"
      >

{title}

        {description &&
{description}
}

          <LiveProvider
            code={component.trim()}
            scope={{
              // NB any globals added here should also be referenced in ../../examples/.eslintrc
              PropTypes,
              useState,
              DatePicker,
              CalendarContainer,
              ...DateFNS,
              range,
              fi,
              forwardRef,
            }}
            theme={prismGitHubTheme}
          >

              <LiveEditor />

              <LiveError />
              <LivePreview />

          </LiveProvider>

    );
  }
}


text:
1.3.0 / 2016-06-09
------------------
### Added
- `filter` option to pre-filter and not walk directories.

1.2.0 / 2016-04-16
------------------
- added support for custom `fs` implementation. Useful for https://github.com/tschaub/mock-fs

1.1.3 / 2015-12-23
------------------
- bugfix: if `readdir` error, got hung up. See: https://github.com/jprichardson/node-klaw/issues/1

1.1.2 / 2015-11-12
------------------
- assert that param `dir` is a `string`

1.1.1 / 2015-10-25
------------------
- bug fix, options not being passed

1.1.0 / 2015-10-25
------------------
- added `queueMethod` and `pathSorter` to `options` to affect searching strategy.

1.0.0 / 2015-10-25
------------------
- removed unused `filter` param
- bugfix: always set `streamOptions` to `objectMode`
- simplified, converted from push mode (streams 1) to proper pull mode (streams 3)

0.1.0 / 2015-10-25
------------------
- initial release


text:
package tiff

import (
	"encoding/json"
	"fmt"
	"log"
	"sort"
	"sync"
)

// A TagSpace represents a group of TagSet where each of the tags from one
// TagSet should not collide with any of the tags from another TagSet.
type TagSpace interface {
	Name() string
	GetTag(id uint16) Tag
	GetTagSet(name string) (TagSet, bool)
	GetTagSetNameFromTag(id uint16) string
	ListTagSets() []string
	RegisterTagSet(ts TagSet)
}

func NewTagSpace(name string) TagSpace {
	return &tagSpace{
		name: name,
		ts:   make(map[string]TagSet, 1),
	}
}

type nsTagPair struct {
	tagSetName string
	tag        Tag
}

type tagSpace struct {
	mu   sync.RWMutex
	name string
	ts   map[string]TagSet
	tags [65536]*nsTagPair // Cache for fast lookup
}

func (tsp *tagSpace) Name() string {
	return tsp.name
}

func (tsp *tagSpace) GetTag(id uint16) Tag {
	tsp.mu.RLock()
	defer tsp.mu.RUnlock()
	// Fast lookup from cache
	if nstp := tsp.tags[id]; nstp != nil {
		return nstp.tag
	}
	// Slower lookup from map
	for _, ts := range tsp.ts {
		if t, ok := ts.GetTag(id); ok {
			// Cache it for faster future lookups
			tsp.tags[id] = &nsTagPair{ts.Name(), t}
			return t
		}
	}
	return NewTag(id, fmt.Sprintf("UNKNOWN_TAG_%d", id), nil)
}

func (tsp *tagSpace) GetTagSet(name string) (TagSet, bool) {
	tsp.mu.RLock()
	ts, ok := tsp.ts[name]
	tsp.mu.RUnlock()
	return ts, ok
}

func (tsp *tagSpace) GetTagSetNameFromTag(id uint16) string {
	tsp.mu.RLock()
	defer tsp.mu.RUnlock()
	// Fast lookup from cache
	if nstp := tsp.tags[id]; nstp != nil {
		return nstp.tagSetName
	}
	// Slower lookup from map
	for _, ts := range tsp.ts {
		if t, ok := ts.GetTag(id); ok {
			// Cache it for faster future lookups
			tsp.tags[id] = &nsTagPair{ts.Name(), t}
			return ts.Name()
		}
	}
	return ""
}

func (tsp *tagSpace) ListTagSets() []string {
	tsp.mu.RLock()
	names := make([]string, len(tsp.ts))
	i := 0
	for name := range tsp.ts {
		names[i] = name
		i++
	}
	tsp.mu.RUnlock()
	sort.Strings(names)
	return names
}

func (tsp *tagSpace) RegisterTagSet(ts TagSet) {
	tsp.mu.Lock()
	tsp.ts[ts.Name()] = ts
	for _, tID := range ts.ListTags() {
		t, _ := ts.GetTag(tID)
		// See if a tag already exists
		if nstp := tsp.tags[tID]; nstp != nil {
			// If the name is not the same, log a warning.
			if nstp.tag.Name() != t.Name() {
				log.Printf("tiff: registration warning: space %q: tag %d: %q in set %q conflicts with existing %q in set %q\n",
					tsp.name, tID, t.Name(), ts.Name(), nstp.tag.Name(), nstp.tagSetName)
			}
			// If the name is the same, we do not care.
		}
		// If the tag already exists, it will be overwritten in the
		// cache for fast lookup.  We leave it up to users of this
		// package to understand when they write over existing tags.  A
		// user can always get the TagSet and then access the
		// conflicting tag that way.
		tsp.tags[tID] = &nsTagPair{ts.Name(), t}
	}
	tsp.mu.Unlock()
}

func (tsp *tagSpace) MarshalJSON() ([]byte, error) {
	tmp := struct {
		Name string
	}{
		Name: tsp.name,
	}
	return json.Marshal(tmp)
}

func (tsp *tagSpace) String() string {
	return fmt.Sprintf("<TagSpace: %q>", tsp.name)
}

//
var DefaultTagSpace = NewTagSpace("Default")

// RegisterTagSet registers a TagSet in the DefaultTagSpace.  Only tags that
// would not cause collisions should be registered this way (i.e. GPS and
// MakerNote tags would cause collisions with the default tiff tag space.)
func RegisterTagSet(ts TagSet) {
	DefaultTagSpace.RegisterTagSet(ts)
}

var allTagSpaceMap = struct {
	mu   sync.RWMutex
	list map[string]TagSpace
}{
	list: make(map[string]TagSpace, 1),
}

func RegisterTagSpace(tsp TagSpace) {
	allTagSpaceMap.mu.Lock()
	allTagSpaceMap.list[tsp.Name()] = tsp
	allTagSpaceMap.mu.Unlock()
}

func GetTagSpace(name string) TagSpace {
	allTagSpaceMap.mu.RLock()
	defer allTagSpaceMap.mu.RUnlock()
	return allTagSpaceMap.list[name]
}

func ListTagSpaceNames() []string {
	allTagSpaceMap.mu.RLock()
	defer allTagSpaceMap.mu.RUnlock()
	names := make([]string, 0, len(allTagSpaceMap.list))
	for k := range allTagSpaceMap.list {
		names = append(names, k)
	}
	sort.Strings(names)
	return names
}


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * The global object.
 * @type {!Object}
 */
const global = this;

// TODO(estade): This should be removed and calls replaced with cr.isMac
const IS_MAC = /^Mac/.test(navigator.platform);

/**
 * Alias for document.getElementById.
 * @param {string} id The ID of the element to find.
 * @return {HTMLElement} The found element or null if not found.
 */
function $(id) {
  return document.getElementById(id);
}

/**
 * Calls chrome.send with a callback and restores the original afterwards.
 * @param {string} name The name of the message to send.
 * @param {!Array} params The parameters to send.
 * @param {string} callbackName The name of the function that the backend calls.
 * @param {!Function} The function to call.
 */
function chromeSend(name, params, callbackName, callback) {
  var old = global[callbackName];
  global[callbackName] = function() {
    // restore
    global[callbackName] = old;

    var args = Array.prototype.slice.call(arguments);
    return callback.apply(global, args);
  };
  chrome.send(name, params);
}

/**
 * Generates a CSS url string.
 * @param {string} s The URL to generate the CSS url for.
 * @return {string} The CSS url string.
 */
function url(s) {
  // http://www.w3.org/TR/css3-values/#uris
  // Parentheses, commas, whitespace characters, single quotes (') and double
  // quotes (") appearing in a URI must be escaped with a backslash
  var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1');
  // WebKit has a bug when it comes to URLs that end with \
  // https://bugs.webkit.org/show_bug.cgi?id=28885
  if (/\\\\$/.test(s2)) {
    // Add a space to work around the WebKit bug.
    s2 += ' ';
  }
  return 'url("' + s2 + '")';
}

/**
 * Parses query parameters from Location.
 * @param {string} s The URL to generate the CSS url for.
 * @return {object} Dictionary containing name value pairs for URL
 */
function parseQueryParams(location) {
  var params = {};
  var query = unescape(location.search.substring(1));
  var vars = query.split("&");
  for (var i=0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    params[pair[0]] = pair[1];
  }
  return params;
}

function findAncestorByClass(el, className) {
  return findAncestor(el, function(el) {
    if (el.classList)
      return el.classList.contains(className);
    return null;
  });
}

/**
 * Return the first ancestor for which the {@code predicate} returns true.
 * @param {Node} node The node to check.
 * @param {function(Node) : boolean} predicate The function that tests the
 *     nodes.
 * @return {Node} The found ancestor or null if not found.
 */
function findAncestor(node, predicate) {
  var last = false;
  while (node != null && !(last = predicate(node))) {
    node = node.parentNode;
  }
  return last ? node : null;
}

function swapDomNodes(a, b) {
  var afterA = a.nextSibling;
  if (afterA == b) {
    swapDomNodes(b, a);
    return;
  }
  var aParent = a.parentNode;
  b.parentNode.replaceChild(a, b);
  aParent.insertBefore(b, afterA);
}

// Handle click on a link. If the link points to a chrome: or file: url, then
// call into the browser to do the navigation.
document.addEventListener('click', function(e) {
  // Allow preventDefault to work.
  if (!e.returnValue)
    return;

  var el = e.target;
  if (el.nodeType == Node.ELEMENT_NODE &&
      el.webkitMatchesSelector('A, A *')) {
    while (el.tagName != 'A') {
      el = el.parentElement;
    }

    if ((el.protocol == 'file:' || el.protocol == 'about:') &&
        (e.button == 0 || e.button == 1)) {
      chrome.send('navigateToUrl', [
        el.href,
        el.target,
        e.button,
        e.altKey,
        e.ctrlKey,
        e.metaKey,
        e.shiftKey
      ]);
      e.preventDefault();
    }
  }
});


text:
' *********************************************************
'
' Copyright © Microsoft Corporation
'
' 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
'
' THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES
' OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
' INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES
' OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
'
' See the Apache 2 License for the specific language
' governing permissions and limitations under the License.
'
' *********************************************************

Imports System.Threading
Imports System.Threading.Tasks
Imports System.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic

<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:="RemoveByValVB"), [Shared]>
Class RemoveByValCodeRefactoringProvider
    Inherits CodeRefactoringProvider

    Public NotOverridable Overrides Async Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task
        Dim document = context.Document
        Dim textSpan = context.Span
        Dim cancellationToken = context.CancellationToken

        Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
        Dim token = root.FindToken(textSpan.Start)

        If token.Kind = SyntaxKind.ByValKeyword AndAlso token.Span.IntersectsWith(textSpan.Start) Then
            context.RegisterRefactoring(New RemoveByValCodeAction("Remove unnecessary ByVal keyword",
                                                                  Function(c) RemoveOccuranceAsync(document, token, c)))
            context.RegisterRefactoring(New RemoveByValCodeAction("Remove all occurrences",
                                                                  Function(c) RemoveAllOccurancesAsync(document, c)))
        End If
    End Function

    Private Async Function RemoveOccuranceAsync(document As Document, token As SyntaxToken, cancellationToken As CancellationToken) As Task(Of Document)
        Dim oldRoot = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
        Dim rewriter = New Rewriter(Function(t) t = token)
        Dim newRoot = rewriter.Visit(oldRoot)
        Return document.WithSyntaxRoot(newRoot)
    End Function

    Private Async Function RemoveAllOccurancesAsync(document As Document, cancellationToken As CancellationToken) As Task(Of Document)
        Dim oldRoot = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
        Dim rewriter = New Rewriter(Function(current) True)
        Dim newRoot = rewriter.Visit(oldRoot)
        Return document.WithSyntaxRoot(newRoot)
    End Function

    Class Rewriter
        Inherits VisualBasicSyntaxRewriter

        Private ReadOnly _predicate As Func(Of SyntaxToken, Boolean)

        Public Sub New(predicate As Func(Of SyntaxToken, Boolean))
            _predicate = predicate
        End Sub

        Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken
            If token.Kind = SyntaxKind.ByValKeyword AndAlso _predicate(token) Then
                Return SyntaxFactory.Token(token.LeadingTrivia, SyntaxKind.ByValKeyword, Nothing, String.Empty)
            End If

            Return token
        End Function
    End Class

    Class RemoveByValCodeAction
        Inherits CodeAction

        Private createChangedDocument As Func(Of Object, Task(Of Document))
        Private _title As String

        Public Sub New(title As String, createChangedDocument As Func(Of Object, Task(Of Document)))
            Me._title = title
            Me.createChangedDocument = createChangedDocument
        End Sub

        Public Overrides ReadOnly Property Title As String
            Get
                Throw New NotImplementedException()
            End Get
        End Property

        Protected Overrides Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document)
            Return Me.createChangedDocument(cancellationToken)
        End Function
    End Class
End Class


text:
// "Replace with 'getOrDefault' method call" "true"
import java.util.Map;

public class Main {
  private static final String NONE = "none";

  private String str;

  public void testGetOrDefault(Map<String, String> map, String key, Main other) {
    /* output none */
      System.out.println(/* output map value */ map.getOrDefault("k", NONE));
  }
}


text:
package com.palantir.conjure.java.client.jaxrs.feignimpl;

import com.google.common.base.Preconditions;
import feign.Param.Expander;
import java.util.Objects;
import java.util.Optional;

/**
 * Expands Optional by using the empty string for {@link Optional#empty()} and the {@link Object#toString()} of the
 * value otherwise.
 */
public final class Java8EmptyOptionalExpander implements Expander {

    @Override
    public String expand(Object value) {
        Preconditions.checkArgument(value instanceof Optional, "Value must be an Optional. Was: %s", value.getClass());
        Optional<?> optional = (Optional<?>) value;
        return optional.isPresent() ? Objects.toString(optional.get()) : "";
    }
}


text:
'use strict';

/* Controllers */

var activitiesControllers = angular.module('activitiesControllers', []);

activitiesControllers.controller('ActivitiesListCtrl', ['$scope', 'Activitie',
  function($scope, Activitie) {
    $scope.activities = Activitie.query();
    $scope.orderProp = 'requestDate';

    //comprueba que la actividad no tenga estado
    $scope.unset = function(obj){
      if(obj.approved == "")
        return true;
    };

    //comprueba que la actividad alla sido no aprobado
    $scope.notApproved = function(obj){
      if(obj.approved == "false")
        return true;
    };

    //comprueba que la actividad sea aprobada
    $scope.approved = function(obj){
      if(obj.approved == "true")
        return true;
    };

    //dada dos fechas devuelve el número de días de diferencia entre ellas
    $scope.dateSub = function(beginDate, endDate){
      var d1 = new Date(beginDate);
      var d2 = new Date(endDate);
      var miliseconds = d2-d1;
      var seconds = miliseconds/1000;
      var minutes = seconds/60;
      var hours = minutes/60;
      var days = hours/24;
      return days;
    }

    //acepta una actividad
    $scope.aceptar = function(activitie){
      activitie.approved = "true";
    }

    //rechaza una oportunidad
    $scope.rechazar = function(activitie){
      activitie.approved = "false";
    }

  }]);


text:
// source: pages/stores.ts
/// <reference path="../typings/mithriljs/mithril.d.ts" />
/// <reference path="../models/store_status.ts" />

// Author: Bram Gruneir (bram+code@cockroachlabs.com)

/**
 * AdminViews is the primary module for Cockroaches administrative web
 * interface.
 */
module AdminViews {
  /**
   * Stores is the view for exploring the status of all Stores.
   */
  export module Stores {
    // TODO(bram): Lots of duplicate code between here and nodes.ts, refactor
    // it into one place.
    export interface RefreshFunction {
      f: () => _mithril.MithrilPromise<any>;
      o: any;
    }

    export interface QueryManagerSourceMap {
      [storeId: number]: { [source: string]: Models.Metrics.QueryManager }
    }

    export var storeStatuses: Models.StoreStatus.Stores = new Models.StoreStatus.Stores();
    export var queryManagers: QueryManagerSourceMap = {};

    export class Controller implements _mithril.MithrilController {
      private static _queryEveryMS = 10000;
      private _interval: number;
      private _storeId: string;
      private _refreshFunctions: RefreshFunction[]

      private _refresh(): void {
        for (var i = 0; i < this._refreshFunctions.length; i++) {
          this._refreshFunctions[i].f.call(this._refreshFunctions[i].o);
        }
      }

      private static _queryManagerBuilder(storeId: string, agg: Models.Metrics.QueryAggregator, source: string): Models.Metrics.QueryManager {
        var query = new Models.Metrics.RecentQuery(10 * 60 * 1000, agg, "cr.store." + source + "." + storeId);
        return new Models.Metrics.QueryManager(query);
      }

      private _addChart(agg: Models.Metrics.QueryAggregator, source: string): void {
        var name = agg + ":" + source;
        if (queryManagers[this._storeId][name] == null) {
          queryManagers[this._storeId][name] = Controller._queryManagerBuilder(this._storeId, agg, source);
        }
        this._refreshFunctions.push({ f: queryManagers[this._storeId][name].refresh, o: queryManagers[this._storeId][name] });
      }

      public constructor(storeId?:string) {
        this._refreshFunctions = [{
          f: storeStatuses.Query,
          o: storeStatuses
        }];

        if (storeId != null) {
          this._storeId = storeId;

          // Add a collection of charts.
          if (queryManagers[storeId] == null) {
            queryManagers[storeId] = {};
          }
          this._addChart(Models.Metrics.QueryAggregator.AVG, "keycount");
          this._addChart(Models.Metrics.QueryAggregator.AVG, "valcount");
          this._addChart(Models.Metrics.QueryAggregator.AVG, "livecount");
          this._addChart(Models.Metrics.QueryAggregator.AVG, "intentcount");
          this._addChart(Models.Metrics.QueryAggregator.AVG, "ranges");

          //TODO(Bram): Byte charts won't display properly.
          //this._addChart(Models.Metrics.QueryAggregator.AVG, "valbytes");
          //this._addChart(Models.Metrics.QueryAggregator.AVG, "livebytes");
          //this._addChart(Models.Metrics.QueryAggregator.AVG, "intentbytes");
          //this._addChart(Models.Metrics.QueryAggregator.AVG, "keybytes");
        } else {
          this._storeId = null;
        }

        this._refresh();
        this._interval = setInterval(() => this._refresh(), Controller._queryEveryMS);
      }

      public onunload() {
        clearInterval(this._interval);
      }
    }

    /**
     * StoresPage show a list of all active stores.
     */
    export module StoresPage {
      export function controller():Controller {
        return new Controller();
      }
      export function view(crtl:Controller) {
        return m("div", [
          m("h2", "Stores List"),
          m("ul", [
            Object.keys(storeStatuses.desc()).sort().map(function(storeId) {
              var desc = storeStatuses.desc()[storeId];
              return m("li", { key: desc.store_id },
                m("div", [
                  m.trust(" • "),
                  m("a[href=/stores/" + storeId + "]", { config: m.route }, "Store:" + storeId),
                  " on ",
                  m("a[href=/nodes/" + desc.node.node_id + "]", { config: m.route },"Node:" + desc.node.node_id),
                  " with Address:" + desc.node.address.network + "-" + desc.node.address.address
                ]));
            }),
            storeStatuses.AllDetails()
          ]),
        ]);
      }
    }

    /**
     * StorePage show the details of a single node.
     */
    export module StorePage {
      export function controller():Controller {
        var storeId = m.route.param("store_id");
        return new Stores.Controller(storeId);
      }
      export function view(crtl:Controller) {
        var storeId = m.route.param("store_id");
        return m("div", [
          m("h2", "Store Status"),
          m("div", [
            m("h3", "Store: " + storeId),
            storeStatuses.Details(storeId)
          ]),
          m("table", [
            m("tr", [
              m("td", [
                m("h4", "Key Count"),
                Components.Metrics.LineGraph.create(Stores.queryManagers[storeId]["1:keycount"])
              ]),
              m("td", [
                m("h4", "Value Count"),
                Components.Metrics.LineGraph.create(Stores.queryManagers[storeId]["1:valcount"])
              ])
            ]),
            m("tr", [
              m("td", [
                m("h4", "Live Count"),
                Components.Metrics.LineGraph.create(Stores.queryManagers[storeId]["1:livecount"])
              ]),
              m("td", [
                m("h4", "Intent Count"),
                Components.Metrics.LineGraph.create(Stores.queryManagers[storeId]["1:intentcount"])
              ])
            ]),
            m("tr", [
              m("td", [
                m("h4", "Range Count"),
                Components.Metrics.LineGraph.create(Stores.queryManagers[storeId]["1:ranges"])
              ]),
              m("td")
            ])
          ])
        ]);
      }
    }
  }
}


text:
package org.apache.felix.http.base.internal.handler;

import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import static jakarta.servlet.http.HttpServletResponse.SC_PAYMENT_REQUIRED;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.apache.felix.http.base.internal.context.ExtServletContext;
import org.apache.felix.http.base.internal.dispatch.InvocationChain;
import org.apache.felix.http.base.internal.runtime.FilterInfo;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceObjects;
import org.osgi.framework.ServiceReference;
import org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants;

import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class FilterHandlerTest
{
    private Filter filter;

    private ExtServletContext context;

    @Before
    public void setUp()
    {
        this.context = Mockito.mock(ExtServletContext.class);
        this.filter = mock(Filter.class);
    }

    @Test
    public void testCompare()
    {
        FilterHandler h1 = createHandler(0, "a");
        FilterHandler h2 = createHandler(10, "b");
        FilterHandler h3 = createHandler(10, "c");

        assertTrue(h1.compareTo(h1) == 0);

        assertTrue(h1.compareTo(h2) > 0);
        assertTrue(h2.compareTo(h1) < 0);

        // h2 is actually registered first, so should be called first...
        assertTrue(h2.compareTo(h3) < 0);
        assertTrue(h3.compareTo(h2) > 0);
    }

    @Test
    public void testDestroy()
    {
        FilterHandler h1 = createHandler(0, "/a");
        h1.init();
        h1.destroy();
        verify(this.filter).destroy();
    }

    @Test
    public void testHandleFound() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/a");
        h1.init();
        HttpServletRequest req = createServletRequest();
        HttpServletResponse res = createServletResponse();
        FilterChain chain = mock(FilterChain.class);
        when(this.context.handleSecurity(req, res)).thenReturn(true);

        when(req.getRequestURI()).thenReturn("/a");
        h1.handle(req, res, chain);

        verify(this.filter).doFilter(req, res, chain);
        verify(chain, never()).doFilter(req, res);
    }

    @Test
    public void testHandleFoundContextRoot() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/");
        h1.init();
        HttpServletRequest req = createServletRequest();
        HttpServletResponse res = createServletResponse();
        FilterChain chain = mock(FilterChain.class);
        when(this.context.handleSecurity(req, res)).thenReturn(true);

        when(req.getRequestURI()).thenReturn(null);
        h1.handle(req, res, chain);

        verify(this.filter).doFilter(req, res, chain);
        verify(chain, never()).doFilter(req, res);
    }

    /**
     * FELIX-3988: only send an error for uncomitted responses with default status codes.
     */
    @Test
    public void testHandleFoundForbidden() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/a");
        final ServletHandler sc = mock(ServletHandler.class);
        when(sc.getContext()).thenReturn(this.context);
        final InvocationChain ic = new InvocationChain(sc, new FilterHandler[] {h1});
        HttpServletRequest req = createServletRequest();
        HttpServletResponse res = createServletResponse();

        when(req.getRequestURI()).thenReturn("/a");
        // Default behaviour: uncomitted response and default status code...
        when(res.isCommitted()).thenReturn(false);
        when(res.getStatus()).thenReturn(SC_OK);

        when(this.context.handleSecurity(req, res)).thenReturn(false);

        ic.doFilter(req, res);

        verify(this.filter, never()).doFilter(req, res, ic);
        verify(res).sendError(SC_FORBIDDEN);
    }

    /**
     * FELIX-3988: do not try to write to an already committed response.
     */
    @Test
    public void testHandleFoundForbiddenCommittedOwnResponse() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/a");
        final ServletHandler sc = mock(ServletHandler.class);
        when(sc.getContext()).thenReturn(this.context);
        final InvocationChain ic = new InvocationChain(sc, new FilterHandler[] {h1});
        HttpServletRequest req = createServletRequest();
        HttpServletResponse res = createServletResponse();

        when(req.getRequestURI()).thenReturn("/a");
        // Simulate an already committed response...
        when(res.isCommitted()).thenReturn(true);
        when(res.getStatus()).thenReturn(SC_OK);

        when(this.context.handleSecurity(req, res)).thenReturn(false);

        ic.doFilter(req, res);

        verify(this.filter, never()).doFilter(req, res, ic);
        // Should not be called from our handler...
        verify(res, never()).sendError(SC_FORBIDDEN);
    }

    /**
     * FELIX-3988: do not overwrite custom set status code.
     */
    @Test
    public void testHandleFoundForbiddenCustomStatusCode() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/a");
        final ServletHandler sc = mock(ServletHandler.class);
        when(sc.getContext()).thenReturn(this.context);
        final InvocationChain ic = new InvocationChain(sc, new FilterHandler[] {h1});
        HttpServletRequest req = createServletRequest();
        HttpServletResponse res = createServletResponse();

        when(req.getRequestURI()).thenReturn("/a");
        // Simulate an uncommitted response with a non-default status code...
        when(res.isCommitted()).thenReturn(false);
        when(res.getStatus()).thenReturn(SC_PAYMENT_REQUIRED);

        when(this.context.handleSecurity(req, res)).thenReturn(false);

        ic.doFilter(req, res);

        verify(this.filter, never()).doFilter(req, res, ic);
        // Should not be called from our handler...
        verify(res, never()).sendError(SC_FORBIDDEN);
    }

    @Test
    public void testHandleNotFound() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/a");
        final ServletHandler sc = mock(ServletHandler.class);
        when(sc.getContext()).thenReturn(this.context);
        final InvocationChain ic = new InvocationChain(sc, new FilterHandler[] {h1});
        HttpServletRequest req = createServletRequest();
        HttpServletResponse res = createServletResponse();

        when(req.getRequestURI()).thenReturn("/");
        ic.doFilter(req, res);

        verify(this.filter, never()).doFilter(req, res, ic);
    }

    @Test
    public void testHandleNotFoundContextRoot() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/a");
        final ServletHandler sc = mock(ServletHandler.class);
        when(sc.getContext()).thenReturn(this.context);
        final InvocationChain ic = new InvocationChain(sc, new FilterHandler[] {h1});
        HttpServletRequest req = createServletRequest();
        HttpServletResponse res = createServletResponse();

        when(req.getRequestURI()).thenReturn(null);
        ic.doFilter(req, res);

        verify(this.filter, never()).doFilter(req, res, ic);
    }

    @Test
    public void testInit() throws Exception
    {
        FilterHandler h1 = createHandler(0, "/a");
        h1.init();
        verify(this.filter).init(any(FilterConfig.class));
    }

    private static long id = 1;

    private FilterHandler createHandler(int ranking, String pattern)
    {
        @SuppressWarnings("unchecked")
        final ServiceReference<Filter> ref = mock(ServiceReference.class);
        when(ref.getProperty(Constants.SERVICE_ID)).thenReturn(id++);
        when(ref.getProperty(Constants.SERVICE_RANKING)).thenReturn(ranking);
        when(ref.getProperty(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN)).thenReturn(pattern);
        when(ref.getPropertyKeys()).thenReturn(new String[0]);
        final FilterInfo info = new FilterInfo(ref);

        @SuppressWarnings("unchecked")
        final ServiceObjects<Filter> so = mock(ServiceObjects.class);
        final BundleContext ctx = mock(BundleContext.class);
        when(ctx.getServiceObjects(ref)).thenReturn(so);
        when(so.getService()).thenReturn(this.filter);
        return  new FilterHandler(-1, this.context, info, ctx);
    }

    private HttpServletRequest createServletRequest()
    {
        return createServletRequest(DispatcherType.REQUEST);
    }

    private HttpServletRequest createServletRequest(DispatcherType type)
    {
        HttpServletRequest result = mock(HttpServletRequest.class);
        when(result.getDispatcherType()).thenReturn(type);
        return result;
    }

    private HttpServletResponse createServletResponse()
    {
        return mock(HttpServletResponse.class);
    }
}


text: export { default } from './Loading.render';