text:
#include "profile.h"

#include <kdbhelper.h>

#include <kdb.h>     //actual namespaces
#include <kdbease.h> //elektraKeyGetRelativeName
#include <kdbos.h>   //elektraNamespace
#include <stdio.h>
#include <string.h>

#include <fnmatch.h>

#define PROFILEPATH "*/sw/*/*/#*/profile"
#define CURRENTPATH "*/sw/*/*/#*/current"

int elektraProfileOpen (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
	// plugin initialization logic
	KeySet * appendedKeys = NULL;
	elektraPluginSetData (handle, appendedKeys);
	return 1; // success
}

int elektraProfileClose (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
	// free all plugin resources and shut it down
	KeySet * appendedKeys = elektraPluginGetData (handle);
	if (appendedKeys) ksDel (appendedKeys);
	return 1; // success
}

static Key * keyDupWithNS (const Key * origKey, elektraNamespace ns)
{
	Key * newKey = NULL;
	switch (ns)
	{
	case KEY_NS_SPEC:
		newKey = keyNew ("spec", KEY_END);
		break;
	case KEY_NS_DIR:
		newKey = keyNew ("dir", KEY_END);
		break;
	case KEY_NS_USER:
		newKey = keyNew ("user", KEY_END);
		break;
	case KEY_NS_SYSTEM:
		newKey = keyNew ("system", KEY_END);
		break;
	case KEY_NS_PROC:
		newKey = keyNew ("proc", KEY_END);
		break;
	case KEY_NS_CASCADING:
	default:
		newKey = keyNew ("/", KEY_CASCADING_NAME, KEY_END);
		break;
	}
	const char * relativeName = keyName (origKey);
	char * nextPtr = NULL;
	if (keyName (origKey)[0] == '/')
		++relativeName;
	else if ((nextPtr = strchr (keyName (origKey), '/')))
		relativeName = (++nextPtr);
	keyAddName (newKey, relativeName);
	return newKey;
}

static void linkProfileKeys (KeySet * swKS, KeySet * profileKeys, KeySet * appendedKeys)
{
	Key * profileCutKey = NULL;
	Key * profileKey = NULL;
	const char * profileString = NULL;
	ksRewind (profileKeys);
	while ((profileKey = ksNext (profileKeys)) != NULL)
	{
		profileString = keyString (profileKey);
		if (profileString)
		{
			profileCutKey = keyDup (profileKey);
			keyAddName (profileCutKey, "..");
			Key * currentProfileKey = keyDup (profileCutKey);
			keyAddBaseName (currentProfileKey, "current");
			keyAddBaseName (profileCutKey, profileString);
			KeySet * profileKS = ksCut (swKS, profileCutKey);
			ksRewind (profileKS);
			Key * cur;
			while ((cur = ksNext (profileKS)) != NULL)
			{
				if (!strcmp (keyName (cur), keyName (profileCutKey))) continue;
				Key * overrideKey = keyDupWithNS (currentProfileKey, KEY_NS_SPEC);
				const char * relativeName = elektraKeyGetRelativeName (cur, profileCutKey);
				keyAddName (overrideKey, relativeName);
				Key * lookupKey = keyDupWithNS (overrideKey, keyGetNamespace (currentProfileKey));
				if (ksLookup (swKS, lookupKey, KDB_O_NONE))
				{
					keyDel (lookupKey);
					keyDel (overrideKey);
					continue;
				}
				keyDel (lookupKey);
				keySetMeta (overrideKey, "override/#0", keyName (cur));
				ksAppendKey (swKS, keyDup (overrideKey));
				ksAppendKey (appendedKeys, keyDup (overrideKey));
				keyDel (overrideKey);
			}
			keyDel (currentProfileKey);
			keyDel (profileCutKey);
			ksAppend (swKS, profileKS);
			ksDel (profileKS);
		}
	}
}

static void linkDefaultKeys (KeySet * swKS, KeySet * profileParents, KeySet * appendedKeys)
{
	ksRewind (profileParents);
	Key * profileParent = NULL;
	while ((profileParent = ksNext (profileParents)) != NULL)
	{
		Key * defaultCutKey = keyDup (profileParent);
		keyAddName (defaultCutKey, "%");
		KeySet * defaultKS = ksCut (swKS, defaultCutKey);
		ksRewind (defaultKS);
		Key * cur;
		Key * currentProfileKey = keyDup (profileParent);
		keyAddName (currentProfileKey, "current");
		while ((cur = ksNext (defaultKS)) != NULL)
		{
			if (!strcmp (keyName (cur), keyName (defaultCutKey))) continue;
			const char * relativeName = elektraKeyGetRelativeName (cur, defaultCutKey);
			Key * overrideKey = keyDupWithNS (currentProfileKey, KEY_NS_SPEC);
			keyAddName (overrideKey, relativeName);
			Key * existingKey = keyDupWithNS (overrideKey, keyGetNamespace (profileParent));
			if (ksLookup (swKS, overrideKey, KDB_O_NONE) || ksLookup (swKS, existingKey, KDB_O_NONE))
			{
				keyDel (overrideKey);
				keyDel (existingKey);
				continue;
			}
			keyDel (existingKey);
			keySetMeta (overrideKey, "override/#0", keyName (cur));
			ksAppendKey (swKS, keyDup (overrideKey));
			ksAppendKey (appendedKeys, keyDup (overrideKey));
			keyDel (overrideKey);
		}
		keyDel (currentProfileKey);
		keyDel (defaultCutKey);
		ksAppend (swKS, defaultKS);
		ksDel (defaultKS);
	}
}

int elektraProfileGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	if (!elektraStrCmp (keyName (parentKey), "system/elektra/modules/profile"))
	{
		KeySet * contract =
			ksNew (30, keyNew ("system/elektra/modules/profile", KEY_VALUE, "profile plugin waits for your orders", KEY_END),
			       keyNew ("system/elektra/modules/profile/exports", KEY_END),
			       keyNew ("system/elektra/modules/profile/exports/open", KEY_FUNC, elektraProfileOpen, KEY_END),
			       keyNew ("system/elektra/modules/profile/exports/close", KEY_FUNC, elektraProfileClose, KEY_END),
			       keyNew ("system/elektra/modules/profile/exports/get", KEY_FUNC, elektraProfileGet, KEY_END),
			       keyNew ("system/elektra/modules/profile/exports/set", KEY_FUNC, elektraProfileSet, KEY_END),
			       keyNew ("system/elektra/modules/profile/exports/error", KEY_FUNC, elektraProfileError, KEY_END),
#include ELEKTRA_README
			       keyNew ("system/elektra/modules/profile/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
		ksAppend (returned, contract);
		ksDel (contract);

		return 1; // success
	}
	// get all keys
	Key * swKey = keyNew ("/sw", KEY_CASCADING_NAME, KEY_END);
	KeySet * swKS = ksCut (returned, swKey);
	keyDel (swKey);
	ksRewind (swKS);
	Key * cur;

	KeySet * appendedKeys = elektraPluginGetData (handle);
	if (!appendedKeys) appendedKeys = ksNew (0, KS_END);
	KeySet * profileKeys = ksNew (0, KS_END);
	while ((cur = ksNext (swKS)) != NULL)
	{
		if (!fnmatch (PROFILEPATH, keyName (cur), FNM_PATHNAME))
		{
			ksAppendKey (profileKeys, cur);
		}
	}
	linkProfileKeys (swKS, profileKeys, appendedKeys);
	ksDel (profileKeys);
	ksDel (appendedKeys);
	ksRewind (swKS);
	KeySet * profileParents = ksNew (0, KS_END);
	while ((cur = ksNext (swKS)) != NULL)
	{
		if (!fnmatch (CURRENTPATH, keyName (cur), FNM_PATHNAME))
		{
			Key * profileParent = keyDup (cur);
			keyAddName (profileParent, "..");
			ksAppendKey (profileParents, keyDup (profileParent));
			keyDel (profileParent);
		}
	}
	linkDefaultKeys (swKS, profileParents, appendedKeys);
	ksDel (profileParents);
	ksAppend (returned, swKS);
	ksDel (swKS);

	return 1; // success
}

int elektraProfileSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	// get all keys
	KeySet * appendedKeys = elektraPluginGetData (handle);
	if (!appendedKeys) return 1;
	ksRewind (appendedKeys);
	Key * cur;
	while ((cur = ksNext (appendedKeys)) != NULL)
	{
		keyDel (ksLookup (returned, cur, KDB_O_POP));
	}
	ksDel (appendedKeys);
	elektraPluginSetData (handle, NULL);
	return 1; // success
}

int elektraProfileError (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	// set all keys

	return 1; // success
}

Plugin * ELEKTRA_PLUGIN_EXPORT
{
	// clang-format off
	return elektraPluginExport ("profile",
			ELEKTRA_PLUGIN_OPEN,	&elektraProfileOpen,
			ELEKTRA_PLUGIN_CLOSE,	&elektraProfileClose,
			ELEKTRA_PLUGIN_GET,	&elektraProfileGet,
			ELEKTRA_PLUGIN_SET,	&elektraProfileSet,
			ELEKTRA_PLUGIN_ERROR,	&elektraProfileError,
			ELEKTRA_PLUGIN_END);
}


text:
using namespace std;

#ifndef DRAWABLE_C
#define DRAWABLE_C
class Drawable
{
	public:
		Drawable();
		sf::Sprite GetSprite(void);
		bool SetPosition(int, int);
		bool SetCoordinates(int, int);
		void SetImage(sf::Image);
		static void Draw(sf::RenderWindow*);

	protected:
		sf::Image image;
		sf::Sprite sprite;
		int col, row;
		int x, y;
		static list<Drawable*> Drawables;
		~Drawable();
};

#include "drawable.cpp"
#endif

redpajama_set_name: RedPajamaGithub


text:
package org.oscm.operatorsvc.client.commands;

import java.util.Collections;
import java.util.List;

import org.oscm.operatorsvc.client.CommandContext;
import org.oscm.internal.vo.VOTimerInfo;

public class RetrieveTimerExpirationsCommand extends AbstractTimerCommand {

    public String getName() {
        return "retrievetimerexpirations";
    }

    public String getDescription() {
        return "Retrieves the settings of the currently registered timers.";
    }

    public List<String> getArgumentNames() {
        final List<String> none = Collections.emptyList();
        return none;
    }

