text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

def print_tensor_shape(tensor, string):

# input: tensor and string to describe it

    if __debug__:
        print('DEBUG ' + string, tensor.get_shape())

def inference(images, size, keep_prob=1, batch_size=1, regularization_constant=0.0):

#   input: tensor of images
#   output: tensor of computed logits

# resize the image tensors to add the number of channels, 1 in this case
# required to pass the images to various layers upcoming in the graph
    #print("Image size:", size)
    #num_channels = size[0], depth = size[0], height = size[1], width = size[2], num_channels = size[3]
    print_tensor_shape(images, "images")
# Convolution layer
    with tf.name_scope('Matmul1'):

        W_matmul1 = tf.Variable(tf.truncated_normal([size[0]*size[1]*size[2]*size[3], 4096],stddev=0.1,
                     dtype=tf.float32),name='W_matmul1')
        print_tensor_shape( W_matmul1, 'W_matmul1 shape')

        matmul1_op = tf.matmul(images, W_matmul1)

        print_tensor_shape( matmul1_op, 'matmul1_op shape')

        W_bias1 = tf.Variable( tf.zeros([4096], dtype=tf.float32),
                          name='W_bias1')
        print_tensor_shape( W_bias1, 'W_bias1 shape')

        bias1_op = matmul1_op + W_bias1
        print_tensor_shape( bias1_op, 'bias1_op shape')

        relu1_op = tf.nn.relu( bias1_op, name='relu1_op' )
        print_tensor_shape( relu1_op, 'relu1_op shape')

    with tf.name_scope('Matmul2'):

        W_matmul2 = tf.Variable(tf.truncated_normal([4096, 2048],stddev=0.1,
                     dtype=tf.float32),name='W_matmul2')
        print_tensor_shape( W_matmul2, 'W_matmul2 shape')

        matmul2_op = tf.matmul(relu1_op, W_matmul2)

        print_tensor_shape( matmul2_op, 'matmul2_op shape')

        W_bias2 = tf.Variable( tf.zeros([2048], dtype=tf.float32),
                          name='W_bias2')
        print_tensor_shape( W_bias2, 'W_bias2 shape')

        bias2_op = matmul2_op + W_bias2
        print_tensor_shape( bias2_op, 'bias2_op shape')

        relu2_op = tf.nn.relu( bias2_op, name='relu1_op' )
        print_tensor_shape( relu2_op, 'relu2_op shape')

    with tf.name_scope('Matmul3'):

        W_matmul3 = tf.Variable(tf.truncated_normal([2048, 1024],stddev=0.1,
                     dtype=tf.float32),name='W_matmul3')
        print_tensor_shape( W_matmul3, 'W_matmul3 shape')

        matmul3_op = tf.matmul(relu2_op, W_matmul3)

        print_tensor_shape( matmul3_op, 'matmul3_op shape')

        W_bias3 = tf.Variable( tf.zeros([1024], dtype=tf.float32),
                          name='W_bias3')
        print_tensor_shape( W_bias3, 'W_bias3 shape')

        bias3_op = matmul3_op + W_bias3
        print_tensor_shape( bias3_op, 'bias3_op shape')

        relu3_op = tf.nn.relu( bias3_op, name='relu1_op' )
        print_tensor_shape( relu3_op, 'relu3_op shape')

    with tf.name_scope('Matmul4'):

        W_matmul4 = tf.Variable(tf.truncated_normal([1024, 512],stddev=0.1,
                     dtype=tf.float32),name='W_matmul4')
        print_tensor_shape( W_matmul4, 'W_matmul3 shape')

        matmul4_op = tf.matmul(relu3_op, W_matmul4)

        print_tensor_shape( matmul4_op, 'matmul4_op shape')

        W_bias4 = tf.Variable( tf.zeros([512], dtype=tf.float32),
                          name='W_bias4')
        print_tensor_shape( W_bias4, 'W_bias4 shape')

        bias4_op = matmul4_op + W_bias4
        print_tensor_shape( bias4_op, 'bias4_op shape')

        relu4_op = tf.nn.relu( bias4_op, name='relu1_op' )
        print_tensor_shape( relu4_op, 'relu4_op shape')

        drop_op = tf.nn.dropout( relu4_op, keep_prob )
        print_tensor_shape( drop_op, 'drop_op shape' )

    with tf.name_scope('Matmul5'):

        W_matmul5 = tf.Variable(tf.truncated_normal([512, 2],stddev=0.1,
                     dtype=tf.float32),name='W_matmul5')
        print_tensor_shape( W_matmul5, 'W_matmul5 shape')

        matmul5_op = tf.matmul(drop_op, W_matmul5)
        print_tensor_shape( matmul5_op, 'matmul5_op shape')

        W_bias5 = tf.Variable( tf.zeros([2], dtype=tf.float32),
                          name='W_bias5')
        print_tensor_shape( W_bias5, 'W_bias5 shape')

        bias5_op = matmul5_op + W_bias5
        print_tensor_shape( bias5_op, 'bias5_op shape')

    #Regularization of all the weights in the network for the loss function
    with tf.name_scope('Regularization'):
      Reg_constant = tf.constant(regularization_constant)
      reg_op = tf.nn.l2_loss(W_matmul1) + tf.nn.l2_loss(W_matmul2)  + tf.nn.l2_loss(W_matmul3) + tf.nn.l2_loss(W_matmul4) + tf.nn.l2_loss(W_matmul5)
      reg_op = reg_op*Reg_constant
      tf.summary.scalar('reg_op', reg_op)

    return bias5_op + reg_op

def evaluation(logits, labels):
    #return tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits,1), tf.argmax(labels,1)), tf.float32))
    values, indices = tf.nn.top_k(labels, 1);
    correct = tf.reshape(tf.nn.in_top_k(logits, tf.cast(tf.reshape( indices, [-1 ] ), tf.int32), 1), [-1] )
    print_tensor_shape( correct, 'correct shape')
    return tf.reduce_mean(tf.cast(correct, tf.float32), name='accuracy')

def training(loss, learning_rate, decay_steps, decay_rate):
    # input: loss: loss tensor from loss()
    # input: learning_rate: scalar for gradient descent
    # output: train_op the operation for training

#    Creates a summarizer to track the loss over time in TensorBoard.

#    Creates an optimizer and applies the gradients to all trainable variables.

#    The Op returned by this function is what must be passed to the
#    `sess.run()` call to cause the model to train.

  # Add a scalar summary for the snapshot loss.

  # Create a variable to track the global step.
    global_step = tf.Variable(0, name='global_step', trainable=False)

  # create learning_decay
    lr = tf.train.exponential_decay( learning_rate,
                                     global_step,
                                     decay_steps,
                                     decay_rate, staircase=True )

    tf.summary.scalar('2learning_rate', lr )

  # Create the gradient descent optimizer with the given learning rate.
#    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    optimizer = tf.train.GradientDescentOptimizer(lr)

  # Use the optimizer to apply the gradients that minimize the loss
  # (and also increment the global step counter) as a single training step.
    train_op = optimizer.minimize(loss, global_step=global_step)

    return train_op

def loss(logits, labels):

    print_tensor_shape( logits, 'logits shape')
    print_tensor_shape( labels, 'labels shape')

    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, labels, name='cross_entropy')

    loss = tf.reduce_mean(cross_entropy, name='cross_entropy_mean')

    return loss


text:
package com.hyh.tools.download.paser;

/**
 * @author Administrator
 * @description
 * @data 2018/3/1
 */

public class SimpleDataHelper {

    public static boolean isSimpleData(Object object) {
        if (object == null) {
            return false;
        }
        Class[] simpleDataClasses = {String.class, Byte.class, Short.class, Integer.class, Long.class,
                Float.class, Double.class, Boolean.class, Character.class};
        for (Class simpleDataClass : simpleDataClasses) {
            if (simpleDataClass.equals(object.getClass())) {
                return true;
            }
        }
        return false;
    }

}

redpajama_set_name: RedPajamaGithub


