text:
#include "config.h"
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "list.h"
#include "util.h"
#include "usb.h"
#include "ipc.h"
#include "dispatch.h"
#include "net.h"
#include "log.h"
#include "frame.h"

// Network protocol:
// struct BusMessage {
//     address:uint8_t
//     command:uint8_t
// }
// struct Request {
//     address:uint8_t
//     command:uint8_t
// }
// struct Response {
//     response:uint8_t
//     status:Status
// }
// enum Status:uint8_t {
//     0:ok
//     1:error
// }

// Listen on this port
const unsigned short DEFAULT_NET_PORT = 55825;
// Bind to this address
const char *DEFAULT_NET_ADDRESS = "127.0.0.1";
// Network frame size
const size_t DEFAULT_NET_FRAMESIZE = 4;
// Network protocol number
const size_t DEFAULT_NET_PROTOCOL = 2;
// Default log level
const unsigned int DEFAULT_LOG_LEVEL = LOG_LEVEL_INFO;
// PID file
const char *DEFAULT_PID_FILE = "/var/run/daliserver.pid";

typedef enum {
	NET_STATUS_SUCCESS = 0,
	NET_STATUS_RESPONSE = 1,
	NET_STATUS_BROADCAST = 2,
	NET_STATUS_ERROR = 255,
} NetStatus;

typedef enum {
	NET_TYPE_SEND,
} NetCommand;

typedef struct {
	unsigned short port;
	char *address;
	unsigned int loglevel;
	int dryrun;
	int syslog;
	char *logfile;
	int background;
	char *pidfile;
	int usbbus;
	int usbdev;
} Options;

static IpcPtr killsocket;
static int running;

static void signal_handler(int sig);
static void dali_outband_handler(UsbDaliError err, DaliFramePtr frame, unsigned int status, void *arg);
static void dali_inband_handler(UsbDaliError err, DaliFramePtr frame, unsigned int response, unsigned int status, void *arg);
static void net_frame_handler(void *arg, const char *buffer, size_t bufsize, ConnectionPtr conn);
static void net_dequeue_connection(void *arg, ConnectionPtr conn);
static Options *parse_opt(int argc, char *const argv[]);
static void free_opt(Options *opts);
static int split_usbdev(const char *arg, int *usbbus, int *usbdev);
static void show_help();
static void show_banner();

int main(int argc, char *const argv[]) {
	int error = 0;

	log_debug("Parsing options");
	Options *opts = parse_opt(argc, argv);
	if (!opts) {
		show_banner();
		show_help();
		return -1;
	}
	log_set_level(opts->loglevel);
	if (opts->logfile) {
		log_set_logfile(opts->logfile);
		log_set_logfile_level(LOG_LEVEL_MAX);
	}
#ifdef HAVE_VSYSLOG
	if (opts->syslog) {
		log_set_syslog("daliserver");
	}
#endif
	if (opts->background) {
		daemonize(opts->pidfile);
	} else {
		show_banner();
	}

	log_info("Starting daliserver");

	log_debug("Initializing dispatch queue");
	DispatchPtr dispatch = dispatch_new();
	if (!dispatch) {
		error = -1;
	} else {
		//dispatch_set_timeout(dispatch, 100);

		UsbDaliPtr usb = NULL;
		if (!opts->dryrun) {
			log_debug("Initializing USB connection");
			usb = usbdali_open(NULL, dispatch, opts->usbbus, opts->usbdev);
			if (!usb) {
				error = -1;
			}
		}

		if (opts->dryrun || usb) {
			log_debug("Initializing server");
			ServerPtr server = server_open(dispatch, opts->address, opts->port, DEFAULT_NET_FRAMESIZE, net_frame_handler, usb);

			if (!server) {
				error = -1;
			} else {
				server_set_connection_destroy_callback(server, net_dequeue_connection, usb);

				if (usb) {
					usbdali_set_outband_callback(usb, dali_outband_handler, server);
					usbdali_set_inband_callback(usb, dali_inband_handler);
				}

				log_debug("Creating shutdown notifier");
				killsocket = ipc_new();

				if (!killsocket) {
					error = -1;
				} else {
					ipc_register(killsocket, dispatch);

					log_info("Server ready, waiting for events");
					running = 1;
					signal(SIGTERM, signal_handler);
					signal(SIGINT, signal_handler);
					while (running && dispatch_run(dispatch, usbdali_get_timeout(usb)));

					log_info("Shutting daliserver down");
					ipc_free(killsocket);
				}

				server_close(server);
			}

			if (usb) {
				usbdali_close(usb);
			}
		}

		dispatch_free(dispatch);
	}

	free_opt(opts);

	log_info("Exiting");
	return error;
}

static void signal_handler(int sig) {
	if (running) {
		log_info("Signal received, shutting down");
		running = 0;
		ipc_notify(killsocket);
	} else {
		log_fatal("Another signal received, killing process");
		kill(getpid(), SIGKILL);
		ipc_notify(killsocket);
	}
}

static void dali_outband_handler(UsbDaliError err, DaliFramePtr frame, unsigned int status, void *arg) {
	log_debug("Outband message received");
	if (err == USBDALI_SUCCESS) {
		log_info("Broadcast (0x%02x 0x%02x) [0x%04x]", frame->address, frame->command, status);
		ServerPtr server = (ServerPtr) arg;
		if (server) {
			char rbuffer[DEFAULT_NET_FRAMESIZE];
			rbuffer[0] = DEFAULT_NET_PROTOCOL;
			rbuffer[1] = NET_STATUS_BROADCAST;
			rbuffer[2] = frame->address;
			rbuffer[3] = frame->command;
			server_broadcast(server, rbuffer, sizeof(rbuffer));
		}
	}
}

static void dali_inband_handler(UsbDaliError err, DaliFramePtr frame, unsigned int response, unsigned int status, void *arg) {
	log_debug("Inband message received");
	if (err == USBDALI_SUCCESS || err == USBDALI_RESPONSE) {
		log_info("Response to (0x%02x 0x%02x): 0x%02x [0x%04x]", frame->address, frame->command, response, status);
		ConnectionPtr conn = (ConnectionPtr) arg;
		if (conn) {
			char rbuffer[DEFAULT_NET_FRAMESIZE];
			rbuffer[0] = DEFAULT_NET_PROTOCOL;
			if (err == USBDALI_RESPONSE) {
				rbuffer[1] = NET_STATUS_RESPONSE;
				rbuffer[2] = (uint8_t) response;
			} else {
				rbuffer[1] = NET_STATUS_SUCCESS;
				rbuffer[2] = 0;
			}
			rbuffer[3] = 0;
			connection_reply(conn, rbuffer, sizeof(rbuffer));
		}
	} else {
		log_error("Error sending DALI message: %s", usbdali_error_string(err));
		ConnectionPtr conn = (ConnectionPtr) arg;
		if (conn) {
			char rbuffer[DEFAULT_NET_FRAMESIZE];
			rbuffer[0] = DEFAULT_NET_PROTOCOL;
			rbuffer[1] = NET_STATUS_ERROR;
			rbuffer[2] = 0;
			rbuffer[3] = 0;
			connection_reply(conn, rbuffer, sizeof(rbuffer));
		}
	}
}

static void net_frame_handler(void *arg, const char *buffer, size_t bufsize, ConnectionPtr conn) {
	if (buffer && bufsize >= DEFAULT_NET_FRAMESIZE) {
		log_info("Got frame: 0x%02x 0x%02x 0x%02x 0x%02x", (uint8_t) buffer[0], (uint8_t) buffer[1], (uint8_t) buffer[2], (uint8_t) buffer[3]);
		if ((uint8_t) buffer[0] == DEFAULT_NET_PROTOCOL) {
			if ((uint8_t) buffer[1] == NET_TYPE_SEND) {
				UsbDaliPtr dali = (UsbDaliPtr) arg;
				if (dali) {
					DaliFramePtr frame = daliframe_new((uint8_t) buffer[2], (uint8_t) buffer[3]);
					usbdali_queue(dali, frame, conn);
				} else {
					uint8_t response = 0;
					log_info("Faking response: 0x%02x", response);
					char rbuffer[DEFAULT_NET_FRAMESIZE];
					rbuffer[0] = DEFAULT_NET_PROTOCOL;
					rbuffer[1] = NET_STATUS_RESPONSE;
					rbuffer[2] = (uint8_t) response;
					rbuffer[3] = 0;
					connection_reply(conn, rbuffer, sizeof(rbuffer));
				}
			} else {
				log_warn("Frame with unsupported command received: %u", (uint8_t) buffer[1]);
			}
		} else {
			log_warn("Frame with invalid protocol version received: %u", (uint8_t) buffer[0]);
		}
	}
}

void net_dequeue_connection(void *arg, ConnectionPtr conn) {
	if (arg && conn) {
		log_debug("Dequeueing connection %p", conn);
		UsbDaliPtr usb = (UsbDaliPtr) arg;
		usbdali_cancel(usb, conn);
	}
}

static Options *parse_opt(int argc, char *const argv[]) {
	Options *opts = malloc(sizeof(Options));
	opts->address = strdup(DEFAULT_NET_ADDRESS);
	opts->port = DEFAULT_NET_PORT;
	opts->dryrun = 0;
	opts->loglevel = DEFAULT_LOG_LEVEL;
	opts->syslog = 0;
	opts->logfile = NULL;
	opts->background = 0;
	opts->pidfile = NULL;
	opts->usbbus = -1;
	opts->usbdev = -1;

	int opt;
	opterr = 0;
	while ((opt = getopt(argc, argv, "d:l:p:nsf:br:u:")) != -1) {
		switch (opt) {
		case 'd':
			if (strcmp(optarg, "fatal") == 0) {
				opts->loglevel = LOG_LEVEL_FATAL;
			} else if (strcmp(optarg, "error") == 0) {
				opts->loglevel = LOG_LEVEL_ERROR;
			} else if (strcmp(optarg, "warn") == 0) {
				opts->loglevel = LOG_LEVEL_WARN;
			} else if (strcmp(optarg, "info") == 0) {
				opts->loglevel = LOG_LEVEL_INFO;
			} else if (strcmp(optarg, "debug") == 0) {
				opts->loglevel = LOG_LEVEL_DEBUG;
			} else {
				free_opt(opts);
				return NULL;
			}
			break;
		case 'l':
			free(opts->address);
			opts->address = strdup(optarg);
			break;
		case 'p':
			opts->port = (unsigned short) (strtol(optarg, NULL, 0) & 0xffff);
			break;
		case 'n':
			opts->dryrun = 1;
			break;
#ifdef HAVE_VSYSLOG
		case 's':
			opts->syslog = 1;
			break;
#endif
		case 'f':
			opts->logfile = strdup(optarg);
			break;
		case 'b':
			opts->background = 1;
			if (!opts->pidfile) {
				opts->pidfile = strdup(DEFAULT_PID_FILE);
			}
			break;
		case 'r':
			free(opts->pidfile);
			opts->pidfile = strdup(optarg);
			break;
		case 'u':
			if (!split_usbdev(optarg, &opts->usbbus, &opts->usbdev)) {
				free_opt(opts);
				return NULL;
			}
			break;
		default:
			free_opt(opts);
			return NULL;
		}
	}

	return opts;
}

