text:
#include "lib.h"
#include "lib-signals.h"
#include "ioloop.h"
#include "abspath.h"
#include "array.h"
#include "strescape.h"
#include "env-util.h"
#include "home-expand.h"
#include "process-title.h"
#include "restrict-access.h"
#include "fd-close-on-exec.h"
#include "settings-parser.h"
#include "syslog-util.h"
#include "master-instance.h"
#include "master-login.h"
#include "master-service-ssl.h"
#include "master-service-private.h"
#include "master-service-settings.h"

#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <syslog.h>

#define DEFAULT_CONFIG_FILE_PATH SYSCONFDIR"/dovecot.conf"

/* getenv(MASTER_CONFIG_FILE_ENV) provides path to configuration file/socket */
#define MASTER_CONFIG_FILE_ENV "CONFIG_FILE"

/* getenv(MASTER_DOVECOT_VERSION_ENV) provides master's version number */
#define MASTER_DOVECOT_VERSION_ENV "DOVECOT_VERSION"

/* when we're full of connections, how often to check if login state has
   changed. we normally notice it immediately because of a signal, so this is
   just a fallback against race conditions. */
#define MASTER_SERVICE_STATE_CHECK_MSECS 1000

/* If die callback hasn't managed to stop the service for this many seconds,
   force it. */
#define MASTER_SERVICE_DIE_TIMEOUT_MSECS (30*1000)

struct master_service *master_service;

static void master_service_io_listeners_close(struct master_service *service);
static void master_service_refresh_login_state(struct master_service *service);

const char *master_service_getopt_string(void)
{
	return "c:i:ko:OL";
}

static void sig_die(const siginfo_t *si, void *context)
{
	struct master_service *service = context;

	/* SIGINT comes either from master process or from keyboard. we don't
	   want to log it in either case.*/
	if (si->si_signo != SIGINT) {
		i_warning("Killed with signal %d (by pid=%s uid=%s code=%s)",
			  si->si_signo, dec2str(si->si_pid),
			  dec2str(si->si_uid),
			  lib_signal_code_to_str(si->si_signo, si->si_code));
	} else if ((service->flags & MASTER_SERVICE_FLAG_NO_IDLE_DIE) != 0) {
		/* never die when idling */
		return;
	} else if ((service->flags & MASTER_SERVICE_FLAG_STANDALONE) == 0) {
		/* SIGINT came from master. die only if we're not handling
		   any clients currently. */
		if (service->master_status.available_count !=
		    service->total_available_count)
			return;

		if (service->idle_die_callback != NULL &&
		    !service->idle_die_callback())
			return;
	}

	service->killed = TRUE;
	io_loop_stop(service->ioloop);
}

static void
sig_state_changed(const siginfo_t *si ATTR_UNUSED, void *context)
{
	struct master_service *service = context;

	master_service_refresh_login_state(service);
}

static void master_service_verify_version_string(struct master_service *service)
{
	if (service->version_string != NULL &&
	    strcmp(service->version_string, PACKAGE_VERSION) != 0) {
		i_fatal("Dovecot version mismatch: "
			"Master is v%s, %s is v"PACKAGE_VERSION" "
			"(if you don't care, set version_ignore=yes)",
			service->version_string, service->name);
	}
}

struct master_service *
master_service_init(const char *name, enum master_service_flags flags,
		    int *argc, char **argv[], const char *getopt_str)
{
	struct master_service *service;
	const char *value;
	unsigned int count;

	i_assert(name != NULL);

#ifdef DEBUG
	if (getenv("GDB") == NULL &&
	    (flags & MASTER_SERVICE_FLAG_STANDALONE) == 0) {
		int count;

		value = getenv("SOCKET_COUNT");
		count = value == NULL ? 0 : atoi(value);
		fd_debug_verify_leaks(MASTER_LISTEN_FD_FIRST + count, 1024);
	}
#endif
	if ((flags & MASTER_SERVICE_FLAG_STANDALONE) == 0) {
		/* make sure we can dump core, at least until
		   privileges are dropped. (i'm not really sure why this
		   is needed, because doing the same just before exec
		   doesn't help, and exec shouldn't affect this with
		   non-setuid/gid binaries..) */
		restrict_access_allow_coredumps(TRUE);
	}

	/* NOTE: we start rooted, so keep the code minimal until
	   restrict_access_by_env() is called */
	lib_init();
	/* Set a logging prefix temporarily. This will be ignored once the log
	   is properly initialized */
	i_set_failure_prefix("%s(init): ", name);

	/* ignore these signals as early as possible */
	lib_signals_init();
        lib_signals_ignore(SIGPIPE, TRUE);
        lib_signals_ignore(SIGALRM, FALSE);

	if (getenv(MASTER_UID_ENV) == NULL)
		flags |= MASTER_SERVICE_FLAG_STANDALONE;

	process_title_init(argv);

	service = i_new(struct master_service, 1);
	service->argc = *argc;
	service->argv = *argv;
	service->name = i_strdup(name);
	/* keep getopt_str first in case it contains "+" */
	service->getopt_str = *getopt_str == '\0' ?
		i_strdup(master_service_getopt_string()) :
		i_strconcat(getopt_str, master_service_getopt_string(), NULL);
	service->flags = flags;
	service->ioloop = io_loop_create();
	service->service_count_left = UINT_MAX;
	service->config_fd = -1;

	service->config_path = i_strdup(getenv(MASTER_CONFIG_FILE_ENV));
	if (service->config_path == NULL)
		service->config_path = i_strdup(DEFAULT_CONFIG_FILE_PATH);
	else
		service->config_path_from_master = TRUE;

	if ((flags & MASTER_SERVICE_FLAG_STANDALONE) == 0) {
		service->version_string = getenv(MASTER_DOVECOT_VERSION_ENV);
		service->socket_count = 1;
	} else {
		service->version_string = PACKAGE_VERSION;
	}
	value = getenv("SOCKET_COUNT");
	if (value != NULL)
		service->socket_count = atoi(value);
	value = getenv("SSL_SOCKET_COUNT");
	if (value != NULL)
		service->ssl_socket_count = atoi(value);
	value = getenv("SOCKET_NAMES");
	if (value != NULL) {
		service->listener_names =
			p_strsplit_tabescaped(default_pool, value);
		service->listener_names_count =
			str_array_length((void *)service->listener_names);
	}
	service->want_ssl_settings = service->ssl_socket_count > 0 ||
		(flags & MASTER_SERVICE_FLAG_USE_SSL_SETTINGS) != 0;

	/* set up some kind of logging until we know exactly how and where
	   we want to log */
	if (getenv("LOG_SERVICE") != NULL)
		i_set_failure_internal();
	if (getenv("USER") != NULL)
		i_set_failure_prefix("%s(%s): ", name, getenv("USER"));
	else
		i_set_failure_prefix("%s: ", name);

	if ((flags & MASTER_SERVICE_FLAG_STANDALONE) == 0) {
		/* initialize master_status structure */
		value = getenv(MASTER_UID_ENV);
		if (value == NULL ||
		    str_to_uint(value, &service->master_status.uid) < 0)
			i_fatal(MASTER_UID_ENV" missing");
		service->master_status.pid = getpid();

		/* set the default limit */
		value = getenv(MASTER_CLIENT_LIMIT_ENV);
		if (value == NULL || str_to_uint(value, &count) < 0 ||
		    count == 0)
			i_fatal(MASTER_CLIENT_LIMIT_ENV" missing");
		master_service_set_client_limit(service, count);

		/* seve the process limit */
		value = getenv(MASTER_PROCESS_LIMIT_ENV);
		if (value != NULL && str_to_uint(value, &count) == 0 &&
		    count > 0)
			service->process_limit = count;

		value = getenv(MASTER_PROCESS_MIN_AVAIL_ENV);
		if (value != NULL && str_to_uint(value, &count) == 0 &&
		    count > 0)
			service->process_min_avail = count;

		/* set the default service count */
		value = getenv(MASTER_SERVICE_COUNT_ENV);
		if (value != NULL && str_to_uint(value, &count) == 0 &&
		    count > 0)
			master_service_set_service_count(service, count);

		/* set the idle kill timeout */
		value = getenv(MASTER_SERVICE_IDLE_KILL_ENV);
		if (value != NULL && str_to_uint(value, &count) == 0)
			service->idle_kill_secs = count;
	} else {
		master_service_set_client_limit(service, 1);
		master_service_set_service_count(service, 1);
	}
	if ((flags & MASTER_SERVICE_FLAG_KEEP_CONFIG_OPEN) != 0) {
		/* since we're going to keep the config socket open anyway,
		   open it now so we can read settings even after privileges
		   are dropped. */
		master_service_config_socket_try_open(service);
	}

	master_service_verify_version_string(service);
	return service;
}

int master_getopt(struct master_service *service)
{
	int c;

	while ((c = getopt(service->argc, service->argv,
			   service->getopt_str)) > 0) {
		if (!master_service_parse_option(service, c, optarg))
			break;
	}
	return c;
}

void master_service_init_log(struct master_service *service,
			     const char *prefix)
{
	const char *path, *timestamp;

	if ((service->flags & MASTER_SERVICE_FLAG_STANDALONE) != 0 &&
	    (service->flags & MASTER_SERVICE_FLAG_DONT_LOG_TO_STDERR) == 0) {
		timestamp = getenv("LOG_STDERR_TIMESTAMP");
		if (timestamp != NULL)
			i_set_failure_timestamp_format(timestamp);
		i_set_failure_file("/dev/stderr", "");
		return;
	}

	if (getenv("LOG_SERVICE") != NULL && !service->log_directly) {
		/* logging via log service */
		i_set_failure_internal();
		i_set_failure_prefix("%s", prefix);
		return;
	}

	if (service->set == NULL) {
		i_set_failure_file("/dev/stderr", prefix);
		return;
	}

	if (strcmp(service->set->log_path, "syslog") != 0) {
		/* error logging goes to file or stderr */
		path = home_expand(service->set->log_path);
		i_set_failure_file(path, prefix);
	}

	if (strcmp(service->set->log_path, "syslog") == 0 ||
	    strcmp(service->set->info_log_path, "syslog") == 0 ||
	    strcmp(service->set->debug_log_path, "syslog") == 0) {
		/* something gets logged to syslog */
		int facility;

		if (!syslog_facility_find(service->set->syslog_facility,
					  &facility))
			facility = LOG_MAIL;
		i_set_failure_syslog("dovecot", LOG_NDELAY, facility);
		i_set_failure_prefix("%s", prefix);

		if (strcmp(service->set->log_path, "syslog") != 0) {
			/* set error handlers back to file */
			i_set_fatal_handler(default_fatal_handler);
			i_set_error_handler(default_error_handler);
		}
	}

	if (*service->set->info_log_path != '\0' &&
	    strcmp(service->set->info_log_path, "syslog") != 0) {
		path = home_expand(service->set->info_log_path);
		if (*path != '\0')
			i_set_info_file(path);
	}

	if (*service->set->debug_log_path != '\0' &&
	    strcmp(service->set->debug_log_path, "syslog") != 0) {
		path = home_expand(service->set->debug_log_path);
		if (*path != '\0')
			i_set_debug_file(path);
	}
	i_set_failure_timestamp_format(service->set->log_timestamp);
}

void master_service_set_die_with_master(struct master_service *service,
					bool set)
{
	service->die_with_master = set;
}

void master_service_set_die_callback(struct master_service *service,
				     void (*callback)(void))
{
	service->die_callback = callback;
}

void master_service_set_idle_die_callback(struct master_service *service,
					  bool (*callback)(void))
{
	service->idle_die_callback = callback;
}