text:
source_files := $(wildcard build/*.asm)
source_files += $(addprefix build/,$(wildcard *.asm))

obj_files := $(patsubst %.asm,%.o,$(source_files))
v86_executables := $(patsubst %.asm,%.img,$(source_files))

inc_files := $(addprefix build/,$(wildcard *.inc))

all: $(source_files) $(obj_files) $(inc_files) $(v86_executables)
.PHONY: all

build/%.o: build/%.asm $(inc_files)
	nasm -w+error -felf32 -o $@ $<

# used both as a multiboot image for v86 and as a regular elf executable for gdb
build/%.img: build/%.o
	ld -g $< -m elf_i386 --section-start=.bss=0x100000 --section-start=.text=0x80000 --section-start=.multiboot=0x20000 -o $@

build/%.asm: %.asm
	mkdir -p build; cp $< $@

build/%.inc: %.inc
	mkdir -p build; cp $< $@

.PHONY: clean
clean:
	rm -f *.o *.bin *.img *.fixture gen_*.asm # old location
	rm -f build/*.o build/*.bin build/*.img build/*.fixture build/*.asm


text:
/* This module ALONE requires the window message API from user.h
 * and the default APR include of windows.h will omit it, so
 * preload the API symbols now...
 */

#define _WINUSER_

#include "apr.h"
#include "apr_strings.h"
#include "apr_lib.h"
#if APR_HAS_UNICODE_FS
#include "arch/win32/apr_arch_utf8.h"
#include "arch/win32/apr_arch_misc.h"
#include <wchar.h>
#endif

#include "httpd.h"
#include "http_log.h"
#include "mpm_winnt.h"
#include "ap_regkey.h"

#ifdef NOUSER
#undef NOUSER
#endif
#undef _WINUSER_
#include <winuser.h>
#include <time.h>

APLOG_USE_MODULE(mpm_winnt);

/* Todo; clear up statics */
static char *mpm_service_name = NULL;
static char *mpm_display_name = NULL;

#if APR_HAS_UNICODE_FS
static apr_wchar_t *mpm_service_name_w;
#endif

typedef struct nt_service_ctx_t
{
    HANDLE mpm_thread;       /* primary thread handle of the apache server */
    HANDLE service_thread;   /* thread service/monitor handle */
    DWORD  service_thread_id;/* thread service/monitor ID */
    HANDLE service_init;     /* controller thread init mutex */
    HANDLE service_term;     /* NT service thread kill signal */
    SERVICE_STATUS ssStatus;
    SERVICE_STATUS_HANDLE hServiceStatus;
} nt_service_ctx_t;

static nt_service_ctx_t globdat;

static int ReportStatusToSCMgr(int currentState, int waitHint,
                               nt_service_ctx_t *ctx);

/* Rather than repeat this logic throughout, create an either-or wide or narrow
 * implementation because we don't actually pass strings to OpenSCManager.
 * This election is based on build time defines and runtime os version test.
 */
#undef OpenSCManager
typedef SC_HANDLE (WINAPI *fpt_OpenSCManager)(const void *lpMachine,
                                              const void *lpDatabase,
                                              DWORD dwAccess);
static fpt_OpenSCManager pfn_OpenSCManager = NULL;
static APR_INLINE SC_HANDLE OpenSCManager(const void *lpMachine,
                                          const void *lpDatabase,
                                          DWORD dwAccess)
{
    if (!pfn_OpenSCManager) {
#if APR_HAS_UNICODE_FS
        IF_WIN_OS_IS_UNICODE
            pfn_OpenSCManager = (fpt_OpenSCManager)OpenSCManagerW;
#endif
#if APR_HAS_ANSI_FS
        ELSE_WIN_OS_IS_ANSI
            pfn_OpenSCManager = (fpt_OpenSCManager)OpenSCManagerA;
#endif
    }
    return (*(pfn_OpenSCManager))(lpMachine, lpDatabase, dwAccess);
}

/* exit() for Win32 is macro mapped (horrible, we agree) that allows us
 * to catch the non-zero conditions and inform the console process that
 * the application died, and hang on to the console a bit longer.
 *
 * The macro only maps for http_main.c and other sources that include
 * the service.h header, so we best assume it's an error to exit from
 * _any_ other module.
 *
 * If ap_real_exit_code is reset to 0, it will not be set or trigger this
 * behavior on exit.  All service and child processes are expected to
 * reset this flag to zero to avoid undesirable side effects.
 */
AP_DECLARE_DATA int ap_real_exit_code = 1;

void hold_console_open_on_error(void)
{
    HANDLE hConIn;
    HANDLE hConErr;
    DWORD result;
    time_t start;
    time_t remains;
    char *msg = "Note the errors or messages above, "
                "and press the <ESC> key to exit.  ";
    CONSOLE_SCREEN_BUFFER_INFO coninfo;
    INPUT_RECORD in;
    char count[16];

    if (!ap_real_exit_code)
        return;
    hConIn = GetStdHandle(STD_INPUT_HANDLE);
    hConErr = GetStdHandle(STD_ERROR_HANDLE);
    if ((hConIn == INVALID_HANDLE_VALUE) || (hConErr == INVALID_HANDLE_VALUE))
        return;
    if (!WriteConsole(hConErr, msg, (DWORD)strlen(msg), &result, NULL)
            || !result)
        return;
    if (!GetConsoleScreenBufferInfo(hConErr, &coninfo))
        return;
    if (!SetConsoleMode(hConIn, ENABLE_MOUSE_INPUT | 0x80))
        return;

    start = time(NULL);
    do
    {
        while (PeekConsoleInput(hConIn, &in, 1, &result) && result)
        {
            if (!ReadConsoleInput(hConIn, &in, 1, &result) || !result)
                return;
            if ((in.EventType == KEY_EVENT) && in.Event.KeyEvent.bKeyDown
                    && (in.Event.KeyEvent.uChar.AsciiChar == 27))
                return;
            if (in.EventType == MOUSE_EVENT
                    && (in.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK))
                return;
        }
        remains = ((start + 30) - time(NULL));
        sprintf(count, "%d...",
                (int)remains); /* 30 or less, so can't overflow int */
        if (!SetConsoleCursorPosition(hConErr, coninfo.dwCursorPosition))
            return;
        if (!WriteConsole(hConErr, count, (DWORD)strlen(count), &result, NULL)
                || !result)
            return;
    }
    while ((remains > 0) && WaitForSingleObject(hConIn, 1000) != WAIT_FAILED);
}

static BOOL CALLBACK console_control_handler(DWORD ctrl_type)
{
    switch (ctrl_type)
    {
        case CTRL_BREAK_EVENT:
            fprintf(stderr, "Apache server restarting...\n");
            ap_signal_parent(SIGNAL_PARENT_RESTART);
            return TRUE;
        case CTRL_C_EVENT:
            fprintf(stderr, "Apache server interrupted...\n");
            /* for Interrupt signals, shut down the server.
             * Tell the system we have dealt with the signal
             * without waiting for Apache to terminate.
             */
            ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
            return TRUE;

        case CTRL_CLOSE_EVENT:
        case CTRL_LOGOFF_EVENT:
        case CTRL_SHUTDOWN_EVENT:
            /* for Terminate signals, shut down the server.
             * Wait for Apache to terminate, but respond
             * after a reasonable time to tell the system
             * that we did attempt to shut ourself down.
             */
            fprintf(stderr, "Apache server shutdown initiated...\n");
            ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
            Sleep(30000);
            return TRUE;
    }

    /* We should never get here, but this is (mostly) harmless */
    return FALSE;
}

static void stop_console_handler(void)
{
    SetConsoleCtrlHandler(console_control_handler, FALSE);
}

void mpm_start_console_handler(void)
{
    SetConsoleCtrlHandler(console_control_handler, TRUE);
    atexit(stop_console_handler);
}

void mpm_start_child_console_handler(void)
{
    FreeConsole();
}

/**********************************
  WinNT service control management
 **********************************/

static int ReportStatusToSCMgr(int currentState, int waitHint,
                               nt_service_ctx_t *ctx)
{
    int rv = APR_SUCCESS;

    if (ctx->hServiceStatus)
    {
        if (currentState == SERVICE_RUNNING) {
            ctx->ssStatus.dwWaitHint = 0;
            ctx->ssStatus.dwCheckPoint = 0;
            ctx->ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP
                                             | SERVICE_ACCEPT_SHUTDOWN
                                             | SERVICE_ACCEPT_PRESHUTDOWN;
        }
        else if (currentState == SERVICE_STOPPED) {
            ctx->ssStatus.dwWaitHint = 0;
            ctx->ssStatus.dwCheckPoint = 0;
            /* An unexpected exit?  Better to error! */
            if (ctx->ssStatus.dwCurrentState != SERVICE_STOP_PENDING
                    && !ctx->ssStatus.dwServiceSpecificExitCode)
                ctx->ssStatus.dwServiceSpecificExitCode = 1;
            if (ctx->ssStatus.dwServiceSpecificExitCode)
                ctx->ssStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
        }
        else {
            ++ctx->ssStatus.dwCheckPoint;
            ctx->ssStatus.dwControlsAccepted = 0;
            if(waitHint)
                ctx->ssStatus.dwWaitHint = waitHint;
        }

        ctx->ssStatus.dwCurrentState = currentState;

        rv = SetServiceStatus(ctx->hServiceStatus, &ctx->ssStatus);
    }
    return(rv);
}

/* Note this works on Win2000 and later due to ChangeServiceConfig2
 * Continue to test its existence, but at least drop the feature
 * of revising service description tags prior to Win2000.
 */

/* borrowed from mpm_winnt.c */
extern apr_pool_t *pconf;

static void set_service_description(void)
{
    const char *full_description;
    SC_HANDLE schSCManager;

    /* Nothing to do if we are a console
     */
    if (!mpm_service_name)
        return;

    /* Time to fix up the description, upon each successful restart
     */
    full_description = ap_get_server_description();

    if ((ChangeServiceConfig2) &&
        (schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT)))
    {
        SC_HANDLE schService;

#if APR_HAS_UNICODE_FS
        IF_WIN_OS_IS_UNICODE
        {
            schService = OpenServiceW(schSCManager,
                                      (LPCWSTR)mpm_service_name_w,
                                      SERVICE_CHANGE_CONFIG);
        }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
        ELSE_WIN_OS_IS_ANSI
        {
            schService = OpenService(schSCManager, mpm_service_name,
                                     SERVICE_CHANGE_CONFIG);
        }
#endif
        if (schService) {
            /* Cast is necessary, ChangeServiceConfig2 handles multiple
             * object types, some volatile, some not.
             */
#if APR_HAS_UNICODE_FS
            IF_WIN_OS_IS_UNICODE
            {
                apr_size_t slen = strlen(full_description) + 1;
                apr_size_t wslen = slen;
                apr_wchar_t *full_description_w =
                    (apr_wchar_t*)apr_palloc(pconf,
                                             wslen * sizeof(apr_wchar_t));
                apr_status_t rv = apr_conv_utf8_to_ucs2(full_description, &slen,
                                                        full_description_w,
                                                        &wslen);
                if ((rv != APR_SUCCESS) || slen
                        || ChangeServiceConfig2W(schService, 1
                                                 /*SERVICE_CONFIG_DESCRIPTION*/,
                                                 (LPVOID) &full_description_w))
                    full_description = NULL;
            }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
            ELSE_WIN_OS_IS_ANSI
            {
                if (ChangeServiceConfig2(schService,
                                         1 /* SERVICE_CONFIG_DESCRIPTION */,
                                         (LPVOID) &full_description))
                    full_description = NULL;
            }
#endif
            CloseServiceHandle(schService);
        }
        CloseServiceHandle(schSCManager);
    }
}

/* handle the SCM's ControlService() callbacks to our service */

static DWORD WINAPI service_nt_ctrl(DWORD dwCtrlCode, DWORD dwEventType,
                                    LPVOID lpEventData, LPVOID lpContext)
{
    nt_service_ctx_t *ctx = lpContext;

    /* SHUTDOWN is offered before STOP, accept the first opportunity */
    if ((dwCtrlCode == SERVICE_CONTROL_STOP)
         || (dwCtrlCode == SERVICE_CONTROL_SHUTDOWN)
         || (dwCtrlCode == SERVICE_CONTROL_PRESHUTDOWN))
    {
        ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
        ReportStatusToSCMgr(SERVICE_STOP_PENDING, 30000, ctx);
        return (NO_ERROR);
    }
    if (dwCtrlCode == SERVICE_APACHE_RESTART)
    {
        ap_signal_parent(SIGNAL_PARENT_RESTART);
        ReportStatusToSCMgr(SERVICE_START_PENDING, 30000, ctx);
        return (NO_ERROR);
    }
    if (dwCtrlCode == SERVICE_CONTROL_INTERROGATE) {
        ReportStatusToSCMgr(globdat.ssStatus.dwCurrentState, 0, ctx);
        return (NO_ERROR);
    }

    return (ERROR_CALL_NOT_IMPLEMENTED);
}

/* service_nt_main_fn is outside of the call stack and outside of the
 * primary server thread... so now we _really_ need a placeholder!
 * The winnt_rewrite_args has created and shared mpm_new_argv with us.
 */
extern apr_array_header_t *mpm_new_argv;