    public boolean run(CommandContext ctx) throws Exception {
        final List<VOTimerInfo> info = ctx.getService()
                .getTimerExpirationInformation();
        printTimerInormation(info, ctx.out());
        return true;
    }
}


text:
data.raw.module["speed-module"].effect = {speed = {bonus = 0.15}, consumption = {bonus = 0.5}}
data.raw.module["speed-module-2"].effect = {speed = {bonus = 0.3}, consumption = {bonus = 0.6}}
data.raw.module["speed-module-3"].effect = {speed = {bonus = 0.45}, consumption = {bonus = 0.7}}
data.raw.module["productivity-module"].effect = {
    productivity = {bonus = 0.03},
    consumption = {bonus = 0.4},
    pollution = {bonus = 0.3},
    speed = {bonus = -0.15}
}
data.raw.module["productivity-module-2"].effect = {
    productivity = {bonus = 0.06},
    consumption = {bonus = 0.6},
    pollution = {bonus = 0.4},
    speed = {bonus = -0.20}
}
data.raw.module["productivity-module-3"].effect = {
    productivity = {bonus = 0.09},
    consumption = {bonus = 0.8},
    pollution = {bonus = 0.5},
    speed = {bonus = -0.25}
}
data.raw.module["effectivity-module"].effect = {consumption = {bonus = -0.15}}
data.raw.module["effectivity-module-2"].effect = {consumption = {bonus = -0.3}}
data.raw.module["effectivity-module-3"].effect = {consumption = {bonus = -0.45}}
data.raw.module["speed-module"].icon = "__5dim_module__/graphics/icon/a1.png"
data.raw.module["speed-module-2"].icon = "__5dim_module__/graphics/icon/a2.png"
data.raw.module["speed-module-3"].icon = "__5dim_module__/graphics/icon/a3.png"
data.raw.module["productivity-module"].icon = "__5dim_module__/graphics/icon/r1.png"
data.raw.module["productivity-module-2"].icon = "__5dim_module__/graphics/icon/r2.png"
data.raw.module["productivity-module-3"].icon = "__5dim_module__/graphics/icon/r3.png"
data.raw.module["effectivity-module"].icon = "__5dim_module__/graphics/icon/v1.png"
data.raw.module["effectivity-module-2"].icon = "__5dim_module__/graphics/icon/v2.png"
data.raw.module["effectivity-module-3"].icon = "__5dim_module__/graphics/icon/v3.png"
data.raw.module["speed-module"].icon_size = 32
data.raw.module["speed-module-2"].icon_size = 32
data.raw.module["speed-module-3"].icon_size = 32
data.raw.module["productivity-module"].icon_size = 32
data.raw.module["productivity-module-2"].icon_size = 32
data.raw.module["productivity-module-3"].icon_size = 32
data.raw.module["effectivity-module"].icon_size = 32
data.raw.module["effectivity-module-2"].icon_size = 32
data.raw.module["effectivity-module-3"].icon_size = 32


text:
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <map>
#include <iostream>
#include <string>
#include <glog/logging.h>
#include <sofa/pbrpc/pbrpc.h>
#include <sys/inotify.h>
#include <unistd.h>
#include "agent/agent_impl.h"
#include "agent/options.h"
#include "proto/agent.pb.h"
#include "agent/log_stream.h"
#include <errno.h>
#include <sys/select.h>
#include "proto/scheduler.pb.h"

DECLARE_string(scheduler_addr);
DECLARE_string(db_dir);
DECLARE_string(watch_log_dir);
DECLARE_string(module_name_list);
DECLARE_string(agent_service_port);

extern mdt::agent::EventMask event_masks[21];