static bool get_instance_config(const char *name, const char **config_path_r)
{
	struct master_instance_list *list;
	const struct master_instance *inst;
	const char *instance_path, *path;

	/* note that we don't have any settings yet. we're just finding out
	   which dovecot.conf we even want to read! so we must use the
	   hardcoded state_dir path. */
	instance_path = t_strconcat(PKG_STATEDIR"/"MASTER_INSTANCE_FNAME, NULL);
	list = master_instance_list_init(instance_path);
	inst = master_instance_list_find_by_name(list, name);
	if (inst != NULL) {
		path = t_strdup_printf("%s/dovecot.conf", inst->base_dir);
		if (t_readlink(path, config_path_r) < 0)
			i_fatal("readlink(%s) failed: %m", path);
	}
	master_instance_list_deinit(&list);
	return inst != NULL;
}

bool master_service_parse_option(struct master_service *service,
				 int opt, const char *arg)
{
	const char *path;

	switch (opt) {
	case 'c':
		service->config_path = i_strdup(arg);
		service->config_path_changed_with_param = TRUE;
		break;
	case 'i':
		if (!get_instance_config(arg, &path))
			i_fatal("Unknown instance name: %s", arg);
		service->config_path = i_strdup(path);
		service->config_path_changed_with_param = TRUE;
		break;
	case 'k':
		service->keep_environment = TRUE;
		break;
	case 'o':
		if (!array_is_created(&service->config_overrides))
			i_array_init(&service->config_overrides, 16);
		array_append(&service->config_overrides, &arg, 1);
		break;
	case 'O':
		service->flags |= MASTER_SERVICE_FLAG_NO_CONFIG_SETTINGS;
		break;
	case 'L':
		service->log_directly = TRUE;
		break;
	default:
		return FALSE;
	}
	return TRUE;
}

static void master_service_error(struct master_service *service)
{
	master_service_stop_new_connections(service);
	if (service->master_status.available_count ==
	    service->total_available_count || service->die_with_master) {
		if (service->die_callback == NULL)
			master_service_stop(service);
		else {
			service->to_die =
				timeout_add(MASTER_SERVICE_DIE_TIMEOUT_MSECS,
					    master_service_stop,
					    service);
			service->die_callback();
		}
	}
}

static void master_status_error(struct master_service *service)
{
	/* status fd is a write-only pipe, so if we're here it means the
	   master wants us to die (or died itself). don't die until all
	   service connections are finished. */
	io_remove(&service->io_status_error);

	/* the log fd may also be closed already, don't die when trying to
	   log later */
	i_set_failure_ignore_errors(TRUE);

	master_service_error(service);
}

void master_service_init_finish(struct master_service *service)
{
	enum libsig_flags sigint_flags = LIBSIG_FLAG_DELAYED;
	struct stat st;

	/* set default signal handlers */
	if ((service->flags & MASTER_SERVICE_FLAG_STANDALONE) == 0)
		sigint_flags |= LIBSIG_FLAG_RESTART;
        lib_signals_set_handler(SIGINT, sigint_flags, sig_die, service);
	lib_signals_set_handler(SIGTERM, LIBSIG_FLAG_DELAYED, sig_die, service);
	if ((service->flags & MASTER_SERVICE_FLAG_TRACK_LOGIN_STATE) != 0) {
		lib_signals_set_handler(SIGUSR1, LIBSIG_FLAGS_SAFE,
					sig_state_changed, service);
	}

	if ((service->flags & MASTER_SERVICE_FLAG_STANDALONE) == 0) {
		if (fstat(MASTER_STATUS_FD, &st) < 0 || !S_ISFIFO(st.st_mode))
			i_fatal("Must be started by dovecot master process");

		/* start listening errors for status fd, it means master died */
		service->io_status_error = io_add(MASTER_DEAD_FD, IO_ERROR,
						  master_status_error, service);
	}
	master_service_io_listeners_add(service);
	if (service->want_ssl_settings &&
	    (service->flags & MASTER_SERVICE_FLAG_NO_SSL_INIT) == 0)
		master_service_ssl_ctx_init(service);

	if ((service->flags & MASTER_SERVICE_FLAG_STD_CLIENT) != 0) {
		/* we already have a connection to be served */
		service->master_status.available_count--;
	}
	master_status_update(service);
}

void master_service_env_clean(void)
{
	const char *value = getenv(DOVECOT_PRESERVE_ENVS_ENV);

	if (value == NULL || *value == '\0')
		env_clean();
	else T_BEGIN {
		value = t_strconcat(value, " "DOVECOT_PRESERVE_ENVS_ENV, NULL);
		env_clean_except(t_strsplit_spaces(value, " "));
	} T_END;
}

void master_service_set_client_limit(struct master_service *service,
				     unsigned int client_limit)
{
	unsigned int used;

	i_assert(service->master_status.available_count ==
		 service->total_available_count);

	used = service->total_available_count -
		service->master_status.available_count;
	i_assert(client_limit >= used);

	service->total_available_count = client_limit;
	service->master_status.available_count = client_limit - used;
}

unsigned int master_service_get_client_limit(struct master_service *service)
{
	return service->total_available_count;
}

unsigned int master_service_get_process_limit(struct master_service *service)
{
	return service->process_limit;
}

unsigned int master_service_get_process_min_avail(struct master_service *service)
{
	return service->process_min_avail;
}

unsigned int master_service_get_idle_kill_secs(struct master_service *service)
{
	return service->idle_kill_secs;
}

void master_service_set_service_count(struct master_service *service,
				      unsigned int count)
{
	unsigned int used;

	used = service->total_available_count -
		service->master_status.available_count;
	i_assert(count >= used);

	if (service->total_available_count > count) {
		service->total_available_count = count;
		service->master_status.available_count = count - used;
	}
	service->service_count_left = count;
}

unsigned int master_service_get_service_count(struct master_service *service)
{
	return service->service_count_left;
}

unsigned int master_service_get_socket_count(struct master_service *service)
{
	return service->socket_count;
}

const char *master_service_get_socket_name(struct master_service *service,
					   int listen_fd)
{
	unsigned int i;

	i_assert(listen_fd >= MASTER_LISTEN_FD_FIRST);

	i = listen_fd - MASTER_LISTEN_FD_FIRST;
	return i < service->listener_names_count ?
		service->listener_names[i] : "";
}

void master_service_set_avail_overflow_callback(struct master_service *service,
						void (*callback)(void))
{
	service->avail_overflow_callback = callback;
}

const char *master_service_get_config_path(struct master_service *service)
{
	return service->config_path;
}

const char *master_service_get_version_string(struct master_service *service)
{
	return service->version_string;
}

const char *master_service_get_name(struct master_service *service)
{
	return service->name;
}

void master_service_run(struct master_service *service,
			master_service_connection_callback_t *callback)
{
	service->callback = callback;
	io_loop_run(service->ioloop);
	service->callback = NULL;
}

void master_service_stop(struct master_service *service)
{
        io_loop_stop(service->ioloop);
}

void master_service_stop_new_connections(struct master_service *service)
{
	unsigned int current_count;

	if (service->stopping)
		return;

	service->stopping = TRUE;
	master_service_io_listeners_remove(service);
	master_service_io_listeners_close(service);

	/* make sure we stop after servicing current connections */
	current_count = service->total_available_count -
		service->master_status.available_count;
	service->service_count_left = current_count;
	service->total_available_count = current_count;

	if (current_count == 0)
		master_service_stop(service);
	else {
		/* notify master that we're not accepting any more
		   connections */
		service->master_status.available_count = 0;
		master_status_update(service);
	}
	if (service->login != NULL)
		master_login_stop(service->login);
}

bool master_service_is_killed(struct master_service *service)
{
	return service->killed;
}

bool master_service_is_master_stopped(struct master_service *service)
{
	return service->io_status_error == NULL;
}

void master_service_anvil_send(struct master_service *service, const char *cmd)
{
	ssize_t ret;

	if ((service->flags & MASTER_SERVICE_FLAG_STANDALONE) != 0)
		return;

	ret = write(MASTER_ANVIL_FD, cmd, strlen(cmd));
	if (ret < 0) {
		if (errno == EPIPE) {
			/* anvil process was probably recreated, don't bother
			   logging an error about losing connection to it */
			return;
		}
		i_error("write(anvil) failed: %m");
	} else if (ret == 0)
		i_error("write(anvil) failed: EOF");
	else {
		i_assert((size_t)ret == strlen(cmd));
	}
}

void master_service_client_connection_created(struct master_service *service)
{
	i_assert(service->master_status.available_count > 0);
	service->master_status.available_count--;
	master_status_update(service);
}

void master_service_client_connection_accept(struct master_service_connection *conn)
{
	conn->accepted = TRUE;
}

void master_service_client_connection_destroyed(struct master_service *service)
{
	/* we can listen again */
	master_service_io_listeners_add(service);

	i_assert(service->total_available_count > 0);
	i_assert(service->service_count_left > 0);

	if (service->service_count_left == service->total_available_count) {
		service->total_available_count--;
                service->service_count_left--;
	} else {
		if (service->service_count_left != UINT_MAX)
			service->service_count_left--;

		i_assert(service->master_status.available_count <
			 service->total_available_count);
		service->master_status.available_count++;
	}

	if (service->service_count_left == 0) {
		i_assert(service->master_status.available_count ==
			 service->total_available_count);
		master_service_stop(service);
	} else if ((service->io_status_error == NULL ||
		    service->listeners == NULL) &&
		   service->master_status.available_count ==
		   service->total_available_count) {
		/* we've finished handling all clients, and
		   a) master has closed the connection
		   b) there are no listeners (std-client?) */
		master_service_stop(service);
	} else {
		master_status_update(service);
	}
}

static void master_service_set_login_state(struct master_service *service,
					   enum master_login_state state)
{
	if (service->to_overflow_state != NULL)
		timeout_remove(&service->to_overflow_state);

	switch (state) {
	case MASTER_LOGIN_STATE_NONFULL:
		service->call_avail_overflow = FALSE;
		if (service->master_status.available_count > 0)
			return;

		/* some processes should now be able to handle new connections,
		   although we can't. but there may be race conditions, so
		   make sure that we'll check again soon if the state has
		   changed to "full" without our knowledge. */
		service->to_overflow_state =
			timeout_add(MASTER_SERVICE_STATE_CHECK_MSECS,
				    master_service_refresh_login_state,
				    service);
		return;
	case MASTER_LOGIN_STATE_FULL:
		/* make sure we're listening for more connections */
		service->call_avail_overflow = TRUE;
		master_service_io_listeners_add(service);
		return;
	}
	i_error("Invalid master login state: %d", state);
}

static void master_service_refresh_login_state(struct master_service *service)
{
	int ret;

	ret = lseek(MASTER_LOGIN_NOTIFY_FD, 0, SEEK_CUR);
	if (ret < 0)
		i_error("lseek(login notify fd) failed: %m");
	else
		master_service_set_login_state(service, ret);
}

void master_service_close_config_fd(struct master_service *service)
{
	if (service->config_fd != -1) {
		if (close(service->config_fd) < 0)
			i_error("close(master config fd) failed: %m");
		service->config_fd = -1;
	}
}

void master_service_deinit(struct master_service **_service)
{
	struct master_service *service = *_service;

	*_service = NULL;

	master_service_io_listeners_remove(service);
	master_service_ssl_ctx_deinit(service);

	master_service_close_config_fd(service);
	if (service->to_die != NULL)
		timeout_remove(&service->to_die);
	if (service->to_overflow_state != NULL)
		timeout_remove(&service->to_overflow_state);
	if (service->to_status != NULL)
		timeout_remove(&service->to_status);
	if (service->io_status_error != NULL)
		io_remove(&service->io_status_error);
	if (service->io_status_write != NULL)
		io_remove(&service->io_status_write);
	if (array_is_created(&service->config_overrides))
		array_free(&service->config_overrides);

	if (service->set_parser != NULL) {
		settings_parser_deinit(&service->set_parser);
		pool_unref(&service->set_pool);
	}
	lib_signals_deinit();
	/* run atexit callbacks before destroying ioloop */
	lib_atexit_run();
	io_loop_destroy(&service->ioloop);

	if (service->listener_names != NULL)
		p_strsplit_free(default_pool, service->listener_names);
	i_free(service->listeners);
	i_free(service->getopt_str);
	i_free(service->name);
	i_free(service->config_path);
	i_free(service);

	lib_deinit();
}