#if APR_HAS_UNICODE_FS
static void __stdcall service_nt_main_fn_w(DWORD argc, LPWSTR *argv)
{
    const char *ignored;
    nt_service_ctx_t *ctx = &globdat;
    char *service_name;
    apr_size_t wslen = wcslen(argv[0]) + 1;
    apr_size_t slen = wslen * 3 - 2;

    service_name = malloc(slen);
    (void)apr_conv_ucs2_to_utf8(argv[0], &wslen, service_name, &slen);

    /* args and service names live in the same pool */
    mpm_service_set_name(mpm_new_argv->pool, &ignored, service_name);

    memset(&ctx->ssStatus, 0, sizeof(ctx->ssStatus));
    ctx->ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    ctx->ssStatus.dwCurrentState = SERVICE_START_PENDING;
    ctx->ssStatus.dwCheckPoint = 1;
    if (!(ctx->hServiceStatus =
              RegisterServiceCtrlHandlerExW(argv[0], service_nt_ctrl, ctx)))
    {
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP,
                     apr_get_os_error(), NULL,
                     APLOGNO(00365) "Failure registering service handler");
        return;
    }

    /* Report status, no errors, and buy 3 more seconds */
    ReportStatusToSCMgr(SERVICE_START_PENDING, 30000, ctx);

    /* We need to append all the command arguments passed via StartService()
     * to our running service... which just got here via the SCM...
     * but we have no interest in argv[0] for the mpm_new_argv list.
     */
    if (argc > 1)
    {
        char **cmb_data, **cmb;
        DWORD i;

        mpm_new_argv->nalloc = mpm_new_argv->nelts + argc - 1;
        cmb_data = malloc(mpm_new_argv->nalloc * sizeof(const char *));

        /* mpm_new_argv remains first (of lower significance) */
        memcpy (cmb_data, mpm_new_argv->elts,
                mpm_new_argv->elt_size * mpm_new_argv->nelts);

        /* Service args follow from StartService() invocation */
        memcpy (cmb_data + mpm_new_argv->nelts, argv + 1,
                mpm_new_argv->elt_size * (argc - 1));

        cmb = cmb_data + mpm_new_argv->nelts;

        for (i = 1; i < argc; ++i)
        {
            wslen = wcslen(argv[i]) + 1;
            slen = wslen * 3 - 2;
            service_name = malloc(slen);
            (void)apr_conv_ucs2_to_utf8(argv[i], &wslen, *(cmb++), &slen);
        }

        /* The replacement arg list is complete */
        mpm_new_argv->elts = (char *)cmb_data;
        mpm_new_argv->nelts = mpm_new_argv->nalloc;
    }

    /* Let the main thread continue now... but hang on to the
     * signal_monitor event so we can take further action
     */
    SetEvent(ctx->service_init);

    WaitForSingleObject(ctx->service_term, INFINITE);
}
#endif /* APR_HAS_UNICODE_FS */

#if APR_HAS_ANSI_FS
static void __stdcall service_nt_main_fn(DWORD argc, LPSTR *argv)
{
    const char *ignored;
    nt_service_ctx_t *ctx = &globdat;

    /* args and service names live in the same pool */
    mpm_service_set_name(mpm_new_argv->pool, &ignored, argv[0]);

    memset(&ctx->ssStatus, 0, sizeof(ctx->ssStatus));
    ctx->ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    ctx->ssStatus.dwCurrentState = SERVICE_START_PENDING;
    ctx->ssStatus.dwCheckPoint = 1;

    if (!(ctx->hServiceStatus =
              RegisterServiceCtrlHandlerExA(argv[0], service_nt_ctrl, ctx)))
        {
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP,
                     apr_get_os_error(), NULL,
                     APLOGNO(10008) "Failure registering service handler");
        return;
    }

    /* Report status, no errors, and buy 3 more seconds */
    ReportStatusToSCMgr(SERVICE_START_PENDING, 30000, ctx);

    /* We need to append all the command arguments passed via StartService()
     * to our running service... which just got here via the SCM...
     * but we have no interest in argv[0] for the mpm_new_argv list.
     */
    if (argc > 1)
    {
        char **cmb_data;

        mpm_new_argv->nalloc = mpm_new_argv->nelts + argc - 1;
        cmb_data = malloc(mpm_new_argv->nalloc * sizeof(const char *));

        /* mpm_new_argv remains first (of lower significance) */
        memcpy (cmb_data, mpm_new_argv->elts,
                mpm_new_argv->elt_size * mpm_new_argv->nelts);

        /* Service args follow from StartService() invocation */
        memcpy (cmb_data + mpm_new_argv->nelts, argv + 1,
                mpm_new_argv->elt_size * (argc - 1));

        /* The replacement arg list is complete */
        mpm_new_argv->elts = (char *)cmb_data;
        mpm_new_argv->nelts = mpm_new_argv->nalloc;
    }

    /* Let the main thread continue now... but hang on to the
     * signal_monitor event so we can take further action
     */
    SetEvent(ctx->service_init);

    WaitForSingleObject(ctx->service_term, INFINITE);
}
#endif

 static DWORD WINAPI service_nt_dispatch_thread(LPVOID nada)
 {
#if APR_HAS_UNICODE_FS
    SERVICE_TABLE_ENTRYW dispatchTable_w[] =
    {
        { L"", service_nt_main_fn_w },
        { NULL, NULL }
    };
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
    SERVICE_TABLE_ENTRYA dispatchTable[] =
    {
        { "", service_nt_main_fn },
        { NULL, NULL }
    };
#endif
    apr_status_t rv;

#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
        rv = StartServiceCtrlDispatcherW(dispatchTable_w);
#endif
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
         rv = StartServiceCtrlDispatcherA(dispatchTable);
#endif
    if (rv) {
        rv = APR_SUCCESS;
    }
    else {
        /* This is a genuine failure of the SCM. */
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(00366) "Error starting Windows service control "
                     "dispatcher");
    }
    return (rv);
}

/* The service configuration's is stored under the following trees:
 *
 * HKLM\System\CurrentControlSet\Services\[service name]
 *
 *     \DisplayName
 *     \ImagePath
 *     \Parameters\ConfigArgs
 */

apr_status_t mpm_service_set_name(apr_pool_t *p, const char **display_name,
                                  const char *set_name)
{
    char key_name[MAX_PATH];
    ap_regkey_t *key;
    apr_status_t rv;

    /* ### Needs improvement, on Win2K the user can _easily_
     * change the display name to a string that doesn't reflect
     * the internal service name + whitespace!
     */
    mpm_service_name = apr_palloc(p, strlen(set_name) + 1);
    apr_collapse_spaces((char*) mpm_service_name, set_name);
#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        apr_size_t slen = strlen(mpm_service_name) + 1;
        apr_size_t wslen = slen;
        mpm_service_name_w = apr_palloc(p, wslen * sizeof(apr_wchar_t));
        rv = apr_conv_utf8_to_ucs2(mpm_service_name, &slen,
                                   mpm_service_name_w, &wslen);
        if (rv != APR_SUCCESS)
            return rv;
        else if (slen)
            return APR_ENAMETOOLONG;
    }
#endif /* APR_HAS_UNICODE_FS */

    apr_snprintf(key_name, sizeof(key_name), SERVICECONFIG, mpm_service_name);
    rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, key_name,
                        APR_READ, pconf);
    if (rv == APR_SUCCESS) {
        rv = ap_regkey_value_get(&mpm_display_name, key, "DisplayName", pconf);
        ap_regkey_close(key);
    }
    if (rv != APR_SUCCESS) {
        /* Take the given literal name if there is no service entry */
        mpm_display_name = apr_pstrdup(p, set_name);
    }
    *display_name = mpm_display_name;

    return rv;
}

apr_status_t mpm_merge_service_args(apr_pool_t *p,
                                   apr_array_header_t *args,
                                   int fixed_args)
{
    apr_array_header_t *svc_args = NULL;
    char conf_key[MAX_PATH];
    char **cmb_data;
    apr_status_t rv;
    ap_regkey_t *key;

    apr_snprintf(conf_key, sizeof(conf_key), SERVICEPARAMS, mpm_service_name);
    rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, conf_key, APR_READ, p);
    if (rv == APR_SUCCESS) {
        rv = ap_regkey_value_array_get(&svc_args, key, "ConfigArgs", p);
        ap_regkey_close(key);
    }
    if (rv != APR_SUCCESS) {
        if (rv == ERROR_FILE_NOT_FOUND) {
            ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, APLOGNO(00367)
                         "No ConfigArgs registered for the '%s' service, "
                         "perhaps this service is not installed?",
                         mpm_service_name);
            return APR_SUCCESS;
        }
        else
            return (rv);
    }

    if (!svc_args || svc_args->nelts == 0) {
        return (APR_SUCCESS);
    }

    /* Now we have the mpm_service_name arg, and the mpm_runservice_nt()
     * call appended the arguments passed by StartService(), so it's
     * time to _prepend_ the default arguments for the server from
     * the service's default arguments (all others override them)...
     */
    args->nalloc = args->nelts + svc_args->nelts;
    cmb_data = malloc(args->nalloc * sizeof(const char *));

    /* First three args (argv[0], -f, path) remain first */
    memcpy(cmb_data, args->elts, args->elt_size * fixed_args);

    /* Service args follow from service registry array */
    memcpy(cmb_data + fixed_args, svc_args->elts,
           svc_args->elt_size * svc_args->nelts);

    /* Remaining new args follow  */
    memcpy(cmb_data + fixed_args + svc_args->nelts,
           (const char **)args->elts + fixed_args,
           args->elt_size * (args->nelts - fixed_args));

    args->elts = (char *)cmb_data;
    args->nelts = args->nalloc;

    return APR_SUCCESS;
}

static void service_stopped(void)
{
    /* Still have a thread & window to clean up, so signal now */
    if (globdat.service_thread)
    {
        /* Stop logging to the event log */
        mpm_nt_eventlog_stderr_flush();

        /* Cause the service_nt_main_fn to complete */
        ReleaseMutex(globdat.service_term);

        ReportStatusToSCMgr(SERVICE_STOPPED, 0, &globdat);

        WaitForSingleObject(globdat.service_thread, 5000);
        CloseHandle(globdat.service_thread);
    }
}

apr_status_t mpm_service_to_start(const char **display_name, apr_pool_t *p)
{
    HANDLE hProc = GetCurrentProcess();
    HANDLE hThread = GetCurrentThread();
    HANDLE waitfor[2];

    /* Prevent holding open the (hidden) console */
    ap_real_exit_code = 0;

     /* GetCurrentThread returns a psuedo-handle, we need
      * a real handle for another thread to wait upon.
      */
    if (!DuplicateHandle(hProc, hThread, hProc, &(globdat.mpm_thread),
                         0, FALSE, DUPLICATE_SAME_ACCESS)) {
        return APR_ENOTHREAD;
    }

    globdat.service_init = CreateEvent(NULL, FALSE, FALSE, NULL);
    globdat.service_term = CreateMutex(NULL, TRUE, NULL);
    if (!globdat.service_init || !globdat.service_term) {
         return APR_EGENERAL;
    }

    globdat.service_thread = CreateThread(NULL, 65536,
                                          service_nt_dispatch_thread,
                                          NULL, stack_res_flag,
                                          &globdat.service_thread_id);

    if (!globdat.service_thread) {
        return APR_ENOTHREAD;
    }

    waitfor[0] = globdat.service_init;
    waitfor[1] = globdat.service_thread;

    /* Wait for controlling thread init or termination */
    if (WaitForMultipleObjects(2, waitfor, FALSE, 10000) != WAIT_OBJECT_0) {
        return APR_ENOTHREAD;
    }

    atexit(service_stopped);
    *display_name = mpm_display_name;
    return APR_SUCCESS;
}