static void free_opt(Options *opts) {
	if (opts) {
		free(opts->address);
		free(opts->logfile);
		free(opts->pidfile);
		free(opts);
	}
}

static int split_usbdev(const char *arg, int *usbbus, int *usbdev) {
	if (arg && usbbus && usbdev) {
		char *colon = strchr(arg, ':');
		if (colon) {
			long bus = strtol(arg, NULL, 0);
			long dev = strtol(colon + 1, NULL, 0);
			if (bus >= 0 && bus <= INT_MAX && dev >= 0 && dev <= INT_MAX) {
				*usbbus = (int) bus;
				*usbdev = (int) dev;
				return 1;
			}
		}
	}
	return 0;
}

static void show_help() {
	fprintf(stderr, "Usage: daliserver [-d <loglevel>] [-l <address>] [-p <port>] [-n]\n");
	fprintf(stderr, "\n");
	if (log_debug_enabled()) {
		fprintf(stderr, "-d <loglevel> Set the logging level (fatal, error, warn, info, debug, default=info)\n");
	} else {
		fprintf(stderr, "-d <loglevel> Set the logging level (fatal, error, warn, info, default=info)\n");
	}
	fprintf(stderr, "-l <address>  Set the IP address to listen on (default=127.0.0.1)\n");
	fprintf(stderr, "-p <port>     Set the port to listen on (default=55825)\n");
	fprintf(stderr, "-n            Enable dry-run mode for debugging (USB port won't be opened)\n");
#ifdef HAVE_VSYSLOG
	fprintf(stderr, "-s            Enable syslog (errors only)\n");
#endif
	if (log_debug_enabled()) {
		fprintf(stderr, "-f <logfile>  Write debug messages to logfile\n");
	} else {
		fprintf(stderr, "-f <logfile>  Write info messages to logfile\n");
	}
	fprintf(stderr, "-b            Fork into background (implies -r)\n");
	fprintf(stderr, "-r <file>     Save PID to file (default=/var/run/daliserver.pid)\n");
	fprintf(stderr, "-u <bus:dev>  Only drive the USB device at bus:dev\n");
	fprintf(stderr, "\n");
}

static void show_banner() {
	fprintf(stderr, "DALI USB multiplexer (daliserver)\n");
	fprintf(stderr, "Copyright (c) 2011 onitake All rights reserved.\n");
	fprintf(stderr, "\n");
}


text:
import fs from 'fs';
import path from 'path';
import _ from 'lodash';
import express from 'express';
import socketIo from 'socket.io';
import bodyParser from 'body-parser';
import resolve from 'resolve';
import slugify from 'slugify';
import winston from 'winston';
import Dashboard from './dashboard';
import Plugin from './plugin';
import Widget from './widget';

/*
 * Inits / loads plugins
 */
function loadPlugins(directory) {
  var deps = path.join(directory, 'package.json');

  if (!fs.existsSync(deps)) {
    return;
  }

  this.logger.info('Autoloading plugins from %s', deps);

  deps = require(deps).dependencies;

  if (!deps) {
    return;
  }

  for (const key in deps) {
    if (!key.startsWith('leitstand-')) {
      continue;
    }
    var plugin = require(resolve.sync(key, {basedir: directory}));
    if (plugin instanceof Function) {
      plugin = plugin(this);
    }
    this.plugin(key.substr('leitstand-'.length), plugin);
  }
}

/*
 * Inits app
 */
function initApp() {
  this.app.use(bodyParser.urlencoded({
    extended: true
  }));
  this.app.use(bodyParser.json());

  this.app.set('views', this.options.views.directory);
  this.app.set('view engine', this.options.views.engine);

  this.app.get(this.options.routes.dashboards, dashboards.bind(this));
  this.app.get(this.options.routes.widgets, widgets.bind(this));
  this.app.put(this.options.routes.widgets, widgets.bind(this));
}

/*
 * Inits io
 */
function initIO() {
  /*
  this.nsp.on('connection', function (socket) {

  }.bind(this));
  */

  this.nsp.use(function (socket, next) {
    const id = socket.handshake.query.dashboard;

    if (this.dashboards[id]) {
      socket.join(id);
      return next();
    }
    // call next() with an Error if you need to reject the connection.
    next(new Error('Dashboard not found: ' + id));
  }.bind(this));
}

/*
 * Handle dashboards route
 */
function dashboards(req, res) {
  const dashboard = this.dashboards[req.params.id];

  if (!dashboard) {
    res.status(404);

    res.render('404', {url: req.url});
    return;
  }

  res.render(dashboard.view, {namespace: this.options.sockets.namespace, dashboard: dashboard});
}

/*
 * Handle widgets route
 */
function widgets(req, res) {
  const widget = this.widgets[req.params.id];

  if (!widget) {
    res.status(404);

    res.json({success: false, error: 'Not found'});
    return;
  }

  if (req.method === 'PUT') {
    if (widget.put === true) {
      try {
        widget.set(req.body);
      } catch (error) {
        res.status(400);
        res.json({success: false, error: error});
        return;
      }
    } else {
      res.status(405);
      res.json({success: false, error: 'Method not allowed'});
      return;
    }
  }

  res.json(widget);
}

/*
 * Generate default Leitstand options
 * @return {Object}
 */
function defaults(options, directory) {
  return Object.assign({}, {
    plugins: {
      load: true
    },
    views: {
      engine: 'pug',
      directory: path.join(directory, 'views')
    },
    routes: {
      dashboards: '/dashboards/:id',
      widgets: '/widgets/:id'
    },
    sockets: {
      namespace: '/leitstand'
    },
    schedule: {
      default: '*/1 * * * *',
      auto: true
    }
  }, options);
}

function resource(Type, collection, returnInstance) {
  return (id, second, third) => {
    id = slugify(String(id));
    var current = this[collection][id];

    if (typeof second !== 'object') {
      third = second;
      second = {};
    }

    if (second && (typeof second === 'object' || second instanceof Type)) {
      this.logger.info('%s %s "%s"', current ? 'Upgrading' : 'Creating', Type.name.toLowerCase(), id);
      current = this[collection][id] = Object.assign(current || new Type(id, this), second);
    }

    if (third && typeof third === 'function') {
      third.call(current);
    }
    return returnInstance ? current : this;
  };
}

function onSet(widget) {
  Object.keys(this.dashboards).forEach(id => {
    const widgets = this.dashboards[id].widgets;
    if (widgets[widget.id]) {
      this.logger.debug('Emitting "widget:set" for widget "%s" to dashboard "%s"', widget.id, id);
      this.nsp.to(id).emit('widget:set', widget);
    }
  }, this);
}

export default class Leitstand {
  /**
   * Create a Leitstand instance.
   * @param {Object} options - configuration settings
   * @param {express|express.Router} app - express app
   * @param {Server} io - socket.io
   * @param {winston.Logger} logger
   */
  constructor(options = {}, app = express(), io = socketIo(), logger = null) {
    const directory = options.directory || process.cwd();
    this.options = defaults(options, directory);
    this.app = app;
    this.io = io;
    this.nsp = this.io.of(this.options.sockets.namespace);
    this.logger = logger;

    if (!this.logger) {
      this.logger = new (winston.Logger)({
        transports: [
          new (winston.transports.Console)({
            level: 'info',
            prettyPrint: true,
            depth: 1
          })
        ]
      });
    }

    this.plugins = {};
    this.dashboards = {};
    this.widgets = {};

    this.widget = resource.call(this, Widget, 'widgets').bind(this);
    this.plugin = resource.call(this, Plugin, 'plugins').bind(this);
    this.dashboard = resource.call(this, Dashboard, 'dashboards').bind(this);

    if (this.options.plugins.load) {
      loadPlugins.call(this, directory);
    }

    this.promises = [];
  }

  init(callback) {
    Promise.all(this.promises)
      .then(() => {
        Object.keys(this.widgets).forEach(id => {
          const widget = this.widgets[id];

          if (widget.work instanceof Function) {
            widget.work();
          }

          if (widget.listen instanceof Function) {
            widget.listen();
          }

          widget.removeListener('set', onSet);
          widget.on('set', onSet.bind(this));
        });

        initApp.call(this);
        initIO.call(this);
        callback(null);
      })
      .catch(reason => {
        callback(reason);
      });
  }
}

redpajama_set_name: RedPajamaGithub


text:
from flask import Blueprint

bp = Blueprint('ngstrap', __name__, static_folder='static', template_folder='templates')


text:
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { MILLISECONDS_PER_DAY } from './constants';

// Return the sum of the given key across the given records.
export const getTotal = (records, key) => records.reduce((sum, record) => sum + record[key], 0);

/**
 * Adds a batch to its parent, checking first if there is an existing item to add
 * it to, and otherwise calling the creator passed in. Works for anything with a
 * parent -> item -> batch hierarchy, e.g. transactions and stocktakes.
 *
 * @param {object}    batch       The batch to add.
 * @param {object}    parent      The parent to add the batch to.
 * @param {function}  createItem  A function to create new items to add to the hierarchy.
 */
export const addBatchToParent = (batch, parent, createItem) => {
  let item = parent.items.find(aggItem => aggItem.itemId === batch.itemId);

  // This parent doesn't have a matching item yet, make one.
  // Should also take care of attaching item to its parent.
  if (!item) {
    item = createItem();
  }

  // If the batch is already in the item, we don't want to add it again.
  if (item.batches && item.batches.find(currentBatch => currentBatch.id === batch.id)) return;

  item.addBatch(batch);
};

// Round up to the nearest day.
export const millisecondsToDays = milliseconds => Math.ceil(milliseconds / MILLISECONDS_PER_DAY);