static void master_service_listen(struct master_service_listener *l)
{
	struct master_service *service = l->service;
	struct master_service_connection conn;

	if (service->master_status.available_count == 0) {
		/* we are full. stop listening for now, unless overflow
		   callback destroys one of the existing connections */
		if (service->call_avail_overflow &&
		    service->avail_overflow_callback != NULL)
			service->avail_overflow_callback();

		if (service->master_status.available_count == 0) {
			master_service_io_listeners_remove(service);
			return;
		}
	}

	memset(&conn, 0, sizeof(conn));
	conn.listen_fd = l->fd;
	conn.fd = net_accept(l->fd, &conn.remote_ip, &conn.remote_port);
	if (conn.fd < 0) {
		struct stat st;
		int orig_errno = errno;

		if (conn.fd == -1)
			return;

		if (errno == ENOTSOCK) {
			/* it's not a socket. should be a fifo. */
		} else if (errno == EINVAL &&
			   (fstat(l->fd, &st) == 0 && S_ISFIFO(st.st_mode))) {
			/* BSDI fails accept(fifo) with EINVAL. */
		} else {
			errno = orig_errno;
			i_error("net_accept() failed: %m");
			/* try again later after one of the existing
			   connections has died */
			master_service_io_listeners_remove(service);
			return;
		}
		/* use the "listener" as the connection fd and stop the
		   listener. */
		conn.fd = l->fd;
		conn.listen_fd = l->fd;
		conn.fifo = TRUE;

		io_remove(&l->io);
		l->fd = -1;
	}
	conn.ssl = l->ssl;
	conn.name = l->name;
	net_set_nonblock(conn.fd, TRUE);

	master_service_client_connection_created(service);

	service->callback(&conn);

	if (!conn.accepted) {
		if (close(conn.fd) < 0)
			i_error("close(service connection) failed: %m");
		master_service_client_connection_destroyed(service);
	} else if (conn.fifo) {
		/* reading FIFOs stays open forever, don't count them
		   as real clients */
		master_service_client_connection_destroyed(service);
	}
	if (service->master_status.available_count == 0 &&
	    service->service_count_left == 1) {
		/* we're not going to accept any more connections after this.
		   go ahead and close the connection early. don't do this
		   before calling callback, because it may want to access
		   the listen_fd (e.g. to check socket permissions). */
		i_assert(service->listeners != NULL);
		master_service_io_listeners_remove(service);
		master_service_io_listeners_close(service);
	}
}

static void io_listeners_init(struct master_service *service)
{
	unsigned int i;

	if (service->socket_count == 0)
		return;

	service->listeners =
		i_new(struct master_service_listener, service->socket_count);

	for (i = 0; i < service->socket_count; i++) {
		struct master_service_listener *l = &service->listeners[i];

		l->service = service;
		l->fd = MASTER_LISTEN_FD_FIRST + i;
		l->name = i < service->listener_names_count ?
			service->listener_names[i] : "";

		if (i >= service->socket_count - service->ssl_socket_count)
			l->ssl = TRUE;
	}
}

void master_service_io_listeners_add(struct master_service *service)
{
	unsigned int i;

	if (service->stopping)
		return;

	if (service->listeners == NULL)
		io_listeners_init(service);

	for (i = 0; i < service->socket_count; i++) {
		struct master_service_listener *l = &service->listeners[i];

		if (l->io == NULL && l->fd != -1) {
			l->io = io_add(MASTER_LISTEN_FD_FIRST + i, IO_READ,
				       master_service_listen, l);
		}
	}
}

void master_service_io_listeners_remove(struct master_service *service)
{
	unsigned int i;

	if (service->listeners != NULL) {
		for (i = 0; i < service->socket_count; i++) {
			if (service->listeners[i].io != NULL)
				io_remove(&service->listeners[i].io);
		}
	}
}

void master_service_ssl_io_listeners_remove(struct master_service *service)
{
	unsigned int i;

	if (service->listeners != NULL) {
		for (i = 0; i < service->socket_count; i++) {
			if (service->listeners[i].io != NULL &&
			    service->listeners[i].ssl)
				io_remove(&service->listeners[i].io);
		}
	}
}

static void master_service_io_listeners_close(struct master_service *service)
{
	unsigned int i;

	if (service->listeners != NULL) {
		/* close via listeners. some fds might be pipes that are
		   currently handled as clients. we don't want to close them. */
		for (i = 0; i < service->socket_count; i++) {
			if (service->listeners[i].fd != -1) {
				if (close(service->listeners[i].fd) < 0) {
					i_error("close(listener %d) failed: %m",
						service->listeners[i].fd);
				}
				service->listeners[i].fd = -1;
			}
		}
	} else {
		for (i = 0; i < service->socket_count; i++) {
			int fd = MASTER_LISTEN_FD_FIRST + i;

			if (close(fd) < 0)
				i_error("close(listener %d) failed: %m", fd);
		}
	}
}

static bool master_status_update_is_important(struct master_service *service)
{
	if (service->master_status.available_count == 0)
		return TRUE;
	if (!service->initial_status_sent)
		return TRUE;
	return FALSE;
}

void master_status_update(struct master_service *service)
{
	ssize_t ret;
	bool important_update;

	if ((service->flags & MASTER_SERVICE_FLAG_UPDATE_PROCTITLE) != 0 &&
	    service->set != NULL && service->set->verbose_proctitle) T_BEGIN {
		unsigned int used_count = service->total_available_count -
			service->master_status.available_count;

		process_title_set(t_strdup_printf("[%u connections]",
						  used_count));
	} T_END;

	important_update = master_status_update_is_important(service);
	if (service->master_status.pid == 0 ||
	    service->master_status.available_count ==
	    service->last_sent_status_avail_count) {
		/* a) closed, b) updating to same state */
		if (service->to_status != NULL)
			timeout_remove(&service->to_status);
		if (service->io_status_write != NULL)
			io_remove(&service->io_status_write);
		return;
	}
	if (ioloop_time == service->last_sent_status_time &&
	    !important_update) {
		/* don't spam master */
		if (service->to_status != NULL)
			timeout_reset(service->to_status);
		else {
			service->to_status =
				timeout_add(1000, master_status_update,
					    service);
		}
		if (service->io_status_write != NULL)
			io_remove(&service->io_status_write);
		return;
	}

	if (service->to_status != NULL)
		timeout_remove(&service->to_status);

	ret = write(MASTER_STATUS_FD, &service->master_status,
		    sizeof(service->master_status));
	if (ret == sizeof(service->master_status)) {
		/* success */
		if (service->io_status_write != NULL) {
			/* delayed important update sent successfully */
			io_remove(&service->io_status_write);
		}
		service->last_sent_status_time = ioloop_time;
		service->last_sent_status_avail_count =
			service->master_status.available_count;
		service->initial_status_sent = TRUE;
	} else if (ret >= 0) {
		/* shouldn't happen? */
		i_error("write(master_status_fd) returned %d", (int)ret);
		service->master_status.pid = 0;
	} else if (errno != EAGAIN) {
		/* failure */
		if (errno != EPIPE)
			i_error("write(master_status_fd) failed: %m");
		service->master_status.pid = 0;
	} else if (important_update) {
		/* reader is busy, but it's important to get this notification
		   through. send it when possible. */
		if (service->io_status_write == NULL) {
			service->io_status_write =
				io_add(MASTER_STATUS_FD, IO_WRITE,
				       master_status_update, service);
		}
	}
}

bool version_string_verify(const char *line, const char *service_name,
			   unsigned major_version)
{
	unsigned int minor_version;

	return version_string_verify_full(line, service_name,
					  major_version, &minor_version);
}

bool version_string_verify_full(const char *line, const char *service_name,
				unsigned major_version,
				unsigned int *minor_version_r)
{
	unsigned int service_name_len = strlen(service_name);
	bool ret;

	if (strncmp(line, "VERSION\t", 8) != 0)
		return FALSE;
	line += 8;

	if (strncmp(line, service_name, service_name_len) != 0 ||
	    line[service_name_len] != '\t')
		return FALSE;
	line += service_name_len + 1;

	T_BEGIN {
		const char *p = strchr(line, '\t');

		if (p == NULL)
			ret = FALSE;
		else {
			ret = str_uint_equals(t_strdup_until(line, p),
					      major_version);
			if (str_to_uint(p+1, minor_version_r) < 0)
				ret = FALSE;
		}
	} T_END;
	return ret;
}


text:
'use strict';

/**
 * @ngdoc function
 * @name handbook.controller:Page
 * @description
 * # Pagecontroller
 * Controller of the handbook
 */
angular.module('handbook')
    .controller('Page', function ($scope, $log, yqlService, DataCache) {
        $scope.$parent.query = '';

        $scope.getTop = function() {
            $scope.results = DataCache.get('top');

            if (!$scope.results) {
                yqlService.getAnalytics().then(
                    function(results) {
                        var data = results.data.query.results.json.rows;
                        DataCache.put('top', data);
                        $scope.results = data;
                    },
                    function() {
                        $log.error('Топ50 не загружен');
                    }
                );
            }
        };
    });

redpajama_set_name: RedPajamaGithub


text:
// ==UserScript==
// @name          Stack Exchange Global Flag Summary
// @namespace     http://floern.com/
// @version       1.2.2
// @description   Stack Exchange networkwide flag summary available in your network profile
// @author        Floern
// @include       *://stackexchange.com/users/*/*
// @match         *://*.stackexchange.com/users/flag-summary/*
// @match         *://*.stackoverflow.com/users/flag-summary/*
// @match         *://*.superuser.com/users/flag-summary/*
// @match         *://*.serverfault.com/users/flag-summary/*
// @match         *://*.askubuntu.com/users/flag-summary/*
// @match         *://*.stackapps.com/users/flag-summary/*
// @match         *://*.mathoverflow.net/users/flag-summary/*
// @connect       stackexchange.com
// @connect       stackoverflow.com
// @connect       superuser.com
// @connect       serverfault.com
// @connect       askubuntu.com
// @connect       stackapps.com
// @connect       mathoverflow.net
// @require       https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @grant         GM.xmlHttpRequest
// @grant         GM_xmlhttpRequest
// @grant         GM.addStyle
// @grant         GM_addStyle
// @run-at        document-end
// @updateURL     https://raw.githubusercontent.com/Floern/stackoverflow/master/userscripts/SE_global_flag_summary.meta.js
// @downloadURL   https://raw.githubusercontent.com/Floern/stackoverflow/master/userscripts/SE_global_flag_summary.user.js
// ==/UserScript==

let flagSummaryTable, flagSummaryTableBody, errorView;

let sortedColIndex = 2;
let sortedColAsc = false;

let flagGlobalSummaryStats = {
    sumFlagsTotal: 0,
    sumFlagsDeclined: 0,
    sumFlagsDisputed: 0,
    sumFlagsRetracted: 0,
    sumFlagsExpired: 0,
    sumFlagsPending: 0,
    sumFlagsHelpful: 0
};

let rateLimited = false;