namespace mdt {
namespace agent {

void* SchedulerThread(void* arg) {
    AgentImpl* agent = (AgentImpl*)arg;
    agent->GetServerAddr();
    return NULL;
}

AgentImpl::AgentImpl() {
    pthread_spin_init(&lock_, PTHREAD_PROCESS_SHARED);
    pthread_spin_init(&server_lock_, PTHREAD_PROCESS_SHARED);
    rpc_client_ = new RpcClient();

    info_.qps_use= 0;
    info_.qps_quota= 0;
    info_.bandwidth_use= 0;
    info_.bandwidth_quota= 0;
    info_.max_packet_size= 0;
    info_.min_packet_size= 0;
    info_.average_packet_size= 0;
    info_.error_nr = 0;
    info_.collector_addr = "nil";
    //server_addr_ = "nil";

    stop_scheduler_thread_ = false;
    pthread_create(&scheduler_tid_, NULL, SchedulerThread, this);
}

AgentImpl::~AgentImpl() {

}

void AgentImpl::GetServerAddrCallback(const mdt::LogSchedulerService::GetNodeListRequest* req,
                                      mdt::LogSchedulerService::GetNodeListResponse* resp,
                                      bool failed, int error,
                                      mdt::LogSchedulerService::LogSchedulerService_Stub* service) {
    if (!failed) {
        pthread_spin_lock(&server_lock_);
        info_.collector_addr = resp->primary_server_addr();
        VLOG(50) << "agent, collector addr " << info_.collector_addr;

        info_.qps_use= 0;
        info_.qps_quota= 0;
        info_.bandwidth_use= 0;
        info_.bandwidth_quota= 0;
        info_.max_packet_size= 0;
        info_.min_packet_size= 0;
        info_.average_packet_size= 0;
        info_.error_nr = 0;

        pthread_spin_unlock(&server_lock_);
    }
    delete req;
    delete resp;
    delete service;
    server_addr_event_.Set();
}

void AgentImpl::GetServerAddr() {
    char hostname[255];
    if (0 != gethostname(hostname, 256)) {
        LOG(FATAL) << "fail to report message";
    }
    std::string hostname_str = hostname;

    while (1) {
        if (stop_scheduler_thread_) {
            return;
        }
        std::string agent_addr = hostname_str + ":" + FLAGS_agent_service_port;
        std::string scheduler_addr = FLAGS_scheduler_addr;

        mdt::LogSchedulerService::LogSchedulerService_Stub* service;
        rpc_client_->GetMethodList(scheduler_addr, &service);
        mdt::LogSchedulerService::GetNodeListRequest* req = new mdt::LogSchedulerService::GetNodeListRequest();
        mdt::LogSchedulerService::GetNodeListResponse* resp = new mdt::LogSchedulerService::GetNodeListResponse();
        // set up agent info request
        pthread_spin_lock(&server_lock_);
        req->set_agent_addr(agent_addr);
        req->set_current_server_addr(info_.collector_addr);

        mdt::LogSchedulerService::AgentInfo* info = req->mutable_info();
        info->set_qps_quota(info_.qps_quota);
        info->set_qps_use(info_.qps_use);
        info->set_bandwidth_use(info_.bandwidth_use);
        info->set_bandwidth_quota(info_.bandwidth_quota);
        info->set_max_packet_size(info_.max_packet_size);
        info->set_min_packet_size(info_.min_packet_size);
        info->set_average_packet_size(info_.average_packet_size);
        info->set_error_nr(info_.error_nr);

        pthread_spin_unlock(&server_lock_);

        boost::function<void (const mdt::LogSchedulerService::GetNodeListRequest*,
                              mdt::LogSchedulerService::GetNodeListResponse*,
                              bool, int)> callback =
                boost::bind(&AgentImpl::GetServerAddrCallback,
                            this, _1, _2, _3, _4, service);
        rpc_client_->AsyncCall(service, &mdt::LogSchedulerService::LogSchedulerService_Stub::GetNodeList,
                               req, resp, callback);
        server_addr_event_.Wait();
        sleep(10);
    }
}

int AgentImpl::Init() {
    // open leveldb
    log_options_.db_type = DISKDB;
    log_options_.db_dir = FLAGS_db_dir;
    leveldb::Options options;
    options.create_if_missing = true;
    leveldb::Status status = leveldb::DB::Open(options, log_options_.db_dir.c_str(), &log_options_.db);
    if (!status.ok()) {
        return -1;
    }

    // parse log dir
    std::vector<std::string> log_vec;
    ParseLogDir(log_vec);
    // add watch event
    for (uint32_t i = 0; i < log_vec.size(); i++) {
        AddWatchPath(log_vec[i]);
    }

    return 0;
}

// parse log dir, watch_log_dir=/root/xxx1/;/root/xxx2;/tmp/xxx3
void AgentImpl::ParseLogDir(std::vector<std::string>& log_vec) {
    std::vector<std::string> tmp_vec;
    boost::split(tmp_vec, FLAGS_watch_log_dir, boost::is_any_of(";,: "));

    for (uint32_t i = 0; i < tmp_vec.size(); i++) {
        if (access(tmp_vec[i].c_str(), F_OK) == 0) {
            log_vec.push_back(tmp_vec[i]);
            VLOG(30) << "watch log dir " << tmp_vec[i];
        }
    }
    return;
}

void* WatchThreadWrapper(void* arg) {
    FileSystemInotify* fs_inotify = (FileSystemInotify*)arg;
    fs_inotify->agent->WatchLogDir(fs_inotify);
    return NULL;
}

int AgentImpl::WaitInotifyFDReadable(int fd) {
    fd_set rfds;
    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);
    return select(FD_SETSIZE, &rfds, NULL, NULL, NULL);
}

int AgentImpl::FreadEvent(void* dest, size_t size, FILE* file) {
    char* buf = (char*)dest;
    while (size) {
        int n = fread(buf, 1, size, file);
        if (n == 0) {
            return -1;
        }
        size -= n;
        buf += n;
    }
    return 0;
}

void AgentImpl::WatchLogDir(FileSystemInotify* fs_inotify) {
    while (1) {
        VLOG(35) << "step into watch dir phase, dir " << fs_inotify->log_dir;
        if (fs_inotify->stop) {
            break;
        }

        inotify_event event;
        char filename[256];

        if (FreadEvent(&event, sizeof(event), fs_inotify->inotify_FD) == -1) {
            LOG(WARNING) << "inotify FD " << fs_inotify->log_dir << ", read failed";
            sleep(1);
            continue;
        }
        if (event.len) {
            FreadEvent(filename, event.len, fs_inotify->inotify_FD);
        }

        /*
        if (WaitInotifyFDReadable(fs_inotify->inotify_fd) < 0) {
            VLOG(30) << "inotify fd " << fs_inotify->inotify_fd << ", select failed";
            continue;
        }
        int length = read(fs_inotify->inotify_fd, &event, sizeof(event));
        if (length < 0) {
            LOG(WARNING) << "read event: " << fs_inotify->log_dir << ", errno " << errno;
            continue;
        }

        int namelen = 0;
        if (event.len) {
            namelen = read(fs_inotify->inotify_fd, filename, event.len);
            if (namelen < 0) {
                LOG(WARNING) << "read event file name: " << fs_inotify->log_dir << ", fail";
                continue;
            }
        }
        */
        for (uint32_t i = 0; i < 21; ++i) {
            if (event.mask & event_masks[i].flag) {
                VLOG(35) << "file " << filename << " has event: " << event_masks[i].name;
            }
        }
        // parse event
        if (event.mask & (IN_CREATE | IN_MOVED_TO)) {
            AddWriteEvent(fs_inotify->log_dir, filename, &event);
        //} else if (event.mask & (IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF| IN_MOVED_FROM | IN_CLOSE_WRITE)) {
        } else if (event.mask & (IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF| IN_MOVED_FROM)) {
            DeleteWatchEvent(fs_inotify->log_dir, filename, &event);
        } else if (event.mask & (IN_MODIFY)) {
            AddWriteEvent(fs_inotify->log_dir, filename, &event);
        } else {

        }
    }
}

// module_name_list=galaxy.INFO.;rtg.INFO.;tabletnode.INFO.;mdt.INFO.
void AgentImpl::ParseModuleName(const std::string& filename, std::string* module_name) {
    std::vector<std::string> tmp_vec;
    boost::split(tmp_vec, FLAGS_module_name_list, boost::is_any_of(";,: "));

    for (uint32_t i = 0; i < tmp_vec.size(); i++) {
        std::string& tmpname = tmp_vec[i];
        if ((filename.size() >= tmpname.size()) &&
            (filename.substr(0, tmpname.size()) == tmpname)) {
            *module_name = tmpname;
            return;
        }
    }
    if (module_name->size() == 0) {
        *module_name = "all";
    }
    return;
}

int AgentImpl::FilterFileByMoudle(const std::string& filename, std::string* expect_module_name) {
    pthread_spin_lock(&lock_);
    std::map<std::string, std::string>::iterator it = module_file_set_.begin();
    for (; it != module_file_set_.end(); ++it) {
        const std::string& module_file_name = it->first;
        const std::string& module_name = it->second;
        if (filename.find(module_file_name) != std::string::npos) {
            *expect_module_name = module_name;
            break;
        }
    }
    pthread_spin_unlock(&lock_);
    return 0;
}

int AgentImpl::AddWriteEvent(const std::string& logdir, const std::string& filename, inotify_event* event) {
    std::string module_name;
    //ParseModuleName(filename, &module_name);
    FilterFileByMoudle(filename, &module_name);
    VLOG(35) << "write event, module name " << module_name << ", log dir " << logdir;
    if (module_name.size() == 0) {
        VLOG(35) << "dir " << filename << ", no module match";
        return -1;
    }

    LogStream* stream = NULL;
    pthread_spin_lock(&lock_);
    std::map<std::string, LogStream*>::iterator it = log_streams_.find(module_name);
    if (it != log_streams_.end()) {
        stream = log_streams_[module_name];
    } else {
        stream = new LogStream(module_name, log_options_, rpc_client_, &server_lock_, &info_);
        log_streams_[module_name] = stream;
    }
    pthread_spin_unlock(&lock_);

    stream->AddWriteEvent(logdir + "/" + filename);
    return 0;
}

int AgentImpl::DeleteWatchEvent(const std::string& logdir, const std::string& filename, inotify_event* event) {
    std::string module_name;
    //ParseModuleName(filename, &module_name);
    FilterFileByMoudle(filename, &module_name);
    VLOG(35) << "delete event, module name " << module_name << ", log dir " << logdir;
    if (module_name.size() == 0) {
        VLOG(35) << "dir " << filename << ", no module match";
        return -1;
    }

    LogStream* stream = NULL;
    pthread_spin_lock(&lock_);
    std::map<std::string, LogStream*>::iterator it = log_streams_.find(module_name);
    if (it != log_streams_.end()) {
        stream = log_streams_[module_name];
    } else {
        stream = new LogStream(module_name, log_options_, rpc_client_, &server_lock_, &info_);
        log_streams_[module_name] = stream;
    }
    pthread_spin_unlock(&lock_);

    stream->DeleteWatchEvent(logdir + "/" + filename, true);
    return 0;
}

void AgentImpl::DestroyWatchPath(FileSystemInotify* fs_inotify) {
    if (fs_inotify->stop == false) {
        fs_inotify->stop = true;
        pthread_join(fs_inotify->tid, NULL);
        VLOG(30) << "stop watch thread";
    }
    if (fs_inotify->watch_fd >= 0) {
        inotify_rm_watch(fs_inotify->inotify_fd, fs_inotify->watch_fd);
        VLOG(30) << "remove watch fd";
    }
    if (fs_inotify->inotify_fd >= 0) {
        close(fs_inotify->inotify_fd);
        VLOG(30) << "close inotify fd";
    }
    if (fs_inotify->inotify_FD) {
        fclose(fs_inotify->inotify_FD);
        VLOG(30) << "fclose inotify FD";
    }
    delete fs_inotify;
}

int AgentImpl::AddWatchPath(const std::string& dir) {
    FileSystemInotify* fs_inotify = new FileSystemInotify;
    fs_inotify->log_dir = dir;
    fs_inotify->agent = this;

    fs_inotify->inotify_fd = inotify_init();
    if (fs_inotify->inotify_fd < 0) {
        VLOG(30) << "init inotify fd error";
        DestroyWatchPath(fs_inotify);
        return -1;
    }

    fs_inotify->inotify_flag = IN_CREATE | IN_MOVED_TO |
                     IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF| IN_MOVED_FROM | IN_CLOSE_WRITE |
                     IN_MODIFY |
                     IN_ATTRIB;
    fs_inotify->watch_fd = inotify_add_watch(fs_inotify->inotify_fd, dir.c_str(), fs_inotify->inotify_flag);
    if (fs_inotify->watch_fd < 0) {
        DestroyWatchPath(fs_inotify);
        return -1;
    }
    if ((fs_inotify->inotify_FD = fdopen(fs_inotify->inotify_fd, "r")) == NULL) {
        DestroyWatchPath(fs_inotify);
        return -1;
    }

    VLOG(30) << "add watch addr " << dir << ", watch fd " << fs_inotify->watch_fd;
    fs_inotify->stop = false;
    pthread_create(&fs_inotify->tid, NULL, WatchThreadWrapper, fs_inotify);

    // add to management list
    pthread_spin_lock(&lock_);
    std::map<std::string, FileSystemInotify*>::iterator it = inotify_.find(dir);
    if (it != inotify_.end()) {
        pthread_spin_unlock(&lock_);

        DestroyWatchPath(fs_inotify);
        LOG(WARNING) << "dir " << dir << ", has been watch";
        return -1;
    } else {
        inotify_[dir] = fs_inotify;
    }
    pthread_spin_unlock(&lock_);
    return 0;
}

// log_name := module name's log file name prefix
int AgentImpl::AddWatchModuleStream(const std::string& module_name, const std::string& log_name) {
    VLOG(30) << "add module stream, module name " << module_name << ", file name " << log_name;
    LogStream* stream = NULL;
    pthread_spin_lock(&lock_);
    std::map<std::string, LogStream*>::iterator it = log_streams_.find(module_name);
    if (it != log_streams_.end()) {
        stream = log_streams_[module_name];
    } else {
        stream = new LogStream(module_name, log_options_, rpc_client_, &server_lock_, &info_);
        log_streams_[module_name] = stream;
    }

    std::map<std::string, std::string>::iterator file_it = module_file_set_.find(log_name);
    if (file_it == module_file_set_.end()) {
        module_file_set_[log_name] = module_name;
        stream->AddTableName(log_name);
    }
    pthread_spin_unlock(&lock_);
    return 0;
}

///////////////////////////////////////////
/////       rpc method                /////
///////////////////////////////////////////
void AgentImpl::Echo(::google::protobuf::RpcController* controller,
                     const mdt::LogAgentService::EchoRequest* request,
                     mdt::LogAgentService::EchoResponse* response,
                     ::google::protobuf::Closure* done) {
    LOG(INFO) << "Echo: " << request->message();
    done->Run();
}

void AgentImpl::RpcAddWatchPath(::google::protobuf::RpcController* controller,
                                const mdt::LogAgentService::RpcAddWatchPathRequest* request,
                                mdt::LogAgentService::RpcAddWatchPathResponse* response,
                                ::google::protobuf::Closure* done) {
    if (AddWatchPath(request->watch_path()) < 0) {
        response->set_status(mdt::LogAgentService::kRpcError);
        LOG(WARNING) << "add watch event in dir " << request->watch_path() << " failed";
    } else {
        response->set_status(mdt::LogAgentService::kRpcOk);
    }
    done->Run();
}

void AgentImpl::RpcAddWatchModuleStream(::google::protobuf::RpcController* controller,
                                        const mdt::LogAgentService::RpcAddWatchModuleStreamRequest* request,
                                        mdt::LogAgentService::RpcAddWatchModuleStreamResponse* response,
                                        ::google::protobuf::Closure* done) {
    const std::string& module_name = request->production_name();
    const std::string& log_name = request->log_name(); // use for match log file name, if not match, discard such log file

    if (AddWatchModuleStream(module_name, log_name) < 0) {
        response->set_status(mdt::LogAgentService::kRpcError);
        VLOG(35) << "add watch module " << module_name << " failed";
    } else {
        response->set_status(mdt::LogAgentService::kRpcOk);
    }
    done->Run();
}

void AgentImpl::RpcStoreSpan(::google::protobuf::RpcController* controller,
                             const mdt::LogAgentService::RpcStoreSpanRequest* request,
                             mdt::LogAgentService::RpcStoreSpanResponse* response,
                             ::google::protobuf::Closure* done) {
    done->Run();
}

}
}


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