text:
(function (GGRC, _) {
  'use strict';
  /**
   * Tree View Widgets Configuration module
   */
  var allTypes = [
    'AccessGroup', 'Audit', 'Clause', 'Contract', 'Control', 'Assessment',
    'DataAsset', 'Facility', 'Issue', 'Market', 'Objective', 'OrgGroup',
    'Person', 'Policy', 'Process', 'Product', 'Program', 'Project',
    'Regulation', 'Section', 'Standard', 'System', 'Vendor'
  ];
  // Items allowed for mapping via snapshot.
  var snapshotWidgetsConfig = GGRC.config.snapshotable_objects || [];
  // Items allowed for relationship mapping
  var excludeMappingConfig = [
    'Assessment',
    'AssessmentTemplate',
    'Issue'
  ];
  // Extra Tree View Widgets require to be rendered on Audit View
  var auditInclusion = [
    'Person',
    'Program'
  ];
  var baseWidgetsByType;

  var filteredTypes = _.difference(allTypes, excludeMappingConfig);
  // Audit is excluded and created a separate logic for it
  baseWidgetsByType = {
    AccessGroup: _.difference(filteredTypes, ['AccessGroup']),
    Audit: [].concat(snapshotWidgetsConfig, excludeMappingConfig,
      auditInclusion).sort(),
    Clause: _.difference(filteredTypes, ['Clause']),
    Contract: _.difference(filteredTypes,
      ['Contract', 'Policy', 'Regulation', 'Standard']),
    Control: filteredTypes,
    Assessment: _.difference(filteredTypes, ['Assessment']),
    DataAsset: filteredTypes,
    Facility: filteredTypes,
    Issue: filteredTypes,
    Market: filteredTypes,
    Objective: filteredTypes,
    OrgGroup: filteredTypes,
    Person: _.difference(filteredTypes, ['Person']),
    Policy: _.difference(filteredTypes,
      ['Contract', 'Policy', 'Regulation', 'Standard']),
    Process: filteredTypes,
    Product: filteredTypes,
    Program: _.difference(filteredTypes, ['Program']),
    Project: filteredTypes,
    Regulation: _.difference(filteredTypes,
      ['Contract', 'Policy', 'Regulation', 'Standard']),
    Section: filteredTypes,
    Standard: _.difference(filteredTypes,
      ['Contract', 'Policy', 'Regulation', 'Standard']),
    System: filteredTypes,
    Vendor: filteredTypes
  };

  GGRC.tree_view = GGRC.tree_view || new can.Map();
  GGRC.tree_view.attr('base_widgets_by_type', baseWidgetsByType);
})(this.GGRC, this._);


text:
import asyncio
import json
import sys
import time
import traceback
from concurrent.futures import ThreadPoolExecutor

import aiohttp
import discord
from cleverwrap.cleverwrap import CleverWrap
from discord.ext import commands

from utils import str_split, tcp_echo_client, CheckError, p_check

startup_extensions = ['cogs.music.music', 'cogs.private.repl', 'cogs.private.subproc',
                      'cogs.private.smod_cmds', 'cogs.private.other', 'cogs.public.mod_cmds',
                      'cogs.public.info', 'cogs.public.fun', 'cogs.public.logging']

if len(sys.argv) > 1:
    shard_id, shard_count = int(sys.argv[1]), int(sys.argv[2])
else:
    shard_id, shard_count = 0, 1

async def update(bot, token):
    payload = json.dumps({
        'shard_id': bot.shard_id,
        'shard_count': bot.shard_count,
        'server_count': len(bot.servers)
    })
    payload2 = {
        'token': 'iAJ9cq7Lv4',
        'servers': len(bot.servers)
    }
    headers = {
        'Authorization': token,
        'content-type': 'application/json'
    }
    async with aiohttp.ClientSession() as session:
        async with session.post('https://bots.discord.pw/api/bots/{0}/stats'.format(
                                bot.user.id), data=payload, headers=headers) as resp:
            print(await resp.text())

        async with session.post('https://bots.discordlist.net/api.php', data=payload2) as resp:
            print(await resp.text())
        session.close()

class Bot(commands.Bot):
    def __init__(self, shard_id, shard_count):
        commands.Bot.__init__(self, shard_id=shard_id, shard_count=shard_count, command_prefix=self.get_prefix)
        self.thread_pool = ThreadPoolExecutor(max_workers=4)
        self.uptime = time.time()
        self.config = None
        self.clever_instances = {}
        self.tokens = self.get_json("bot_config")

    def get_json(self, name):
        with open('configs/%s.json' % name) as log:
            output = json.load(log)
            log.close()
            return output

    def write_json(self, name, conf):
        with open('configs/%s.json' % name, 'w') as log:
            json.dump(conf, log, indent=4)
            log.close()

    async def get_cfg(self):
        message = {
            "shard": self.shard_id,
            "servers": len(self.servers),
            "channels": len([i for i in self.get_all_channels()]),
            "members": len([i for i in self.get_all_members()]),
            "playing_on": len([i for i in self.cogs['Music'].voice_states.values() if i.is_playing()])
        }
        received = await tcp_echo_client(json.dumps(message), self.loop)
        return received

    def get_prefix(self, bot, message):
        default = [',', 'hime ', 'Hime ', 'himebot ', 'Himebot ', commands.when_mentioned(bot, message)]
        if message.channel.is_private:
            return default
        if message.server.id in self.get_json('prefix'):
            return [self.get_json('prefix')[message.server.id]] + default[1:]
        return default

    async def on_ready(self):
        self.remove_command('help')
        await self.change_presence(game=discord.Game(name='https://himebot.xyz | .help | invite'))
        print('Logged in as {}, shard {}'.format(self.user.name, self.shard_id))
        print([i.name for i in self.servers])
        for extension in startup_extensions:
            try:
                self.load_extension(extension)
            except ImportError as e:
                traceback.print_stack()
                print('Failed to load extension {}: {}: {}'.format(
                    extension, e.__class__.__name__, e))
        await update(self, self.tokens['discord_bots_token'])
        while True:
            try:
                config = await self.get_cfg()
                self.config = json.loads(config.decode())
                await asyncio.sleep(100)
            except ConnectionRefusedError:
                pass

    async def on_message(self, message):
        content = message.clean_content.lower()
        if message.author.bot:
            return
        if 'hime' in content or self.user in message.mentions:
            if message.author.id not in self.clever_instances:
                self.clever_instances[message.author.id] = await \
                    self.loop.run_in_executor(self.thread_pool, CleverWrap, self.tokens['cleverbot_token'])

            response = await self.loop.run_in_executor(self.thread_pool,
                                                      self.clever_instances[message.author.id].say, content)
            await self.send_message(message.channel, response)

        if content.startswith('wew') and len(content.split()) == 1:
            await self.send_message(message.channel, 'lad')
        if content.startswith('ayy') and len(content.split()) == 1:
            await self.send_message(message.channel, 'lmao')

        if content.startswith('.s') and content.split()[0][1:] in ["sban", "skick", "spurge", "sclear"]:
            await self.delete_message(message)

        await self.process_commands(message)

    async def on_command_error(self, error, ctx):
        channel = ctx.message.channel
        if isinstance(error, commands.MissingRequiredArgument):
            msg = await self.send_message(channel, 'Missing command args dumbass')
            await asyncio.sleep(3)
            await self.delete_message(msg)
        elif isinstance(error, commands.CheckFailure):
            msg = await self.send_message(channel, 'You got no perms fgt')
            await asyncio.sleep(3)
            await self.delete_message(msg)
        elif isinstance(error, commands.BadArgument):
            msg = await self.send_message(channel, 'Bad arguments passed, re-read .help dumbfuck')
            await asyncio.sleep(3)
            await self.delete_message(msg)
        elif isinstance(error, commands.NoPrivateMessage):
            msg = await self.send_message(channel, 'That command is not '
                                                   'available in DMs.')
            await asyncio.sleep(3)
            await self.delete_message(msg)
        elif isinstance(error, commands.CommandOnCooldown):
            msg = await self.send_message(channel, 'You cannot use that command right now')
            await asyncio.sleep(3)
            await self.delete_message(msg)
        elif isinstance(error, CheckError):
            if error.id == 'himebot_music':
                msg = await self.send_message(channel,
                                              'You must have a role named himebot_music in order to use that command')
                await asyncio.sleep(5)
                await self.delete_message(msg)
            elif error.id == 'nsfw':
                msg = await self.send_message(channel, 'You can only use this command in the nsfw channel')
                await asyncio.sleep(5)
                await self.delete_message(msg)
            elif error.id == 'patron':
                msg = await self.send_message(channel, 'You must be a patron to use this feature')
                await asyncio.sleep(5)
                await self.delete_message(msg)

        if not isinstance(error, commands.errors.CommandNotFound):
            channel = discord.utils.get(self.get_all_channels(), id='232190536231026688')
            traceback_msg = "".join(
                traceback.format_exception(error.__class__.__name__, error, error.__traceback__))
            output = str_split(traceback_msg)
            for out in output:
                await self.send_message(channel, out)
            await self.send_message(channel, 'Origin: {},\nCaused by: ``{}``'.format(ctx.message.server,
                                                                                ctx.message.content))

    def start_bot(self):
        token = self.tokens['bot_token']
        self.run(token)

bot = Bot(shard_id, shard_count)
bot.start_bot()


text:
<app-page-template [title]="title" [excerpt]="excerpt" [icon]="icon">
    <app-services-grid></app-services-grid>
</app-page-template>


text:
package net.iaeste.iws.ejb.emails;

import net.iaeste.iws.api.constants.IWSConstants;

import java.io.Serializable;

/**
 * These classes are temporarily placed here. We need the functionality, but it
 * should rightly be placed in the EJB module. Until the EJB module is ready,
 * and we have a GlassFish instance to deploy to, we will keep it here.
 *
 * Move together with NotificationEmail(Delayed)Sender to the EJB module.
 *
 * @author  Pavel Fiala / last $Author:$
 * @version $Revision:$ / $Date:$
 * @since   IWS 1.0
 */
public final class EmailMessage implements Serializable {

    /** {@link IWSConstants#SERIAL_VERSION_UID}. */
    private static final long serialVersionUID = IWSConstants.SERIAL_VERSION_UID;

    private String to = null;
    private String subject = null;
    private String message = null;

    public void setTo(final String to) {
        this.to = to;
    }

    public String getTo() {
        return to;
    }

    public void setSubject(final String subject) {
        this.subject = subject;
    }

    public String getSubject() {
        return subject;
    }