let reloadIcon = `iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADrUlEQVRYR+1WS2gTURRN/OFfURER/10IUtqmS
WYmEQz+EFEXohVxIaLgStHMZJLUFmapuBBRKlbnk4+/xi5c+NkIipui1i4FUXShLiqiiPihfuK5yTOdycwkqdaK4IFDMvPuuXPfffe9
+zwjgYCohzklO5U9jjw42TjFi+oDIXp2Bnv1e4goxvhwLFUXkPRgsDW7WpD1Zk46s9i/t3MsM7EAAeghScsLktYXkjKz2euhQYh2TRB
i2k5e0m7A0Xs4/E5OB6l+FyT1rSDp3Vxc2xpRbo1hUg8vG7mfdoKo3fMoyig2VB0tudxopG8XhC+tH6xM2D8RYvoO+pgQ1W4OvldfRR
SlFFxFNCrGdDi5bnY8VCJb3chMT+m51gC4eHZeSNQemp0NB2sKoEHKTMJ69zo5ICK93zCzO3xMOxmUU+18TD8Kx9fx7oOTvZk1BYBCO
uUkBgdQhCf8ifQCZmqBP9E5DUG1IeXvHLQFVg2Ai54RaIZ2sfqak9WVzKwETtJXCbHU5kAivZuLGwfxAQX2hl1fZNUAkMZrDsKPCGAF
M7EAdZKkLeigcSQC6G9pyY1mciv4A8Yip9ljSVqZiR35vBfj+xC4Q9bsxKH0mCntgJNouQAB9VNRMhNXIP17sPZfCxoEg1r5gi08gJr
4SCwcUkg/L+s9TGIHKv+qLQCsJxuuirCszqUs+sXzs5YpuclEv9I5kYj/42jtXdNPoJly+7NTzaTDiA3/x78HXETm86K+tqH9gq9RyT
URG1ov1bNhO5rbUnXU34nNyXMbfYcym4Lx1DYUIip8kMtdTsJyYAd1OBT1E9d2jL59ulzgwmdU7UzmiAh2AG29ci0CcN9VQwiAzoeng
aS2hElt4CW93UkXko3VzMQOdDbVUeRCzOZ5MJmeyeQl4DxZg7EBB/u+irchrHemXFRgsf0eD8Qz4QblUn1j4uKin+cEzmIvkxfAx9Qt
0NjacuGUjOvrmJkzXAMAyQHSmg7I2aXM3IS8N5RI+3D0XnZrTOgX1U/USgGYiMun9gi/50OiquIy0oXnZ2U2FmL8Ti39xHJ7HS7Sx6k
XsE9UhuX2KmmfOFk/TL9mh7WSlgzF2FHzxwnWAIo3l4Co+rCut83Oa+BdQdYizG3tCEnGdsz4MzmxXp3y3mDMaMKMjqCY7sPmDfV6si
v0fZGetV7UwzFeSvmLml8EJxkb4JguEi9c9qyXejv1emRmYVi+MoWe2djwgI+n1uPq1Mce/w4wqzns7x+Ex/MDD9PvSmMer2UAAAAAS
UVORK5CYII=`;

// init
(function () {
    if (window.location.href.match(/\/users\/flag-summary\/\d+/i)) {
        showGlobalFlagSummaryLink();
        return;
    }

    if (!window.location.href.match(/:\/\/stackexchange\.com\/users\/\d+/i)) {
        return;
    }

    let navigation = document.querySelector('#content .contentWrapper .subheader');
    if (!navigation) {
        return;
    }

    let tabbar = navigation.querySelector('.tabs');

    // verify that we are in the profile of the logged in user
    let tabs = tabbar.getElementsByTagName('a');
    let loggedIn = false;
    for (let i = 0; i < tabs.length; i++) {
        if (tabs[i].textContent.trim().toLowerCase() == 'inbox') {
            loggedIn = true;
            break;
        }
    }
    if (!loggedIn) {
        return;
    }

    // add navigation tab for flags
    let flagTab = document.createElement('a');
    flagTab.setAttribute('href', '?tab=flags');
    flagTab.textContent = 'flags';
    tabs[4].parentNode.insertBefore(flagTab, tabs[4]);

    if (!window.location.href.match(/:\/\/stackexchange\.com\/users\/\d+\/.+?\?tab=flags/i)) {
        return;
    }

    // unselect default tab
    let selectedTab = navigation.querySelector('.youarehere');
    selectedTab.className = '';

    // set selected tab to flags
    flagTab.className = 'youarehere';

    // remove default content
    while (navigation.nextSibling) {
        navigation.parentNode.removeChild(navigation.nextSibling);
    }

    document.querySelector('title').textContent = 'Flag Summary - Stack Exchange';

    let container = document.createElement('div');
    navigation.parentNode.appendChild(container);

    // setup summary table
    flagSummaryTable = document.createElement('table');
    flagSummaryTable.id = 'flag-summary-table';
    flagSummaryTable.style.width = '100%';
    flagSummaryTable.style.textAlign = 'right';
    flagSummaryTable.style.borderCollapse = 'separate';
    flagSummaryTable.style.borderSpacing = '0 5px';
    flagSummaryTable.innerHTML = `

                Site
                helpful
                declined
                disputed
                expired
                retracted
                pending
                total
                helpful %
                last flag

    `;
    container.appendChild(flagSummaryTable);

    // make columns sortable
    let tableLabelNodes = flagSummaryTable.querySelectorAll('#flag-summary-heading-labels th');
    for (let i = 0; i < tableLabelNodes.length; i++) {
        let col = i + 1;
        tableLabelNodes[i].onclick = function() {
            sortedColAsc = col == sortedColIndex ? !sortedColAsc : false;
            sortTable(col, sortedColAsc);
        };
    }

    flagSummaryTableBody = flagSummaryTable.getElementsByTagName('tbody')[0];

    // some table CSS
    GM.addStyle("#flag-summary-heading-labels th { padding-top:6px; cursor:pointer; }");
    GM.addStyle("#flag-summary-global-stats th { padding-bottom:4px; border-bottom:1px #ddd solid; }");
    GM.addStyle("#flag-summary-table tbody tr:hover { background:rgba(127,127,127,.10); }");
    GM.addStyle("#flag-summary-table tbody tr { counter-increment:siteNumber; }");
    GM.addStyle("#flag-summary-table tbody tr td:first-child::before { content:counter(siteNumber); width:14px; " +
                "margin-right: 10px; color: #bbb; font-size:10px; display:inline-block; text-align:right; margin-left:-24px; }");
    GM.addStyle("#flag-summary-table tbody tr td:last-child { width: 0px; position: relative; }");
    GM.addStyle("#flag-summary-table .reloadbutton { cursor:pointer; width:24px; position:absolute; top:0; left:0; " +
                "z-index:1; display:none; }");
    GM.addStyle("#flag-summary-table tbody tr:hover .reloadbutton { display:block; }");
    GM.addStyle("#flag-summary-table tbody tr td:last-child::after { content:''; width:24px; display:inline-block; " +
                "position:absolute; height:100%; top:0;}");

    // init global flag summary
    updateGlobalFlagStats();

    // prepare error view
    errorView = document.createElement('div');
    container.appendChild(errorView);

    // create loading view
    let loadingView = document.createElement('div');
    loadingView.id = 'flag-summary-loading';
    loadingView.style.textAlign = 'center';
    loadingView.innerHTML = '
' +
                            '';
    container.appendChild(loadingView);

    rateLimited = false;

    // load data
    loadAccountList();
})();

/**
 * Add a link to the flag summary page.
 */
function showGlobalFlagSummaryLink() {
    let header = document.querySelector('#content .subheader');
    if (!header) {
        return;
    }

    // add link to header
    let segfsLink = document.createElement('a');
    segfsLink.setAttribute('href', '//stackexchange.com/users/current?tab=flags');
    segfsLink.textContent = 'Global Flag Summary';
    segfsLink.style.float = 'right';
    segfsLink.style.paddingTop = '13px';
    header.insertBefore(segfsLink, header.firstChild);
}

/**
 * Update global flag summary in header.
 */
function updateGlobalFlagStats() {
    let realTotal = flagGlobalSummaryStats.sumFlagsHelpful + flagGlobalSummaryStats.sumFlagsDeclined;
    let helpfulFraction = realTotal == 0 ? 0 : (flagGlobalSummaryStats.sumFlagsHelpful / realTotal);

    document.getElementById('flag-summary-global-stats').innerHTML = `

        ` + formatFlagCount(flagGlobalSummaryStats.sumFlagsHelpful) + `
        ` + formatFlagCount(flagGlobalSummaryStats.sumFlagsDeclined) + `
        ` + formatFlagCount(flagGlobalSummaryStats.sumFlagsDisputed) + `
        ` + formatFlagCount(flagGlobalSummaryStats.sumFlagsExpired) + `
        ` + formatFlagCount(flagGlobalSummaryStats.sumFlagsRetracted) + `
        ` + formatFlagCount(flagGlobalSummaryStats.sumFlagsPending) + `
        ` + formatFlagCount(flagGlobalSummaryStats.sumFlagsTotal) + `
        ` + (realTotal == 0 ? '' : formatFlagPercentage(helpfulFraction)) + `

    `;
}

/**
 * Load the network account list.
 */
function loadAccountList() {
    let accountListUrl = '//stackexchange.com/users/current?tab=accounts';
    GM.xmlHttpRequest({
        method: 'GET',
        url: accountListUrl,
        onload: function(response) {
            parseNetworkAccounts(response.response);
        },
        onerror: function(response) {
            console.error('loadAccountList: ' + JSON.stringify(response));
            showLoadingError(accountListUrl, response.status, null);
        }
    });
}

/**
 * Parse the network account list.
 */