<pma_xml_export version="1.0" xmlns:pma="http://www.phpmyadmin.net/some_doc_url/">

    <database name="aisel">

            <column name="id">19210</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице A1</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2921</column>

            <column name="id">19211</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице A2</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2921</column>

            <column name="id">19212</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице A3</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2921</column>

            <column name="id">19221</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице B</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2922</column>

            <column name="id">19222</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице B</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2922</column>

            <column name="id">1923</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице C</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2923</column>

            <column name="id">1924</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице D</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2924</column>

            <column name="id">1925</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице E</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2925</column>

            <column name="id">1926</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице F</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2926</column>

            <column name="id">1927</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице G</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2927</column>

            <column name="id">1928</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице H</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2928</column>

            <column name="id">1929</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице I</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2929</column>

            <column name="id">1930</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице J</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2930</column>

            <column name="id">1931</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице K</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2931</column>

            <column name="id">1932</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице L</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2932</column>

            <column name="id">1933</column>
            <column name="locale">en</column>
            <column name="title">Отзыв о странице M</column>
            <column name="content">Товарищи! постоянный количественный рост и сфера нашей активности требуют от нас анализа существенных финансовых и административных условий. Значимость этих проблем настолько очевидна, что сложившаяся структура организации позволяет выполнять важные задания по разработке модели развития. Идейные соображения высшего порядка, а также начало повседневной работы по формированию позиции в значительной степени обуславливает создание соответствующий условий активизации.</column>
            <column name="status">1</column>
            <column name="user">3000</column>
            <column name="page">2933</column>

    </database>
</pma_xml_export>


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2013 Live Networks, Inc.  All rights reserved.
// RTP sink for 'ADUized' MP3 frames ("mpa-robust")
// Implementation

#include "MP3ADURTPSink.hh"

MP3ADURTPSink::MP3ADURTPSink(UsageEnvironment& env, Groupsock* RTPgs,
			     unsigned char RTPPayloadType)
  : AudioRTPSink(env, RTPgs, RTPPayloadType, 90000, "MPA-ROBUST") {
}

MP3ADURTPSink::~MP3ADURTPSink() {
}

MP3ADURTPSink*
MP3ADURTPSink::createNew(UsageEnvironment& env, Groupsock* RTPgs,
			 unsigned char RTPPayloadType) {
  return new MP3ADURTPSink(env, RTPgs, RTPPayloadType);
}

static void badDataSize(UsageEnvironment& env, unsigned numBytesInFrame) {
  env << "MP3ADURTPSink::doSpecialFrameHandling(): invalid size ("
      << numBytesInFrame << ") of non-fragmented input ADU!\n";
}

void MP3ADURTPSink::doSpecialFrameHandling(unsigned fragmentationOffset,
					   unsigned char* frameStart,
					   unsigned numBytesInFrame,
					   struct timeval framePresentationTime,
					   unsigned numRemainingBytes) {
  // If this is the first (or only) fragment of an ADU, then
  // check the "ADU descriptor" (that should be at the front) for validity:
  if (fragmentationOffset == 0) {
    unsigned aduDescriptorSize;

    if (numBytesInFrame < 1) {
      badDataSize(envir(), numBytesInFrame);
      return;
    }
    if (frameStart[0]&0x40) {
      // We have a 2-byte ADU descriptor
      aduDescriptorSize = 2;
      if (numBytesInFrame < 2) {
	badDataSize(envir(), numBytesInFrame);
	return;
      }
      fCurADUSize = ((frameStart[0]&~0xC0)<<8) | frameStart[1];
    } else {
      // We have a 1-byte ADU descriptor
      aduDescriptorSize = 1;
      fCurADUSize = frameStart[0]&~0x80;
    }

    if (frameStart[0]&0x80) {
      envir() << "Unexpected \"C\" bit seen on non-fragment input ADU!\n";
      return;
    }

    // Now, check whether the ADU size in the ADU descriptor is consistent
    // with the total data size of (all fragments of) the input frame:
    unsigned expectedADUSize =
      fragmentationOffset + numBytesInFrame + numRemainingBytes
      - aduDescriptorSize;
    if (fCurADUSize != expectedADUSize) {
      envir() << "MP3ADURTPSink::doSpecialFrameHandling(): Warning: Input ADU size "
	      << expectedADUSize << " (=" << fragmentationOffset
	      << "+" << numBytesInFrame << "+" << numRemainingBytes
	      << "-" << aduDescriptorSize
	      << ") did not match the value (" << fCurADUSize
	      << ") in the ADU descriptor!\n";
      fCurADUSize = expectedADUSize;
    }
  } else {
    // This is the second (or subsequent) fragment.
    // Insert a new ADU descriptor:
    unsigned char aduDescriptor[2];
    aduDescriptor[0] = 0xC0|(fCurADUSize>>8);
    aduDescriptor[1] = fCurADUSize&0xFF;
    setSpecialHeaderBytes(aduDescriptor, 2);
  }

  // Important: Also call our base class's doSpecialFrameHandling(),
  // to set the packet's timestamp:
  MultiFramedRTPSink::doSpecialFrameHandling(fragmentationOffset,
					     frameStart, numBytesInFrame,
					     framePresentationTime,
					     numRemainingBytes);
}

unsigned MP3ADURTPSink::specialHeaderSize() const {
  // Normally there's no special header.
  // (The "ADU descriptor" is already present in the data.)
  unsigned specialHeaderSize = 0;

  // However, if we're about to output the second (or subsequent) fragment
  // of a fragmented ADU, then we need to insert a new ADU descriptor at
  // the front of the packet:
  if (curFragmentationOffset() > 0) {
    specialHeaderSize = 2;
  }

  return specialHeaderSize;
}


text:
from msrest.serialization import Model
from msrest.exceptions import HttpOperationError

class ErrorDetails(Model):
    """Error details.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar code: The error code.
    :vartype code: str
    :ivar http_status_code: The HTTP status code.
    :vartype http_status_code: str
    :ivar message: The error message.
    :vartype message: str
    :ivar details: The error details.
    :vartype details: str
    """

    _validation = {
        'code': {'readonly': True},
        'http_status_code': {'readonly': True},
        'message': {'readonly': True},
        'details': {'readonly': True},
    }

    _attribute_map = {
        'code': {'key': 'Code', 'type': 'str'},
        'http_status_code': {'key': 'HttpStatusCode', 'type': 'str'},
        'message': {'key': 'Message', 'type': 'str'},
        'details': {'key': 'Details', 'type': 'str'},
    }

    def __init__(self):
        super(ErrorDetails, self).__init__()
        self.code = None
        self.http_status_code = None
        self.message = None
        self.details = None

class ErrorDetailsException(HttpOperationError):
    """Server responsed with exception of type: 'ErrorDetails'.

    :param deserialize: A deserializer
    :param response: Server response to be deserialized.
    """

    def __init__(self, deserialize, response, *args):

        super(ErrorDetailsException, self).__init__(deserialize, response, 'ErrorDetails', *args)


text:
#ifndef DD_RENDERER
#define DD_RENDERER

#define use_speed_ 0

#include <cv.h>
#include <highgui.h>
#include "HandSynth.hpp"

namespace deformable_depth
{
  using cv::VideoCapture;
  using cv::Mat_;
  using cv::Mat;
  using cv::MatND;

  class Renderer
  {
  private:
    HandRenderer hand;
  public:
    Renderer();
    HandData doIteration(Mat&Zrnd,Mat&RGBrnd);
    HandRenderer& getHand();
  protected:
    void draw();
    void doOpenGL(Mat&Zrnd,Mat&RGBrnd);
  };

  // GL functions to read the rendered data back to OpenCV.
  void gl_get_camera_parameter_from_perspective_matrix(
    double & fovy_rad,
    double & fovx_rad,
    double & clip_min,
    double & clip_max);
  void gl_cv_read_buffers(Mat&Zrnd,Mat&RGBrnd,int W,int H);
  void gl_cv_read_buffers_RGB(Mat&RGBrnd,int W,int H);
  void gl_cv_read_buffers_Z(Mat&Zrnd,int W,int H);
  // GLUT utility functions
  void reshape(int width, int height);
  void init_glut(int argc, char**argv, void (* fn_render)( void ));
}

#endif


text:
@extends("layout.main")

@section("content")

        @foreach($notices as $notice)

{{$notice->title}}

{{$notice->content}}

        @endforeach

@endsection


text:
package marc.henrard.book.algorithmicdifferentiation.type;

/**
 * Enumeration of the operation types currently available for {@link DoubleAad}.
 */
public enum OperationTypeAad {

  /** Input with respect to which the derivatives are computed. */
  INPUT,
  /** Used for manual code providing AD results in a Automatic AD setting. */
  MANUAL,
  /** Addition of two AAD doubles. */
  ADDITION,
  /** Addition of one AAD doubles with a constant double. */
  ADDITION1,
  /** Subtraction of two AAD doubles. */
  SUBTRACTION,
  /** Multiplication of two AAD doubles. */
  MULTIPLICATION,
  /** Multiplication of one AAD double with a constant double. */
  MULTIPLICATION1,
  /** Division of two AAD doubles. */
  DIVISION,
  /** Sine of a AAD double. */
  SIN,
  /** Cosine of a AAD double. */
  COS,
  /** Exponential of a AAD double. */
  EXP,
  /** Logarithm of a AAD double. */
  LOG,
  /** Square root of a AAD double. */
  SQRT,
  /** Power of a AAD double by another AAD double. */
  POW,
  /** Power of a AAD double with a standard double. */
  POW1,
  /** Normal cumulative density function of a AAD double. */
  NORMALCDF

}


text:
package org.apache.dubbo.config.spring.extension;

import org.apache.dubbo.common.extension.ExtensionFactory;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashSet;

import com.alibaba.spring.util.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Set;

/**
 * SpringExtensionFactory
 */
public class SpringExtensionFactory implements ExtensionFactory {
    private static final Logger logger = LoggerFactory.getLogger(SpringExtensionFactory.class);

    private static final Set<ApplicationContext> CONTEXTS = new ConcurrentHashSet<ApplicationContext>();

    public static void addApplicationContext(ApplicationContext context) {
        CONTEXTS.add(context);
        if (context instanceof ConfigurableApplicationContext) {
            ((ConfigurableApplicationContext) context).registerShutdownHook();
        }
    }

    public static void removeApplicationContext(ApplicationContext context) {
        CONTEXTS.remove(context);
    }

    public static Set<ApplicationContext> getContexts() {
        return CONTEXTS;
    }

    // currently for test purpose
    public static void clearContexts() {
        CONTEXTS.clear();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getExtension(Class<T> type, String name) {

        //SPI should be get from SpiExtensionFactory
        if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
            return null;
        }

        for (ApplicationContext context : CONTEXTS) {
            T bean = BeanFactoryUtils.getOptionalBean(context, name, type);
            if (bean != null) {
                return bean;
            }
        }

        //logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " + type.getName());

        return null;
    }
}