    public void setMessage(final String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}


text:
module.exports = function (app) {
  require('./reactiveFns')(app);
};


text:
import { render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { CommonTestWrapper } from 'src/TestWrapper';
import { Apis } from '../lib/Apis';
import { testBestPractices } from '../TestUtils';
import ArtifactPreview from './ArtifactPreview';

testBestPractices();
describe('ArtifactPreview', () => {
  it('handles undefined artifact', () => {
    render(
      <CommonTestWrapper>
        <ArtifactPreview value={undefined} />
      </CommonTestWrapper>,
    );
    screen.getByText('Can not retrieve storage path from artifact uri: undefined');
  });

  it('handles null artifact', () => {
    render(
      <CommonTestWrapper>
        <ArtifactPreview value={null as any} />
      </CommonTestWrapper>,
    );
    screen.getByText('Can not retrieve storage path from artifact uri: null');
  });

  it('handles empty artifact', () => {
    expect(() => {
      render(
        <CommonTestWrapper>
          <ArtifactPreview value={'i am random path'} />
        </CommonTestWrapper>,
      );
    }).toThrow(new Error('Unsupported storage path: i am random path'));
  });

  it('handles invalid artifact: no bucket', async () => {
    jest.spyOn(Apis, 'readFile').mockRejectedValue(new Error('server error: no bucket'));

    render(
      <CommonTestWrapper>
        <ArtifactPreview value={'minio://'} namespace={'kubeflow'} />
      </CommonTestWrapper>,
    );
    await waitFor(() => screen.getByText('Error in retrieving artifact preview.'));
  });

  it('handles gcs artifact', async () => {
    jest.spyOn(Apis, 'readFile').mockResolvedValue('gcs preview');
    render(
      <CommonTestWrapper>
        <ArtifactPreview value={'gs://bucket/key'} />
      </CommonTestWrapper>,
    );
    await waitFor(() => screen.getByText('gs://bucket/key'));
    await waitFor(() => screen.getByText('gcs preview'));
  });

  it('handles minio artifact with namespace', async () => {
    jest.spyOn(Apis, 'readFile').mockResolvedValueOnce('minio content');
    render(
      <CommonTestWrapper>
        <ArtifactPreview value={'minio://bucket/key'} namespace={'kubeflow'} />
      </CommonTestWrapper>,
    );
    await waitFor(() => screen.getByText('minio://bucket/key'));
    await waitFor(() =>
      expect(screen.getByText('View All').getAttribute('href')).toEqual(
        'artifacts/get?source=minio&namespace=kubeflow&bucket=bucket&key=key',
      ),
    );
  });

  it('handles artifact that previews with maxlines', async () => {
    const data = `012\n345\n678\n910`;
    jest.spyOn(Apis, 'readFile').mockResolvedValueOnce(data);
    render(
      <CommonTestWrapper>
        <ArtifactPreview
          value={'minio://bucket/key'}
          namespace={'kubeflow'}
          maxbytes={data.length}
          maxlines={2}
        />
      </CommonTestWrapper>,
    );
    await waitFor(() => screen.getByText('minio://bucket/key'));
    await waitFor(() => screen.getByText(`012 345 ...`));
  });

  it('handles artifact that previews with maxbytes', async () => {
    const data = `012\n345\n678\n910`;
    jest.spyOn(Apis, 'readFile').mockResolvedValueOnce(data);
    render(
      <CommonTestWrapper>
        <ArtifactPreview
          value={'minio://bucket/key'}
          namespace={'kubeflow'}
          maxbytes={data.length - 5}
        />
      </CommonTestWrapper>,
    );
    await waitFor(() => screen.getByText('minio://bucket/key'));
    await waitFor(() => screen.getByText(`012 345 67 ...`));
  });
});


text:
'use strict';

var validation = require('validator');

function getValidationResult() {
    var valid = arguments[0] === undefined ? false : arguments[0];
    var message = arguments[1] === undefined ? '' : arguments[1];

    if (valid) {
        return { error: false };
    }

    return { error: true, message: message };
}

function parseDate(date) {
    var type = arguments[1] === undefined ? 'date' : arguments[1];

    function addZero(num) {
        var num = parseInt(num);
        return num >= 0 && num < 10 ? '0' + num : num.toString();
    }

    var d = new Date(date);
    var fullDate = [d.getFullYear(), addZero(d.getMonth() + 1), addZero(d.getDate())].join('-');

    if (type === 'date-time') {
        var fullTime = [addZero(d.getHours()), addZero(d.getMinutes()), addZero(d.getSeconds())].join(':') + 'Z';

        return [fullDate, 'T', fullTime].join('');
    }

    return fullDate;
}

function updateValueFormat(value) {
    var type = arguments[1] === undefined ? 'string' : arguments[1];
    var format = arguments[2] === undefined ? '' : arguments[2];

    type = type.toLowerCase();
    format = format.toLowerCase();

    var dataType = {
        'number': function number(_x6, format) {
            var value = arguments[0] === undefined ? '' : arguments[0];

            // Format can be float or double
            return format === 'float' || format === 'double' ? parseFloat(value) : parseInt(value);
        },
        'integer': function integer(_x7, format) {
            var value = arguments[0] === undefined ? '' : arguments[0];

            // Format can be int32 or int64
            return parseInt(value);
        },
        'string': function string(value, format) {
            // Format can be string, bytes, date, date-time or password
            return format === 'date' && value ? parseDate(value) : format === 'date-time' && value ? parseDate(value, 'date-time') : value;
        },
        'boolean': function boolean(value, format) {
            return Boolean(value);
        }
    };

    var update = dataType[type];

    if (update) {
        return update(value, format);
    } else {
        console.warn('Warning: Unknown type ' + type + ' in updateValueFormat');
    }

    return value;
}

function getSchemaProperties(schema, definition) {
    if (!schema || !definition) {
        return null;
    }

    var definitions = schema.definitions;
    var properties = {};

    Object.keys(definitions).map(function (def) {
        if (def === definition.replace('#/definitions/', '')) {
            properties = definitions[def].properties;
        }
    });

    return properties;
}

function Validator() {
    this.errors = [];
}

Validator.validation = {
    validateRequired: function validateRequired() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(input, 'This field is required!');
    },
    validateMinimumLength: function validateMinimumLength() {
        var input = arguments[0] === undefined ? { length: 0 } : arguments[0];
        var length = arguments[1] === undefined ? 0 : arguments[1];

        return getValidationResult(input.length >= parseInt(length) || parseInt(length) === 0, ['Minimum of', length, 'characters'].join(' '));
    },
    validateMaximumLength: function validateMaximumLength() {
        var input = arguments[0] === undefined ? { length: 0 } : arguments[0];
        var length = arguments[1] === undefined ? 0 : arguments[1];

        return getValidationResult(input.length <= parseInt(length) || parseInt(length) === 0, ['Maximum of', length, 'characters'].join(' '));
    },
    validateMinimum: function validateMinimum() {
        var input = arguments[0] === undefined ? 0 : arguments[0];
        var length = arguments[1] === undefined ? 0 : arguments[1];

        return getValidationResult(input >= parseInt(length), ['Minimum of', length].join(' '));
    },
    validateMaximum: function validateMaximum() {
        var input = arguments[0] === undefined ? 0 : arguments[0];
        var length = arguments[1] === undefined ? 0 : arguments[1];

        return getValidationResult(input <= parseInt(length), ['Maximum of', length].join(' '));
    },
    validatePattern: function validatePattern() {
        var input = arguments[0] === undefined ? '' : arguments[0];
        var pattern = arguments[1] === undefined ? '' : arguments[1];

        return getValidationResult(new RegExp(pattern, 'g').test(input), 'Does not match ' + pattern);
    },
    validateEmail: function validateEmail() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(validation.isEmail(input), 'Email Error');
    },
    validateUrl: function validateUrl() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(validation.isURL(input), 'Url Error');
    },
    validateDate: function validateDate() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(validation.isDate(input), 'Date Error');
    },
    validateTelephone: function validateTelephone() {
        var input = arguments[0] === undefined ? '' : arguments[0];
        var pattern = arguments[1] === undefined ? '' : arguments[1];

        return getValidationResult(new RegExp(pattern, 'g').test(input), 'Invalid Telephone. Does not match ' + pattern);
    },
    validatePassword: function validatePassword() {
        var input = arguments[0] === undefined ? '' : arguments[0];
        var pattern = arguments[1] === undefined ? '' : arguments[1];

        return getValidationResult(new RegExp(pattern, 'g').test(input), 'Invalid Password. Does not match ' + pattern);
    },
    validateDateTime: function validateDateTime() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(validation.isDate(input), 'Date Time Error');
    },
    validateFloat: function validateFloat() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(validation.isFloat(input), 'Float Error');
    },
    validateInteger: function validateInteger() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(validation.isInt(input), 'Integer Error');
    },
    validateNumber: function validateNumber() {
        var input = arguments[0] === undefined ? '' : arguments[0];

        return getValidationResult(validation.isNumeric(input), 'Number Error');
    }
};

Validator.prototype.validate = function (_x30, _x31, customValidation) {
    var input = arguments[0] === undefined ? '' : arguments[0];
    var attributes = arguments[1] === undefined ? {} : arguments[1];
    var schemaInfo = arguments[3] === undefined ? {} : arguments[3];

    if (!attributes) {
        console.warn('Warning: One or more Validator.validate parameters missing or empty');
    }

    var result = [];

    // Eventually remove this and add data-attributes when generating the form
    if (schemaInfo && schemaInfo.schema && schemaInfo.definition) {
        if (schemaInfo.field) {
            var properties = getSchemaProperties(schemaInfo.schema, schemaInfo.definition);
            if (properties) {
                results = this.schemaInfoValidate(value, schemaInfo.field, schemaInfo.schema, properties, schemaInfo.definition);
            }
        } else {
            console.warn('Warning: The property `field` must be available for schema based validation. Check if `this.props.field` is defined in your component.');
        }
    } else {
        Object.keys(attributes).forEach((function (attr) {
            if (attr === 'validateRequired' || input) {
                //If there is an input, continue validation
                var validate = Validator.validation[attr];
                if (validate) {
                    result.push(validate(input, attributes[attr]));
                }
            }
        }).bind(this));
    }

    // Add custom validation
    if (customValidation && input) {
        // If there is an input, continue validation
        var customResult = customValidation(input);
        if (typeof customResult.result === undefined) {
            console.warn('Warning: custom validation does not have valid inputs. Object returned should have a result and message property. Ex: `{ result: true, message: "message" }`');
        }

        result.push(getValidationResult(customResult.isResultValid, customResult.message));
    }

    return result;
};