apr_status_t mpm_service_started(void)
{
    set_service_description();
    ReportStatusToSCMgr(SERVICE_RUNNING, 0, &globdat);
    return APR_SUCCESS;
}

void mpm_service_stopping(void)
{
    ReportStatusToSCMgr(SERVICE_STOP_PENDING, 30000, &globdat);
}

apr_status_t mpm_service_install(apr_pool_t *ptemp, int argc,
                                 const char * const * argv, int reconfig)
{
    char key_name[MAX_PATH];
    char *launch_cmd;
    ap_regkey_t *key;
    apr_status_t rv;
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;
    DWORD       rc;
#if APR_HAS_UNICODE_FS
    apr_wchar_t *display_name_w;
    apr_wchar_t *launch_cmd_w;
#endif

    fprintf(stderr, reconfig ? "Reconfiguring the '%s' service\n"
                             : "Installing the '%s' service\n",
                    mpm_display_name);

#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        apr_size_t slen = strlen(mpm_display_name) + 1;
        apr_size_t wslen = slen;
        display_name_w = apr_palloc(ptemp, wslen * sizeof(apr_wchar_t));
        rv = apr_conv_utf8_to_ucs2(mpm_display_name, &slen,
                                   display_name_w, &wslen);
        if (rv != APR_SUCCESS)
            return rv;
        else if (slen)
            return APR_ENAMETOOLONG;

        launch_cmd_w = apr_palloc(ptemp, (MAX_PATH + 17) * sizeof(apr_wchar_t));
        launch_cmd_w[0] = L'"';
        rc = GetModuleFileNameW(NULL, launch_cmd_w + 1, MAX_PATH);
        wcscpy(launch_cmd_w + rc + 1, L"\" -k runservice");
    }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        launch_cmd = apr_palloc(ptemp, MAX_PATH + 17);
        launch_cmd[0] = '"';
        rc = GetModuleFileName(NULL, launch_cmd + 1, MAX_PATH);
        strcpy(launch_cmd + rc + 1, "\" -k runservice");
    }
#endif
    if (rc == 0) {
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(00368) "GetModuleFileName failed");
        return rv;
    }

    schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
                                 SC_MANAGER_CREATE_SERVICE);
    if (!schSCManager) {
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(00369)  "Failed to open the Windows service "
                     "manager, perhaps you forgot to log in as Adminstrator?");
        return (rv);
    }

    if (reconfig) {
#if APR_HAS_UNICODE_FS
        IF_WIN_OS_IS_UNICODE
        {
            schService = OpenServiceW(schSCManager, mpm_service_name_w,
                                      SERVICE_CHANGE_CONFIG);
        }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
        ELSE_WIN_OS_IS_ANSI
        {
            schService = OpenService(schSCManager, mpm_service_name,
                                     SERVICE_CHANGE_CONFIG);
        }
#endif
        if (!schService) {
            rv = apr_get_os_error();
            CloseServiceHandle(schSCManager);
            ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                         APLOGNO(00373) "Failed to open the '%s' service",
                         mpm_display_name);
            return (rv);
        }

#if APR_HAS_UNICODE_FS
        IF_WIN_OS_IS_UNICODE
        {
            rc = ChangeServiceConfigW(schService,
                                      SERVICE_WIN32_OWN_PROCESS,
                                      SERVICE_AUTO_START,
                                      SERVICE_ERROR_NORMAL,
                                      launch_cmd_w, NULL, NULL,
                                      L"Tcpip\0Afd\0", NULL, NULL,
                                      display_name_w);
        }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
        ELSE_WIN_OS_IS_ANSI
        {
            rc = ChangeServiceConfig(schService,
                                     SERVICE_WIN32_OWN_PROCESS,
                                     SERVICE_AUTO_START,
                                     SERVICE_ERROR_NORMAL,
                                     launch_cmd, NULL, NULL,
                                     "Tcpip\0Afd\0", NULL, NULL,
                                     mpm_display_name);
        }
#endif
        if (!rc) {
            ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP,
                         apr_get_os_error(), NULL,
                         APLOGNO(02652) "ChangeServiceConfig failed");

            /* !schService aborts configuration below */
            CloseServiceHandle(schService);
            schService = NULL;
        }
    }
    else {
        /* RPCSS is the Remote Procedure Call (RPC) Locator required
         * for DCOM communication pipes.  I am far from convinced we
         * should add this to the default service dependencies, but
         * be warned that future apache modules or ISAPI dll's may
         * depend on it.
         */
#if APR_HAS_UNICODE_FS
        IF_WIN_OS_IS_UNICODE
        {
            schService = CreateServiceW(schSCManager,    // SCManager database
                                 mpm_service_name_w,   // name of service
                                 display_name_w,   // name to display
                                 SERVICE_ALL_ACCESS,   // access required
                                 SERVICE_WIN32_OWN_PROCESS,  // service type
                                 SERVICE_AUTO_START,   // start type
                                 SERVICE_ERROR_NORMAL, // error control type
                                 launch_cmd_w,         // service's binary
                                 NULL,                 // no load svc group
                                 NULL,                 // no tag identifier
                                 L"Tcpip\0Afd\0",      // dependencies
                                 NULL,                 // use SYSTEM account
                                 NULL);                // no password
        }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
        ELSE_WIN_OS_IS_ANSI
        {
            schService = CreateService(schSCManager,     // SCManager database
                                 mpm_service_name,     // name of service
                                 mpm_display_name,     // name to display
                                 SERVICE_ALL_ACCESS,   // access required
                                 SERVICE_WIN32_OWN_PROCESS,  // service type
                                 SERVICE_AUTO_START,   // start type
                                 SERVICE_ERROR_NORMAL, // error control type
                                 launch_cmd,           // service's binary
                                 NULL,                 // no load svc group
                                 NULL,                 // no tag identifier
                                 "Tcpip\0Afd\0",       // dependencies
                                 NULL,                 // use SYSTEM account
                                 NULL);                // no password
        }
#endif
        if (!schService)
        {
            rv = apr_get_os_error();
            ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                         APLOGNO(00370) "Failed to create the '%s' service",
                         mpm_display_name);
            CloseServiceHandle(schSCManager);
            return (rv);
        }
    }

    CloseServiceHandle(schService);
    CloseServiceHandle(schSCManager);

    set_service_description();

    /* Store the service ConfigArgs in the registry...
     */
    apr_snprintf(key_name, sizeof(key_name), SERVICEPARAMS, mpm_service_name);
    rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, key_name,
                        APR_READ | APR_WRITE | APR_CREATE, pconf);
    if (rv == APR_SUCCESS) {
        rv = ap_regkey_value_array_set(key, "ConfigArgs", argc, argv, pconf);
        ap_regkey_close(key);
    }
    if (rv != APR_SUCCESS) {
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(00371) "Failed to store ConfigArgs for the "
                     "'%s' service in the registry.", mpm_display_name);
        return (rv);
    }
    fprintf(stderr, "The '%s' service is successfully installed.\n",
                    mpm_display_name);
    return APR_SUCCESS;
}

apr_status_t mpm_service_uninstall(void)
{
    apr_status_t rv;
    SC_HANDLE schService;
    SC_HANDLE schSCManager;

    fprintf(stderr, "Removing the '%s' service\n", mpm_display_name);

    schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
                                 SC_MANAGER_CONNECT);
    if (!schSCManager) {
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(10009)  "Failed to open the Windows service "
                     "manager, perhaps you forgot to log in as Adminstrator?");
        return (rv);
    }

#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        schService = OpenServiceW(schSCManager, mpm_service_name_w, DELETE);
    }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        schService = OpenService(schSCManager, mpm_service_name, DELETE);
    }
#endif
    if (!schService) {
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(10010) "Failed to open the '%s' service",
                     mpm_display_name);
        return (rv);
    }

    /* assure the service is stopped before continuing
     *
     * This may be out of order... we might not be able to be
     * granted all access if the service is running anyway.
     *
     * And do we want to make it *this easy* for them
     * to uninstall their service unintentionally?
     */
    /* ap_stop_service(schService);
     */

    if (DeleteService(schService) == 0) {
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(00374) "Failed to delete the '%s' service",
                     mpm_display_name);
        return (rv);
    }

    CloseServiceHandle(schService);
    CloseServiceHandle(schSCManager);

    fprintf(stderr, "The '%s' service has been removed successfully.\n",
                    mpm_display_name);
    return APR_SUCCESS;
}

/* signal_service_transition is a simple thunk to signal the service
 * and monitor its successful transition.  If the signal passed is 0,
 * then the caller is assumed to already have performed some service
 * operation to be monitored (such as StartService), and no actual
 * ControlService signal is sent.
 */

static int signal_service_transition(SC_HANDLE schService, DWORD signal,
                                     DWORD pending, DWORD complete)
{
    if (signal && !ControlService(schService, signal, &globdat.ssStatus))
        return FALSE;

    do {
        Sleep(1000);
        if (!QueryServiceStatus(schService, &globdat.ssStatus))
            return FALSE;
    } while (globdat.ssStatus.dwCurrentState == pending);

    return (globdat.ssStatus.dwCurrentState == complete);
}

apr_status_t mpm_service_start(apr_pool_t *ptemp, int argc,
                               const char * const * argv)
{
    apr_status_t rv;
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    fprintf(stderr, "Starting the '%s' service\n", mpm_display_name);

    schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
                                 SC_MANAGER_CONNECT);
    if (!schSCManager) {
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(10011)  "Failed to open the Windows service "
                     "manager, perhaps you forgot to log in as Adminstrator?");
        return (rv);
    }

#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        schService = OpenServiceW(schSCManager, mpm_service_name_w,
                                  SERVICE_START | SERVICE_QUERY_STATUS);
    }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        schService = OpenService(schSCManager, mpm_service_name,
                                 SERVICE_START | SERVICE_QUERY_STATUS);
    }
#endif
    if (!schService) {
        rv = apr_get_os_error();
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
                     APLOGNO(10012) "Failed to open the '%s' service",
                     mpm_display_name);
        CloseServiceHandle(schSCManager);
        return (rv);
    }

    if (QueryServiceStatus(schService, &globdat.ssStatus)
        && (globdat.ssStatus.dwCurrentState == SERVICE_RUNNING)) {
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL,
                     APLOGNO(00377) "The '%s' service is already started!",
                     mpm_display_name);
        CloseServiceHandle(schService);
        CloseServiceHandle(schSCManager);
        return 0;
    }

    rv = APR_EINIT;