text:
var searchData=
[
  ['hackedbaseactortest_2ecs',['HackedBaseActorTest.cs',['../_hacked_base_actor_test_8cs.html',1,'']]],
  ['helloworldcontroller_2ecs',['HelloWorldController.cs',['../_hello_world_controller_8cs.html',1,'']]],
  ['hostconfiguration_2ecs',['HostConfiguration.cs',['../_host_configuration_8cs.html',1,'']]]
];


text:
package com.gemstone.gemfire.internal.util.concurrent;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ConcurrentMap;

import junit.framework.TestCase;

import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.internal.concurrent.CustomEntryConcurrentHashMap;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class ConcurrentHashMapIteratorTest extends TestCase {

  public void test() throws InterruptedException {

    //Apparently, we need a distributed system to create
    //this CHM, because it's locks use DS properties.
    Properties props = new Properties();
    props.setProperty("mcast-port", "0");
    DistributedSystem.connect(props);
    java.util.concurrent.ConcurrentHashMap baselineMap = new java.util.concurrent.ConcurrentHashMap();
    CustomEntryConcurrentHashMap testMap = new CustomEntryConcurrentHashMap();
    Map initialSet;

    createBaseline(baselineMap, testMap, 0, 100);
    assertEquals(baselineMap, testMap);
    initialSet = new HashMap(baselineMap);

//    putter = new Putter(baselineMap, testMap, 1000, 2000);
//    putter.run();

    RandomMutations randomer = new RandomMutations(baselineMap, testMap, 1001, 50000);
    randomer.start();

    for(int i = 0; i < 1000; i++) {
      checkForInitialSet(i, testMap, initialSet);
    }

    randomer.cancel();

    assertEquals(baselineMap, testMap);
  }

  private void checkForInitialSet(int i, ConcurrentMap testMap, Map initialSet) {
    HashSet found = new HashSet(testMap.values());
    if(!found.containsAll(initialSet.values())) {
      HashSet missed = new HashSet(initialSet.values());
      missed.removeAll(found);
      fail("On run " + i + " did not find these elements of the initial set using the iterator " + missed);
    }
  }

  public void createBaseline(ConcurrentMap baselineMap, ConcurrentMap testMap,
      int start, int end) {
    for(int i = start; i < end; i++) {
      baselineMap.put(i, i);
      testMap.put(i, i);
    }
  }

  public static class RandomMutations extends Thread {
    private final ConcurrentMap baselineMap;
    private final ConcurrentMap testMap;
    private int start;
    private int end;
    private volatile boolean done;

    public RandomMutations(ConcurrentMap baselineMap, ConcurrentMap testMap, int start, int end) {
      this.baselineMap = baselineMap;
      this.testMap = testMap;
      this.start = start;
      this.end = end;
    }

    public void run() {
      Random random = new Random();
      while(!done) {
        int key = random.nextInt(end - start) + start;
        boolean put = random.nextBoolean();
        if(put) {
          baselineMap.put(key,key);
          testMap.put(key, key);
        } else {
          baselineMap.remove(key);
          testMap.remove(key);
        }
      }
    }

    public void cancel() throws InterruptedException {
      this.done = true;
      this.join();
    }
  }

}


text:
<?php

declare(strict_types=1);

use Laminas\ConfigAggregator\ArrayProvider;
use Laminas\ConfigAggregator\ConfigAggregator;
use Laminas\ConfigAggregator\PhpFileProvider;

// To enable or disable caching, set the `ConfigAggregator::ENABLE_CACHE` boolean in
// `config/autoload/local.php`.
$cacheConfig = [
    'config_cache_path' => 'data/cache/app_config.php',
];

$aggregator = new ConfigAggregator([
    Mezzio\Hal\ConfigProvider::class,
    Mezzio\Authorization\Rbac\ConfigProvider::class,
    Mezzio\Authorization\ConfigProvider::class,
    Mezzio\Authentication\Session\ConfigProvider::class,
    Mezzio\ProblemDetails\ConfigProvider::class,
    Laminas\Diactoros\ConfigProvider::class,
    Phly\EventDispatcher\ConfigProvider::class,
    Mezzio\Authentication\ConfigProvider::class,
    Mezzio\Session\Cache\ConfigProvider::class,
    Mezzio\Plates\ConfigProvider::class,
    Laminas\Paginator\ConfigProvider::class,
    Laminas\InputFilter\ConfigProvider::class,
    Laminas\Filter\ConfigProvider::class,
    Laminas\Validator\ConfigProvider::class,
    Mezzio\Session\ConfigProvider::class,
    Mezzio\Csrf\ConfigProvider::class,
    Mezzio\ConfigProvider::class,
    Laminas\HttpHandlerRunner\ConfigProvider::class,
    Mezzio\Helper\ConfigProvider::class,
    Mezzio\Router\ConfigProvider::class,
    Mezzio\Router\FastRouteRouter\ConfigProvider::class,
    Mezzio\Swoole\ConfigProvider::class,

    // Conditional, as it will not be used in production
    class_exists(Mezzio\Tooling\ConfigProvider::class)
        ? Mezzio\Tooling\ConfigProvider::class
        : function (): array {
            return [];
        },

    // App-specific modules
    Mwop\App\ConfigProvider::class,
    Mwop\ActivityPub\ConfigProvider::class,
    Mwop\Art\ConfigProvider::class,
    Mwop\Blog\ConfigProvider::class,
    Mwop\Comics\ConfigProvider::class,
    Mwop\Console\ConfigProvider::class,
    Mwop\Contact\ConfigProvider::class,
    Mwop\Cron\ConfigProvider::class,
    Mwop\Feed\ConfigProvider::class,
    Mwop\Github\ConfigProvider::class,
    Mwop\Hooks\ConfigProvider::class,
    Mwop\Mastodon\ConfigProvider::class,
    Mwop\Now\ConfigProvider::class,

    // Include cache configuration
    new ArrayProvider($cacheConfig),

    // Load application config in a pre-defined order in such a way that local settings
    // overwrite global settings. (Loaded as first to last):
    //   - `global.php`
    //   - `*.global.php`
    //   - `local.php`
    //   - `*.local.php`
    new PhpFileProvider('config/autoload/{{,*.}global,{,*.}local}.php'),

    // Load development config if it exists
    new PhpFileProvider('config/development.config.php'),
], $cacheConfig['config_cache_path']);

return $aggregator->getMergedConfig();


text:
module.exports = function(mixdown, options) {
  this.mixdown = mixdown;
  this.options = options;

  // TODO: add support to override options from argv

  // Start doing stuff.  This should start service or resume the service if stop was previously called.
  this.start = function(done) {

    done();
  };

  // stop running the app.  stop() is responsible for pausing processing, saving state, or whatever so that it can pick up where it left off.
  // This is called on shutdown and also called on reload from config.
  this.stop = function(done) {
    done();
  };
};


text:
package net.spy.memcached;

import java.util.concurrent.Callable;

import net.spy.memcached.transcoders.LongTranscoder;
import net.spy.test.SyncThread;

/**
 * Test the CAS mutator.
 */
public class CASMutatorTest extends ClientBaseCase {

	private CASMutation<Long> mutation;
	private CASMutator<Long> mutator;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		mutation=new CASMutation<Long>() {
			public Long getNewValue(Long current) {
				return current+1;
			}
		};
		mutator=new CASMutator<Long>(client, new LongTranscoder(), 50);
	}

	public void testDefaultConstructor() {
		// Just validate that this doesn't throw an exception.
		new CASMutator<Long>(client, new LongTranscoder());
	}

	public void testConcurrentCAS() throws Throwable {
		int num=SyncThread.getDistinctResultCount(20, new Callable<Long>(){
			public Long call() throws Exception {
				return mutator.cas("test.cas.concurrent", 0L, 0, mutation);
			}});
		assertEquals(20, num);
	}

	public void testIncorrectTypeInCAS() throws Throwable {
		// Stick something for this CAS in the cache.
		client.set("x", 0, "not a long");
		try {
			Long rv=mutator.cas("x", 1L, 0, mutation);
			fail("Expected RuntimeException on invalid type mutation, got "
				+ rv);
		} catch(RuntimeException e) {
			assertEquals("Couldn't get a CAS in 50 attempts", e.getMessage());
		}
	}

	public void testCASValueToString() {
		CASValue<String> c=new CASValue<String>(717L, "hi");
		assertEquals("{CasValue 717/hi}", c.toString());
	}
}


text:
module.exports = {
  db: 'localhost',

  localAuth: true,
  sessionSecret: "Your Session Secret goes here",

  mailgun: {
    login: 'Your Mailgun SMTP Username',
    password: 'Your Mailgun SMTP Password'
  },

  sendgrid: {
    user: 'Your SendGrid Username',
    password: 'Your SendGrid Password'
  },

  nyt: {
    key: 'Your New York Times API Key'
  },

  lastfm: {
    api_key: 'Your API Key',
    secret: 'Your API Secret'
  },

  facebookAuth: true,
  facebook: {
    clientID: 'Your App ID',
    clientSecret: 'Your App Secret',
    callbackURL: '/auth/facebook/callback',
    passReqToCallback: true
  },

  githubAuth: true,
  github: {
    clientID: 'Your Client ID',
    clientSecret: 'Your Client Secret',
    callbackURL: '/auth/github/callback',
    passReqToCallback: true
  },

  twitterAuth: true,
  twitter: {
    consumerKey: 'Your Consumer Key',
    consumerSecret: 'Your Consumer Secret',
    callbackURL: '/auth/twitter/callback',
    passReqToCallback: true
  },

  googleAuth: true,
  google: {
    clientID: 'Your Client ID',
    clientSecret: 'Your Client Secret',
    callbackURL: '/auth/google/callback',
    passReqToCallback: true
  },

  steam: {
    apiKey: 'Your Steam API Key'
  },

  twilio: {
    sid: 'Your Account SID',
    token: 'Your Auth Token'
  },

  tumblr: {
    consumerKey: 'Your Consumer Key',
    consumerSecret: 'Your Consumer Secret',
    callbackURL: '/auth/tumblr/callback'
  },

  foursquare: {
    clientId: 'Your Client ID',
    clientSecret: 'Your Client Secret',
    redirectUrl: 'http://localhost:3000/auth/foursquare/callback'
  },

  venmo: {
    clientId: 'Your Venmo Client ID',
    clientSecret: 'Your Venmo Client Secret',
    redirectUrl: 'http://localhost:3000/auth/venmo/callback'
  },

  paypal: {
    host: 'api.sandbox.paypal.com', // or api.paypal.com
    client_id: 'Your Client ID',
    client_secret: 'Your Client Secret',
    returnUrl: 'http://localhost:3000/api/paypal/success',
    cancelUrl: 'http://localhost:3000/api/paypal/cancel'
  }
};