Validator.prototype.serverValidate = function (_x33, _x34, customFormValidation, overrideFormValidation) {
    var formData = arguments[0] === undefined ? {} : arguments[0];
    var reactComponents = arguments[1] === undefined ? [] : arguments[1];

    var _this = this;

    var errors = [];

    if (overrideFormValidation) {
        var customErrors = overrideFormValidation(formData, reactComponents) || [];
        if (customErrors.length) {
            customErrors.forEach(function (custom) {
                var errorObj = {
                    custom: true,
                    name: custom.name,
                    id: custom.id,
                    value: custom.value,
                    dataset: custom.dataset,
                    component: custom.component,
                    errors: []
                };

                custom.errors.forEach(function (error) {
                    errorObj.errors.push(getValidationResult(error.isResultValid, error.message));
                });

                if (errorObj.errors.length) {
                    errors.push(errorObj);
                }
            });
        }
    } else {
        reactComponents.forEach(function (item) {
            var props = item.props;
            if (props.name && props.validationEvent !== 'none') {
                // No need to continue if there is no name
                var schemaInfo = props.schemaInfo || {};
                var _value = formData[props.name].value;
                var dataset = formData[props.name].dataset;
                var _results = _this.validate(_value, dataset, props.customValidation, {
                    value: _value,
                    field: props.field,
                    schema: schemaInfo.schema,
                    definition: schemaInfo.definition
                });

                if (_results.length) {
                    (function () {
                        var errorObj = {
                            custom: false,
                            name: props.name,
                            id: props.id,
                            value: _value,
                            dataset: dataset,
                            component: item,
                            errors: []
                        };

                        _results.forEach(function (result) {
                            if (result.error) {
                                errorObj.errors.push(result);
                            }
                        });

                        if (errorObj.errors.length) {
                            errors.push(errorObj);
                        }
                    })();
                }
            }
        });
    }

    if (customFormValidation) {
        var customErrors = customFormValidation(formData, reactComponents) || [];
        if (customErrors.length) {
            customErrors.forEach(function (custom) {
                var errorObj = {
                    override: false,
                    custom: true,
                    name: custom.name,
                    id: custom.id,
                    value: custom.value,
                    dataset: custom.dataset,
                    component: custom.component,
                    errors: []
                };

                custom.errors.forEach(function (error) {
                    errorObj.errors.push(formValidation.getValidationResult(error.isResultValid, error.message));
                });

                if (errorObj.errors.length) {
                    errors.push(errorObj);
                }
            });
        }
    }

    return errors;
};

Validator.prototype.findValidatedComponent = function () {
    var formValidationResults = arguments[0] === undefined ? [] : arguments[0];
    var props = arguments[1] === undefined ? {} : arguments[1];

    for (var i = 0, l = formValidationResults.length; i < l; i++) {
        if (formValidationResults[i].id === props.id) {
            return formValidationResults[i];
        }
    }

    return null;
};

Validator.prototype.getApiValidationResults = function () {
    var json = arguments[0] === undefined ? {} : arguments[0];
    var formData = arguments[1] === undefined ? {} : arguments[1];
    var reactComponents = arguments[2] === undefined ? [] : arguments[2];

    var apiValidationResults = [];

    reactComponents.forEach(function (item) {
        var props = item.props;
        var apiResults = json[props.name];

        if (props.name && apiResults) {
            (function () {
                // No need to continue if there is no name
                var data = formData[props.name];

                var value = data ? data.value : '';
                var dataset = data ? data.dataset : '';

                var errorObj = {
                    custom: false,
                    name: props.name,
                    id: props.id,
                    value: value,
                    dataset: dataset,
                    component: item,
                    errors: []
                };

                if (Array.isArray(apiResults)) {
                    apiResults.forEach(function (res) {
                        errorObj.errors.push({
                            error: true,
                            message: res
                        });
                    });
                } else {
                    errorObj.errors.push({
                        error: true,
                        message: apiResults
                    });
                }

                if (errorObj.errors.length) {
                    apiValidationResults.push(errorObj);
                }
            })();
        }
    });

    return apiValidationResults;
};

Validator.prototype.schemaInfoValidate = function () {
    var fieldValue = arguments[0] === undefined ? '' : arguments[0];
    var field = arguments[1] === undefined ? '' : arguments[1];
    var schema = arguments[2] === undefined ? '' : arguments[2];
    var propertyObj = arguments[3] === undefined ? {} : arguments[3];
    var definition = arguments[4] === undefined ? '' : arguments[4];

    var errors = [];

    // require( 'swagger-tools' ) causes issues so I'm commenting this section out
    /*if( schema && definition && Object.getOwnPropertyNames( propertyObj ).length > 0 && field ){
        let swaggerTools = require( 'swagger-tools' );
        let spec = swaggerTools.specs.v2;
        let properties = {};
         Object.keys(propertyObj).forEach( ( item ) => {
            properties[item] = "";
        });
         properties[field] = updateValueFormat( fieldValue, propertyObj[field].type, propertyObj[field].format);
         // Required doesn't seem to validate correctly yet.
        // A required field of type string will not error out if empty ??
        // A required field of type number will error out as invalid type
        // Still investigating but perhaps a bug in the swagger-tools module
         spec.validateModel( schema, definition, properties, ( err, result ) => {
            if ( result && result.errors ) {
                result.errors.forEach(  ( error ) => {
                    if ( error.path[0] === field ) {
                        errors.push( getValidationResult( false , error.message ) );
                    }
                });
            }
        })
    }else{
        console.warn( 'Warning: One or more Validator.swaggerValidate parameters missing or empty' );
    }*/

    return errors;
};

module.exports = Validator;


text:
#ifndef LLVM_NODE_H_
#define LLVM_NODE_H_

#include <map>
#include <set>
#include <utility>

#include <llvm/IR/Type.h>
#include <llvm/IR/Value.h>

#include "dg/Node.h"

namespace dg {

class LLVMDependenceGraph;
class LLVMNode;

using LLVMBBlock = dg::BBlock<LLVMNode>;
using LLVMDGParameter = dg::DGParameterPair<LLVMNode>;
using LLVMDGParameters = dg::DGParameters<LLVMNode>;

/// ------------------------------------------------------------------
//  -- LLVMNode
/// ------------------------------------------------------------------
class LLVMNode : public Node<LLVMDependenceGraph, llvm::Value *, LLVMNode> {
#if LLVM_VERSION_MAJOR >= 5
    struct LLVMValueDeleter {
        void operator()(llvm::Value *val) const { val->deleteValue(); }
    };
#endif

  public:
    LLVMNode(llvm::Value *val, bool owns_value = false)
            : dg::Node<LLVMDependenceGraph, llvm::Value *, LLVMNode>(val) {
        if (owns_value)
#if LLVM_VERSION_MAJOR >= 5
            owned_key = std::unique_ptr<llvm::Value, LLVMValueDeleter>(val);
#else
            owned_key = std::unique_ptr<llvm::Value>(val);
#endif
    }

    LLVMNode(llvm::Value *val, LLVMDependenceGraph *dg) : LLVMNode(val) {
        setDG(dg);
    }

    LLVMDGParameters *getOrCreateParameters() {
        auto *params = getParameters();
        if (!params) {
            params = new LLVMDGParameters(this);
            setParameters(params);
        }
        return params;
    }

    llvm::Value *getValue() const { return getKey(); }

    // create new subgraph with actual parameters that are given
    // by call-site and add parameter edges between actual and
    // formal parameters. The argument is the graph of called function.
    // Must be called only when node is call-site.
    void addActualParameters(LLVMDependenceGraph * /*funcGraph*/);
    void addActualParameters(LLVMDependenceGraph * /*funcGraph*/,
                             llvm::Function * /*func*/, bool fork = false);

    bool isVoidTy() const { return getKey()->getType()->isVoidTy(); }

  private:
    // the owned key will be deleted with this node
#if LLVM_VERSION_MAJOR >= 5
    std::unique_ptr<llvm::Value, LLVMValueDeleter> owned_key;
#else
    std::unique_ptr<llvm::Value> owned_key;
#endif
};

} // namespace dg

#endif // LLVM_NODE_H_