#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        LPWSTR *start_argv_w = malloc((argc + 1) * sizeof(LPCWSTR));
        int i;

        for (i = 0; i < argc; ++i)
        {
            apr_size_t slen = strlen(argv[i]) + 1;
            apr_size_t wslen = slen;
            start_argv_w[i] = malloc(wslen * sizeof(WCHAR));
            rv = apr_conv_utf8_to_ucs2(argv[i], &slen, start_argv_w[i], &wslen);
            if (rv != APR_SUCCESS)
                return rv;
            else if (slen)
                return APR_ENAMETOOLONG;
        }
        start_argv_w[argc] = NULL;

        if (StartServiceW(schService, argc, start_argv_w)
            && signal_service_transition(schService, 0, /* test only */
                                         SERVICE_START_PENDING,
                                         SERVICE_RUNNING))
                rv = APR_SUCCESS;
    }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        char **start_argv = malloc((argc + 1) * sizeof(const char *));
        memcpy(start_argv, argv, argc * sizeof(const char *));
        start_argv[argc] = NULL;

        if (StartService(schService, argc, start_argv)
            && signal_service_transition(schService, 0, /* test only */
                                         SERVICE_START_PENDING,
                                         SERVICE_RUNNING))
                rv = APR_SUCCESS;
    }
#endif
    if (rv != APR_SUCCESS)
        rv = apr_get_os_error();

    CloseServiceHandle(schService);
    CloseServiceHandle(schSCManager);

    if (rv == APR_SUCCESS)
        fprintf(stderr, "The '%s' service is running.\n", mpm_display_name);
    else
        ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00378)
                     "Failed to start the '%s' service",
                     mpm_display_name);

    return rv;
}

/* signal is zero to stop, non-zero for restart */

void mpm_signal_service(apr_pool_t *ptemp, int signal)
{
    int success = FALSE;
    SC_HANDLE   schService;
    SC_HANDLE   schSCManager;

    schSCManager = OpenSCManager(NULL, NULL, /* default machine & database */
                                 SC_MANAGER_CONNECT);

    if (!schSCManager) {
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP,
                     apr_get_os_error(), NULL,
                     APLOGNO(10013)  "Failed to open the Windows service "
                     "manager, perhaps you forgot to log in as Adminstrator?");
        return;
    }

#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        schService = OpenServiceW(schSCManager, mpm_service_name_w,
                                  SERVICE_INTERROGATE | SERVICE_QUERY_STATUS |
                                  SERVICE_USER_DEFINED_CONTROL |
                                  SERVICE_START | SERVICE_STOP);
    }
#endif /* APR_HAS_UNICODE_FS */
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        schService = OpenService(schSCManager, mpm_service_name,
                                 SERVICE_INTERROGATE | SERVICE_QUERY_STATUS |
                                 SERVICE_USER_DEFINED_CONTROL |
                                 SERVICE_START | SERVICE_STOP);
    }
#endif
    if (schService == NULL) {
        /* Could not open the service */
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP,
                     apr_get_os_error(), NULL,
                     APLOGNO(10014) "Failed to open the '%s' service",
                     mpm_display_name);
        CloseServiceHandle(schSCManager);
        return;
    }

    if (!QueryServiceStatus(schService, &globdat.ssStatus)) {
        ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP,
                     apr_get_os_error(), NULL,
                     APLOGNO(00381) "Query of the '%s' service failed",
                     mpm_display_name);
        CloseServiceHandle(schService);
        CloseServiceHandle(schSCManager);
        return;
    }

    if (!signal && (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED)) {
        fprintf(stderr, "The '%s' service is not started.\n", mpm_display_name);
        CloseServiceHandle(schService);
        CloseServiceHandle(schSCManager);
        return;
    }

    fprintf(stderr, signal ? "The '%s' service is restarting.\n"
                           : "The '%s' service is stopping.\n",
                    mpm_display_name);

    if (!signal)
        success = signal_service_transition(schService,
                                            SERVICE_CONTROL_STOP,
                                            SERVICE_STOP_PENDING,
                                            SERVICE_STOPPED);
    else if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) {
        mpm_service_start(ptemp, 0, NULL);
        CloseServiceHandle(schService);
        CloseServiceHandle(schSCManager);
        return;
    }
    else
        success = signal_service_transition(schService,
                                            SERVICE_APACHE_RESTART,
                                            SERVICE_START_PENDING,
                                            SERVICE_RUNNING);

    CloseServiceHandle(schService);
    CloseServiceHandle(schSCManager);

    if (success)
        fprintf(stderr, signal ? "The '%s' service has restarted.\n"
                               : "The '%s' service has stopped.\n",
                        mpm_display_name);
    else
        fprintf(stderr, signal ? "Failed to restart the '%s' service.\n"
                               : "Failed to stop the '%s' service.\n",
                        mpm_display_name);
}


text:
package com.mattjtodd.functional.stream;

import org.junit.Test;

import static com.mattjtodd.functional.stream.Streams.*;
import static com.mattjtodd.functional.stream.Tuple.tupleOf;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Tests for {@link Streams}.
 */
public class StreamsTest {

  @Test
  public void someCheckingIsValueContainer() throws Exception {
    Object value = new Object();

    assertThat(some(value), is(of(value)));
  }

  @Test
  public void noneCheckingIsEmptyOptional() throws Exception {
    assertThat(none(), is(empty()));
  }

  @Test
  public void tailOfEmptyListCheckingEmptyList() throws Exception {
    assertThat(tailOf(emptyList()), is(emptyList()));
  }

  @Test
  public void tailOfSingletonListCheckingEmptyList() throws Exception {
    assertThat(tailOf(singletonList(new Object())), is(emptyList()));
  }

  @Test
  public void tailOfListCheckingList() throws Exception {
    Object tailValue = new Object();

    assertThat(tailOf(asList(new Object(), tailValue)), is(singletonList(tailValue)));
  }

  @Test
  public void sumWhenEmptyStreamIsZero() {
    assertThat(sum(Stream.empty()), is(0));
  }

  @Test
  public void sumWhenOneValueStreamIsOne() {
    assertThat(sum(streamOf(singletonList(1))), is(1));
  }

  @Test
  public void sumWhenFiveValuesStreamIsFive() {
    assertThat(sum(streamOf(asList(1, 1, 1, 1, 1))), is(5));
  }

  @Test
  public void sumWhenLargeValueNoStackOverflow() {
    assertThat(sum(Streams.constant(1).take(100000)), is(100000));
  }

  @Test
  public void unfoldTest() {
    Streams
        .unfold(0, value -> value > 10 ? none() : some(tupleOf(value, value + 1)))
        .toList();
  }
}


text:
<macros>
    <token name="@TOOL_VERSION@">2.3</token>
    <token name="@INTYPES@">
        fasta,fasta.gz,fastq,fastq.gz,fastqsanger,fastqsanger.gz
    </token>
    <xml name="requirements">
        <requirements>
            <requirement type="package" version="@TOOL_VERSION@">mash</requirement>
        </requirements>
    </xml>
    <xml name="citations">
        <citations>
            <citation type="doi">10.1186/s13059-016-0997-x</citation>
        </citations>
    </xml>
    <xml name="version_command">
        <version_command>mash --version</version_command>
    </xml>
</macros>


text:
#ifndef INTERNAL_WARNINGS_H                              /*-*-C-*-vi:se ft=c:*/
#define INTERNAL_WARNINGS_H
/**
 * @author     Ruby developers <ruby-core@ruby-lang.org>
 * @copyright  This  file  is   a  part  of  the   programming  language  Ruby.
 *             Permission  is hereby  granted,  to  either redistribute  and/or
 *             modify this file, provided that  the conditions mentioned in the
 *             file COPYING are met.  Consult the file for details.
 * @brief      Internal header to suppress / mandate warnings.
 */
#include "ruby/internal/warning_push.h"
#define COMPILER_WARNING_PUSH          RBIMPL_WARNING_PUSH()
#define COMPILER_WARNING_POP           RBIMPL_WARNING_POP()
#define COMPILER_WARNING_ERROR(flag)   RBIMPL_WARNING_ERROR(flag)
#define COMPILER_WARNING_IGNORED(flag) RBIMPL_WARNING_IGNORED(flag)
#endif /* INTERNAL_WARNINGS_H */


text:
---
uid: SolidEdgePart.HoleTypeToDeleteConstants
summary: Hole Type To Delete Constants
remarks:
---


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('stats', '0020_awards_example'),
    ]

    operations = [
        migrations.AddField(
            model_name='player',
            name='sorties_streak_current',
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name='player',
            name='sorties_streak_max',
            field=models.IntegerField(default=0),
        ),
        migrations.AlterField(
            model_name='award',
            name='img',
            field=models.ImageField(help_text='Image size should be 180x180', upload_to='awards/', verbose_name='image'),
        ),
    ]


text:
const promise = new Promise(resolve => {
    console.info(">> inside a promise");
    resolve();
});

console.info(">> script start");