text:
package org.mapfish.print.http;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.AbstractClientHttpResponse;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;

/**
 * Creates tasks for caching Http Requests that can be run simultaneously.
 */
public final class HttpRequestCache {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestCache.class);

    private final List<CachedClientHttpRequest> requests = new ArrayList<>();

    private final File temporaryDirectory;

    private final MetricRegistry registry;

    private boolean cached = false;

    /**
     * Constructor.
     *
     * @param temporaryDirectory temporary directory for cached requests
     * @param registry the metric registry
     */
    public HttpRequestCache(final File temporaryDirectory, final MetricRegistry registry) {
        this.temporaryDirectory = temporaryDirectory;
        this.registry = registry;
    }

    private CachedClientHttpRequest save(final CachedClientHttpRequest request) {
        this.requests.add(request);
        return request;
    }

    /**
     * Register a http request for caching. Returns a handle to the HttpRequest that will be cached.
     *
     * @param originalRequest the original request
     * @return the cached http request
     */
    public ClientHttpRequest register(final ClientHttpRequest originalRequest) {
        return save(new CachedClientHttpRequest(originalRequest));
    }

    /**
     * Register a URI for caching. Returns a handle to the HttpRequest that will be cached.
     *
     * @param factory the request factory
     * @param uri the uri
     * @return the cached http request
     * @throws IOException in case of I/O errors
     */
    public ClientHttpRequest register(final MfClientHttpRequestFactory factory, final URI uri)
            throws IOException {
        return register(factory.createRequest(uri, HttpMethod.GET));
    }

    /**
     * Cache all requests at once.
     *
     * @param requestForkJoinPool request fork join pool
     */
    public void cache(final ForkJoinPool requestForkJoinPool) {
        if (!this.cached) {
            requestForkJoinPool.invokeAll(this.requests);
            this.cached = true;
        } else {
            LOGGER.warn("Attempting to cache twice!");
        }
    }

    private final class CachedClientHttpResponse extends AbstractClientHttpResponse {

        private final File cachedFile;
        private final HttpHeaders headers;
        private final int status;
        private final String statusText;
        private InputStream body;

        private CachedClientHttpResponse(final ClientHttpResponse originalResponse) throws IOException {
            this.headers = originalResponse.getHeaders();
            this.status = originalResponse.getRawStatusCode();
            this.statusText = originalResponse.getStatusText();
            this.cachedFile =
                    File.createTempFile("cacheduri", null, HttpRequestCache.this.temporaryDirectory);
            try (InputStream is = originalResponse.getBody()) {
                try (OutputStream os = new FileOutputStream(this.cachedFile)) {
                    IOUtils.copy(is, os);
                }
            }
        }

        @Override
        public InputStream getBody() throws IOException {
            if (this.body == null) {
                this.body = new FileInputStream(this.cachedFile);
            }
            return this.body;
        }

        @Override
        public HttpHeaders getHeaders() {
            return this.headers;
        }

        @Override
        public int getRawStatusCode() {
            return this.status;
        }

        @Override
        public String getStatusText() {
            return this.statusText;
        }

        @Override
        public void close() {
            if (this.body != null) {
                try {
                    this.body.close();
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }

    private final class CachedClientHttpRequest implements ClientHttpRequest, Callable<Void> {
        private final ClientHttpRequest originalRequest;
        private ClientHttpResponse response;

        private CachedClientHttpRequest(final ClientHttpRequest request) {
            this.originalRequest = request;
        }

        @Override
        public HttpMethod getMethod() {
            return this.originalRequest.getMethod();
        }

        @Override
        public URI getURI() {
            return this.originalRequest.getURI();
        }

        @Override
        public HttpHeaders getHeaders() {
            return this.originalRequest.getHeaders();
        }

        @Override
        public OutputStream getBody() {
            //body should be written before creating this object
            throw new UnsupportedOperationException();
        }

        @Override
        public ClientHttpResponse execute() {
            if (!HttpRequestCache.this.cached) {
                LOGGER.warn("Attempting to load cached URI before actual caching: " +
                                    this.originalRequest.getURI());
            } else if (this.response == null) {
                LOGGER.warn("Attempting to load cached URI from failed request: " +
                                    this.originalRequest.getURI());
            } else {
                LOGGER.debug("Loading cached URI resource " + this.originalRequest.getURI());
            }
            return this.response;
        }

        @Override
        public Void call() throws Exception {
            final String baseMetricName = HttpRequestCache.class.getName() + ".read." + getURI().getHost();
            final Timer.Context timerDownload = HttpRequestCache.this.registry.timer(baseMetricName).time();
            ClientHttpResponse originalResponse = null;
            try {
                originalResponse = this.originalRequest.execute();
                LOGGER.debug("Caching URI resource " + this.originalRequest.getURI());
                this.response = new CachedClientHttpResponse(originalResponse);
            } catch (IOException e) {
                LOGGER.error("Request failed " + this.originalRequest.getURI(), e);
                this.response = new AbstractClientHttpResponse() {
                    @Override
                    public HttpHeaders getHeaders() {
                        return new HttpHeaders();
                    }

                    @Override
                    public InputStream getBody() {
                        return StreamUtils.emptyInput();
                    }

                    @Override
                    public int getRawStatusCode() {
                        return 500;
                    }

                    @Override
                    public String getStatusText() {
                        return e.getMessage();
                    }

                    @Override
                    public void close() {
                    }
                };
                HttpRequestCache.this.registry.counter(baseMetricName + ".error").inc();
                throw e;
            } finally {
                if (originalResponse != null) {
                    originalResponse.close();
                }
                timerDownload.stop();
            }
            return null;
        }
    }
}


text:
import React = require("react");
// import {Group, Surface, Text, Shape, Transform, LinearGradient, ClippingRectangle } from "react-art";
import {wrapText} from "./string-functions";

/** An attempt to create a text wrapped component for React Art.
 *  Text will written in the middle of the specified rectangle.
 */
export const WrappedSvgText = (props: {
    text: string,
    /** Left coordinate */
    x: number,
    /** Top coordinate */
    y: number,
    /** Width of rectangle to write text */
    width: number,
    /** Height of rectangle to write text */
    height: number,
    /** Line-height to write text (for multiple lines) */
    lineHeight: number,
    /** Average width of font */
    fontWidth: number,
    fontWeight?: number,
    textColor?:string;
}) => {
    // return <Text key="DD" x={props.x} y={props.y} width={props.width} height={props.height}/>;
    const {text, height, width, x, y, lineHeight, fontWidth} = props;
    const texts = wrapText(text, Math.round(width / fontWidth * 1.7));
    const adjustedLineHeight = Math.min(lineHeight, height / texts.length);
    const yLine1 = height / 2 - (texts.length / 2 * adjustedLineHeight);
    const textColor = props.textColor || "black";
    return (
        <g>
            <defs>
                <clipPath key={"rect"} id={"clip"+text}>
                <rect
                    y={y}
                    x={x}
                    width={width}
                    height={height}/>
                </clipPath>
            </defs>
            {
        texts.map((str, i) => (
            <text key={"text" + i}
                y={y + yLine1 + adjustedLineHeight * i}
                x={x + 4}
                textAnchor="start"
                alignmentBaseline="hanging"
                width={width - 8}
                height={adjustedLineHeight}
                fontWeight={props.fontWeight}
                font={{ fontSize: fontWidth, fontFamily: "Arial", fontWeight: "600" }}
                fill={textColor}
                clipPath={"url(#clip" + text + ")"}
                strokeWidth={0}>{str}</text>))
    }
        </g >);
};


text:
import os
import yaml
import time
import functools
from datetime import datetime
import csv

from netmiko import ConnectHandler, __version__
from perf_utils import commands

import network_utilities

# import logging
# logging.basicConfig(filename='test.log', level=logging.DEBUG)
# logger = logging.getLogger("netmiko")

PRINT_DEBUG = False

def generate_csv_timestamp():
    """yyyy-MM-dd HH:mm:ss"""
    now = datetime.now()
    t_stamp = f"{now.year}-{now.month}-{now.day} {now.hour}:{now.minute}:{now.second}"
    return t_stamp

def write_csv(device_name, netmiko_results):
    results_file = "netmiko_performance.csv"
    file_exists = os.path.isfile(results_file)
    with open(results_file, "a") as csv_file:
        field_names = ["date", "netmiko_version", "device_name"] + list(
            netmiko_results.keys()
        )
        t_stamp = generate_csv_timestamp()
        csv_write = csv.DictWriter(csv_file, fieldnames=field_names)

        # Write the header only once
        if not file_exists:
            csv_write.writeheader()

        entry = {
            "date": t_stamp,
            "netmiko_version": __version__,
            "device_name": device_name,
        }

        for func_name, exec_time in netmiko_results.items():
            entry[func_name] = exec_time
        csv_write.writerow(entry)

def f_exec_time(func):
    @functools.wraps(func)
    def wrapper_decorator(*args, **kwargs):
        start_time = datetime.now()
        result = func(*args, **kwargs)
        end_time = datetime.now()
        time_delta = end_time - start_time
        print(f"{str(func)}: Elapsed time: {time_delta}")
        return (time_delta, result)

    return wrapper_decorator

def read_devices():
    f_name = os.environ.get("TEST_DEVICES", "test_devices.yml")
    with open(f_name) as f:
        return yaml.safe_load(f)

@f_exec_time
def connect(device):
    with ConnectHandler(**device) as conn:
        prompt = conn.find_prompt()
        PRINT_DEBUG and print(prompt)

@f_exec_time
def send_command_simple(device):
    with ConnectHandler(**device) as conn:
        platform = device["device_type"]
        cmd = commands(platform)["basic"]
        output = conn.send_command(cmd)
        PRINT_DEBUG and print(output)

@f_exec_time
def save_config(device):
    platform = device["device_type"]
    if "cisco_xr" in platform or "juniper" in platform:
        return
    with ConnectHandler(**device) as conn:
        platform = device["device_type"]
        output = conn.save_config()
        PRINT_DEBUG and print(output)

@f_exec_time
def send_config_simple(device):
    with ConnectHandler(**device) as conn:
        platform = device["device_type"]
        cmd = commands(platform)["config"][0]
        output = conn.send_config_set(cmd)
        PRINT_DEBUG and print(output)

@f_exec_time
def send_config_large_acl(device):

    # Results will be marginally distorted by generating the ACL here.
    device_type = device["device_type"]
    func_name = f"generate_{device_type}_acl"
    func = getattr(network_utilities, func_name)

    with ConnectHandler(**device) as conn:
        cfg = func(entries=100)
        output = conn.send_config_set(cfg)
        PRINT_DEBUG and print(output)

@f_exec_time
def cleanup(device):

    # Results will be marginally distorted by generating the ACL here.
    platform = device["device_type"]
    if "juniper_junos" in platform:
        remove_acl_cmd = "rollback 0"
    elif "hp_procurve" in platform:
        remove_acl_cmd = None
    elif "cisco_asa" in platform:
        remove_acl_cmd = "clear configure access-list netmiko_test_large_acl"
    elif "linux" in platform:
        # Do nothing i.e. no cleanup
        return
    else:
        base_acl_cmd = commands(platform)["config_long_acl"]["base_cmd"]
        remove_acl_cmd = f"no {base_acl_cmd}"
    cleanup_generic(device, remove_acl_cmd)

def cleanup_generic(device, command):
    if command is None:
        return
    with ConnectHandler(**device) as conn:
        output = conn.send_config_set(command)
        PRINT_DEBUG and print(output)

def remove_old_data(device_name):
    results_file = "netmiko_performance.csv"
    entries = []
    with open(results_file) as f:
        read_csv = csv.DictReader(f)
        for entry in read_csv:
            entry = dict(entry)
            version, device = entry["netmiko_version"], entry["device_name"]
            if (
                version != __version__ and device == device_name
            ) or device_name != device:
                entries.append(entry)

    with open(results_file, "w", newline="") as csv_file:
        field_names = list(entries[0].keys())
        csv_write = csv.DictWriter(csv_file, fieldnames=field_names)
        csv_write.writeheader()
        csv_write.writerows(entries)

def main():
    PASSWORD = os.environ["NETMIKO_PASSWORD"]
    HP_PASSWORD = os.environ["HPE_PASSWORD"]

    devices = read_devices()
    print("\n\n")
    for dev_name, params in devices.items():
        remove_old_data(dev_name)
        dev_dict = params["device"]
        if dev_name != "linux_srv1":
            continue
        # if dev_name != "cisco_xr_azure":
        #    continue
        print("-" * 80)
        print(f"Device name: {dev_name}")
        print("-" * 12)

        dev_dict["password"] = PASSWORD
        if dev_name == "cisco_asa":
            dev_dict["secret"] = PASSWORD
        elif dev_name == "hp_procurve":
            dev_dict["password"] = HP_PASSWORD

        # Run tests
        operations = [
            "connect",
            "send_command_simple",
            # "save_config",
            "send_config_simple",
            "send_config_large_acl",
            "cleanup",
        ]
        results = {}
        platform = dev_dict["device_type"]
        for op in operations:
            func = globals()[op]
            time_delta, result = func(dev_dict)
            if op != "cleanup":
                results[op] = time_delta
            # Some platforms have an issue where the last test affects the
            # next test?
            if "procurve" in platform:
                print("Sleeping 30 seconds...")
                time.sleep(30)
                print("Done")
        print("-" * 80)
        print()

        write_csv(dev_name, results)

    print("\n\n")

def test_performance():
    main()

if __name__ == "__main__":
    main()


text:
module.exports = {
  verbose: true,
  collectCoverage: true,
  bail: true,
  coverageDirectory: './coverage/',
  testEnvironment: 'node',
};


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.realm.examples.threads" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ThreadExampleActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package com.drew.metadata.xmp.handlers;

import com.adobe.xmp.*;
import com.drew.metadata.Metadata;
import com.drew.metadata.xmp.XmpDirectory;
import com.drew.metadata.xmp.XmpHandler;

/**
 * @author Payton Garland
 */
public class InddHandler implements XmpHandler
{
    @Override
    public void process(Metadata metadata)
    {
        XmpDirectory directory = metadata.getFirstDirectoryOfType(XmpDirectory.class);
        if (directory == null) {
            directory.addError("No XMP directory found in directory, aborting XMP process method");
            return;
        }

        XMPMeta xmpMeta = directory.getXMPMeta();
        if (xmpMeta == null) {
            directory.addError("No XMP data found in directory, aborting XMP process method");
            return;
        }

        InddXmpDirectory inddXmpDirectory = new InddXmpDirectory();
        metadata.addDirectory(inddXmpDirectory);

        try {
            for (int i = 1; xmpMeta.doesPropertyExist("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]") == true; i++) {
                if (xmpMeta.doesStructFieldExist("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/t/pg/", "PageNumber")) {
                    String pageNumber = xmpMeta.getStructField("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/t/pg/", "PageNumber").getValue();
                    inddXmpDirectory.getTagNameMap().put(inddXmpDirectory.currentKey, "[" + i + "]Page Number");
                    inddXmpDirectory.setString(inddXmpDirectory.currentKey, pageNumber);
                    inddXmpDirectory.currentKey++;
                }
                if (xmpMeta.doesStructFieldExist("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "format")) {
                    String format = xmpMeta.getStructField("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "format").getValue();
                    inddXmpDirectory.getTagNameMap().put(inddXmpDirectory.currentKey, "[" + i + "]Format");
                    inddXmpDirectory.setString(inddXmpDirectory.currentKey, format);
                    inddXmpDirectory.currentKey++;
                }
                if (xmpMeta.doesStructFieldExist("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "width")) {
                    String width = xmpMeta.getStructField("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "width").getValue();
                    inddXmpDirectory.getTagNameMap().put(inddXmpDirectory.currentKey, "[" + i + "]Width");
                    inddXmpDirectory.setString(inddXmpDirectory.currentKey, width);
                    inddXmpDirectory.currentKey++;
                }
                if (xmpMeta.doesStructFieldExist("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "height")) {
                    String height = xmpMeta.getStructField("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "height").getValue();
                    inddXmpDirectory.getTagNameMap().put(inddXmpDirectory.currentKey, "[" + i + "]Height");
                    inddXmpDirectory.setString(inddXmpDirectory.currentKey, height);
                    inddXmpDirectory.currentKey++;
                }
                if (xmpMeta.doesStructFieldExist("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "image")) {
                    byte[] image = xmpMeta.getStructField("http://ns.adobe.com/xap/1.0/", "PageInfo[" + i + "]", "http://ns.adobe.com/xap/1.0/g/img/", "image").getValue().getBytes();
                    inddXmpDirectory.getTagNameMap().put(inddXmpDirectory.currentKey, "[" + i + "]Image");
                    inddXmpDirectory.setByteArray(inddXmpDirectory.currentKey, image);
                    inddXmpDirectory.currentKey++;
                }
            }
        } catch (XMPException ignored) {
            ignored.printStackTrace();
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }
}


text:
Simple REST API Provider implements an abstract which allows you to make a requests to REST API, get a response and map it to your class object (RestApiProvider::Resource).

## Setup
This gem was not published to RubyGems.org so far, so in your Gemfile use:
```ruby
gem 'rest_api_provider', git: 'git@github.com:madeinussr/rest_api_provider.git'
```
```
bundle install
```
then either create a proper config file (in ``` /config/initializers ``` folder if you use Ruby on Rails) or just call that code:
```ruby
RestApiProvider.configure do |config|
  config.api_root = 'https://api.example.com'
  # if you need to include an Authorization header in every request
  config.auth_token = 'Basic XxXxxXxx='
end
```

## Define a Resource
You can define a simple Resource like this:
``` ruby
class TestResource < RestApiProvider::Resource
  resource_path '/test_resources/:slug'

  # 'application/json' - default
  content_type 'application/x-www-form-urlencoded'

  # include only fields that you want to map to object
  field :slug
  field :title
  field :description
end
```

### Types
You can define an explicit field type and a default value:

``` ruby
class TestResource < RestApiProvider::Resource
  resource_path '/test_resources/:slug'

  field :slug
  field :title, type: String, default: 'Hello World!'
  field :description
end
```

Supported field types:
* String
* Integer
* Fixnum
* Bignum
* Float
* Date
* Time
* Array
* Hash

and...
* your custom classes

### Slugs and included Resources
Consider _slug_ as an identifier of the particular Resource item.
You can define included Resources like this:

``` ruby
class SubResource < RestApiProvider::Resource
  resource_path '/test_resources/:resource_slug/sub_resources/:subresource_slug'

  field :resource_slug
  field :subresource_slug
  field :title
  field :description
end
```

### Validation
There is the list of supported (so far) ActiveRecord-like validations:
* presence
* length
* numericality
* minimum
* maximum
* &block

``` ruby
class TestResource < RestApiProvider::Resource
  resource_path '/test_resources/:slug'

  field :slug
  field :number
  field :description

  validates :slug, presence: true
  validates :number, numericality: true
end
```

### Relations
You can define relations between Resources. Relations implementation based on the [HATEOAS](https://en.wikipedia.org/wiki/HATEOAS) principle.
Supported relations:
* belongs_to
* has_one
* has_many

Before using relations you might configure HATEOAS attributes in config (if it is differ from default 'links'):
``` ruby
RestApiProvider.configure do |config|
  config.api_root = 'https://api.test.com:9999'
  config.verify_ssl = false
  config.auth_token = "Basic #{Rails.application.secrets.basic_auth_token}"
  config.hateoas_links = 'refs'
end
```

You can define a relation in Rails-like way:
``` ruby
class Book < RestApiProvider::Resource
  belongs_to :author, rel: 'lib:author'
end

class Author < RestApiProvider::Resource
  has_many :books, rel: 'lib:books'
end
```

by default, rel is equal to relation name
``` ruby
class Book < RestApiProvider::Resource
  belongs_to :author
end

Book.relations
>> {:type=>:one2one, :rel=>"author"}
```

If you need to use relation name differ from resource class name, you can specify target type:
``` ruby
class Book < RestApiProvider::Resource
  belongs_to :author, rel: 'lib:author'
end

class Author < RestApiProvider::Resource
  has_many :writings, rel: 'lib:books', type: Book
end
```

Sometimes it worth to specify a source data path (for example: rel href guide you to paged data: ```{data:[obj, obj, obj...], paging:{...}}```

In this case you can define a data path like this:
``` ruby
class Book < RestApiProvider::Resource
  belongs_to :author, rel: 'lib:author'
end

class Author < RestApiProvider::Resource
  has_many :books, rel: 'lib:books', data_path: '/data'
end
```

By default, related resources requested from API each time, but you can switch on the ability to store (cache) previous request result, then provide 'true' attribute to fetch related resource from cache (if you sure that resource was not modified):
``` ruby
class Book < RestApiProvider::Resource
 enable_relations_caching

 belongs_to :author, rel: 'lib:author'
end

class Author < RestApiProvider::Resource
 has_many :books, rel: 'lib:books', data_path: '/data'
end

book = Book.new
Book.relations_caching_enabled? #true
book.author(true) #will be requested from API, because cache is empty at the moment
book.author #will be requested from API, because attribute wasn't provided
book.author(true) #will be fetched from cache
```

Each relation calling without 'true' attribute will refresh cache data.

## Requests
### Default methods
There are some pre-defined request methods (name=>http_verb):
API_METHODS = {all: 'get', grouped: 'get', find: 'get', create: 'post', update: 'put', destroy: 'delete'}
You can use them in this way (slugs are based on a Resource path)
```ruby
TestResource.find slugs:{slug_1: 'qwe', slug_2: 'rty'}, params: {}, body: {}, headers: {}
```
* params: {} - url querystring-params
* body: {} - request's body
* headers: {} - request's headers

Default methods has some limitations:
* their target element (response source element) always root
* .all result - Array object
* .grouped result - Hash object
* .find, .create, .update, .destroy result - itself object

### Custom methods
You always can declare your own custom methods ``` http_verb method_name, custom_path ```
``` ruby
class TestResource < RestApiProvider::Resource
  resource_path '/test_resources/:slug'

  field :slug
  field :number
  field :description

  get :custom_get, '/some_resource/:some_slug/some_method'
  post :custom_post, '/some_resource/:some_slug/some_method'
  put :custom_put, '/some_resource/:some_slug/some_method'
  delete :custom_delete, '/some_resource/:some_slug/some_method'
end
```

You can specify mapping result's class (Hash or Array, by default - your Resource class itself):
``` ruby
class TestResource < RestApiProvider::Resource
  resource_path '/test_resources/:slug'

  field :slug
  field :number

  get :custom_get, '/some_resource/:some_slug/some_method', result: Hash
end
```

You're free to specify data source element path for mapping (by default - root) if your Resource data is not defined in the response's root:
``` ruby
class TestResource < RestApiProvider::Resource
  resource_path '/test_resources/:slug'

  field :slug
  field :number

  get :custom_get, '/some_resource/:some_slug/some_method', result: Hash, data_path: '/data/sub_data'
end
```

The same usage:
```ruby
TestResource.custom_get slugs:{some_slug: 'qwe'}, params: {}, body: {}, headers: {}
```

### Paths
```.resource_path``` defines the default Resource path. But you always can declare a custom path for a particular method.
``` ruby
class TestResource < RestApiProvider::Resource
  resource_path '/test_resources/:slug'

  field :slug
  field :number
  field :description

  get :custom_method, '/some_resource/:some_slug/some_method'
end
```
If you've not specified the resource_path it would be set as ```/resource_name_pluralised/:slug```

## Response mapping
This gem awaits that request is a JSON.
Actually, methods .all, .find etc. and custom methods returns a mapped result.
So far you can get a mapping JSON to:
* object
* Array
* Hash

_If a response body is blank, then ::Mapper provides ::ApiResponse class object._

### TODO
* escape/unescape HTML fields
* async requests
* cache


text:
layout: page-fullwidth
#subheadline: "Biography"
permalink: "/charles-sande/"
header: no
---

Home

Team

Charles Sande

Charles Sande (Bsc, Msc, PhD)

Postdoc

Contact

Department Of Epidemiology
& Demography

Kemri Wellcome Trust

Kilifi, Kenya

☎:

kemri-wellcome<org" target="_top" onclick = "this.href=this.href
.replace(/>/,'@')
.replace(/</,'.')"> ✉ Email me

Background

I am a Wellcome Trust research fellow at KEMRI-Wellcome Trust research programme and the University of Oxford.

My main research interests are in the development and validation of prognostic biomarkers for acute respiratory infections in infants. I am also involved in early preclinical development of virus vectored vaccines for respiratory syncytial virus (RSV) and have previously worked in the clinical evaluation of first-in-man vaccine studies of RSV in early phase I trials. Prior to that I undertook studies on the development of protective immunity to RSV infants.

Selected Publications

Absence of association between cord specific antibody levels and severe respiratory syncytial virus (RSV) disease in early infants: a case control study from coastal Kenya.

Nyiro, J.U., Sande, C.J., Mutunga, M., Kiyuka, P.K., Munywoki, P.K., Scott, J.A.G. and Nokes, D.J.

PLoS One, 11(11), p.e0166706 (2016)

Non-specific immunological effects of selected routine childhood immunisations: systematic review.

Kandasamy, R., Voysey, M., McQuaid, F., de Nie, K., Ryan, R., Orr, O., Uhlig, U., Sande, C., O'Connor, D. and Pollard, A.J.

 bmj, 355, p.i5225 (2016)

Best practice in the prevention and management of paediatric respiratory syncytial virus infection.

Drysdale, S.B., Green, C.A. and Sande, C.J.

Therapeutic advances in infectious disease, p.2049936116630243 (2016)

RSV vaccine use–the missing data.

Drysdale, S.B., Sande, C.J., Green, C.A. and Pollard, A.J.

Expert review of vaccines, 15(2), pp.149-152 (2016)

Admission to hospital for bronchiolitis in England: trends over five decades, geographical variation and association with perinatal characteristics and subsequent asthma.

Green, C.A., Yeates, D., Goldacre, A., Sande, C., Parslow, R.C., McShane, P., Pollard, A.J. and Goldacre, M.J.

Archives of disease in childhood, pp.archdischild-2015 (2015)

 --> view all Dr. Charles Sande's publications


text:
class HomeController < ApplicationController
  skip_before_action :require_authentication

  def index
  end
end


text:
<?php

/**
 * PHPCI - Continuous Integration for PHP. Plugin for using Symfony2 commands.
 *
 * @package    PHPCI\Plugin
 * @author     Alexander Gansky <a.gansky@mindteam.com.ua>
 * @license    https://github.com/mindteam/phpci-symfony2-plugin/blob/master/LICENSE
 * @link       http://mindteam.com.ua
 */

namespace Mindteam\PHPCI\Plugin;

use PHPCI;
use PHPCI\Builder;
use PHPCI\Model\Build;
use Symfony\Component\Yaml\Parser as YamlParser;
use PHPCI\Plugin as BaseInterface;

/**
 * Plugin for Symfony2 commands
 */
class SymfonyCommands implements BaseInterface
{

    protected $directory;
    protected $phpci;
    protected $build;
    protected $commandList = array();

    /**
     * Set up the plugin, configure options, etc.
     *
     * @param Builder $phpci
     * @param Build $build
     * @param array $options
     */
    public function __construct(Builder $phpci, Build $build, array $options = array())
    {
        $this->phpci = $phpci;
        $this->build = $build;
        $this->directory = $phpci->buildPath;
        if (isset($options['commands'])) {
            $this->commandList = $options['commands'];
        }
    }

    /**
     * Executes Symfony2 commands
     *
     * @return boolean plugin work status
     */
    public function execute()
    {
        $success = true;
        foreach ($this->commandList as $command) {
            if (!$this->runSingleCommand($command)) {
                $success = false;
                break;
            }
        }
        return $success;
    }

    /**
     * Run one command
     *
     * @param string $command command for cymfony
     *
     * @return boolean
     */
    public function runSingleCommand($command)
    {
        $cmd = 'php ' . $this->directory . 'app/console ';

        return $this->phpci->executeCommand($cmd . $command, $this->directory);
    }

}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _child_process = require('child_process');

var _child_process2 = _interopRequireDefault(_child_process);

var _gulpUtil = require('gulp-util');

var _gulpUtil2 = _interopRequireDefault(_gulpUtil);

var _gulpToolsLibUtils = require('gulp-tools/lib/utils');

var sutils = _interopRequireWildcard(_gulpToolsLibUtils);

var _gulpTools = require('gulp-tools');

var Sass = (function (_Plugin) {
  _inherits(Sass, _Plugin);

  function Sass() {
    _classCallCheck(this, Sass);

    _get(Object.getPrototypeOf(Sass.prototype), 'constructor', this).call(this, 'gulp-sass-native');
  }

  _createClass(Sass, [{
    key: 'configure',
    value: function configure(options) {
      this.options = options ? options : {};
      this.option("stream", false, function (v) {
        return v === true || v === false;
      });
      this.option("handler", function (v) {
        return true;
      });
    }
  }, {
    key: 'handle_string',
    value: function handle_string(file, value, callback) {
      var isWin = /^win/.test(process.platform);
      if (isWin) {
        var sass_process = _child_process2['default'].spawn('ruby', ['C:\\Ruby22-x64\\bin\\sass', '-I.', '-s', '--scss'], { cwd: file.base });
      } else {
        var sass_process = _child_process2['default'].spawn('sass', ['-I.', '-s', '--scss'], { cwd: file.base });
      }
      var failed = false;
      var self = this;
      sutils.read_from_stream(sass_process.stderr, 'utf8', function (value) {
        if (value) {
          failed = true;
          var error = new _gulpUtil2['default'].PluginError(self.name, value, { fileName: file.path });
          if (!self.options.stream) {
            callback(error);
          } else {
            self.options.handler(error);
            callback();
          }
        }
      });
      sutils.read_from_stream(sass_process.stdout, 'utf8', function (value) {
        if (value && !failed) {
          file.path = _gulpUtil2['default'].replaceExtension(file.path, '.css');
          file.contents = new Buffer(value);
          callback(null, file);
        }
      });
      sass_process.stdin.write(value);
      sass_process.stdin.end();
    }
  }]);

  return Sass;
})(_gulpTools.Plugin);

exports['default'] = new Sass().handler();
module.exports = exports['default'];


text:
            Add Form Template

                            Action
                            Questions
                            Name
                            Form Subject
                            Description

                            Edit
                            Questions
                            {{ form.Name }}
                            {{ form.FormSubject }}
                            {{ form.Description }}