function parseNetworkAccounts(html) {
    let parser = new DOMParser();
    let pageNode = parser.parseFromString(html, 'text/html');

    let accounts = [];

    // iterate all accounts
    let accountNodes = pageNode.querySelectorAll('.contentWrapper .account-container');
    for (let i = 0; i < accountNodes.length; ++i) {
        let accountNode = accountNodes[i];

        let siteLinkNode = accountNode.querySelector('.account-site a');
        if (!siteLinkNode) {
            continue;
        }
        if (siteLinkNode.href.indexOf('area51.stackexchange.com/') != -1) {
            // use area51.meta.SE instead
            siteLinkNode.href = siteLinkNode.href.replace('//area51.st', '//area51.meta.st');
        }

        let siteName = siteLinkNode.textContent.trim();
        let siteFlagSummaryUrl = siteLinkNode.href.replace(/users\/(\d+)\/.*$/i, 'users/flag-summary/$1');

        // get badge count, used for prioritization
        let badgeCount = 0;
        let badgeNodes = accountNode.querySelectorAll('.badgecount');
        for (let j = 0; j < badgeNodes.length; ++j) {
            badgeCount += parseInt(badgeNodes[j].textContent.trim());
        }

        accounts.push({siteName: siteName, flagSummaryUrl: siteFlagSummaryUrl, loadPriority: badgeCount});

        // add meta site
        if (!/(meta\.stackexchange|area51\.stackexchange|stackapps)\.com\//.test(siteFlagSummaryUrl)) {
            let metaSiteFlagSummaryUrl;
            if (/\.stackexchange\.com\//.test(siteFlagSummaryUrl)) // SE 2.0 sites
                metaSiteFlagSummaryUrl = siteFlagSummaryUrl.replace('.stackexchange.com', '.meta.stackexchange.com');
            else if (/\/\/[a-z]{2}\.stackoverflow\.com\//.test(siteFlagSummaryUrl)) // localized SO sites
                metaSiteFlagSummaryUrl = siteFlagSummaryUrl.replace('.stackoverflow.com', '.meta.stackoverflow.com');
            else // SE 1.0 sites
                metaSiteFlagSummaryUrl = siteFlagSummaryUrl.replace('//', '//meta.');
            accounts.push({siteName: siteName + " Meta", flagSummaryUrl: metaSiteFlagSummaryUrl, loadPriority: badgeCount - 1.5});
        }
    }

    // sort by badge count desc, so we load sites with more badges earlier, since those have higher chances having our flags
    accounts = accounts.sort(function (a, b) {
        return b.loadPriority - a.loadPriority;
    });

    // load the sites
    let i = -1;
    let loaded = 0;
    function loadNextSite() {
        i++;
        if (i >= accounts.length) {
            // end of list
            return;
        }

        let account = accounts[i];
        let delay = (i < 25 ? 100 : (i < 160 ? 450 : 1111));
        setTimeout(function() {
            if (rateLimited) {
                return;
            }
            loadSiteFlagSummary(account.siteName, account.flagSummaryUrl, function() {
                loaded++;
                let progressText = document.getElementById('flag-summary-loading-progress');
                if (rateLimited) {
                    progressText.textContent = 'aborted (rate limited)';
                    document.getElementById('flag-summary-loading-anim').style.visibility = 'hidden';
                }
                else {
                    progressText.textContent = loaded + ' / ' + accounts.length;
                }
                if (loaded >= accounts.length) {
                    // end of list
                    document.getElementById('flag-summary-loading').style.visibility = 'hidden';
                }
            });
            loadNextSite();
        }, delay);
    }

    loadNextSite();
}

/**
 * Load the flag summary of the specified site.
 */
function loadSiteFlagSummary(siteName, siteFlagSummaryUrl, finishedCallback) {
    console.log('loading ' + siteName);
    GM.xmlHttpRequest({
        method: 'GET',
        url: siteFlagSummaryUrl,
        onload: function(response) {
            if (response.status < 400) {
                parseSiteFlagSummary(siteName, siteFlagSummaryUrl, response.response);
            }
            else {
                showLoadingError(siteFlagSummaryUrl, response.status, siteName);
                if (response.status == 429) {
                    rateLimited = true;
                }
            }
            finishedCallback();
        },
        onerror: function(response) {
            console.error('loadSiteFlagSummary: ' + siteFlagSummaryUrl);
            console.error('loadSiteFlagSummary: ' + JSON.stringify(response));
            showLoadingError(siteFlagSummaryUrl, response.status, siteName);
            finishedCallback();
        }
    });
}

/**
 * Parse the flag summary site and extract the stats.
 */
function parseSiteFlagSummary(siteName, siteFlagSummaryUrl, html) {
    let parser = new DOMParser();
    let pageNode = parser.parseFromString(html, 'text/html');

    let sumFlagsTotal = 0;
    let sumFlagsDeclined = 0;
    let sumFlagsDisputed = 0;
    let sumFlagsRetracted = 0;
    let sumFlagsExpired = 0;
    let sumFlagsPending = 0;
    let sumFlagsHelpful = 0;

    // search for flag stats
    let flagCountNodes = pageNode.querySelectorAll('#sidebar ul li a[href*="status="]');
    for (let i = 0; i < flagCountNodes.length; i++) {
        let flagType = parseInt(flagCountNodes[i].href.replace(/^.+?\bstatus=(\d+).*$/, '$1'));
        let flagCount = parseInt(flagCountNodes[i].children[1].textContent.replace(/\D/g, ''));

        sumFlagsTotal += flagCount;

        switch (flagType) {
            case 1: // pending
                sumFlagsPending += flagCount; break;
            case 2: // helpful
                sumFlagsHelpful += flagCount; break;
            case 3: // declined
                sumFlagsDeclined += flagCount; break;
            case 4: // disputed
                sumFlagsDisputed += flagCount; break;
            case 5: // expired
                sumFlagsExpired += flagCount; break;
            case 6: // retracted
                sumFlagsRetracted += flagCount; break;
            default:
                console.error('parseSiteFlagSummary: unknown flag type #' + flagType);
                break;
        }
    }

    if (sumFlagsTotal == 0) {
        // skip site with no flags
        return;
    }

    // update global summary
    flagGlobalSummaryStats.sumFlagsTotal += sumFlagsTotal;
    flagGlobalSummaryStats.sumFlagsDeclined += sumFlagsDeclined;
    flagGlobalSummaryStats.sumFlagsDisputed += sumFlagsDisputed;
    flagGlobalSummaryStats.sumFlagsRetracted += sumFlagsRetracted;
    flagGlobalSummaryStats.sumFlagsExpired += sumFlagsExpired;
    flagGlobalSummaryStats.sumFlagsPending += sumFlagsPending;
    flagGlobalSummaryStats.sumFlagsHelpful += sumFlagsHelpful;

    updateGlobalFlagStats();

    // compute helpful percentage
    let realTotal = sumFlagsHelpful + sumFlagsDeclined;
    let helpfulFraction = realTotal == 0 ? 0 : (sumFlagsHelpful / realTotal);

    // get most recent flag date
    let flagHistoryDates = pageNode.querySelectorAll('.user-flag-history .mod-flag .relativetime');
    let mostRecentflagHistoryDateNode = flagHistoryDates[0];
    let lastFlagTimestamp = mostRecentflagHistoryDateNode.title;
    let lastFlagTimeDisplay = formatTimeRelative(lastFlagTimestamp);

    // get site icon
    let siteFaviconURL = pageNode.querySelector('link[rel*="icon"]').href;

    // create table row for this site
    let siteFlagSummaryTr = document.createElement('tr');
    siteFlagSummaryTr.innerHTML = `
        <img src="` + siteFaviconURL + `"
            style="width:16px;height:16px;vertical-align:middle" />
        <a href="` + siteFlagSummaryUrl + `">` + siteName + `
        ` + formatFlagCount(sumFlagsHelpful) + `
        ` + formatFlagCount(sumFlagsDeclined) + `
        ` + formatFlagCount(sumFlagsDisputed) + `
        ` + formatFlagCount(sumFlagsExpired) + `
        ` + formatFlagCount(sumFlagsRetracted) + `
        ` + formatFlagCount(sumFlagsPending) + `
        ` + formatFlagCount(sumFlagsTotal) + `
        ` + (realTotal == 0 ? '–' : formatFlagPercentage(helpfulFraction)) + `
        <td style="color:#999" title="` + lastFlagTimestamp + `">` + lastFlagTimeDisplay + `
        <img style="width:16px;height:16px;vertical-align:middle;"
             src="data:image/png;base64,` + reloadIcon + `" />
    `;
    let reloadButton = siteFlagSummaryTr.getElementsByClassName('reloadbutton')[0];
    reloadButton.onclick = function(e) {
        reloadButton.innerHTML = '';
        loadSiteFlagSummary(siteName, siteFlagSummaryUrl, function() {
            // remove old row
            flagSummaryTableBody.removeChild(siteFlagSummaryTr);
            flagGlobalSummaryStats.sumFlagsTotal -= sumFlagsTotal;
            flagGlobalSummaryStats.sumFlagsDeclined -= sumFlagsDeclined;
            flagGlobalSummaryStats.sumFlagsDisputed -= sumFlagsDisputed;
            flagGlobalSummaryStats.sumFlagsRetracted -= sumFlagsRetracted;
            flagGlobalSummaryStats.sumFlagsExpired -= sumFlagsExpired;
            flagGlobalSummaryStats.sumFlagsPending -= sumFlagsPending;
            flagGlobalSummaryStats.sumFlagsHelpful -= sumFlagsHelpful;
            updateGlobalFlagStats();
        });
    };

    let anchorBottom = window.pageYOffset > 9 && (window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2;

    flagSummaryTableBody.appendChild(siteFlagSummaryTr);

    // keep order
    sortTable(sortedColIndex, sortedColAsc);

    if (anchorBottom) {
        // keep scroll position at bottom
        window.scrollTo(window.pageXOffset, document.body.scrollHeight);
    }
}

/**
 * Format flag count, empty if 0.
 */
function formatFlagCount(flagCount) {
    if (flagCount == 0)
        return '';
    else
        return flagCount;
}

/**
 * Format helpful flag percentage.
 */
function formatFlagPercentage(fraction) {
    return (fraction * 100).toFixed(2) + '%';
}

/**
 * Format relative time.
 */
function formatTimeRelative(e) {
    if (null != e && 20 == e.length) {
        e = e.substr(0, 10) + "T" + e.substr(11, 10);
        let date = new Date(e),
            dsecs = Math.floor((Date.now() - date.getTime()) / 1e3),
            ddays = Math.floor(dsecs / 86400);
        if (0 <= ddays && ddays < 7 || ddays == 42) {
            if (dsecs < 2) return 'just now';
            if (dsecs < 60) return dsecs + ' secs ago';
            if (dsecs < 120) return '1 min ago';
            let dmins = Math.floor(dsecs / 60);
            if (dmins < 60) return dmins + ' mins ago';
            if (dmins < 120) return '1 hour ago';
            let dhrs = Math.floor(dmins / 60);
            if (dhrs < 18) return dhrs + ' hours ago';
            if (dhrs < 48) return 'yesterday';
            else return ddays + ' days ago';
        }
        else {
            let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            return months[date.getMonth()] + ' ' + date.getDate() +
                (date.getFullYear() != new Date().getFullYear() ? " '" + date.getFullYear() % 100 : '');
        }
    }
    else {
        return e;
    }
}

/**
 * Show an error.
 */
function showLoadingError(url, statuscode, siteName) {
    let errorMsg = document.createElement('div');
    errorMsg.style.paddingTop = '4px';
    let errorHtml = 'Failed to load ' + (siteName || url) + ' ';
    if (statuscode <= 0 && siteName) errorHtml += '(retry)';
    else if (statuscode == 429) errorHtml += '(rate limited)';
    else errorHtml += 'with status ' + statuscode;
    errorMsg.innerHTML = errorHtml;
    let retrybtn = errorMsg.getElementsByClassName('segfs-retry');
    if (retrybtn.length > 0) {
        retrybtn[0].onclick = function(e) {
            loadSiteFlagSummary(siteName, url, function(){});
            errorMsg.outerHTML = '';
            return false;
        };
    }
    errorView.appendChild(errorMsg);
}

/**
 * Sort the table by column index `col` and bool `asc`.
 */
function sortTable(col, asc) {
    sortedColIndex = col;
    let trs = [].slice.call(flagSummaryTableBody.rows, 0);
    asc = -((+asc) || -1);
    if (col == 1) {
        // site name
        trs = trs.sort(function (a, b) {
            return asc * (a.cells[col].textContent.trim().localeCompare(b.cells[col].textContent.trim()));
        });
    }
    else if (col == 10) {
        // date
        trs = trs.sort(function (a, b) {
            return asc * (b.cells[col].title.localeCompare(a.cells[col].title));
        });
    }
    else {
        trs = trs.sort(function (a, b) {
            let va = parseInt(a.cells[col].textContent.replace(/\D/g, '')) || 0;
            let vb = parseInt(b.cells[col].textContent.replace(/\D/g, '')) || 0;
            if (va != vb) // primary order
                return asc * (vb - va);
            else // secondary order
                return a.cells[1].textContent.trim().localeCompare(b.cells[1].textContent.trim());
        });
    }
    for (let i = 0; i < trs.length; ++i) flagSummaryTableBody.appendChild(trs[i]);
}


text:
* Web Develompent Anno Dazumal ([])
* Flexbox - Ein Dehnbarer Begriff ([])
* MeteorJS - Fullstack ([])
* ToolZoo ([])


text:
import getopt
import sys
import time
import ConfigParser
import platform
import functools

from twisted.application.internet import UDPServer, TCPServer
from twisted.application.service import MultiService
from twisted.python import usage, log
from twisted.plugin import getPlugins

from txstatsd.client import InternalClient
from txstatsd.metrics.metrics import Metrics
from txstatsd.metrics.extendedmetrics import ExtendedMetrics
from txstatsd.server.processor import MessageProcessor
from txstatsd.server.configurableprocessor import ConfigurableMessageProcessor
from txstatsd.server.loggingprocessor import LoggingMessageProcessor
from txstatsd.server.protocol import (
    StatsDServerProtocol, StatsDTCPServerFactory)
from txstatsd.server.router import Router
from txstatsd.server import httpinfo
from txstatsd.report import ReportingService
from txstatsd.itxstatsd import IMetricFactory
from twisted.application.service import Service
from twisted.internet import task

def accumulateClassList(classObj, attr, listObj,
                        baseClass=None, excludeClass=None):
    """Accumulate all attributes of a given name in a class hierarchy
    into a single list.

    Assuming all class attributes of this name are lists.
    """
    for base in classObj.__bases__:
        accumulateClassList(base, attr, listObj, excludeClass=excludeClass)
    if excludeClass != classObj:
        if baseClass is None or baseClass in classObj.__bases__:
            listObj.extend(classObj.__dict__.get(attr, []))

class OptionsGlue(usage.Options):
    """Extends usage.Options to also read parameters from a config file."""

    optParameters = [
        ["config", "c", None, "Config file to use."]]

    def __init__(self):
        parameters = []
        accumulateClassList(self.__class__, 'optParameters',
                            parameters, excludeClass=OptionsGlue)
        for parameter in parameters:
            if parameter[0] == "config" or parameter[1] == "c":
                raise ValueError("the --config/-c parameter is reserved.")

        self.overridden_options = []

        super(OptionsGlue, self).__init__()

    def opt_config(self, config_path):
        self['config'] = config_path

    opt_c = opt_config

    def parseOptions(self, options=None):
        """Obtain overridden options."""

        if options is None:
            options = sys.argv[1:]
        try:
            opts, args = getopt.getopt(options,
                                       self.shortOpt, self.longOpt)
        except getopt.error, e:
            raise usage.UsageError(str(e))

        for opt, arg in opts:
            if opt[1] == '-':
                opt = opt[2:]
            else:
                opt = opt[1:]
            self.overridden_options.append(opt)

        super(OptionsGlue, self).parseOptions(options=options)

    def postOptions(self):
        """Read the configuration file if one is provided."""
        if self['config'] is not None:
            config_file = ConfigParser.RawConfigParser()
            config_file.read(self['config'])

            self.configure(config_file)

    def overridden_option(self, opt):
        """Return whether this option was overridden."""
        return opt in self.overridden_options

    def configure(self, config_file):
        """Read the configuration items, coercing types as required."""
        for name, value in config_file.items(self.config_section):
            self._coerce_option(name, value)

        for section in sorted(config_file.sections()):
            if section.startswith("plugin_"):
                self[section] = config_file.items(section)
            if section.startswith("carbon-cache"):
                for name, value in config_file.items(section):
                    self._coerce_option(name, value)

    def _coerce_option(self, name, value):
        """Coerce a single option, checking for overriden options."""
        # Overridden options have precedence
        if not self.overridden_option(name):
            # Options appends '=' when gathering the parameters
            if (name + '=') in self.longOpt:
                # Coerce the type if required
                if name in self._dispatch:
                    if isinstance(self._dispatch[name], usage.CoerceParameter):
                        value = self._dispatch[name].coerce(value)
                    else:
                        self._dispatch[name](name, value)
                        return
                self[name] = value

class StatsDOptions(OptionsGlue):
    """
    The set of configuration settings for txStatsD.
    """

    optParameters = [
        ["carbon-cache-host", "h", None,
         "The host where carbon cache is listening.", str],
        ["carbon-cache-port", "p", None,
         "The port where carbon cache is listening.", int],
        ["carbon-cache-name", "n", None,
         "An identifier for the carbon-cache instance."],
        ["listen-port", "l", 8125,
         "The UDP port where we will listen.", int],
        ["flush-interval", "i", 60000,
         "The number of milliseconds between each flush.", int],
        ["prefix", "x", None,
         "Prefix to use when reporting stats.", str],
        ["instance-name", "N", None,
         "Instance name for our own stats reporting.", str],
        ["report", "r", None,
         "Which additional stats to report {process|net|io|system}.", str],
        ["monitor-message", "m", "txstatsd ping",
         "Message we expect from monitoring agent.", str],
        ["monitor-response", "o", "txstatsd pong",
         "Response we should send monitoring agent.", str],
        ["statsd-compliance", "s", 1,
         "Produce StatsD-compliant messages.", int],
        ["dump-mode", "d", 0,
         "Dump received and aggregated metrics"
         " before passing them to carbon.", int],
        ["routing", "g", "",
         "Routing rules", str],
        ["listen-tcp-port", "t", None,
         "The TCP port where we will listen.", int],
        ["max-queue-size", "Q", 20000,
         "Maximum send queue size per destination.", int],
        ["max-datapoints-per-message", "M", 1000,
         "Maximum datapoints per message to carbon-cache.", int],
        ["http-port", "P", None,
         "The httpinfo port.", int],
        ]

    def __init__(self):
        self.config_section = 'statsd'
        super(StatsDOptions, self).__init__()
        self["carbon-cache-host"] = []
        self["carbon-cache-port"] = []
        self["carbon-cache-name"] = []

    def opt_carbon_cache_host(self, host):
        self["carbon-cache-host"].append(host)

    def opt_carbon_cache_port(self, port):
        self["carbon-cache-port"].append(usage.portCoerce(port))

    def opt_carbon_cache_name(self, name):
        self["carbon-cache-name"].append(name)

class StatsDService(Service):

    def __init__(self, carbon_client, processor, flush_interval, clock=None):
        self.carbon_client = carbon_client
        self.processor = processor
        self.flush_interval = flush_interval
        self.flush_task = task.LoopingCall(self.flushProcessor)
        if clock is not None:
            self.flush_task.clock = clock

    def flushProcessor(self):
        """Flush messages queued in the processor to Graphite."""
        flushed = 0
        start = time.time()
        for metric, value, timestamp in self.processor.flush(
                interval=self.flush_interval):
            self.carbon_client.sendDatapoint(metric, (timestamp, value))
            flushed += 1
        log.msg("Flushed total %d metrics in %.6f" %
                (flushed, time.time() - start))

    def startService(self):
        self.flush_task.start(self.flush_interval / 1000, False)

    def stopService(self):
        if self.flush_task.running:
            self.flush_task.stop()

def report_client_manager_stats():
    from carbon.instrumentation import stats

    current_stats = stats.copy()
    for name, value in list(current_stats.items()):
        del current_stats[name]
        if name.startswith("destinations"):
            current_stats[name.replace(":", "_")] = value
        stats[name] = 0
    return current_stats

def createService(options):
    """Create a txStatsD service."""
    from carbon.routers import ConsistentHashingRouter
    from carbon.client import CarbonClientManager
    from carbon.conf import settings

    settings.MAX_QUEUE_SIZE = options["max-queue-size"]
    settings.MAX_DATAPOINTS_PER_MESSAGE = options["max-datapoints-per-message"]

    root_service = MultiService()
    root_service.setName("statsd")

    prefix = options["prefix"]
    if prefix is None:
        prefix = "statsd"

    instance_name = options["instance-name"]
    if not instance_name:
        instance_name = platform.node()

    # initialize plugins
    plugin_metrics = []
    for plugin in getPlugins(IMetricFactory):
        plugin.configure(options)
        plugin_metrics.append(plugin)

    processor = None
    if options["dump-mode"]:
        # LoggingMessageProcessor supersedes
        #  any other processor class in "dump-mode"
        assert not hasattr(log, 'info')
        log.info = log.msg # for compatibility with LMP logger interface
        processor = functools.partial(LoggingMessageProcessor, logger=log)

    if options["statsd-compliance"]:
        processor = (processor or MessageProcessor)(plugins=plugin_metrics)
        input_router = Router(processor, options['routing'], root_service)
        connection = InternalClient(input_router)
        metrics = Metrics(connection)
    else:
        processor = (processor or ConfigurableMessageProcessor)(
            message_prefix=prefix,
            internal_metrics_prefix=prefix + "." + instance_name + ".",
            plugins=plugin_metrics)
        input_router = Router(processor, options['routing'], root_service)
        connection = InternalClient(input_router)
        metrics = ExtendedMetrics(connection)

    if not options["carbon-cache-host"]:
        options["carbon-cache-host"].append("127.0.0.1")
    if not options["carbon-cache-port"]:
        options["carbon-cache-port"].append(2004)
    if not options["carbon-cache-name"]:
        options["carbon-cache-name"].append(None)

    reporting = ReportingService(instance_name)
    reporting.setServiceParent(root_service)

    reporting.schedule(report_client_manager_stats,
                       options["flush-interval"] / 1000,
                       metrics.gauge)

    if options["report"] is not None:
        from txstatsd import process
        from twisted.internet import reactor

        reporting.schedule(
            process.report_reactor_stats(reactor), 60, metrics.gauge)
        reports = [name.strip() for name in options["report"].split(",")]
        for report_name in reports:
            for reporter in getattr(process, "%s_STATS" %
                                    report_name.upper(), ()):
                reporting.schedule(reporter, 60, metrics.gauge)

    # XXX Make this configurable.
    router = ConsistentHashingRouter()
    carbon_client = CarbonClientManager(router)
    carbon_client.setServiceParent(root_service)

    for host, port, name in zip(options["carbon-cache-host"],
                                options["carbon-cache-port"],
                                options["carbon-cache-name"]):
        carbon_client.startClient((host, port, name))

    statsd_service = StatsDService(carbon_client, input_router,
                                   options["flush-interval"])
    statsd_service.setServiceParent(root_service)

    statsd_server_protocol = StatsDServerProtocol(
        input_router,
        monitor_message=options["monitor-message"],
        monitor_response=options["monitor-response"])

    listener = UDPServer(options["listen-port"], statsd_server_protocol)
    listener.setServiceParent(root_service)

    if options["listen-tcp-port"] is not None:
        statsd_tcp_server_factory = StatsDTCPServerFactory(
                input_router,
                monitor_message=options["monitor-message"],
                monitor_response=options["monitor-response"])

        listener = TCPServer(options["listen-tcp-port"],
            statsd_tcp_server_factory)
        listener.setServiceParent(root_service)

    httpinfo_service = httpinfo.makeService(options, processor, statsd_service)
    httpinfo_service.setServiceParent(root_service)

    return root_service


text:
using System.Windows;

namespace Caliburn.Micro.Hello
{
    public class HelloBootstrapper : BootstrapperBase
    {
        public HelloBootstrapper()
        {
            Initialize();
        }

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            DisplayRootViewFor<ShellViewModel>();
        }
    }
}


text:
package java.util.zip;
public class CheckedInputStream extends java.io.FilterInputStream {
	public CheckedInputStream(java.io.InputStream var0, java.util.zip.Checksum var1) { super((java.io.InputStream) null); }
	public int read() throws java.io.IOException { return 0; }
	public int read(byte[] var0, int var1, int var2) throws java.io.IOException { return 0; }
	public java.util.zip.Checksum getChecksum() { return null; }
	public long skip(long var0) throws java.io.IOException { return 0l; }
}


text: {item}


text:
package iip.nodes;

import java.io.*;
import java.util.*;
import java.util.function.*;
import java.util.concurrent.*;
import javax.annotation.PostConstruct;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.annotation.Bean;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import io.micrometer.core.instrument.*;
import static de.iip_ecosphere.platform.support.function.IOVoidFunction.optional;
import de.iip_ecosphere.platform.support.identities.*;
import de.iip_ecosphere.platform.support.resources.*;
import de.iip_ecosphere.platform.support.iip_aas.Id;
import de.iip_ecosphere.platform.transport.Transport;
import de.iip_ecosphere.platform.transport.status.TraceRecord;
import de.iip_ecosphere.platform.transport.serialization.*;
import de.iip_ecosphere.platform.transport.connectors.*;
import de.iip_ecosphere.platform.transport.spring.SerializerMessageConverter;
import de.iip_ecosphere.platform.services.environment.switching.ServiceSelector;
import de.iip_ecosphere.platform.services.environment.*;
import de.iip_ecosphere.platform.services.environment.switching.*;
import de.iip_ecosphere.platform.services.environment.metricsProvider.MonitoredTranslatingProtocolAdapter;
import de.iip_ecosphere.platform.services.environment.spring.Starter;
import de.iip_ecosphere.platform.services.environment.spring.SpringAsyncServiceBase;
import de.iip_ecosphere.platform.services.environment.spring.metricsProvider.MetricsProvider;
import de.iip_ecosphere.platform.connectors.ConnectorParameter;
import de.iip_ecosphere.platform.connectors.ConnectorParameter.CacheMode;
import de.iip_ecosphere.platform.connectors.types.*;
import de.iip_ecosphere.platform.connectors.model.*;
import iip.datatypes.*;
import iip.interfaces.*;
import iip.serializers.*;

/**
 * Spring Cloud Stream service frame for net node 'Simple Data Transformer3'.
 *
 * @author EASy-Producer.
 */
@Component
@ConditionalOnProperty(value="iip.service.SimpleTransformer3", havingValue="true", matchIfMissing=true)
@EnableScheduling
public class SimpleDataTransformer3 extends SpringAsyncServiceBase {

    @Value("${iip.service.SimpleTransformer3:true}")
    private String activated;
    @Autowired
    private StreamBridge streamBridge;
    private SimpleDataTransformer3Interface service;
    // so far plain delegation, preparation but so far no support for service switching
    @Autowired
    private MetricsProvider metrics;
    private Counter serviceSent;
    private Counter serviceReceived;
    private io.micrometer.core.instrument.Timer processingTime;

     /**
     * Creates an instance.
     */
    public SimpleDataTransformer3() {
        service = AbstractService.createInstance("de.iip_ecosphere.platform.test.apps.serviceImpl.SimpleTransformer3Impl",
            SimpleDataTransformer3Interface.class,
            "SimpleTransformer3",
            "deployment.yml");

    }

    /**
    * Called when data arrived that shall be processed (synchronously).
    *
    * @return the data transformation functor
    */
    @Bean
    public Function<Rec13, Rec13> transformRec13Rec13_SimpleTransformer3() {
        return data -> service.transformRec13(data);
    }

    /**
     * Initializes the service when feasible in Spring lifecycle.
     */
    @PostConstruct
    public void initService() {
        if (null == activated || "".equals(activated) || "true".equals(activated)) {
            LoggerFactory.getLogger(getClass()).info("Initializing service SimpleTransformer3: {}", activated);
            serviceSent = Counter.builder("service.sent")
                .baseUnit("tuple/s")
                .description("Tuples sent out by a service")
                .tags("service", "SimpleTransformer3", "application", "SimpleMeshApp3", "device", Id.getDeviceId())
                .register(metrics.getRegistry());
            serviceReceived = Counter.builder("service.received")
                .baseUnit("tuple/s")
                .description("Tuples received by a service")
                .tags("service", "SimpleTransformer3", "application", "SimpleMeshApp3", "device", Id.getDeviceId())
                .register(metrics.getRegistry());
            processingTime = io.micrometer.core.instrument.Timer.builder("service.processed")
                .description("Main processing time of a service")
                .tags("service", "SimpleTransformer3", "application", "SimpleMeshApp3", "device", Id.getDeviceId())
                .register(metrics.getRegistry());
                MonitoringService.setUp(service, metrics);
            Starter.mapService(service);

        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<WindowOpeningMode>LockOwnerWindow</WindowOpeningMode>
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1"/>
	<Events>
		<Event name="BeforeWriteAtServer">ПередЗаписьюНаСервере</Event>
		<Event name="OnWriteAtServer">ПриЗаписиНаСервере</Event>
		<Event name="FillCheckProcessingAtServer">ОбработкаПроверкиЗаполненияНаСервере</Event>
	</Events>
	<ChildItems>
		<InputField name="Номенклатура" id="5">
			<DataPath>Запись.Номенклатура</DataPath>
			<ReadOnly>true</ReadOnly>
			<ContextMenu name="НоменклатураКонтекстноеМеню" id="6"/>
			<ExtendedTooltip name="НоменклатураExtendedTooltip" id="11"/>
		</InputField>
		<InputField name="Характеристика" id="7">
			<DataPath>Запись.Характеристика</DataPath>
			<ReadOnly>true</ReadOnly>
			<ContextMenu name="ХарактеристикаКонтекстноеМеню" id="8"/>
			<ExtendedTooltip name="ХарактеристикаExtendedTooltip" id="12"/>
		</InputField>
		<InputField name="Упаковка" id="9">
			<DataPath>Запись.Упаковка</DataPath>
			<ReadOnly>true</ReadOnly>
			<ContextMenu name="УпаковкаКонтекстноеМеню" id="10"/>
			<ExtendedTooltip name="УпаковкаExtendedTooltip" id="13"/>
		</InputField>
		<InputField name="Код" id="3">
			<DataPath>Запись.Код</DataPath>
			<ChoiceButton>false</ChoiceButton>
			<ChoiceListButton>true</ChoiceListButton>
			<ContextMenu name="КодКонтекстноеМеню" id="4"/>
			<ExtendedTooltip name="КодExtendedTooltip" id="14"/>
			<Events>
				<Event name="StartListChoice">КодНачалоВыбораИзСписка</Event>
			</Events>
		</InputField>
	</ChildItems>
	<Attributes>
		<Attribute name="Запись" id="1">
			<Type>
				<v8:Type>cfg:InformationRegisterRecordManager.КодыТоваровПодключаемогоОборудованияOffline</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<SavedData>true</SavedData>
		</Attribute>
	</Attributes>
</Form>


text:
require 'space_invaders/behaviors/mesurable'
require 'space_invaders/behaviors/collideable'
module SpaceInvaders
  class Invader < Base
    include Mesurable
    include Collideable

    attr_reader :original_x_position

    def initialize app, x_position, y_position
      super app

      @was_first_image = true
      @x_position = x_position
      @original_x_position = x_position
      @y_position = y_position
      @image = @first_image
    end

    def update(direction, y_offset=0)
      x_offset = direction == :right ? 10 : -10
      @x_position += x_offset
      @y_position += y_offset

      @was_first_image = !@was_first_image
      @image = @was_first_image ? @first_image : @second_image
    end

    def draw
      @image.draw x_position, y_position, 1
    end

    def points
      raise NotImplementedError.new("You must implement the inherited points method")
    end

  end
end


text:
package org.apache.camel.component.atlasmap;

import twitter4j.Status;
import twitter4j.User;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class Util {

    public static Status generateMockTwitterStatus() {
        Status status = mock(Status.class);
        User user = mock(User.class);
        when(user.getName()).thenReturn("Bob Vila");
        when(user.getScreenName()).thenReturn("bobvila1982");
        when(status.getUser()).thenReturn(user);
        when(status.getText()).thenReturn("Let's build a house!");
        return status;
    }

}


text:
FOUNDATION_EXPORT double ExploreVersionNumber;
FOUNDATION_EXPORT const unsigned char ExploreVersionString[];


text:
from lxml import etree
import webob
import webob.dec
import webob.exc

from nova.api import openstack as openstack_api
from nova.api.openstack import wsgi
import nova.context
from nova import exception
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes

class APITest(test.TestCase):

    def _wsgi_app(self, inner_app):
        # simpler version of the app than fakes.wsgi_app
        return openstack_api.FaultWrapper(inner_app)

    def test_malformed_json(self):
        req = webob.Request.blank('/')
        req.method = 'POST'
        req.body = '{'
        req.headers["content-type"] = "application/json"

        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(res.status_int, 400)

    def test_malformed_xml(self):
        req = webob.Request.blank('/')
        req.method = 'POST'
        req.body = '<hi im not xml>'
        req.headers["content-type"] = "application/xml"

        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(res.status_int, 400)

    def test_vendor_content_type_json(self):
        ctype = 'application/vnd.openstack.compute+json'

        req = webob.Request.blank('/')
        req.headers['Accept'] = ctype

        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(res.status_int, 200)
        self.assertEqual(res.content_type, ctype)

        body = jsonutils.loads(res.body)

    def test_vendor_content_type_xml(self):
        ctype = 'application/vnd.openstack.compute+xml'

        req = webob.Request.blank('/')
        req.headers['Accept'] = ctype

        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(res.status_int, 200)
        self.assertEqual(res.content_type, ctype)

        body = etree.XML(res.body)

    def test_exceptions_are_converted_to_faults_webob_exc(self):
        @webob.dec.wsgify
        def raise_webob_exc(req):
            raise webob.exc.HTTPNotFound(explanation='Raised a webob.exc')

        #api.application = raise_webob_exc
        api = self._wsgi_app(raise_webob_exc)
        resp = webob.Request.blank('/').get_response(api)
        self.assertEqual(resp.status_int, 404, resp.body)

    def test_exceptions_are_converted_to_faults_api_fault(self):
        @webob.dec.wsgify
        def raise_api_fault(req):
            exc = webob.exc.HTTPNotFound(explanation='Raised a webob.exc')
            return wsgi.Fault(exc)

        #api.application = raise_api_fault
        api = self._wsgi_app(raise_api_fault)
        resp = webob.Request.blank('/').get_response(api)
        self.assertTrue('itemNotFound' in resp.body, resp.body)
        self.assertEqual(resp.status_int, 404, resp.body)

    def test_exceptions_are_converted_to_faults_exception(self):
        @webob.dec.wsgify
        def fail(req):
            raise Exception("Threw an exception")

        #api.application = fail
        api = self._wsgi_app(fail)
        resp = webob.Request.blank('/').get_response(api)
        self.assertTrue('{"computeFault' in resp.body, resp.body)
        self.assertEqual(resp.status_int, 500, resp.body)

    def test_exceptions_are_converted_to_faults_exception_xml(self):
        @webob.dec.wsgify
        def fail(req):
            raise Exception("Threw an exception")

        #api.application = fail
        api = self._wsgi_app(fail)
        resp = webob.Request.blank('/.xml').get_response(api)
        self.assertTrue('<computeFault' in resp.body, resp.body)
        self.assertEqual(resp.status_int, 500, resp.body)

    def _do_test_exception_safety_reflected_in_faults(self, expose):
        class ExceptionWithSafety(exception.NovaException):
            safe = expose

        @webob.dec.wsgify
        def fail(req):
            raise ExceptionWithSafety('some explanation')

        api = self._wsgi_app(fail)
        resp = webob.Request.blank('/').get_response(api)
        self.assertTrue('{"computeFault' in resp.body, resp.body)
        expected = ('ExceptionWithSafety: some explanation' if expose else
                    'The server has either erred or is incapable '
                    'of performing the requested operation.')
        self.assertTrue(expected in resp.body, resp.body)
        self.assertEqual(resp.status_int, 500, resp.body)

    def test_safe_exceptions_are_described_in_faults(self):
        self._do_test_exception_safety_reflected_in_faults(True)

    def test_unsafe_exceptions_are_not_described_in_faults(self):
        self._do_test_exception_safety_reflected_in_faults(False)

    def _do_test_exception_mapping(self, exception_type, msg):
        @webob.dec.wsgify
        def fail(req):
            raise exception_type(msg)

        api = self._wsgi_app(fail)
        resp = webob.Request.blank('/').get_response(api)
        self.assertTrue(msg in resp.body, resp.body)
        self.assertEqual(resp.status_int, exception_type.code, resp.body)

        if hasattr(exception_type, 'headers'):
            for (key, value) in exception_type.headers.iteritems():
                self.assertTrue(key in resp.headers)
                self.assertEquals(resp.headers[key], value)

    def test_quota_error_mapping(self):
        self._do_test_exception_mapping(exception.QuotaError, 'too many used')

    def test_non_nova_notfound_exception_mapping(self):
        class ExceptionWithCode(Exception):
            code = 404

        self._do_test_exception_mapping(ExceptionWithCode,
                                        'NotFound')

    def test_non_nova_exception_mapping(self):
        class ExceptionWithCode(Exception):
            code = 417

        self._do_test_exception_mapping(ExceptionWithCode,
                                        'Expectation failed')

    def test_exception_with_none_code_throws_500(self):
        class ExceptionWithNoneCode(Exception):
            code = None

        msg = 'Internal Server Error'

        @webob.dec.wsgify
        def fail(req):
            raise ExceptionWithNoneCode()

        api = self._wsgi_app(fail)
        resp = webob.Request.blank('/').get_response(api)
        self.assertEqual(500, resp.status_int)

    def test_request_id_in_response(self):
        req = webob.Request.blank('/')
        req.method = 'GET'
        context = nova.context.RequestContext('bob', 1)
        context.request_id = 'test-req-id'
        req.environ['nova.context'] = context

        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(res.headers['x-compute-request-id'], 'test-req-id')


text:
/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://igorlino.github.io/fancybox-plus/
 *
 * Version: 1.3.5 (20.06.2015)
 * Requires: jQuery v1.3+
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */

#fbplus-loading {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 40px;
    height: 40px;
    margin-top: -20px;
    margin-left: -20px;
    cursor: pointer;
    overflow: hidden;
    z-index: 1104;
    display: none;
}

#fbplus-loading div {
    position: absolute;
    top: 0;
    left: 0;
    width: 40px;
    height: 480px;
    background-image: url('../assets/img/fbplus/fbplus.png');
}

#fbplus-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1100;
    display: none;
}

#fbplus-tmp {
    padding: 0;
    margin: 0;
    border: 0;
    overflow: auto;
    display: none;
}

#fbplus-wrap {
    position: absolute;
    top: 0;
    left: 0;
    padding: 20px;
    z-index: 1101;
    outline: none;
    display: none;
}