text:
function UFwrite (Problem, Master, arg3, arg4)
%UFWRITE write a Problem in Matrix Market or Rutherford/Boeing format
% containing a set of text files in either Matrix Market or Rutherford/Boeing
% format.  The Problem can be read from the files back into MATLAB via UFread.
% See http://www.cise.ufl.edu/research/sparse/matrices for the UF Sparse
% Matrix Collection home page.  The Problem directory is optionally compressed
% via tar and gzip.  Arguments 3 and 4, below, are optional and can appear in
% any order.
%
%    UFwrite (Problem)          % Matrix Market format, no tar, use current dir.
%
% The following usages write the Problem into the Master/Group/Name directory,
% where Problem.name = 'Group/Name' is given in the Problem.
%
%    UFwrite (Problem, Master)                 % Matrix Market, no tar
%    UFwrite (Problem, Master, 'MM')           % ditto
%    UFwrite (Problem, Master, 'RB')           % Rutherford/Boeing, no tar
%    UFwrite (Problem, Master, 'tar')          % Matrix Market, with tar
%    UFwrite (Problem, Master, 'MM', 'tar')    % ditto
%    UFwrite (Problem, Master, 'RB', 'tar')    % Rutherford/Boeing, with tar
%
% Problem is a struct, in the UF Sparse Matrix format (see below).  Master is
% the top-level directory in which directory containing the problem will be
% placed.  Master defaults to the current working directory if not present (an
% empty string also means the current directory will be used).
%
% The following fields are always present in a UF Sparse Matrix Problem:
%
%       name    the group directory and problem name (i.e. 'HB/arc130')
%
%       title   short descriptive title
%
%       A       an m-by-n sparse matrix, real or complex
%
%       id      an integer in the range of 1 to the # of problems in the
%               collection.  Identical to the line number of
%               http://www.cise.ufl.edu/research/sparse/mat/UF_Listing.txt
%               containing the Problem.name.  New matrices are always added at
%               the end of this list.
%
%       date    a string containing the date the matrix was created, or added
%               to the collection if the creating date is unknown (but is likely
%               close to the creation date); empty string otherwise.
%
%       author  a string containing the name of the author; the computational
%               scientist who created the matrix from his or her application.
%               Empty string, or "author unknown" if unknown.
%
%       ed      a string containing the name of the editor/collector; the person
%               who acquired the matrix from the author, for inclusion in this
%               (or other) sparse matrix / graph collections.
%
%       kind    a string (i.e. 'directed graph') describing the type of problem;
%               a list of words from a well-defined set (see the UF Sparse
%               Matrix Collection home page for a description, or
%               http://www.cise.ufl.edu/research/sparse/matrices/kind.html).
%
% A Problem struct may also have the following optional fields.
%
%       Zeros   pattern of explicit zero entries in A as a binary m-by-n matrix.
%               These entries are provided by the matrix submittor with zero
%               numerical value.  MATLAB drops explicit zero entries from any
%               sparse matrix.  These entries can be important to the problem,
%               if (for example) the matrix is first in a series of matrices
%               arising in a nonlinear solver (those entries will become nonzero
%               later).  These entries are thus kept in the binary matrix Zeros.
%
%       b       right-hand-side, any size, real or complex, full or sparse
%
%       x       supposed solution to A*x=b, any size, real or complex, full or
%               sparse
%
%       notes   a character array with notes about the problem.
%
%       aux     a struct, containing auxiliary information.  The contents of
%               this struct are problem dependent, but its fields must not
%               end with '_[0-9]*' where [0-9]* means zero or more digits, nor
%               can there be an aux.b or aux.x matrix (there can be aux.b
%               and aux.x cells).  The aux struct must not include any structs,
%               just matrices and cell arrays of matrices.  The matrices in aux
%               can be full or sparse, and real, complex, or char.
%
% -------------------------------------------------
% for Problems written in Rutherford/Boeing format:
% -------------------------------------------------
%
% The Problem.name (including the full 'Group/Name'), date, author, and editor
% define the Rutherford/Boeing title (first line of the file), followed by a
% '|' in the 72nd column, and then up to 8 characters of the key.  If the key
% is an empty string, the Problem.id is used as the key.  The A and Zeros
% matrices are merged and written to this file.  The full name, title, id,
% kind, date, author, editor, and notes are written to a file of the same name
% as the primary file, but with a .txt extension.
%
% Additional Rutherford/Boeing files are created for b, x, and each sparse
% matrix in aux.  Full arrays are written using a tiny subset of the Matrix
% Market format.  The first line of the file is the header, either of:
%
%   %%MatrixMarket array real general
%   %%MatrixMarket array complex general
%
% The 2nd row contains the # of rows and columns, and subsequent lines contain
% one matrix entry each (two values if complex) listed in column-major order.
% No comments or blank lines are permitted.  The header is ignored when the
% matrix is read back in by UFread; the real/complex case is determined by how
% many entries appear on each line.  You can of course read these files with
% mread, the Matrix Market reader.  The header is added only to make it easier
% for functions *other* than UFread to read and understand the data (the file
% can be read in by mread, for example, but mread is not required).  Thus, a
% complete Rutherord/Boeing directory can be read/written via UFread/UFwrite,
% without requiring the installation of mread/mwrite (in CHOLMOD), or
% mmread/mmread (M-file functions from NIST that read/write a Matrix Market
% file).
%
% ---------------------------------------------
% for Problems written in Matrix Market format:
% ---------------------------------------------
%
% The name, title, A, id, Zeros, kind, date, author, editor, and notes fields of
% the Problem are written to the primary Matrix Market file, with a .mtx
% extension.  Additional Matrix Market files are created for b (as name_b),
% x (as name_x), and each sparse or full matrix in aux.
%
% -----------------
% for both formats:
% -----------------
%
% A matrix Problem.aux.whatever is written out as name_whatever.xxx, without
% the 'aux' part.  If Problem.aux.whatever is a char array, it is written as
% the file name_whatever.txt, with one line per row of the char array (trailing
% spaces in each line are not printed).  If aux.whatever is a cell array, each
% entry aux.whatever{i} is written as the file name_whatever_<i>.xxx
% (name_whatever_1.mtx, name_whatever_2.mtx, etc).  All files are placed in the
% single directory, given by the Problem.name (Group/Name, or 'HB/arc130' for
% example).  Each directory can only hold one MATLAB Problem struct of the UF
% Sparse Matrix Collection.
%
% Example:
%
%   Problem = UFget ('HB/arc130')   % get the HB/arc130 MATLAB Problem
%   UFwrite (Problem) ;             % write a MM version in current directory
%   UFwrite (Problem, 'MM') ;       % write a MM version in MM/HB/arc130
%   UFwrite (Problem, '', 'RB') ;   % write a RB version in current directory
%
% See also mwrite, mread, RBwrite, RBread, UFread, UFget, tar

% Optionally uses the CHOLMOD mwrite mexFunction, for writing Problems in
% Matrix Market format.

% Copyright 2006-2007, Timothy A. Davis, University of Florida.

%-------------------------------------------------------------------------------
% check inputs
%-------------------------------------------------------------------------------

if (nargin < 2)
    % place the result in the current directory
    Master = '' ;
end
if (nargin < 3)
    arg3 = '' ;
end
if (nargin < 4)
    arg4 = '' ;
end
arg3 = lower (arg3) ;
arg4 = lower (arg4) ;

do_tar = (strcmp (arg3, 'tar') | strcmp (arg4, 'tar')) ;
RB = (strcmp (arg3, 'rb') | strcmp (arg4, 'rb')) ;

Master = regexprep (Master, '[\/\\]', filesep) ;
if (~isempty (Master) && Master (end) ~= filesep)
    Master = [Master filesep] ;
end

%-------------------------------------------------------------------------------
% create the problem directory.  Do not report any errors
%-------------------------------------------------------------------------------

t = find (Problem.name == '/') ;
group = Problem.name (1:t-1) ;
name = Problem.name (t+1:end) ;
groupdir = [Master group] ;
probdir = [groupdir filesep name] ;
probname = [probdir filesep name] ;

s = warning ('query', 'MATLAB:MKDIR:DirectoryExists') ;	    % get current state
warning ('off', 'MATLAB:MKDIR:DirectoryExists') ;
mkdir (groupdir) ;
mkdir (probdir) ;
warning (s) ;						    % restore state

%-------------------------------------------------------------------------------
% write the name, title, id, kind, date, author, ed, list of fields, and notes
%-------------------------------------------------------------------------------

cfile = [probname '.txt'] ;
if (RB)
    prefix = '%' ;
else
    prefix = '' ;
end
cf = fopen (cfile, 'w') ;
print_header (cf, prefix, Problem.name) ;
fprintf (cf, '%s [%s]\n', prefix, Problem.title) ;
fprintf (cf, '%s id: %d\n', prefix, Problem.id) ;
fprintf (cf, '%s date: %s\n', prefix, Problem.date) ;
fprintf (cf, '%s author: %s\n', prefix, Problem.author) ;
fprintf (cf, '%s ed: %s\n', prefix, Problem.ed) ;
fprintf (cf, '%s fields:', prefix) ;
s = fields (Problem) ;
for k = 1:length(s)
    fprintf (cf, ' %s', s {k}) ;
end
fprintf (cf, '\n') ;
if (isfield (Problem, 'aux'))
    aux = Problem.aux ;
    fprintf (cf, '%s aux:', prefix) ;
    auxfields = fields (aux) ;
    for k = 1:length(auxfields)
	fprintf (cf, ' %s', auxfields {k}) ;
    end
    fprintf (cf, '\n') ;
else
    auxfields = { } ;
end
fprintf (cf, '%s kind: %s\n', prefix, Problem.kind) ;
print_separator (cf, prefix) ;
if (isfield (Problem, 'notes'))
    fprintf (cf, '%s notes:\n', prefix) ;
    for k = 1:size (Problem.notes,1)
	fprintf (cf, '%s %s\n', prefix, Problem.notes (k,:)) ;
    end
    print_separator (cf, prefix) ;
end
fclose(cf) ;

%-------------------------------------------------------------------------------
% write out the A and Z matrices to the RB or MM primary file
%-------------------------------------------------------------------------------

A = Problem.A ;
[m n] = size (A) ;
if (~issparse (A) || m == 0 || n == 0)
    error ('A must be sparse and non-empty') ;
end
if (isfield (Problem, 'Zeros'))
    Z = Problem.Zeros ;
    if (any (size (A) ~= size (Z)) || ~isreal (Z) || ~issparse (Z))
	error ('Zeros must have same size as A, and be sparse and real') ;
    end
else
    Z = [ ] ;
end

% use the Problem.id number as the RB key
key = sprintf ('%d', Problem.id) ;

if (RB)
    % write the files in Rutherford/Boeing form
    ptitle = [Problem.name '; ' Problem.date '; ' etal(Problem.author)] ;
    ptitle = [ptitle '; ed: ' etal(Problem.ed)] ;
    % note that b, g, and x are NOT written to the RB file
    RBwrite ([probname '.rb'], A, Z, ptitle, key) ;
else
    % write the files in Matrix Market form
    mwrite ([probname '.mtx'], A, Z, cfile) ;
    delete (cfile) ;    % the comments file has been included in the .mtx file.
end

%-------------------------------------------------------------------------------
% write out the b and x matrices as separate files
%-------------------------------------------------------------------------------

if (isfield (Problem, 'b'))
    write_component (probname, Problem.name, 'b', Problem.b, cfile, ...
	prefix, RB, [key 'b']) ;
end
if (isfield (Problem, 'x'))
    write_component (probname, Problem.name, 'x', Problem.x, cfile, ...
	prefix, RB, [key 'x']) ;
end

%-------------------------------------------------------------------------------
% write out each component of aux, each in a separate file
%-------------------------------------------------------------------------------

for k = 1:length(auxfields)
    what = auxfields {k} ;
    X = aux.(what) ;

    if (~iscell (X) && (strcmp (what, 'b') || strcmp (what, 'x')))
	% aux.b or aux.x would get written out with the same filename as the
	% Problem.b and Problem.x matrices, and read back in by UFread as
	% Problem.b and Problem.x instead of aux.b and aux.x.
	error (['invalid aux component: ' what]) ;
    end

    if (regexp (what, '_[0-9]*\>'))
	% aux.whatever_42 would be written as the file name_whatever_42, which
	% would be intrepretted as aux.whatever{42} when read back in by UFread.
	error (['invalid aux component: ' what]) ;
    end

    if (iscell (X))
	len = length (X) ;
	for i = 1:len
	    % this problem includes a sequence of matrices in the new
	    % format (kind = 'sequence', and Problem.id > 1377).
	    write_component (probname, Problem.name, ...
		sprintf (fmt (i, len), what, i) , X{i}, cfile, ...
		prefix, RB, [key what(1) sprintf('%d', i)]) ;
	end
    else
	% This is a non-cell component of aux.  For an LP problem, this might
	% be c, lo, or hi.  For an Oberwolfach model reduction problem, this
	% might be M, C, or E.  For a graph in the Pajek collection, it could
	% be a vector 'year', with the publication of each article in the graph.
	% The possibilities are endless, and problem dependent.  Adding new
	% components to aux can be done without modifying UFread or UFwrite.
	write_component (probname, Problem.name, what, X, cfile, ...
	    prefix, RB, [key what]) ;
    end
end

%-------------------------------------------------------------------------------
% tar up the result, if requested
%-------------------------------------------------------------------------------

if (do_tar)
    try
	tar ([probdir '.tar.gz'], probdir) ;
	rmdir (probdir, 's') ;
    catch
	warning ('SuiteSparse:UFwrite', ...
	    'unable to create tar file; directly left uncompressed') ;
    end
end

%-------------------------------------------------------------------------------
% fmt
%-------------------------------------------------------------------------------

function s = fmt (i, len)
% fmt: determine the format to use for the name of component in a aux.cell array
if (len < 10)
    s = '%s_%d' ;		% x1 through x9
elseif (len < 100)
    if (i < 10)
	s = '%s_0%d' ;		% x01 through x09
    else
	s = '%s_%d' ;		% x10 through x99
    end
else
    if (i < 10)
	s = '%s_00%d' ;		% x001 through x009
    elseif (i < 100)
	s = '%s_0%d' ;		% x010 through x099
    else
	s = '%s_%d' ;		% x100 through x999
    end
end

%-------------------------------------------------------------------------------
% write_component
%-------------------------------------------------------------------------------

function write_component (probname, name, what, X, cfile, prefix, RB, key)
% write_component: write out a single component of the Problem to a file
if (isempty (X))
    % empty matrices (one or more zero dimensions) are not supported
    error (['invalid component: ' what ' (cannot be empty)']) ;
elseif (ischar (X))
    % Write out a char array as a text file.  Remove trailing spaces from the
    % strings.  Keep the leading spaces; they might be significant.
    ff = fopen ([probname '_' what '.txt'], 'w') ;
    for i = 1:size (X,1)
	fprintf (ff, '%s\n', deblank (X (i,:))) ;
    end
    fclose (ff) ;
elseif (RB)
    % write out a full or sparse matrix in Rutherford/Boeing format
    if (issparse (X))
	% write out the component as a Rutherford/Boeing sparse matrix
	RBwrite ([probname '_' what '.rb'], X, [ ], [name '_' what], key) ;
    else
	% Write out a full matrix in column oriented form,
	% using a tiny subset of the Matrix Market format for full matrices.
	UFfull_write ([probname '_' what '.mtx'], X) ;
    end
else
    % write out the component in Matrix Market format (full or sparse)
    cf = fopen (cfile, 'w') ;
    print_header (cf, prefix, name, what) ;
    print_separator (cf, prefix) ;
    fclose(cf) ;
    mwrite ([probname '_' what '.mtx'], X, cfile) ;
    delete (cfile) ;
end

%-------------------------------------------------------------------------------
% print_separator
%-------------------------------------------------------------------------------

function print_separator (cf, prefix)
% print_separator: print a separator line in the comment file
fprintf (cf, '%s---------------------------------------', prefix) ;
fprintf (cf, '----------------------------------------\n') ;

%-------------------------------------------------------------------------------
% print_header
%-------------------------------------------------------------------------------

function print_header (cf, prefix, name, what)
% print_header: print the header to the comment file
print_separator (cf, prefix) ;
fprintf (cf, '%s UF Sparse Matrix Collection, Tim Davis\n', prefix) ;
fprintf (cf, '%s http://www.cise.ufl.edu/research/sparse/matrices/%s\n', ...
    prefix, name) ;
fprintf (cf, '%s name: %s', prefix, name) ;
if (nargin > 3)
    fprintf (cf, ' : %s matrix', what) ;
end
fprintf (cf, '\n') ;

%-------------------------------------------------------------------------------
% etal
%-------------------------------------------------------------------------------

function s = etal(name)
% etal: change a long list of authors to first author 'et al.'
t = find (name == ',') ;
if (length (t) > 1)
    s = [name(1:t(1)-1) ' et al.'] ;
else
    s = name ;
end


text:
/* Variables */
/* line 2, ../sass/_base.scss */
#feature {
  border-bottom: 1px solid #ccc;
  margin: -1em -5.55% 0;
}
/* line 5, ../sass/_base.scss */
#feature ul {
  list-style: none;
  margin: 0;
  padding-bottom: 20px;
}
/* line 10, ../sass/_base.scss */
#feature li {
  display: none;
}
/* line 12, ../sass/_base.scss */
#feature li.feature {
  display: block;
}
/* line 16, ../sass/_base.scss */
#feature .feature-image {
  text-align: center;
}