text:
# Micro Whalla
[![npm version](https://badge.fury.io/js/micro-whalla.svg)](https://badge.fury.io/js/micro-whalla)
[![Build Status](https://travis-ci.org/czerwonkabartosz/Micro-Whalla.svg?branch=master)](https://travis-ci.org/czerwonkabartosz/Micro-Whalla)
[![Coverage Status](https://coveralls.io/repos/github/czerwonkabartosz/Micro-Whalla/badge.svg?branch=master)](https://coveralls.io/github/czerwonkabartosz/Micro-Whalla?branch=master)
[![Dependency Status](https://david-dm.org/czerwonkabartosz/Micro-Whalla.svg)](https://david-dm.org/czerwonkabartosz/Micro-Whalla)
[![Gitter](https://badges.gitter.im/czerwonkabartosz/Micro-Whalla.svg)](https://gitter.im/czerwonkabartosz/Micro-Whalla?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

A simple, fast framework for writing microservices in Node.js communicate using RPC / IPC.
It uses Redis server for communicate clients and services, it is making it fast, stable and easily scaling.
It can be used for interprocess communication, or for communication between servers.

```javascript
var micro = require('micro-whalla');
var Client = micro.Client;
var client = new Client('example-service');

client
    .request('method2', {param: new Date()})
    .timeout(1000)
    .send()
    .on('succeeded', function (result) {
        console.log(result);
    })
    .on('progress', function (progress) {
        console.log(result);
    })
    .on('failed', function (error) {
        console.error(result);
    });
```

```javascript
var util = require('util');
var micro = require('micro-whalla');
var Service = micro.Service;
var service;

function ExampleService() {
  this.repository = function () {
      return [1, 2, 3];
    };

  Service.call(this, 'example-service');
}

util.inherits(ExampleService, Service);

service = new ExampleService();

service.register('method', function (req, res) {
    res.done(this.repository());
});

service.register('method2', function (req, res) {
  res.progress(50);
  setTimeout(function () {
    res.done(req.data);
  }, 300);
});

service.start();

```

## Features
- Focus on high performance
- Concurrent processing
- Design based on Redis
- Many methods in the service
- Interprocess communication (IPC)
- Servers communication (RPC)
- Request timeouts
- Fire And Forget
- Processing callback events
- 100% code coverage

## Installation

```javascript
npm install micro-whalla
```

## Tests
To run tests, first install the dependencies, then run ```gulp test```
```javascript
npm install
gulp test
```

# API Reference

## Initialization
Used to configuration for redis.
This function should only be called once at the beginning of the application.
```javascript
var micro = require('micro-whalla');
micro.init({ host: '192.168.99.100', port: 32768 });
```
The ```opts``` fields are:
- ```host```: string, Redis host.
- ```port```: number, Redis port.
- ```db```: number, Redis DB index.

## Client
### Client(serviceName, opts)
It creates a new Client dedicated for communicate with other Service.

```javascript
var Client = require('micro-whalla').Client;
var client = new Client('service');
```

### Client.prototype.request(method, data, callback)

Used to create new request to other service. This function return new ```Request```.
```javascript
var request = client.request('method', { param: new Date() });
```

- ```method``` - [required] name method which be executed
- ```data``` - [required] params and data for method which be executed
- ```callback``` - [optional]  callback of request - executed when client received succeed or failed status

## Service
### Service(serviceName, opts)
It creates a new Service.

```javascript
var Service = require('micro-whalla').Service;
var service = new Service('service', {});
```

The ```opts``` fields are:
- ```concurrency``` - (optional) maximum number of simultaneously active jobs for this processor. It defaults to 1

### Service.prototype.register(name, handler(req, res))

Used to register method in service before start service.

```javascript
service.register('method', function (req, res) {
  res.done(req.data);
});
```

The name of handler should be unique.

The handler function should:
- call ```res.done(result)``` or ```res.error(error)```
- not block event loop for very long time

The handler function is called with ```Request``` and ```Response```params.

### Service.prototype.start()
Used to start service.

### Service.prototype.findAndRegisterMethods(pattern)
Used to find all methods in folders and register them in the service.

- ```pattern``` - [optional] pattern used to find methods. It defaults to ```/methods/**/*.method.js```

All files should exports Method.

```javascript
var Method = require('micro-whalla').Method;

function getUser(req, res) {
  var self = this;
  var userId = req.data.userId;

  self.usersRepository.findUserById(userId, function (err, user) {
    if (err) {
      return res.error(err);
    }

    return res.done(user);
  });
}

module.exports = new Method('getUser', getUser);

```

## Request

- ```id``` - number, unique id
- ```method``` - string, name of method in remote service
- ```data``` - object, data / params for method
- ```options``` - object, used by framework
- ```sent``` - date, sent date

### Request.prototype.timeout(timeout)

Sets a reqeust timeout. After the time has elapsed without a response is returned error.

```javascript
var request = client.request('method', { param: new Date() }).timeout(1000);
```

### Request.prototype.cache(time)

Sets a reqeust cache time. During this time result is returned from the cache.

```javascript
var request = client.request('method', { param: new Date() }).cache(1000);
```

### Request.prototype.fireAndForget()

Indication that are not expected to result from the request.

```javascript
var request = client.request('method', { param: new Date() }).fireAndForget();
```

### Request.prototype.send(callback)

Send request to service.

```javascript
var request = client.request('method', { param: new Date() }).send();
```

### Request.on(event, listener)

Set listeners for callback events.
Default events:
- succeeded
- failed
- info
- progress

```javascript
var request = client.request('method', { param: new Date() })
  .on('succeeded', function (result) {
    console.log(result);
  })
  .on('failed', function (error) {
    console.log(error);
  }).send();
```

## Response

### Response.prototype.done(result)

Ends the process and returns result for the client.

```javascript
 res.done({date: new Date()});
```

**Event: ```succeeded```**

### Response.prototype.error(error)

Ends the process and returns error for the client.

```javascript
 res.error(new Error(''));
```

**Event: ```failed```**

### Response.prototype.info(data)

Sends information to client with data.

```javascript
res.info({ information: '' });
```

**Event: ```info```**

### Response.prototype.progress(progress)

Sends progress information to client with progress value.

```javascript
res.progress(50);
```

**Event: ```progress```**

### Response.prototype.event(name, data, err)

Sends any custom events to client.

```javascript
res.event('custom', { data: 1 });
```

# License
[MIT](LICENSE)


text:
module Polisher
  module Git
    module PkgUpdater
      def update_metadata(gem)
        @version = gem.version
      end

      # Update the local spec to the specified gem version
      def update_spec_to(gem, update_args={})
        in_repo do
          spec.update_to(gem, update_args)
          File.write(spec_file, spec.to_string)
          @dirty_spec = true
        end
      end

      # Generate new sources file
      def gen_sources_for(gem)
        require_dep! 'awesome_spawn'
        require_cmd! md5sum_cmd
        in_repo do
          AwesomeSpawn.run "#{md5sum_cmd} #{gem.gem_path} > sources"
          File.write('sources', File.read('sources').gsub("#{GemCache::DIR}/", ''))
        end
      end

      # Update git ignore to ignore gem
      def ignore(gem)
        in_repo do
          nl = File.exist?('.gitignore') ? "\n" : ''
          content = "#{nl}#{gem.name}-#{gem.version}.gem"
          File.open(".gitignore", 'a') { |f| f.write content }
        end
      end

      # Update the local pkg to specified gem
      #
      # @param [Polisher::Gem] gem instance of gem containing metadata to update to
      def update_to(gem, update_args={})
        update_metadata gem
        update_spec_to gem, update_args
        gen_sources_for gem
        ignore gem
        self
      end
    end # module PkgUpdate
  end # module Git
end # module Polisher


text:
__author__ = "Brian Lenihan <brian.lenihan@gmail.com"
__copyright__ = "Copyright (c) 2012 Python for Android Project"
__license__ = "Apache License, Version 2.0"

import os
import logging
import android

"""
Create and set a new Tasker variable, display the variable's value in a Tasker
popup, and then clear the variable.

Misc / Allow External Access must be set in Tasker's prefs.

Tasker action code reference:
  http://tasker.dinglisch.net/ActionCodes.java
"""
SET_VARIABLE = 547
CLEAR_VARIABLE = 549
POPUP = 550

logging.basicConfig(level=logging.INFO)

class Tasker(object):
  def __init__(self):
    self.droid = android.Android()
    self.extras = dict(
      version_number = '1.0',
      task_name = 'tasker_demo.{}'.format(os.getpid()),
      task_priority = 9)
    self.actions = 0

  def bundle(self, action, *args):
    # Unused parameters are padded with False
    args = list(args)
    args.extend([False]*(6-len(args)))

    self.actions += 1
    self.extras.update(
      {'action{}'.format(self.actions) : dict(
        {'action' : action,
         'arg:1' : args[0],
         'arg:2' : args[1],
         'arg:3' : args[2],
         'arg:4' : args[3],
         'arg:5' : args[4],
         'arg:6' : args[5]})
         })

  def broadcast_intent(self):
    intent = self.droid.makeIntent(
      'net.dinglisch.android.tasker.ACTION_TASK', None, None, self.extras).result
    logging.debug("-- {}".format(intent))
    self.droid.sendBroadcastIntent(intent)

if __name__ == "__main__":
  tasker = Tasker()
  tasker.bundle(SET_VARIABLE, "%PY4A_DEMO", "Hello from python")
  # Popup: String title, String text, String background image, Scene layout,
  # Integer timeout, Boolean show over keyguard, Boolean condition
  tasker.bundle(POPUP, "Tasker", "%PY4A_DEMO", "", "Popup", 5, True, False)
  tasker.bundle(CLEAR_VARIABLE, "%PY4A_DEMO")
  tasker.broadcast_intent()


text:
package backend.engine

/**
  * A trait offering the compile method for texts of posts
  *
  * @author Stefan Bleibinhaus
  *
  */
trait TextCompiler {
  /**
    * Compiles the text of a post to an enriched abstract text and an enriched main text
    *
    * @param text The text of the post
    * @return Two strings. The first string is the enriched abstract text
    *  and the second string is the enriched main text.
    */
  def compile(text: String): (String, String)
}


text:
package org.zaproxy.zap.extension.bugtracker;

import java.awt.BorderLayout;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.OptionsParam;
import org.parosproxy.paros.view.AbstractParamPanel;
import org.zaproxy.zap.extension.bugtracker.BugTrackerBugzilla.BugTrackerBugzillaMultipleOptionsPanel;

public class BugTrackerBugzillaOptionsPanel extends AbstractParamPanel {

    private static final long serialVersionUID = 1L;
    private BugTrackerBugzillaMultipleOptionsPanel bugzillaPanel;

    public BugTrackerBugzillaOptionsPanel() {
        super();
        setLayout(new BorderLayout());
        this.setName(Constant.messages.getString("bugtracker.trackers.bugzilla.tab"));
        bugzillaPanel = new BugTrackerBugzillaMultipleOptionsPanel(getBugzillaModel());

        add(bugzillaPanel, BorderLayout.CENTER);
    }

    private BugTrackerBugzillaTableModel bugzillaModel;

    private BugTrackerBugzillaTableModel getBugzillaModel() {
        if (bugzillaModel == null) {
            bugzillaModel = new BugTrackerBugzillaTableModel();
        }
        return bugzillaModel;
    }

    @Override
    public void initParam(Object obj) {
        OptionsParam optionsParam = (OptionsParam) obj;
        BugTrackerBugzillaParam options = optionsParam.getParamSet(BugTrackerBugzillaParam.class);
        bugzillaModel.setConfigs(options.getConfigs());
    }

    @Override
    public void validateParam(Object obj) throws Exception {}

    @Override
    public void saveParam(Object obj) throws Exception {
        OptionsParam optionsParam = (OptionsParam) obj;
        BugTrackerBugzillaParam options = optionsParam.getParamSet(BugTrackerBugzillaParam.class);
        options.setConfigs(bugzillaModel.getElements());
    }

    @Override
    public String getHelpIndex() {
        return "addon.bugtracker.bugtracker";
    }
}


text:
{% extends "base.html" %}
{% block page_content %}

{{ user.username }}

    {% if user.name or user.location %}

        {% if user.name %}{{ user.name }}{% endif %}
        {% if user.location %}
            From
        {{ user.location }}

        {% endif %}

    {% endif %}
    {% if current_user.is_administrator() %}

{{ user.email }}

    {% endif %}
    {% if current_user.about_me %}

{{ user.about_me}}

    {% endif %}

        Member since {{ moment(user.member_since).format('L')}}.
        Last seen {{ moment(user.last_seen).fromNow()}}.

    {% if user == current_user %}
        {% if current_user.is_administrator() %}

                Edit_Profile [admin]

        {% else %}

                Edit Profile

        {% endif %}
    {% endif %}

Post by {{ user.username }}

    {% include '_posts.html' %}

{% endblock %}


text:
title: Evaluating Polynomials Synthetic Division
---
## Evaluating Polynomials Synthetic Division

This is a stub. Help our community expand it.

This quick style guide will help ensure your pull request gets accepted.

#### More Information:


text:
<?php

namespace Srosato\BowlingBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;

class SrosatoBowlingExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
    }

    public function getAlias()
    {
        return 'srosato_bowling';
    }
}


text:
import {Bean, PostConstruct, Autowired} from "../context/context";
import {Utils as _} from '../utils';
import {ICellRenderer, ICellRendererFunc} from "./cellRenderers/iCellRenderer";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {EventService} from "../eventService";
import {ExpressionService} from "../expressionService";
import {SelectionRendererFactory} from "../selectionRendererFactory";
import {AnimateSlideCellRenderer} from "./cellRenderers/animateSlideCellRenderer";
import {AnimateShowChangeCellRenderer} from "./cellRenderers/animateShowChangeCellRenderer";
import {GroupCellRenderer} from "./cellRenderers/groupCellRenderer";

@Bean('cellRendererFactory')
export class CellRendererFactory {

    private static ANIMATE_SLIDE = 'animateSlide';
    private static ANIMATE_SHOW_CHANGE = 'animateShowChange';
    private static GROUP = 'group';

    @Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
    @Autowired('selectionRendererFactory') private selectionRendererFactory: SelectionRendererFactory;
    @Autowired('expressionService') private expressionService: ExpressionService;
    @Autowired('eventService') private eventService: EventService;

    private cellRendererMap: {[key: string]: {new(): ICellRenderer} | ICellRendererFunc} = {};

    @PostConstruct
    private init(): void {
        this.cellRendererMap[CellRendererFactory.ANIMATE_SLIDE] = AnimateSlideCellRenderer;
        this.cellRendererMap[CellRendererFactory.ANIMATE_SHOW_CHANGE] = AnimateShowChangeCellRenderer;
        this.cellRendererMap[CellRendererFactory.GROUP] = GroupCellRenderer;
    }

    public addCellRenderer(key: string, cellRenderer: {new(): ICellRenderer} | ICellRendererFunc): void {
        this.cellRendererMap[key] = cellRenderer;
    }

    public getCellRenderer(key: string): {new(): ICellRenderer} | ICellRendererFunc {

        var result = this.cellRendererMap[key];
        if (_.missing(result)) {
            console.warn('ag-Grid: unable to find cellRenderer for key ' + key);
            return null;
        }

        return result;
    }
}


text:
<?php
require_once('back/conn.php');
if (!isset($_SESSION)) {
 		 session_start();
	}
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "" . $theValue . "" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return @$theValue;
}
}

$mysqli->set_charset('utf8');
if(isset($_GET['eid'])){
	$event_id = GetSQLValueString($_GET['eid'],"int");
	@$all = "select * from events";
	@$case = " where id = ".@$event_id;
	@$query_Recordset1 = @$all.@$case;
	@$Recordset1 = $mysqli->query(@$query_Recordset1);
	if($Recordset1->num_rows==0){
		echo "检索不到该记录";
	}else{
		$event_get = $Recordset1->fetch_assoc();
	}
}

?>
<!DOCTYPE HTML>

<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="Bookmark" href="/favicon.ico" >
<link rel="Shortcut Icon" href="/favicon.ico" />

<link rel="stylesheet" type="text/css" href="static/h-ui/css/H-ui.min.css" />
<link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/H-ui.admin.css" />
<link rel="stylesheet" type="text/css" href="lib/Hui-iconfont/1.0.8/iconfont.css" />
<link rel="stylesheet" type="text/css" href="static/h-ui.admin/skin/default/skin.css" id="skin" />
<link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/style.css" />

<title>编辑记录</title>

	<form method="post" class="form form-horizontal" id="form-member-add" enctype="multipart/form-data">

			*断面里程:

				<input disabled="disabled" required="required" type="text" class="input-text" placeholder="" id="section_mileage" name="section_mileage" value="<?php echo @$event_get['section_mileage'];?>"/>

			*管片号

				<input disabled="disabled" required="required" type="text" class="input-text" placeholder="" id="segment_num" name="segment_num" value="<?php echo @$event_get['segment_num'];?>"/>

			*传感器号:

				<input disabled="disabled" required="required" type="text" class="input-text" placeholder="" id="sensor_num" name="sensor_num" value="<?php echo @$event_get['sensor_num'];?>"/>

			当前波长:

				<input type="text" class="input-text" placeholder="" name="current_wl" id="current_wl" value="<?php echo @$event_get['current_wl'];?>">

			监测对象

				<input disabled="disabled" type="text" class="input-text" placeholder="" name="obj" id="obj" value="<?php echo @$event_get['obj'];?>">

			*物理量

				<input disabled="disabled" required="required" type="text" class="input-text" placeholder="" name="quantity" id="quantity" value="<?php echo @$event_get['quantity'];?>">

			当前值

				<input type="text" class="input-text" placeholder="" name="value" id="value" value="<?php echo @$event_get['value'];?>">

			*单位

				<input disabled="disabled" required="required" type="text" class="input-text" placeholder="" name="unit" id="unit" value="<?php echo @$event_get['unit'];?>">

			预警值

				<input disabled="disabled" type="text" class="input-text" placeholder="" name="warning" id="warning" value="<?php echo @$event_get['warning'];?>">

			报警值

				<input disabled="disabled" type="text" class="input-text" placeholder="" name="alarm" id="alarm" value="<?php echo @$event_get['alarm'];?>">

			传感器状态

				<input type="text" class="input-text" placeholder="" name="status" id="status" value="<?php echo @$event_get['status'];?>">

			记录时间

				<input disabled="disabled" type="text" class="input-text" placeholder="" name="rec_time" id="rec_time" value="<?php echo @$event_get['rec_time'];?>">

			备注

				<input type="text" class="input-text" placeholder="" name="remarks" id="remarks" value="<?php echo @$event_get['remarks'];?>">

				<input class="btn btn-primary radius" type="button" onclick="formsubmit()" value="  提交  ">

		<input type="hidden" id="eventid" name="eventid" value="<?php echo $event_get['id'];?>"/>
	</form>


text:
package jsettlers.algorithms.landmarks;

/**
 * This interface specifies the methods needed by a map that should be handle with the LandmarksCorrectingThread.
 *
 * @author Andreas Eberle
 *
 */
public interface IEnclosedBlockedAreaFinderGrid {

	public boolean isBlocked(int x, int y);

	public short getPartitionAt(int x, int y);

	public boolean isInBounds(int x, int y);

	public void setPartitionAt(int x, int y, short newPartition);

	public short getHeight();

	public short getWidth();

}


text:
namespace base {
class Version;
}  // namespace base

namespace extensions {
class Extension;
}  // namespace extensions

namespace media_router {

// NOTE: Do not renumber enums as that would confuse interpretation of
// previously logged data. When making changes, also update the enum list
// in tools/metrics/histograms/histograms.xml to keep it in sync.

// Why the Media Route Provider process was woken up.
enum class MediaRouteProviderWakeReason {
  CREATE_ROUTE = 0,
  JOIN_ROUTE = 1,
  TERMINATE_ROUTE = 2,
  SEND_SESSION_MESSAGE = 3,
  SEND_SESSION_BINARY_MESSAGE = 4,
  DETACH_ROUTE = 5,
  START_OBSERVING_MEDIA_SINKS = 6,
  STOP_OBSERVING_MEDIA_SINKS = 7,
  START_OBSERVING_MEDIA_ROUTES = 8,
  STOP_OBSERVING_MEDIA_ROUTES = 9,
  LISTEN_FOR_ROUTE_MESSAGES = 10,
  STOP_LISTENING_FOR_ROUTE_MESSAGES = 11,
  CONNECTION_ERROR = 12,
  REGISTER_MEDIA_ROUTE_PROVIDER = 13,
  CONNECT_ROUTE_BY_ROUTE_ID = 14,
  ENABLE_MDNS_DISCOVERY = 15,
  UPDATE_MEDIA_SINKS = 16,

  // NOTE: Add entries only immediately above this line.
  TOTAL_COUNT = 17
};

// The install status of the Media Router component extension.
enum class MediaRouteProviderVersion {
  // Installed but version is invalid or cannot be determined.
  UNKNOWN = 0,
  // Installed and the extension version matches the browser version.
  SAME_VERSION_AS_CHROME = 1,
  // Installed and the extension version is one version behind the browser
  // version.
  ONE_VERSION_BEHIND_CHROME = 2,
  // Installed and the extension version is more than one version behind the
  // browser version.
  MULTIPLE_VERSIONS_BEHIND_CHROME = 3,
  // Note: Add entries only immediately above this line.
  TOTAL_COUNT = 4
};

// The outcome of an attempt to wake the Media Router component event page.
enum class MediaRouteProviderWakeup {
  SUCCESS = 0,
  ERROR_UNKNOWN = 1,
  ERROR_TOO_MANY_RETRIES = 2,
  // Note: Add entries only immediately above this line.
  TOTAL_COUNT = 3
};

class MediaRouterMojoMetrics {
 public:
  // Records the installed version of the Media Router component extension.
  static void RecordMediaRouteProviderVersion(
      const extensions::Extension& extension);

  // Records why the media route provider extension was woken up.
  static void RecordMediaRouteProviderWakeReason(
      MediaRouteProviderWakeReason reason);

  // Records the outcome of an attempt to wake the Media Router component event
  // page.
  static void RecordMediaRouteProviderWakeup(MediaRouteProviderWakeup wakeup);

 private:
  FRIEND_TEST_ALL_PREFIXES(MediaRouterMojoMetricsTest,
                           TestGetMediaRouteProviderVersion);

  // Returns the version status of the Media Router component extension.
  static MediaRouteProviderVersion GetMediaRouteProviderVersion(
      const base::Version& extension_version,
      const base::Version& browser_version);
};

}  // namespace media_router

#endif  // CHROME_BROWSER_MEDIA_ROUTER_MOJO_MEDIA_ROUTER_MOJO_METRICS_H_


text:
// eslint-disable-next-line import/no-extraneous-dependencies, @typescript-eslint/no-var-requires
const typescriptTransform = require('i18next-scanner-typescript');

module.exports = {
	input: ['src/**/*.{js,ts,tsx}'],
	options: {
		debug: true,
		sort: true,
		func: {
			list: ['t'],
			extensions: ['.js'],
		},
		lngs: ['en'],
		defaultNs: 'tui-forms',
		defaultValue: '__STRING_NOT_TRANSLATED__',
		resource: {
			savePath: 'i18n/{{ns}}.json',
		},
	},
	// Be careful when providing custom arguments: <Trans> detection will break if you don't provide tsConfig: target: es2018
	transform: typescriptTransform(),
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Platformer
{
    public class Background
    {
        public int ID
        {
            get;
            set;
        }

        public Vector2 Velocity
        {
            get;
            set;
        }

        public Vector2 Position
        {
            get;
            set;
        }
    }
}


text:
void SHA1_init()
{
boost::python::class_<SHA1, boost::python::bases<Hash>>("SHA1")
    .def(boost::python::init<const std::string &>())
    .def("digestsize", &SHA1::digestsize)
    .def("blocksize", &SHA1::blocksize)
    .def("hexdigest", &SHA1::hexdigest)
    .def("update", &SHA1::update)
    ;
}


text: import randomChecker


text:
package system.plugins;

import crawler.graph.DefaultNode;
import crawler.graph.DirectedGraph;
import system.processor.MausPage;

/**
 * creates page contents and therefore
 * gets plugged into the mausprocessor
 *
 * Created by Fabi on 23.02.2015.
 */
public interface MausPageContentFactoryInterface <N extends Comparable<N>> {
    public String getContentName();
    public MausPageContentInterface createContent(MausPage page, DirectedGraph<DefaultNode<N>> graph);
}


text:
class DiffNote < Note
  include NoteOnDiff

  serialize :original_position, Gitlab::Diff::Position
  serialize :position, Gitlab::Diff::Position

  validates :original_position, presence: true
  validates :position, presence: true
  validates :diff_line, presence: true
  validates :line_code, presence: true, line_code: true
  validates :noteable_type, inclusion: { in: ['Commit', 'MergeRequest'] }
  validate :positions_complete
  validate :verify_supported

  before_validation :set_original_position, :update_position, on: :create
  before_validation :set_line_code
  after_save :keep_around_commits

  class << self
    def build_discussion_id(noteable_type, noteable_id, position)
      [super(noteable_type, noteable_id), *position.key].join("-")
    end
  end

  def new_diff_note?
    true
  end

  def diff_attributes
    { position: position.to_json }
  end

  def discussion_id
    @discussion_id ||= self.class.build_discussion_id(noteable_type, noteable_id || commit_id, position)
  end

  def original_discussion_id
    @original_discussion_id ||= self.class.build_discussion_id(noteable_type, noteable_id || commit_id, original_position)
  end

  def position=(new_position)
    if new_position.is_a?(String)
      new_position = JSON.parse(new_position) rescue nil
    end

    if new_position.is_a?(Hash)
      new_position = new_position.with_indifferent_access
      new_position = Gitlab::Diff::Position.new(new_position)
    end

    super(new_position)
  end

  def diff_file
    @diff_file ||= self.original_position.diff_file(self.project.repository)
  end

  def diff_line
    @diff_line ||= diff_file.line_for_position(self.original_position) if diff_file
  end

  def for_line?(line)
    diff_file.position(line) == self.original_position
  end

  def active?(diff_refs = nil)
    return false unless supported?
    return true if for_commit?

    diff_refs ||= self.noteable.diff_refs

    self.position.diff_refs == diff_refs
  end

  private

  def supported?
    !self.for_merge_request? || self.noteable.support_new_diff_notes?
  end

  def set_original_position
    self.original_position = self.position.dup
  end

  def set_line_code
    self.line_code = self.position.line_code(self.project.repository)
  end

  def update_position
    return unless supported?
    return if for_commit?

    return if active?

    Notes::DiffPositionUpdateService.new(
      self.project,
      nil,
      old_diff_refs: self.position.diff_refs,
      new_diff_refs: self.noteable.diff_refs,
      paths: self.position.paths
    ).execute(self)
  end

  def verify_supported
    return if supported?

    errors.add(:noteable, "doesn't support new-style diff notes")
  end

  def positions_complete
    return if self.original_position.complete? && self.position.complete?

    errors.add(:position, "is invalid")
  end

  def keep_around_commits
    project.repository.keep_around(self.original_position.base_sha)
    project.repository.keep_around(self.original_position.start_sha)
    project.repository.keep_around(self.original_position.head_sha)

    if self.position != self.original_position
      project.repository.keep_around(self.position.base_sha)
      project.repository.keep_around(self.position.start_sha)
      project.repository.keep_around(self.position.head_sha)
    end
  end
end


text:
require "blogger/engine"

module Blogger
	mattr_accessor :user_class
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
	@package	flystaff
	@copyright	Copyright (c)2013 Nicholas K. Dionysopoulos / AkeebaBackup.com
	@license	GNU General Public License version 2 or later

	Items view form file
-->
<form
	type="browse"
	show_header="1"
	show_filters="1"
	show_pagination="1"
	norows_placeholder="COM_VIDIYAL_COMMON_NORECORDS"
>
	<headerset>
		<header name="vidiyal_donor_id" type="rowselect" tdwidth="20" />

		<header name="Name" type="fieldsearchable" sortable="true"
			buttons="no" buttonclass="btn"
		/>

		<header name="Amount" type="field" sortable="true"
			buttons="no" buttonclass="btn"
		/>
		<header name="Currency" type="field" sortable="true"
			buttons="no" buttonclass="btn"
		/>

		<header name="email" type="fieldsearchable" sortable="true"
			buttons="no" buttonclass="btn"
		/>

		<header name="Note" type="field" sortable="true"
			buttons="no" buttonclass="btn"
		/>

		<header name="DateOfBirth" type="field" sortable="true"
			buttons="no" buttonclass="btn"
		/>

		<header name="DateOfPayment" type="field" sortable="true"
			buttons="no" buttonclass="btn"
		/>

		<header name="enabled" type="published" sortable="true" tdwidth="8%" />
	</headerset>

	<fieldset name="items">
		<field name="vidiyal_item_id" type="selectrow"/>

		<field name="Name" type="text"
						show_link="true"
			url="index.php?option=com_vidiyal&view=donor&id=[ITEM:ID]"/>

		<field name="Amount" type="text"/>

		<field name="Currency" type="text"/>

		<field name="EMail" type="text"/>
		<field name="Note" type="text"/>
		<field name="DateOfBirth" type="text"/>
		<field name="DateOfPayment" type="text"/>

		<field name="enabled" type="published"/>
	</fieldset>
</form>


text:
require_relative 'deck'
require_relative 'flashcard'

module Controller

  def self.run(file_name)
    cards = create_flashcards(file_name)
    deck = create_deck(cards)

    until deck.flashcards.empty?
      flashcard = remove_flashcard(deck)
      View.display_question(flashcard.question)
      educated_guess = View.get_input_from_user
      if flashcard.correct?(educated_guess)
        deck.correct_answers += 1
        View.display_confirmation
      else
        View.display_rejection
      end
    end
    View.display_summary(deck.correct_answers, deck.decklength)
  end

  private

  def self.remove_flashcard(deck)
    deck.flashcards.shuffle!.shift
  end

  def self.create_deck(cards)
    Deck.new(cards)
  end

  def self.create_flashcards(file_name)
    array = []
    File.foreach(file_name).each_slice(3) do | three_lines |
      hash = {
      :question => three_lines[0].chomp("\n"),
      :answer => three_lines[1].chomp("\n")
      }
      array << hash
    end
    array.map do | hash |
      Flashcard.new(hash)
    end
  end
end


text:
/*
 *
 */
package org.processmining.openslex.metamodel;

import java.sql.ResultSet;

// TODO: Auto-generated Javadoc
/**
 * The Class SLEXMMObjectResultSet.
 *
 * @author Eduardo Gonzalez Lopez de Murillas
 * @see OpenSLEX
 */
public class SLEXMMObjectResultSet extends AbstractRSetElement<SLEXMMObject> {

	/**
	 * Instantiates a new SLEXMM object result set.
	 *
	 * @param storage the storage
	 * @param rset the rset
	 */
	public SLEXMMObjectResultSet(SLEXMMStorageMetaModel storage, ResultSet rset) {
		super(storage, rset, SLEXMMObject.class);
	}

	/**
	 * Gets the next.
	 *
	 * @return the next
	 */
	public SLEXMMObject getNext() {
		SLEXMMObject ev = null;
		try {
			if (this.rset != null && this.rset.next()) {

				int id = this.rset.getInt("id");
				int classId = this.rset.getInt("class_id");
				ev = storage.getFromCache(SLEXMMObject.class, id);
				if (ev == null) {
					ev = new SLEXMMObject((SLEXMMStorageMetaModel) storage);
					ev.setId(id);
					ev.setClassId(classId);
					ev.setDirty(false);
					ev.setInserted(true);
					storage.putInCache(ev);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ev == null) {
				close();
			}
		}
		return ev;
	}

}


text:
I will no longer maintain lego-wrapper as its functionality has been completely deprecated by [Certbot](https://certbot.eff.org/) which I fully recommend as a replacement.

# lego-wrapper
Wrapper for [xenolf's lego](https://github.com/xenolf/lego) Let's Encrypt client automation.

Each file in /etc/lego-wrapper.d/domains contains list of domains for which **one** certificate is generated. First line is expected to contain the base domain, other lines will be added to the certificate as aliases (subjAltName).

Configurable via /etc/lego-wrapper.d/lego-wrapper.conf (default config file, can be edited in the script).

Do not forget to add your email addres to lego-wrapper.conf (EMAIL=your@e-mail.example.com).

Make sure you read and accept [Let's Encrypt's TOS](https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf) **before** you run this script **OR** remove the TOC= configuration option to be prompted for acceptance by Lego at runtime.

Don't forget to unset the TESTSERVER variable to make live working certificates. By default the wrapper only produces testing certificates.

This script is suitable for running by cron or any other automation tools. Certificates will only be renewed when in renewal window set by RENEWWINDOW (defaults to within the last 30 days of validity)

!!! Warning !!!
Be **extremely careful** when running with '-i' parameter, any pre-existing certificate and key files bearing the name of the base domain in system storage (usually /etc/ssl/{certs,private}) **WILL BE OVERWRITTEN**, no questions asked. You have been warned.