#fbplus-outer {
    position: relative;
    width: 100%;
    height: 100%;
    background: #fff;
}

#fbplus-content {
    width: 0;
    height: 0;
    padding: 0;
    outline: none;
    position: relative;
    overflow: hidden;
    z-index: 1102;
    border: 0px solid #fff;
}

#fbplus-hide-sel-frame {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: transparent;
    z-index: 1101;
}

#fbplus-close {
    position: absolute;
    top: -15px;
    right: -15px;
    width: 30px;
    height: 30px;
    background: transparent url('../assets/img/fbplus/fbplus.png') -40px 0px;
    cursor: pointer;
    z-index: 1103;
    display: none;
}

#fbplus-error {
    color: #444;
    font: normal 12px/20px Arial;
    padding: 14px;
    margin: 0;
}

#fbplus-img {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    border: none;
    outline: none;
    line-height: 0;
    vertical-align: top;
    cursor: url('../assets/img/cursor.png'), auto;
}

#fbplus-frame {
    width: 100%;
    height: 100%;
    border: none;
    display: block;
}

#fbplus-left, #fbplus-right {
    position: absolute;
    bottom: 0px;
    height: 100%;
    width: 35%;
    cursor: pointer;
    outline: none;
    background: transparent url('../assets/img/fbplus/blank.gif');
    z-index: 1102;
    display: none;
}