/* line 21, ../sass/_base.scss */
.feature-description {
  margin: 0 5%;
}
/* line 23, ../sass/_base.scss */
.feature-description h2 {
  font-size: 18px;
  line-height: 20px;
  margin: 20px 0px 10px;
}

/* Variables */
/* line 7, ../sass/_slider.scss */
.anythingSlider,
.anythingSlider #slider,
.anythingSlider .fade .panel {
  width: 100% !important;
}

/* line 12, ../sass/_slider.scss */
#feature .anythingSlider ul {
  padding-bottom: 0;
}
/* line 15, ../sass/_slider.scss */
#feature .anythingSlider li {
  display: list-item;
}

/* line 20, ../sass/_slider.scss */
.anythingSlider {
  padding-bottom: 20px;
}
/* line 25, ../sass/_slider.scss */
.anythingSlider .anythingControls, .anythingSlider .arrow a, .anythingSlider .arrow:after {
  -webkit-transition: opacity 0.2s ease;
  -moz-transition: opacity 0.2s ease;
  -o-transition: opacity 0.2s ease;
  transition: opacity 0.2s ease;
  opacity: 0;
}
/* line 30, ../sass/_slider.scss */
.anythingSlider.anythingSlider-hovered .arrow a, .touch .anythingSlider .arrow a {
  opacity: 0;
}
/* line 34, ../sass/_slider.scss */
.anythingSlider.anythingSlider-hovered .anythingControls,
.anythingSlider.anythingSlider-hovered .arrow:after, .touch .anythingSlider .anythingControls,
.touch .anythingSlider .arrow:after {
  opacity: 1;
}
/* line 39, ../sass/_slider.scss */
.anythingSlider li {
  display: block;
}
/* line 43, ../sass/_slider.scss */
.anythingSlider .arrow {
  display: block;
  position: absolute;
  z-index: 3;
  top: 196px;
  left: 0;
  width: 50px;
  height: 60px;
  margin-top: -30px;
}
/* line 53, ../sass/_slider.scss */
.anythingSlider .arrow:after {
  pointer-events: none;
  display: block;
  content: "";
  color: white;
  text-indent: 0;
  font-size: 50px;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
  position: absolute;
  width: 30px;
  height: 40px;
  background: transparent url("img/slider-nav.png") top left no-repeat;
  top: 50%;
  left: 40%;
  margin: -20px 0 0 -10px;
}
/* line 68, ../sass/_slider.scss */
.svg .anythingSlider .arrow:after {
  background-image: url("img/slider-nav.svg");
}
/* line 74, ../sass/_slider.scss */
.anythingSlider .arrow a {
  text-indent: -999em;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: black;
}
/* line 81, ../sass/_slider.scss */
.anythingSlider .arrow a:hover {
  text-decoration: none;
  opacity: .25;
}
/* line 87, ../sass/_slider.scss */
.anythingSlider .arrow.back a {
  -moz-border-radius-topright: 20%;
  -webkit-border-top-right-radius: 20%;
  border-top-right-radius: 20%;
  -moz-border-radius-bottomright: 20%;
  -webkit-border-bottom-right-radius: 20%;
  border-bottom-right-radius: 20%;
}
/* line 92, ../sass/_slider.scss */
.anythingSlider .arrow.forward {
  left: auto;
  right: 0;
}
/* line 96, ../sass/_slider.scss */
.anythingSlider .arrow.forward a {
  -moz-border-radius-topleft: 20%;
  -webkit-border-top-left-radius: 20%;
  border-top-left-radius: 20%;
  -moz-border-radius-bottomleft: 20%;
  -webkit-border-bottom-left-radius: 20%;
  border-bottom-left-radius: 20%;
}
/* line 101, ../sass/_slider.scss */
.anythingSlider .arrow.forward:after {
  background-position: -30px 0;
}
/* line 105, ../sass/_slider.scss */
.anythingSlider .arrow:hover {
  opacity: 1;
}

/* line 113, ../sass/_slider.scss */
.anythingControls {
  position: absolute;
  width: 100%;
  height: 20px;
  bottom: 0px;
  z-index: 2;
  text-align: center;
}
/* line 120, ../sass/_slider.scss */
.anythingControls .thumbNav {
  display: inline-block;
  margin: 0 auto;
}
/* line 124, ../sass/_slider.scss */
.anythingControls li {
  display: inline-block !important;
  margin: 0 5px;
}
/* line 128, ../sass/_slider.scss */
.anythingControls a {
  -webkit-transition: opacity 0.2s ease;
  -moz-transition: opacity 0.2s ease;
  -o-transition: opacity 0.2s ease;
  transition: opacity 0.2s ease;
  display: block;
  width: 20px;
  height: 20px;
  background-color: black;
  text-indent: -999em;
  overflow: hidden;
  opacity: .15;
}
/* line 137, ../sass/_slider.scss */
.anythingControls a.cur, .anythingControls a:hover {
  opacity: .3;
}

@media all and (min-width: 600px) {
  /* line 148, ../sass/_slider.scss */
  #feature {
    margin: -1em -11% 0;
  }

  /* line 151, ../sass/_slider.scss */
  .feature-description {
    margin: 0 8% 0 9%;
  }
  /* line 153, ../sass/_slider.scss */
  .feature-description h2 {
    font-size: 24px;
    line-height: 30px;
    margin: 20px 0px 10px;
  }
}
@media all and (max-width: 939px) {
  /* line 166, ../sass/_slider.scss */
  .feature-description {
    border-left: none !important;
    background-color: transparent !important;
    -webkit-box-shadow: none !important;
    -moz-box-shadow: none !important;
    box-shadow: none !important;
  }
}
@media all and (min-width: 940px) {
  /* line 174, ../sass/_slider.scss */
  #feature {
    border-bottom: none;
  }
  /* line 176, ../sass/_slider.scss */
  #feature .feature-image {
    text-align: left;
  }

  /* line 181, ../sass/_slider.scss */
  #feature #slider {
    width: 940px;
    margin-left: auto;
    margin-right: auto;
    position: relative;
    padding-bottom: 0;
  }

  /* line 189, ../sass/_slider.scss */
  .anythingSlider {
    padding-bottom: 0;
  }

  /* line 193, ../sass/_slider.scss */
  .anythingWindow {
    width: 940px !important;
    height: 393px !important;
    margin: 0 auto;
    position: relative;
  }

  /* line 200, ../sass/_slider.scss */
  .anythingControls {
    width: 240px;
    right: 50%;
    bottom: 15px;
    margin-right: -470px;
  }

  /* line 207, ../sass/_slider.scss */
  .feature-description {
    position: absolute;
    top: 0;
    right: 0;
    width: 190px;
    margin: 0;
    background-color: #e0edf9;
    height: 393px;
    padding: 0 25px;
    border-left: 1px solid #e0edf9;
    -webkit-box-shadow: inset 0 0 110px 5px rgba(145, 178, 210, 0.5), 0 0 12px rgba(0, 0, 0, 0.25);
    -moz-box-shadow: inset 0 0 110px 5px rgba(145, 178, 210, 0.5), 0 0 12px rgba(0, 0, 0, 0.25);
    box-shadow: inset 0 0 110px 5px rgba(145, 178, 210, 0.5), 0 0 12px rgba(0, 0, 0, 0.25);
  }
  /* line 219, ../sass/_slider.scss */
  .feature-description a, .feature-description a:link, .feature-description a:visited, .feature-description a:active, .feature-description a:hover, .feature-description a:focus {
    color: #336699;
  }
  /* line 222, ../sass/_slider.scss */
  .feature-description.lightText {
    color: white;
  }
  /* line 224, ../sass/_slider.scss */
  .feature-description.lightText * {
    opacity: 0.75;
  }
  /* line 227, ../sass/_slider.scss */
  .feature-description.lightText a, .feature-description.lightText a:link, .feature-description.lightText a:visited, .feature-description.lightText a:active, .feature-description.lightText a:hover, .feature-description.lightText a:focus {
    color: white;
    opacity: 1;
  }
}
/*
	AnythingSlider v1.8+ Default theme
	By Chris Coyier: http://css-tricks.com
	with major improvements by Doug Neiner: http://pixelgraphics.us/
	based on work by Remy Sharp: http://jqueryfordesigners.com/
*/
/*****************************
  SET DEFAULT DIMENSIONS HERE
 *****************************/
/* change the ID & dimensions to match your slider */
/* line 12, ../sass/_anythingslider.scss */
#slider {
  width: 100%;
  height: auto;
  list-style: none;
  /* Prevent FOUC (see FAQ page) and keep things readable if javascript is disabled */
  overflow-y: auto;
  overflow-x: hidden;
}

/******************
  SET STYLING HERE
 ******************

/***********************
  IE8 AND OLDER STYLING
 ***********************/
/* Navigation Arrows */
/* line 31, ../sass/_anythingslider.scss */
.as-oldie .anythingSlider-default .arrow {
  top: 30%;
}

/* line 34, ../sass/_anythingslider.scss */
.as-oldie .anythingSlider-default .arrow a {
  margin: 0;
}

/* margin between nav buttons just looks better */
/* line 39, ../sass/_anythingslider.scss */
.as-oldie .anythingSlider-default .anythingControls li {
  margin-left: 3px;
}

/* When using the navigationSize option, the side margins need to be zero
	None of the navigation panels look good in IE7 now =( */
/* line 45, ../sass/_anythingslider.scss */
.as-oldie .anythingSlider-default .anythingControls a {
  margin: 0;
}

/* line 48, ../sass/_anythingslider.scss */
.as-oldie .anythingSlider-default .anythingNavWindow {
  margin: 0 2px;
}

/* line 51, ../sass/_anythingslider.scss */
.as-oldie .anythingSlider-default .anythingNavWindow li {
  padding: 3px 0 0 0;
}

/***********************
  COMMON SLIDER STYLING
 ***********************/
/* Overall Wrapper */
/* line 59, ../sass/_anythingslider.scss */
.anythingSlider {
  display: block;
  overflow: visible !important;
  position: relative;
}

/* anythingSlider viewport window */
/* line 65, ../sass/_anythingslider.scss */
.anythingSlider .anythingWindow {
  overflow: hidden;
  position: relative;
  width: 100%;
  height: 100%;
}

/* anythingSlider base (original element) */
/* line 72, ../sass/_anythingslider.scss */
.anythingSlider .anythingBase {
  background: transparent;
  list-style: none;
  position: absolute;
  overflow: visible !important;
  top: 0;
  left: 0;
  margin: 0;
  padding: 0;
}

/* Navigation arrow text; indent moved to span inside "a", for IE7;
  apparently, a negative text-indent on an "a" link moves the link as well as the text */
/* line 85, ../sass/_anythingslider.scss */
.anythingSlider .arrow span {
  display: block;
  visibility: hidden;
}

/* disabled arrows, hide or reduce opacity: opacity: .5; filter: alpha(opacity=50); */
/* line 90, ../sass/_anythingslider.scss */
.anythingSlider .arrow.disabled {
  display: none;
}

/* all panels inside the slider; horizontal mode */
/* line 94, ../sass/_anythingslider.scss */
.anythingSlider .panel {
  background: transparent;
  display: block;
  overflow: hidden;
  float: left;
  padding: 0;
  margin: 0;
}

/* vertical mode */
/* line 103, ../sass/_anythingslider.scss */
.anythingSlider .vertical .panel {
  float: none;
}

/* fade mode */
/* line 107, ../sass/_anythingslider.scss */
.anythingSlider .fade .panel {
  float: none;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
}

/* fade mode active page - visible & on top */
/* line 115, ../sass/_anythingslider.scss */
.anythingSlider .fade .activePage {
  z-index: 1;
}

/***********************
  RTL STYLING
 ***********************/
/* slider autoplay right-to-left, reverse order of nav links to look better */
/* line 123, ../sass/_anythingslider.scss */
.anythingSlider.rtl .anythingWindow {
  direction: ltr;
  unicode-bidi: bidi-override;
}

/* line 127, ../sass/_anythingslider.scss */
.anythingSlider.rtl .anythingControls ul {
  float: left;
}

/* move nav link group to left */
/* line 128, ../sass/_anythingslider.scss */
.anythingSlider.rtl .anythingControls ul a {
  float: right;
}

/* reverse order of nav links */
/* line 129, ../sass/_anythingslider.scss */
.anythingSlider.rtl .start-stop {
  /* float: right; */
}

/* move start/stop button - in case you want to switch sides */
/* probably not necessary, but added just in case */
/* line 136, ../sass/_anythingslider.scss */
.anythingSlider,
.anythingSlider .anythingWindow,
.anythingSlider .anythingControls ul a,
.anythingSlider .arrow a,
.anythingSlider .start-stop {
  transition-duration: 0;
  -o-transition-duration: 0;
  -moz-transition-duration: 0;
  -webkit-transition-duration: 0;
}


text:
module HPack.Iface (module X) where

import HPack.Iface.Iface as X
import HPack.Iface.IfaceExtract as X
import HPack.Iface.IfaceRepo as X
import HPack.Iface.LoadIface as X


text:
(function () {
    "use strict";

    describe("Tests for home routes: ", function() {
        var testAuthed, testUnAuthed;

        beforeEach(function () {
            module("mfl.home");
            module("mflAppConfig");
            module("templates-app");
            module("mfl.auth.service");

            inject(["$rootScope", "$state", "api.auth",
                function ($rootScope, $state, auth) {
                    testAuthed = function (name) {
                        spyOn(auth, "getToken").andReturn({access_token: "DSA"});
                        spyOn(auth, "fetchToken");
                        $state.go(name);
                        $rootScope.$digest();
                        expect($state.current.name).toEqual(name);
                        expect(auth.fetchToken).not.toHaveBeenCalled();
                    };
                    testUnAuthed = function (name) {
                        spyOn(auth, "getToken").andReturn(null);
                        spyOn(auth, "fetchToken");
                        $state.go(name);
                        $rootScope.$digest();
                        expect($state.current.name).toEqual(name);
                        expect(auth.fetchToken).toHaveBeenCalled();
                    };
                }]
            );
        });

        it("should load home state (authed)", function () {
            testAuthed("home");
        });

        it("should load home state (unauthed)", function () {
            testUnAuthed("home");
        });
    });

})();


text:
require 'rails_helper'

describe 'post creation' do
  let(:user) { create(:user, :confirmed) }

  before do
    sign_user_in(user)
  end

  it 'happens on the signed in root url' do
    expect(page).to have_content "Update Status"
  end

  it 'requires the user to fill in the content field' do
    click_button 'Post'
    expect(page).to have_content "Content can't be blank"
  end

  it 'has a show page after creation' do
    fill_in 'post_content', with: 'Nonsense'
    click_button 'Post'

    visit post_path(Post.last)
    expect(page).to have_content 'Nonsense'
  end
end


text:
/**
 * Created by josh on 8/13/15.
 */
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props

class HelloActor extends Actor {
  def receive = {
    case "hello" => println("hello back at you")
    case _       => println("huh?")
  }
}

object Main extends App {

  // an actor needs an ActorSystem
  val system = ActorSystem("HelloSystem")

  // create and start the actor
  val helloActor = system.actorOf(Props[HelloActor], name = "helloactor")

  // send the actor two messages
  helloActor ! "hello"
  helloActor ! "buenos dias"

  // shut down the system
  system.terminate()

}


text:
CookieReminterFactory::CookieReminterFactory()
    : ProfileKeyedServiceFactory("CookieReminter") {
  DependsOn(IdentityManagerFactory::GetInstance());
}

CookieReminterFactory::~CookieReminterFactory() {}

// static
CookieReminter* CookieReminterFactory::GetForProfile(Profile* profile) {
  return static_cast<CookieReminter*>(
      GetInstance()->GetServiceForBrowserContext(profile, true));
}

// static
CookieReminterFactory* CookieReminterFactory::GetInstance() {
  return base::Singleton<CookieReminterFactory>::get();
}

KeyedService* CookieReminterFactory::BuildServiceInstanceFor(
    content::BrowserContext* context) const {
  Profile* profile = Profile::FromBrowserContext(context);
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(profile);
  return new CookieReminter(identity_manager);
}


text:
// $Id$

/// \file TestMUONPreprocessor.h
/// \brief The definitions for the macro TestMUONPreprocessor.C

#ifndef TESTMUONPREPROCESSOR_H
#define TESTMUONPREPROCESSOR_H

class TMap;

/// Create a fake DCS alias map
TMap* CreateDCSAliasMap(const char* inputCDB, Int_t runNumber);

#endif