#fbplus-left {
    left: 0px;
}

#fbplus-right {
    right: 0px;
}

#fbplus-left-ico, #fbplus-right-ico {
    position: absolute;
    top: 50%;
    left: -9999px;
    width: 30px;
    height: 30px;
    margin-top: -15px;
    cursor: pointer;
    z-index: 1102;
    display: block;
}

#fbplus-left-ico {
    background-image: url('../assets/img/fbplus/fbplus.png');
    background-position: -40px -30px;
}

#fbplus-right-ico {
    background-image: url('../assets/img/fbplus/fbplus.png');
    background-position: -40px -60px;
}

#fbplus-left:hover, #fbplus-right:hover {
    visibility: visible; /* IE6 */
}

#fbplus-left:hover span {
    left: 20px;
}

#fbplus-right:hover span {
    left: auto;
    right: 20px;
}

.fbplus-bg {
    position: absolute;
    padding: 0;
    margin: 0;
    border: 0;
    width: 20px;
    height: 20px;
    z-index: 1001;
}

#fbplus-bg-n {
    top: -20px;
    left: 0;
    width: 100%;
    background-image: url('../assets/img/fbplus/fbplus-x.png');
}

#fbplus-bg-ne {
    top: -20px;
    right: -20px;
    background-image: url('../assets/img/fbplus/fbplus.png');
    background-position: -40px -162px;
}

#fbplus-bg-e {
    top: 0;
    right: -20px;
    height: 100%;
    background-image: url('../assets/img/fbplus/fbplus-y.png');
    background-position: -20px 0px;
}

#fbplus-bg-se {
    bottom: -20px;
    right: -20px;
    background-image: url('../assets/img/fbplus/fbplus.png');
    background-position: -40px -182px;
}

#fbplus-bg-s {
    bottom: -20px;
    left: 0;
    width: 100%;
    background-image: url('../assets/img/fbplus/fbplus-x.png');
    background-position: 0px -20px;
}

#fbplus-bg-sw {
    bottom: -20px;
    left: -20px;
    background-image: url('../assets/img/fbplus/fbplus.png');
    background-position: -40px -142px;
}

#fbplus-bg-w {
    top: 0;
    left: -20px;
    height: 100%;
    background-image: url('../assets/img/fbplus/fbplus-y.png');
}

#fbplus-bg-nw {
    top: -20px;
    left: -20px;
    background-image: url('../assets/img/fbplus/fbplus.png');
    background-position: -40px -122px;
}

#fbplus-title {
    font-family: Helvetica;
    font-size: 12px;
    z-index: 1102;
}

.fbplus-title-inside {
    padding-bottom: 10px;
    text-align: center;
    color: #333;
    background: #fff;
    position: relative;
}

.fbplus-title-outside {
    padding-top: 10px;
    color: #fff;
}

.fbplus-title-over {
    position: absolute;
    bottom: 0;
    left: 0;
    color: #FFF;
    text-align: left;
}

#fbplus-title-over {
    padding: 10px;
    background-image: url('../assets/img/fbplus/fbplus_title_over.png');
    display: block;
}

.fbplus-title-float {
    position: absolute;
    left: 0;
    bottom: 20px;
    height: 32px;
}

#fbplus-title-float-wrap {
    border: none;
    border-collapse: collapse;
    width: auto;
}

#fbplus-title-float-wrap td {
    border: none;
    white-space: nowrap;
}

#fbplus-title-float-left {
    padding: 0 0 0 15px;
    background: url('../assets/img/fbplus/fbplus.png') -40px -90px no-repeat;
}

#fbplus-title-float-main {
    color: #FFF;
    line-height: 29px;
    font-weight: bold;
    padding: 0 0 3px 0;
    background: url('../assets/img/fbplus/fbplus-x.png') 0px -40px;
}

#fbplus-title-float-right {
    padding: 0 0 0 15px;
    background: url('../assets/img/fbplus/fbplus.png') -55px -90px no-repeat;
}

/* IE6 */

.fbplus-ie6 #fbplus-close {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_close.png', sizingMethod='scale');
}

.fbplus-ie6 #fbplus-left-ico {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_nav_left.png', sizingMethod='scale');
}

.fbplus-ie6 #fbplus-right-ico {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_nav_right.png', sizingMethod='scale');
}

.fbplus-ie6 #fbplus-title-over {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_title_over.png', sizingMethod='scale');
    zoom: 1;
}

.fbplus-ie6 #fbplus-title-float-left {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_title_left.png', sizingMethod='scale');
}

.fbplus-ie6 #fbplus-title-float-main {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_title_main.png', sizingMethod='scale');
}

.fbplus-ie6 #fbplus-title-float-right {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_title_right.png', sizingMethod='scale');
}

.fbplus-ie6 #fbplus-bg-w, .fbplus-ie6 #fbplus-bg-e, .fbplus-ie6 #fbplus-left, .fbplus-ie6 #fbplus-right, #fbplus-hide-sel-frame {
    height: expression(this.parentNode.clientHeight + "px");
}

#fbplus-loading.fbplus-ie6 {
    position: absolute;
    margin-top: 0;
    top: expression( (-20 + (document.documentElement.clientHeight ? document.documentElement.clientHeight/2 : document.body.clientHeight/2 ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop )) + 'px');
}

#fbplus-loading.fbplus-ie6 div {
    background: transparent;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_loading.png', sizingMethod='scale');
}

/* IE6, IE7, IE8 */

.fbplus-ie .fbplus-bg {
    background: transparent !important;
}

.fbplus-ie #fbplus-bg-n {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_n.png', sizingMethod='scale');
}

.fbplus-ie #fbplus-bg-ne {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_ne.png', sizingMethod='scale');
}

.fbplus-ie #fbplus-bg-e {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_e.png', sizingMethod='scale');
}

.fbplus-ie #fbplus-bg-se {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_se.png', sizingMethod='scale');
}

.fbplus-ie #fbplus-bg-s {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_s.png', sizingMethod='scale');
}

.fbplus-ie #fbplus-bg-sw {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_sw.png', sizingMethod='scale');
}

.fbplus-ie #fbplus-bg-w {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_w.png', sizingMethod='scale');
}

.fbplus-ie #fbplus-bg-nw {
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/fbplus/fbplus_shadow_nw.png', sizingMethod='scale');
}


text:
<?php
//
// Copyright (c) 2020-2022 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//

defined("XYO_CLOUD") or die("Access is denied");

if (count($this->toolbar)) {

	foreach ($this->toolbar as $item) {

		if($item["type"]=="item"){
			echo "type."\" href=\"".$item["module"]."\">";
				echo $item["img"];
				echo "";
				echo $item["title"];
				echo "";
			echo "";
			continue;
		};

		if($item["type"]=="item-target"){
			echo "type."\" href=\"".$item["module"]."\" target=\"".$item["parameters"]."\">";
				echo $item["img"];
				echo "";
				echo $item["title"];
				echo "";
			echo "";
			continue;
		};

		if($item["type"]=="item-js"){
			$uid=$this->getUID();
			echo "type."\" href=\"#\">";
				echo $item["img"];
				echo "";
				echo $item["title"];
				echo "";
			echo "";
			$this->ejsBegin();
			echo "document.getElementById(\"".$uid."\").onclick=function(){".$item["parameters"].";return false;};";
			$this->ejsEnd();
			continue;
		};

		if($item["type"]=="item.important"){
			echo "type."\" href=\"".$item["module"]."\">";
				echo $item["img"];
				echo "";
				echo $item["title"];
				echo "";
			echo "";
			continue;
		};

		if($item["type"]=="item-js.important"){
			$uid=$this->getUID();
			echo "type."\" href=\"#\">";
				echo $item["img"];
				echo "";
				echo $item["title"];
				echo "";
			echo "";
			$this->ejsBegin();
			echo "document.getElementById(\"".$uid."\").onclick=function(){".$item["parameters"].";return false;};";
			$this->ejsEnd();
			continue;
		};

		if($item["type"]=="separator"){
			echo "

";
			continue;
		};

		if($item["type"]=="application-menu") {
			echo "
type."\" id=\"popup-menu-application-action\">";
				echo $item["img"];
			echo "
";
			continue;
		};

	};

};


text:
package com.networknt.petstore.handler;

import com.networknt.handler.LightHttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import java.util.HashMap;
import java.util.Map;

public class UserUsernameGetHandler implements LightHttpHandler {
    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {

            exchange.endExchange();

    }
}