text:
#include "igb.h"
#include "e1000_82575.h"
#include "e1000_hw.h"

#ifdef IGB_PROCFS
#ifndef IGB_HWMON

#include <linux/module.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/device.h>
#include <linux/netdevice.h>

static struct proc_dir_entry *igb_top_dir = NULL;

bool igb_thermal_present(struct igb_adapter *adapter)
{
	s32 status;
	struct e1000_hw *hw;

	if (adapter == NULL)
		return false;
	hw = &adapter->hw;

	/*
	 * Only set I2C bit-bang mode if an external thermal sensor is
	 * supported on this device.
	 */
	if (adapter->ets) {
		status = e1000_set_i2c_bb(hw);
		if (status != E1000_SUCCESS)
			return false;
	}

	status = hw->mac.ops.init_thermal_sensor_thresh(hw);
	if (status != E1000_SUCCESS)
		return false;

	return true;
}

static int igb_macburn(char *page, char **start, off_t off, int count,
			int *eof, void *data)
{
	struct e1000_hw *hw;
	struct igb_adapter *adapter = (struct igb_adapter *)data;
	if (adapter == NULL)
		return snprintf(page, count, "error: no adapter\n");

	hw = &adapter->hw;
	if (hw == NULL)
		return snprintf(page, count, "error: no hw data\n");

	return snprintf(page, count, "0x%02X%02X%02X%02X%02X%02X\n",
		       (unsigned int)hw->mac.perm_addr[0],
		       (unsigned int)hw->mac.perm_addr[1],
		       (unsigned int)hw->mac.perm_addr[2],
		       (unsigned int)hw->mac.perm_addr[3],
		       (unsigned int)hw->mac.perm_addr[4],
		       (unsigned int)hw->mac.perm_addr[5]);
}

static int igb_macadmn(char *page, char **start, off_t off,
		       int count, int *eof, void *data)
{
	struct e1000_hw *hw;
	struct igb_adapter *adapter = (struct igb_adapter *)data;
	if (adapter == NULL)
		return snprintf(page, count, "error: no adapter\n");

	hw = &adapter->hw;
	if (hw == NULL)
		return snprintf(page, count, "error: no hw data\n");

	return snprintf(page, count, "0x%02X%02X%02X%02X%02X%02X\n",
		       (unsigned int)hw->mac.addr[0],
		       (unsigned int)hw->mac.addr[1],
		       (unsigned int)hw->mac.addr[2],
		       (unsigned int)hw->mac.addr[3],
		       (unsigned int)hw->mac.addr[4],
		       (unsigned int)hw->mac.addr[5]);
}

static int igb_numeports(char *page, char **start, off_t off, int count,
			 int *eof, void *data)
{
	struct e1000_hw *hw;
	int ports;
	struct igb_adapter *adapter = (struct igb_adapter *)data;
	if (adapter == NULL)
		return snprintf(page, count, "error: no adapter\n");

	hw = &adapter->hw;
	if (hw == NULL)
		return snprintf(page, count, "error: no hw data\n");

	ports = 4;

	return snprintf(page, count, "%d\n", ports);
}

static int igb_porttype(char *page, char **start, off_t off, int count,
			int *eof, void *data)
{
	struct igb_adapter *adapter = (struct igb_adapter *)data;
	if (adapter == NULL)
		return snprintf(page, count, "error: no adapter\n");

	return snprintf(page, count, "%d\n",
			test_bit(__IGB_DOWN, &adapter->state));
}

static int igb_therm_location(char *page, char **start, off_t off,
				     int count, int *eof, void *data)
{
	struct igb_therm_proc_data *therm_data =
		(struct igb_therm_proc_data *)data;

	if (therm_data == NULL)
		return snprintf(page, count, "error: no therm_data\n");

	return snprintf(page, count, "%d\n", therm_data->sensor_data->location);
}

static int igb_therm_maxopthresh(char *page, char **start, off_t off,
				    int count, int *eof, void *data)
{
	struct igb_therm_proc_data *therm_data =
		(struct igb_therm_proc_data *)data;

	if (therm_data == NULL)
		return snprintf(page, count, "error: no therm_data\n");

	return snprintf(page, count, "%d\n",
			therm_data->sensor_data->max_op_thresh);
}

static int igb_therm_cautionthresh(char *page, char **start, off_t off,
				      int count, int *eof, void *data)
{
	struct igb_therm_proc_data *therm_data =
		(struct igb_therm_proc_data *)data;

	if (therm_data == NULL)
		return snprintf(page, count, "error: no therm_data\n");

	return snprintf(page, count, "%d\n",
			therm_data->sensor_data->caution_thresh);
}

static int igb_therm_temp(char *page, char **start, off_t off,
			     int count, int *eof, void *data)
{
	s32 status;
	struct igb_therm_proc_data *therm_data =
		(struct igb_therm_proc_data *)data;

	if (therm_data == NULL)
		return snprintf(page, count, "error: no therm_data\n");

	status = e1000_get_thermal_sensor_data(therm_data->hw);
 	if (status != E1000_SUCCESS)
		snprintf(page, count, "error: status %d returned\n", status);

	return snprintf(page, count, "%d\n", therm_data->sensor_data->temp);
}

struct igb_proc_type{
	char name[32];
	int (*read)(char*, char**, off_t, int, int*, void*);
};

struct igb_proc_type igb_proc_entries[] = {
	{"numeports", &igb_numeports},
	{"porttype", &igb_porttype},
	{"macburn", &igb_macburn},
	{"macadmn", &igb_macadmn},
	{"", NULL}
};

struct igb_proc_type igb_internal_entries[] = {
	{"location", &igb_therm_location},
	{"temp", &igb_therm_temp},
	{"cautionthresh", &igb_therm_cautionthresh},
	{"maxopthresh", &igb_therm_maxopthresh},
	{"", NULL}
};

void igb_del_proc_entries(struct igb_adapter *adapter)
{
	int index, i;
	char buf[16];	/* much larger than the sensor number will ever be */

	if (igb_top_dir == NULL)
		return;

	for (i = 0; i < E1000_MAX_SENSORS; i++) {
		if (adapter->therm_dir[i] == NULL)
			continue;

		for (index = 0; ; index++) {
			if (igb_internal_entries[index].read == NULL)
				break;

			 remove_proc_entry(igb_internal_entries[index].name,
					   adapter->therm_dir[i]);
		}
		snprintf(buf, sizeof(buf), "sensor_%d", i);
		remove_proc_entry(buf, adapter->info_dir);
	}

	if (adapter->info_dir != NULL) {
		for (index = 0; ; index++) {
			if (igb_proc_entries[index].read == NULL)
				break;
		        remove_proc_entry(igb_proc_entries[index].name,
					  adapter->info_dir);
		}
		remove_proc_entry("info", adapter->eth_dir);
	}

	if (adapter->eth_dir != NULL)
		remove_proc_entry(pci_name(adapter->pdev), igb_top_dir);
}

/* called from igb_main.c */
void igb_procfs_exit(struct igb_adapter *adapter)
{
	igb_del_proc_entries(adapter);
}

int igb_procfs_topdir_init(void)
{
	igb_top_dir = proc_mkdir("driver/igb", NULL);
	if (igb_top_dir == NULL)
		return (-ENOMEM);

	return 0;
}

void igb_procfs_topdir_exit(void)
{
	remove_proc_entry("driver/igb", NULL);
}

/* called from igb_main.c */
int igb_procfs_init(struct igb_adapter *adapter)
{
	int rc = 0;
	int i;
	int index;
	char buf[16];	/* much larger than the sensor number will ever be */

	adapter->eth_dir = NULL;
	adapter->info_dir = NULL;
	for (i = 0; i < E1000_MAX_SENSORS; i++)
		adapter->therm_dir[i] = NULL;

	if ( igb_top_dir == NULL ) {
		rc = -ENOMEM;
		goto fail;
	}

	adapter->eth_dir = proc_mkdir(pci_name(adapter->pdev), igb_top_dir);
	if (adapter->eth_dir == NULL) {
		rc = -ENOMEM;
		goto fail;
	}

	adapter->info_dir = proc_mkdir("info", adapter->eth_dir);
	if (adapter->info_dir == NULL) {
		rc = -ENOMEM;
		goto fail;
	}
	for (index = 0; ; index++) {
		if (igb_proc_entries[index].read == NULL) {
			break;
		}
		if (!(create_proc_read_entry(igb_proc_entries[index].name,
					   0444,
					   adapter->info_dir,
					   igb_proc_entries[index].read,
					   adapter))) {

			rc = -ENOMEM;
			goto fail;
		}
	}
	if (igb_thermal_present(adapter) == false)
		goto exit;

	for (i = 0; i < E1000_MAX_SENSORS; i++) {

		 if (adapter->hw.mac.thermal_sensor_data.sensor[i].location== 0)
			continue;

		snprintf(buf, sizeof(buf), "sensor_%d", i);
		adapter->therm_dir[i] = proc_mkdir(buf, adapter->info_dir);
		if (adapter->therm_dir[i] == NULL) {
			rc = -ENOMEM;
			goto fail;
		}
		for (index = 0; ; index++) {
			if (igb_internal_entries[index].read == NULL)
				break;
			/*
			 * therm_data struct contains pointer the read func
			 * will be needing
			 */
			adapter->therm_data[i].hw = &adapter->hw;
			adapter->therm_data[i].sensor_data =
				&adapter->hw.mac.thermal_sensor_data.sensor[i];

			if (!(create_proc_read_entry(
					   igb_internal_entries[index].name,
					   0444,
					   adapter->therm_dir[i],
					   igb_internal_entries[index].read,
					   &adapter->therm_data[i]))) {
				rc = -ENOMEM;
				goto fail;
			}
		}
	}
	goto exit;

fail:
	igb_del_proc_entries(adapter);
exit:
	return rc;
}

#endif /* !IGB_HWMON */
#endif /* IGB_PROCFS */


text:
import os

from annotypes import Anno, add_call_types
from tornado.web import RedirectHandler, StaticFileHandler

from malcolm.core import APartName, Part, PartRegistrar

from ..hooks import ReportHandlersHook, UHandlerInfos
from ..infos import HandlerInfo

www_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "www"))

with Anno("Path to www directory to get files from"):
    APath = str

# Always serve index.html, no matter what the route
class IndexHandler(StaticFileHandler):
    @classmethod
    def get_absolute_path(cls, root, path):
        return super(IndexHandler, cls).get_absolute_path(root, "index.html")

class GuiServerPart(Part):
    """Static file server to be used as a fallback. Must be last part"""

    GuiHandler = IndexHandler

    def __init__(self, name: APartName = "gui", path: APath = www_dir) -> None:
        super().__init__(name)
        self.path = path

    def setup(self, registrar: PartRegistrar) -> None:
        super().setup(registrar)
        # Hooks
        registrar.hook(ReportHandlersHook, self.on_report_handlers)

    @add_call_types
    def on_report_handlers(self) -> UHandlerInfos:
        infos = [
            # Redirect / to /gui/
            HandlerInfo(r"/", RedirectHandler, url="/gui/"),
            # Serve index.html for /gui or /details
            HandlerInfo(r"/(gui|details).*", self.GuiHandler, path=self.path),
            # Anything else should be a static file handle
            HandlerInfo(r"/(.*)", StaticFileHandler, path=self.path),
        ]
        return infos

redpajama_set_name: RedPajamaGithub


text:
define([
  './util',
  './assets/default-content.js'
],
function (util, defaultContent) {
  describe('the snippet', function () {
    var iframe = document.querySelector('iframe');

    before(function (done) {
      iframe.src = 'assets/test-inject.html?css';
      util.waitOnFrame(iframe, done);
    });

    it('should inject the styles exactly once', function () {
      var styles = iframe.contentDocument.
        querySelectorAll(util.getWidgetSelector('styles'));

      expect(styles.length).to.be(1);
    });

    describe('for each .waterfall-subscription-widget', function () {
      var widgets =
        iframe.contentDocument.querySelectorAll(util.getWidgetSelector(''));

      it('should inject the markup', function () {
        $(widgets).each(function (i, el) {
          expect(el.innerHTML.length).to.be.greaterThan(0);
        });
      });

      it('should populate the injected markup with default content',
        function () {
          var html = iframe.contentDocument.
            querySelector('[data-waterfall-widgetid="abc123"]').innerHTML;
          for (var k in defaultContent) {
            expect(html).to.contain(defaultContent[k]);
          }
        });

      it('should override the default content if a data attr is specified',
        function () {
          var el = iframe.contentDocument.
            querySelector('[data-waterfall-widgetid="456def"]');
          var html = el.innerHTML;
          var attr;

          for (var k in defaultContent) {
            attr =
              'data-waterfall-' + k.replace(/([A-Z])/g, '-$1').toLowerCase();

            if (el.hasAttribute(attr)) {
              expect(html).to.contain(el.getAttribute(attr));
            }
          }
        });

      it('the submit frame location.hash should match its src (#1)',
        function () {
          var el = iframe.contentDocument.
            querySelector('[data-waterfall-widgetid="issue-1"]');
          var frameEl = el.querySelector('iframe');

          expect(frameEl.contentWindow.location.hash).to.be('#' + el.id);
        });
    });
  });
});


text:
#ifndef XDMF_WRITER_BACKENDS_POSIX_H
#define XDMF_WRITER_BACKENDS_POSIX_H

#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#include "utils/stringutils.h"

#include "Base.h"

namespace xdmfwriter
{

namespace backends
{

#define checkErr(...) _checkErr(__VA_ARGS__, __FILE__, __LINE__)

template<typename T>
class Posix : public Base<T>
{
private:
	/** File handles */
	int* m_fh;

public:
	Posix() : Base<T>("Binary"),
		m_fh(0L)
	{
	}

	void open(const std::string &outputPrefix, const std::vector<VariableData> &variableData, bool create = true)
	{
		Base<T>::open(outputPrefix, variableData, create);

		if (create) {
			if (Base<T>::rank() == 0) {
				Base<T>::backup(outputPrefix);
				checkErr(mkdir(outputPrefix.c_str(), 0755));
			}

#ifdef USE_MPI
			// Ensure that everybody sees the new directory
			MPI_Barrier(Base<T>::comm());
#endif // USE_MPI
		}
	}

	void setMesh(unsigned int meshId,
		unsigned long totalElements, unsigned int localElements, unsigned long offset)
	{
		Base<T>::setMesh(totalElements, localElements, offset, true);

		// Backup the old folder an create a new one
		std::string folder = Base<T>::pathPrefix() + "/mesh" + utils::StringUtils::toString(meshId);

		if (Base<T>::rank() == 0) {
			// Check if the folder still exists (if we run from a checkpoint)
			struct stat statBuffer;
			if (stat(folder.c_str(), &statBuffer) != 0)
				checkErr(mkdir(folder.c_str(), 0755));
		}

#ifdef USE_MPI
		// Ensure that everybody sees the change
		MPI_Barrier(Base<T>::comm());
#endif // USE_MPI

		if (m_fh)
			closeFiles();
		else
			m_fh = new int[Base<T>::variables().size()];

		if (Base<T>::localElements() > 0) {
			for (unsigned int i = 0; i < Base<T>::variables().size(); i++) {
				m_fh[i] = open(filename(Base<T>::pathPrefix(), meshId, Base<T>::variables()[i].name).c_str());
			}
		} else {
			delete [] m_fh;
			m_fh = 0L;
		}
	}

	void flush()
	{
		if (m_fh) {
			for (unsigned int i = 0; i < Base<T>::variables().size(); i++)
				checkErr(fsync(m_fh[i]));
		}
	}

	/**
	 * Closes the POSIX files
	 */
	void close()
	{
		Base<T>::close();

		closeFiles();
		delete [] m_fh;
		m_fh = 0L;
	}

	/**
	 * @param var
	 * @return The location name in the XDMF file for a data item
	 */
	std::string dataLocation(unsigned int meshId, const char* var) const
	{
		return filename(Base<T>::dataLocation(meshId, var), meshId, var);
	}

protected:
	void write(unsigned int timestep, unsigned int id, const void* data)
	{
		if (Base<T>::localElements() == 0)
			// Nothing to write
			return;

		size_t offset = 0;
		if (Base<T>::variables()[id].hasTime)
			offset = Base<T>::totalElements() * timestep;
		offset += Base<T>::offset();
		offset *=  Base<T>::variables()[id].count * Base<T>::variableSize(Base<T>::variables()[id].type);
		write(m_fh[id], data, offset,
			Base<T>::localElements() * Base<T>::variables()[id].count * Base<T>::variableSize(Base<T>::variables()[id].type));
	}

private:
	void closeFiles()
	{
		if (m_fh) {
			for (unsigned int i = 0; i < Base<T>::variables().size(); i++)
				checkErr(::close(m_fh[i]));
		}
	}

private:
	/**
	 * @return The file name for a given variable
	 */
	static std::string filename(const std::string &prefix, unsigned int meshId, const char* var)
	{
		return prefix + "/mesh" + utils::StringUtils::toString(meshId) + "/" + var + ".bin";
	}

	static int open(const char* filename)
	{
		int fh = open64(filename, O_WRONLY | O_CREAT,
				S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
		checkErr(fh);
		return fh;
	}

	static void write(int fh, const void* buffer, size_t offset, size_t size)
	{
		checkErr(lseek64(fh, offset, SEEK_SET));

		const char* buf = reinterpret_cast<const char*>(buffer);
		while (size > 0) {
			ssize_t written = ::write(fh, buf, size);
			if (written <= 0)
				checkErr(written, size);
			buf += written;
			size -= written;
		}
	}

	template<typename TT>
	static void _checkErr(TT ret, const char* file, int line)
	{
		if (ret < 0)
			logError() << utils::nospace
				<< "An POSIX error occurred in the XDMF writer (" << file << ": " << line << "): " << strerror(errno);
	}

	/**
	 * Can be used to check read/write errors
	 *
	 * @param ret The return value
	 * @param target The expected return value (> 0)
	 */
	template<typename TT, typename U>
	static void _checkErr(TT ret, U target, const char* file, int line)
	{
		_checkErr(ret, file, line);
		if (ret != static_cast<TT>(target))
			logError() << utils::nospace
				<< "Error in XDMF writer (" << file << ": " << line << "): "
				<< target << " bytes expected; " << ret << " bytes gotten";
	}
};

#undef checkErr

}

}

#endif // XDMF_WRITER_BACKENDS_POSIX_H


text:
"use strict";

define([
    './feature1/values/feature1Value'
],
    function (feature1Value) {
        return {
            'meanSeed.feature1.values.feature1Value': feature1Value
        };
    });


text:
FactoryBot.define do
  factory :condition, class: 'Hanuman::Condition' do
    question
    rule
    operator { Hanuman::Condition::OPERATORS.sample }
  end
end


text:
using Windows.ApplicationModel.Email;
using Windows.System;
using DjvuApp.Common;
using System;
using Windows.ApplicationModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace DjvuApp.Pages
{
    public sealed partial class AboutPage : Page
    {
        private readonly NavigationHelper _navigationHelper;

        public AboutPage()
        {
            this.InitializeComponent();
            _navigationHelper = new NavigationHelper(this);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var version = Package.Current.Id.Version;
            versionTextBlock.Text = $@"Version {version.Major}.{version.Minor}.{version.Build}.{version.Revision}
By Eldar Dordzhiev
From Russia with love :)";
        }

        private async void ContactMeButtonClickHandler(object sender, RoutedEventArgs e)
        {
            var recipient = new EmailRecipient("djvureaderwp@gmail.com", "Djvu Reader developer");
            var message = new EmailMessage();
            message.To.Add(recipient);
            message.Subject = "DjVu Reader";
            await EmailManager.ShowComposeNewEmailAsync(message);
        }

        private async void ShowMyAppsButtonClickHandler(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("ms-windows-store:Publisher?name=Eldar%20Dordzhiev"));
        }

        private async void RateButtonClickHandler(object sender, RoutedEventArgs e)
        {
            await App.RateAppAsync();
        }
    }
}


text:
#pragma once
#include "afxwin.h"

// CDlgSecretSharingIntro-Dialogfeld

class CDlgSecretSharingIntro : public CDialog
{

public:
	CDlgSecretSharingIntro(CWnd* pParent = NULL);   // Standardkonstruktor
	virtual ~CDlgSecretSharingIntro();

// Dialogfelddaten
	//{{AFX_DATA(CDlgSecretSharingIntro)
	enum { IDD = IDD_SECRETSHARING_INTRO };
	BOOL m_hide_intro;
	//}}AFX_DATA

	// Überschreibungen
	// Vom Klassen-Assistenten generierte virtuelle Funktionsüberschreibungen
	//{{AFX_VIRTUAL(CDlgSecretSharingSetup)
protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV-Unterstützung
	//}}AFX_VIRTUAL

protected:
	// Generierte Nachrichtenzuordnungsfunktionen
	//{{AFX_MSG(CDlgSecretSharingIntro)
	afx_msg void OnOk();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};


text:
#include "ipc/message_types.h"

#include "ipc/testing.h"

namespace {

#define DECLARE_IPC_MSG(id, type) ipc::MSG_##type,
const uint32 kPredefinedMessageTypes[] = {
#include "ipc/message_types_decl.h"
};
#undef DECLARE_IPC_MSG

TEST(MessageTypesTest, Basic) {
  EXPECT_EQ(0, ipc::MSG_INVALID);
}

TEST(MessageTypesTest, Name) {
  EXPECT_STREQ("INVALID", ipc::GetMessageName(ipc::MSG_INVALID));
  EXPECT_STREQ("CREATE_INPUT_CONTEXT",
               ipc::GetMessageName(ipc::MSG_CREATE_INPUT_CONTEXT));
  EXPECT_STREQ("SYSTEM_RESERVED",
               ipc::GetMessageName(ipc::MSG_SYSTEM_RESERVED_START));
  EXPECT_STREQ("SYSTEM_RESERVED",
               ipc::GetMessageName(ipc::MSG_SYSTEM_RESERVED_START + 1));
  EXPECT_STREQ("SYSTEM_RESERVED",
               ipc::GetMessageName(ipc::MSG_SYSTEM_RESERVED_END));
  EXPECT_STREQ("USER_DEFINED",
               ipc::GetMessageName(ipc::MSG_USER_DEFINED_START));
  EXPECT_STREQ("USER_DEFINED",
               ipc::GetMessageName(ipc::MSG_USER_DEFINED_START + 1));
  EXPECT_STREQ("UNDEFINED",
               ipc::GetMessageName(ipc::MSG_SYSTEM_RESERVED_START - 1));
}

TEST(MessageTypesTest, Sorted) {
  for (size_t i = 1; i < arraysize(kPredefinedMessageTypes); ++i)
    EXPECT_LT(kPredefinedMessageTypes[i - 1], kPredefinedMessageTypes[i]);
}

}  // namespace


text:
package org.hippoecm.repository.api;

import javax.jcr.NodeIterator;

/**
 * Extends a #javax.jcr.NodeIterator interface, with an additional method.  Not all NodeIterator objects returned by
 * a repository are HippoNodeIterator objects, and when an object is a HippoNodeIterator the additional information
 * provided by these methods may still not be available.
 */
public interface HippoNodeIterator extends NodeIterator {

    /**
     * Obtains the number of elements that would be retrievable if the user your have access to all elements in the repository
     * @return the total size or -1 when not available.
     * @since 2.17.00
     */
     public long getTotalSize();
}


text:
var mysql = require('mysql');
var orm = require("orm");
var fs = require('fs');
var News = require('../models/news.server.model.js');

module.exports = {
    //获取1条新闻
    getById: function (req, res, next, id) {
        News.getModel(function (dbmodel) {
            dbmodel.find({ NewsId: id }, function (err, news) {
                res.json(news);
            });
        });
    },

    //删除
    delById: function (req, res, next, id) {
        News.getModel(function (dbmodel) {
            dbmodel.find({NewsId: id}).remove(function (err) {
                if (err)
                    throw err;
                res.send({ "result": 0 });
            });
        });
    },

    //返回所有-分页
    listpage: function (req, res, next, page) {
        News.getModel(function (dbmodel) {
            dbmodel.find({}).limit(5).offset(page * 5).order('-NewsId').run(function (err, news) {
                res.json(news);
            });
        });
    },

    //根据栏目id返回
    listByCatid: function (req, res, next, catid) {
        News.getModel(function (dbmodel) {
            dbmodel.find({CategoryId:catid}, function (err, news) {
                res.json(news);
            });
        });
    },

    //返回all
    list: function (req, res, next) {
        News.getModel(function (dbmodel) {
            dbmodel.find({}).order('-NewsId').run(function (err, news) {
                res.json(news);
            });
        });
    },

    //添加&更新 新闻
    create: function (mid, req, res, next) {

        var filename = '';
        if (req.files && req.files.image_file && req.files.image_file.size > 0) {
            var filetype = req.files.image_file.type;
            if (filetype.length > 5 && filetype.substr(0, 5) == 'image') {
                var ext = req.files.image_file.path.substr(req.files.image_file.path.lastIndexOf('.'));
                filename = '' + Date.parse(new Date()) + ext;

                //不是一个盘符会报错
                //fs.rename(req.files.image_file.path, './upload/' + filename);

                //通过文件读取复制的方法
                var readStream = fs.createReadStream(req.files.image_file.path);
                var writeStream = fs.createWriteStream("./upload/" + filename);
                readStream.pipe(writeStream);
                readStream.on('end', function () {
                    fs.unlinkSync(req.files.image_file.path);
                });

            }
            else {
                fs.unlink(req.files.image_file.path);
            }
        }

        var txtimageurl = req.body.txtimageurl;
        if (filename == '')
            filename = txtimageurl;
        var NewsTitle = req.body.NewsTitle;
        while (NewsTitle.indexOf('<') >= 0)
            NewsTitle = NewsTitle.replace('<', '<');
        while (NewsTitle.indexOf('>') >= 0)
            NewsTitle = NewsTitle.replace('>', '>');
        while (NewsTitle.indexOf('"') >= 0)
            NewsTitle = NewsTitle.replace('"', '"');

        News.getModel(function (dbmodel) {
            if (req.body.NewsId != "0") {
                //更新
                dbmodel.find({ NewsId: req.body.NewsId }, function (err, rows) {
                    if (err) throw err;
                    if (rows.length > 0) {
                        rows[0].NewsTitle = NewsTitle;
                        rows[0].CategoryId = req.body.CategoryId;
                        rows[0].NewsContent = req.body.NewsContent;
                        rows[0].NewsImg = filename;
                        rows[0].save(function (errFinal) {
                            if (errFinal) throw errFinal;
                            res.type("html");
                            res.send("<script>window.location.href = 'http://localhost:3000/admin/';</script>");
                        })
                    }
                });

            }
            else {
                //创建
                dbmodel.create({ NewsTitle: req.body.NewsTitle, CategoryId: req.body.CategoryId, NewsContent: req.body.NewsContent, NewsImg: filename, AddTime: (new Date().getFullYear()) + '-' + ((new Date().getMonth() + 1)) + '-' + (new Date().getDate()) }, function (err) {
                    if (err)
                        throw err;
                    res.type("html");
                    res.send("<script>window.location.href = 'http://localhost:3000/admin/';</script>");
                });
            }
        });
    }

};


text:
package com.helion3.prism.commands;

import com.helion3.prism.Prism;
import com.helion3.prism.api.flags.Flag;
import com.helion3.prism.api.query.QuerySession;
import com.helion3.prism.api.query.Sort;
import com.helion3.prism.api.records.Actionable;
import com.helion3.prism.api.records.ActionableResult;
import com.helion3.prism.api.records.Result;
import com.helion3.prism.util.*;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.text.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

public class ApplierCommand {

    private ApplierCommand() {
    }

    public static CommandSpec getCommand(Sort sort) {
        return CommandSpec.builder()
        .permission("prism.rollback")
        .arguments(GenericArguments.remainingJoinedStrings(Text.of("parameters")))
        .executor((source, args) -> {
            // Create a new query session
            final QuerySession session = new QuerySession(source);
            session.addFlag(Flag.NO_GROUP);
            try {
                source.sendMessage(Format.heading("Querying records..."));

                CompletableFuture<Void> future = session.newQueryFromArguments(args.<String>getOne("parameters").get());
                // Ignore user order flag, if used, for proper rollback/restore order to be used.
                session.setSortBy(sort);
                future.thenAccept((v) -> runApplier(session, sort));
            } catch(Exception e) {
                source.sendMessage(Format.error(Text.of(e.getMessage())));
                e.printStackTrace();
            }

            return CommandResult.success();
        })
        .build();
    }

    /**
     * Use a designated QuerySession
     * @param session
     * @param sort
     */
    public static void runApplier(QuerySession session, Sort sort) {
        session.getQuery().setLimit(Prism.getInstance().getConfig().getLimitCategory().getMaximumActionable());
        CommandSource source = session.getCommandSource();
        try {
            List<ActionableResult> actionResults = new ArrayList<>();
            // Iterate query results
            CompletableFuture<List<Result>> futureResults = Prism.getInstance().getStorageAdapter().records().query(session, false);
            futureResults.thenAccept(results -> {
                if (results.isEmpty()) {
                    source.sendMessage(Format.error("No results."));
                } else {
                    try {
                        // Iterate record results
                        Task.builder().execute(() -> {
                            results.forEach(result -> {
                                try {
                                    if (result instanceof Actionable) {

                                        Actionable actionable = (Actionable) result;

                                        if (sort.equals(Sort.NEWEST_FIRST)) {
                                            actionResults.add(actionable.rollback());
                                        } else {
                                            actionResults.add(actionable.restore());
                                        }
                                    }
                                } catch (Exception e) {
                                    source.sendMessage(Format.error(Text.of(e.getMessage())));
                                    e.printStackTrace();
                                }
                            });
                            sendResults(source, actionResults);
                        }).submit(Prism.getInstance());
                    } catch(Exception e) {
                        e.printStackTrace();
                    }

                    if (source instanceof Player) {
                        int changes = 0;

                        if (session.hasFlag(Flag.CLEAN)) {
                            changes += WorldUtil.removeIllegalBlocks(
                                ((Player) source).getLocation(), session.getRadius());
                            changes += WorldUtil.removeItemEntitiesAroundLocation(((Player) source).getLocation(), session.getRadius());
                        }

                        if (session.hasFlag(Flag.DRAIN)) {
                            changes += WorldUtil.removeLiquidsAroundLocation(
                                ((Player) source).getLocation(), session.getRadius());
                        }

                        if (changes > 0) {
                            source.sendMessage(Format.bonus("Cleaning area..."));
                        }
                    }

                }
            });
        } catch (Exception e) {
            source.sendMessage(Format.error(Text.of(e.getMessage())));
            e.printStackTrace();
        }
    }

    private static void sendResults(CommandSource source, List<ActionableResult> actionResults) {
        int appliedCount = 0;
        int skippedCount = 0;
        for (ActionableResult result : actionResults) {
            if (result.applied()) {
                appliedCount++;
            } else {
                skippedCount++;
            }
        }

        Map<String, String> tokens = new HashMap<>();
        tokens.put("appliedCount", ""+appliedCount);
        tokens.put("skippedCount", ""+skippedCount);

        final String messageTemplate;
        if (skippedCount > 0) {
            messageTemplate = Translation.from("rollback.success.withskipped");
        } else {
            messageTemplate = Translation.from("rollback.success");
        }

        source.sendMessage(Format.heading(
            Text.of(Template.parseTemplate(messageTemplate, tokens)),
            " ", Format.bonus(Translation.from("rollback.success.bonus"))
        ));

        if (source instanceof Player) {
            Prism.getInstance().getLastActionResults().put(((Player) source).getUniqueId(), actionResults);
        }
    }
}


text:
// ***********************************************************************
// Copyright (c) 2013-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework.Compatibility;
using NUnit.TestUtilities;

namespace NUnit.Framework.Internal
{
    public class RandomizerTests
    {
        private Randomizer _randomizer;

        [SetUp]
        public void CreateRandomizer()
        {
            _randomizer = new Randomizer();
        }

        #region Ints

        [Test]
        public void RandomIntsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.Next(), 10, 100);
        }

        [Test]
        public void RandomIntsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.Next(-300, 300), 10, 100);
        }

        #endregion

        #region Unsigned Ints

        [Test]
        public void RandomUInt()
        {
            uint u = _randomizer.NextUInt();
            Assert.That(u, Is.GreaterThan(0u));
        }

        [Test]
        public void RandomUIntWithMaximum()
        {
            uint val = _randomizer.NextUInt(100u);
            Assert.That(val >= 0u && val < 100u, "Out of range");
        }

        [Test]
        public void RandomUIntInRange()
        {
            uint val = _randomizer.NextUInt(42u, 99u);
            Assert.That(val >= 42u && val < 99u, "Out of range");
        }

        [Test]
        public void RandomUintInRange_Reversed()
        {
            Assert.That(() => _randomizer.NextUInt(99u, 42u), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomUintInRange_MinEqualsMax()
        {
            Assert.That(_randomizer.NextUInt(42u, 42u), Is.EqualTo(42u));
        }

        [Test]
        public void RandomUIntsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextUInt(), 10, 100);
        }

        [Test]
        public void RandomUIntsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextUInt(27u, 777u), 10, 100);
        }

        #endregion

        #region Shorts

        [Test]
        public void RandomShort()
        {
            short s = _randomizer.NextShort();
            Assert.That(s, Is.GreaterThan((short)0));
        }

        [Test]
        public void RandomShortWithMaximum()
        {
            short zero = 0;
            short max = 100;
            short s = _randomizer.NextShort(max);
            Assert.That(s >= zero && s < max, "Out of range");
        }

        [Test]
        public void RandomShortInRange()
        {
            short min = -10;
            short max = 100;
            short s = _randomizer.NextShort(min, max);
            Assert.That(s >= min && s < max, "Out of range");
        }

        [Test]
        public void RandomShortInRange_Reversed()
        {
            short min = 100;
            short max = -10;
            Assert.That(() => _randomizer.NextShort(min, max), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomShortInRange_MinEqualsMax()
        {
            short s = 42;
            Assert.That(_randomizer.NextShort(s, s), Is.EqualTo(s));
        }

        [Test]
        public void RandomShortsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextShort(), 10, 100);
        }

        [Test]
        public void RandomShortsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextShort(-300, 300), 10, 100);
        }

        #endregion

        #region Unsigned Shorts

        [Test]
        public void RandomUShort()
        {
            ushort us = _randomizer.NextUShort();
            Assert.That(us, Is.GreaterThan((ushort)0));
        }

        [Test]
        public void RandomUShortWithMaximum()
        {
            ushort zero = 0;
            ushort max = 100;
            ushort us = _randomizer.NextUShort(max);
            Assert.That(us >= zero && us < max, "Out of range");
        }

        [Test]
        public void RandomUShortInRange()
        {
            ushort min = 42;
            ushort max = 99;
            ushort val = _randomizer.NextUShort(min, max);
            Assert.That(val >= min && val < max, "Out of range");
        }

        [Test]
        public void RandomUShortInRange_Reversed()
        {
            ushort min = 99;
            ushort max = 42;
            Assert.That(() => _randomizer.NextUShort(min, max), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomUShortInRange_MinEqualsMax()
        {
            ushort val = 42;
            Assert.That(_randomizer.NextUShort(val, val), Is.EqualTo(val));
        }

        [Test]
        public void RandomUShortsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextUShort(), 10, 100);
        }

        [Test]
        public void RandomUShortsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextUShort((ushort)27, (ushort)200), 10, 100);
        }

        #endregion

        #region Longs

        [Test]
        public void RandomLong()
        {
            long val = _randomizer.NextLong();
            Assert.That(val, Is.GreaterThan(0L));
            Assert.That(val, Is.Not.EqualTo(long.MaxValue)); // Not much of a test!
        }

        [Test]
        public void RandomLongWithMaximum()
        {
            long val = _randomizer.NextLong(1066L);
            Assert.That(val >= 0L && val < 1066L, "Out of range");
        }

        [Test]
        public void RandomLongInRange()
        {
            long val = _randomizer.NextLong(1066L, 1942L);
            Assert.That(val >= 1066L && val < 1942L, "Out of range");
        }

        [Test]
        public void RandomLongInRange_Reversed()
        {
            Assert.That(() => _randomizer.NextLong(1942L, 1066L), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomLongInRange_MinEqualsMax()
        {
            long val = 42L;
            Assert.That(_randomizer.NextLong(val, val), Is.EqualTo(val));
        }

        [Test]
        public void RandomLongsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextLong(), 10, 100);
        }

        [Test]
        public void RandomLongsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextLong(1066L, 2010L), 10, 100);
        }

        #endregion

        #region Unsigned Longs

        [Test]
        public void RandomULong()
        {
            ulong val = _randomizer.NextULong();
            Assert.That(val, Is.Not.EqualTo(ulong.MaxValue)); // Not much of a test!
        }

        [Test]
        public void RandomULongWithMaximum()
        {
            ulong val = _randomizer.NextULong(1066UL);
            Assert.That(val < 1066UL, "Out of range");
        }

        [Test]
        public void RandomULongInRange()
        {
            ulong val = _randomizer.NextULong(1066UL, 1942UL);
            Assert.That(val >= 1066UL && val < 1942UL, "Out of range");
        }

        [Test]
        public void RandomULongInRange_Reversed()
        {
            Assert.That(() => _randomizer.NextULong(1942UL, 1066UL), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomULongInRange_MinEqualsMax()
        {
            ulong val = 42ul;
            Assert.That(_randomizer.NextULong(val, val), Is.EqualTo(val));
        }

        [Test]
        public void RandomULongsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextULong(), 10, 100);
        }

        [Test]
        public void RandomULongsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextULong(1066UL, 2010UL), 10, 100);
        }

        #endregion

        #region Bytes

        [Test]
        public void RandomByte()
        {
            byte b = _randomizer.NextByte();
            Assert.That(b >= byte.MinValue && b < byte.MaxValue);
        }

        [Test]
        public void RandomByteWithMaximum()
        {
            byte max = (byte)96;
            byte b = _randomizer.NextByte(max);
            Assert.That(b >= byte.MinValue && b < max);
        }

        [Test]
        public void RandomByteInRange()
        {
            byte min = (byte)16;
            byte max = (byte)96;
            byte b = _randomizer.NextByte(min, max);
            Assert.That(b >= min && b < max);
        }

        [Test]
        public void RandomByteInRange_Reversed()
        {
            byte min = (byte)96;
            byte max = (byte)16;
            Assert.That(() => _randomizer.NextByte(min, max), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomByteInRange_MinEqualsMax()
        {
            byte val = 42;
            Assert.That(_randomizer.NextByte(val, val), Is.EqualTo(val));
        }

        [Test]
        public void RandomBytesAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextByte(), 10, 1000);
        }

        [Test]
        public void RandomBytesInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextByte(byte.MinValue, byte.MaxValue), 10, 1000);
        }

        #endregion

        #region SBytes

        [Test]
        public void RandomSByte()
        {
            sbyte b = _randomizer.NextSByte();
            Assert.That(b >= sbyte.MinValue && b < sbyte.MaxValue);
        }

        [Test]
        public void RandomSByteWithMaximum()
        {
            sbyte max = (sbyte)96;
            sbyte b = _randomizer.NextSByte(max);
            Assert.That(b >= 0 && b < max);
        }

        [Test]
        public void RandomSByteInRange()
        {
            sbyte min = (sbyte)16;
            sbyte max = (sbyte)96;
            sbyte b = _randomizer.NextSByte(min, max);
            Assert.That(b >= min && b < max);
        }

        [Test]
        public void RandomSByteInRange_Reversed()
        {
            sbyte min = (sbyte)96;
            sbyte max = (sbyte)16;
            Assert.That(() => _randomizer.NextSByte(min, max), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomSbyteInRange_MinEqualsMax()
        {
            sbyte val = 42;
            Assert.That(_randomizer.NextSByte(val, val), Is.EqualTo(val));
        }

        [Test]
        public void RandomSBytesAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextSByte(), 10, 1000);
        }

        [Test]
        public void RandomSBytesInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextSByte(sbyte.MinValue, sbyte.MaxValue), 10, 1000);
        }

        #endregion

        #region Bool

        [Test]
        public void RandomBool()
        {
            UniqueValues.Check(() => _randomizer.NextBool(), 2, 100);
        }

        [Test]
        public void RandomBoolWithProbability()
        {
            UniqueValues.Check(() => _randomizer.NextBool(.25), 2, 200);
        }

        [Test]
        public void RandomBoolWithProbabilityOutOfRange()
        {
            Assert.That(() => _randomizer.NextBool(2.0), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomBoolWithProbabilityZeroIsAlwaysFalse()
        {
            for (int i = 0; i < 10; i++)
                Assert.False(_randomizer.NextBool(0.0));
        }

        public void RandomBoolWithProbabilityOneIsAlwaysTrue()
        {
            for (int i = 0; i < 10; i++)
                Assert.True(_randomizer.NextBool(1.0));
        }

        #endregion

        #region Doubles

        [Test]
        public void RandomDouble()
        {
            double d = _randomizer.NextDouble();
            Assert.That(d, Is.GreaterThan(0.0));
        }

        [Test]
        public void RandomDoubleWithMaximum()
        {
            double d = _randomizer.NextDouble(100.0);
            Assert.That(d >= 0.0 && d < 100.0, "Out of range");
        }

        [Test]
        public void RandomDoubleInRange()
        {
            double d = _randomizer.NextDouble(0.2, 0.7);
            Assert.That(d >= 0.2 && d < 0.7, "Out of range");
        }

        [Test]
        public void RandomDoubleInRange_Reversed()
        {
            Assert.That(() => _randomizer.NextDouble(0.7, 0.2), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomDoubleInRange_MinEqualsMax()
        {
            double val = 42.0;
            Assert.That(_randomizer.NextDouble(val, val), Is.EqualTo(val));
        }

        [Test]
        public void RandomDoublesAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextDouble(), 10, 100);
        }

        [Test]
        public void RandomDoublesInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextDouble(0.1, 0.7), 10, 100);
        }

        #endregion

        #region Floats

        [Test]
        public void RandomFloat()
        {
            float f = _randomizer.NextFloat();
            Assert.That(f, Is.GreaterThan(0.0f));
        }

        [Test]
        public void RandomFloatWithMaximum()
        {
            float f = _randomizer.NextFloat(100.0f);
            Assert.That(f >= 0.0f && f < 100.0f, "Out of range");
        }

        [Test]
        public void RandomFloatInRange()
        {
            float f = _randomizer.NextFloat(0.2f, 0.7f);
            Assert.That(f >= 0.2f && f < 0.7f, "Out of range");
        }

        [Test]
        public void RandomFloatInRange_Reversed()
        {
            Assert.That(() => _randomizer.NextFloat(0.7f, 0.2f), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomFloatInRange_MinEqualsMax()
        {
            float val = 42.0f;
            Assert.That(_randomizer.NextFloat(val, val), Is.EqualTo(val));
        }

        [Test]
        public void RandomFloatsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextFloat(), 10, 100);
        }

        [Test]
        public void RandomFloatsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextFloat(0.5f, 1.5f), 10, 100);
        }

        /// <summary>
        /// Return an array of random floats between 0.0 and 1.0.
        /// </summary>
        public float[] GetFloats(int count)
        {
            float[] floats = new float[count];

            for (int index = 0; index < count; index++)
                floats[index] = _randomizer.NextFloat();

            return floats;
        }

        /// <summary>
        /// Return an array of random floats with values in a specified range.
        /// </summary>
        public float[] GetFloats(float min, float max, int count)
        {
            float[] floats = new float[count];

            for (int index = 0; index < count; index++)
                floats[index] = _randomizer.NextFloat(min, max);

            return floats;
        }

        #endregion

        #region Decimals

        [Test]
        public void RandomDecimal()
        {
            decimal d = _randomizer.NextDecimal();
            Assert.That(d, Is.InRange(0M, decimal.MaxValue));
            CheckScaleIsZero(d);
        }

        private static void CheckScaleIsZero(decimal d)
        {
            int[] bits = decimal.GetBits(d);
            Assert.That(bits[3] & 0x00ff0000, Is.EqualTo(0));
        }

        [Test]
        public void RandomDecimalWithMaximum()
        {
            decimal d = _randomizer.NextDecimal(1000M);
            Assert.That(d, Is.InRange(0M, 999M));
            CheckScaleIsZero(d);
        }

        [Test]
        public void RandomDecimalInRange()
        {
            decimal d = _randomizer.NextDecimal(-500M, 500M);
            Assert.That(d, Is.InRange(-500M, 499M));
            CheckScaleIsZero(d);
        }

        [Test]
        public void RandomDecimalInRange_Reversed()
        {
            Assert.That(() => _randomizer.NextDecimal(1000M, 100M), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void RandomDecimalInRange_MinEqualsMax()
        {
            Assert.That(_randomizer.NextDecimal(42M, 42M), Is.EqualTo(42M));
        }

        [Test]
        public void RandomDecimalRangeTooGreat()
        {
            Assert.That(() => _randomizer.NextDecimal(-1M, decimal.MaxValue), Throws.InstanceOf<ArgumentException>());
        }

        [Test]
        public void RandomDecimalsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextDecimal(), 10, 100);
        }

        [Test]
        public void RandomDecimalsInRangeAreUnique()
        {
            UniqueValues.Check(() => _randomizer.NextDecimal(1066M, 2010M), 10, 100);
        }

        #endregion

        #region Strings

        [Test]
        [Description("Test that all generated strings are unique")]
        public void RandomStringsAreUnique()
        {
            UniqueValues.Check(() => _randomizer.GetString(), 10, 10);
        }

        [TestCase(30, "Theɋúickƃròwnf߀хjumpëԁoѵertհëlaȥydoɢ")]
        [TestCase(200, "aèí߀ù123456")]
        [TestCase(1000, Randomizer.DefaultStringChars)]
        [Description("Test that all generated strings are unique for varying output length")]
        public void RandomStringsAreUnique(int outputLength, string allowedChars)
        {
            UniqueValues.Check(() => _randomizer.GetString(outputLength, allowedChars), 10, 10);
        }

        #endregion

        #region Enums

        [Test]
        public void RandomEnum()
        {
            UniqueValues.Check(() => _randomizer.NextEnum(typeof(AttributeTargets)), 5, 50);
        }

        [Test]
        public void RandomEnum_Generic()
        {
            UniqueValues.Check(() => _randomizer.NextEnum<AttributeTargets>(), 5, 50);
        }

        #endregion

        #region Repeatability

        public static class Repeatability
        {
            [Test]
            public static void RandomizersWithSameSeedsReturnSameValues()
            {
                var r1 = new Randomizer(1234);
                var r2 = new Randomizer(1234);

                for (int i = 0; i < 10; i++)
                    Assert.That(r1.NextDouble(), Is.EqualTo(r2.NextDouble()));
            }

            [Test]
            public static void RandomizersWithDifferentSeedsReturnDifferentValues()
            {
                var r1 = new Randomizer(1234);
                var r2 = new Randomizer(4321);

                for (int i = 0; i < 10; i++)
                    Assert.That(r1.NextDouble(), Is.Not.EqualTo(r2.NextDouble()));
            }

            [Test]
            public static void ReturnsSameRandomizerForSameParameter()
            {
                ParameterInfo p = testMethod1.GetParameters()[0];
                var r1 = Randomizer.GetRandomizer(p);
                var r2 = Randomizer.GetRandomizer(p);
                Assert.That(r1, Is.SameAs(r2));
            }

            [Test]
            public static void ReturnsSameRandomizerForDifferentParametersOfSameMethod()
            {
                ParameterInfo p1 = testMethod1.GetParameters()[0];
                ParameterInfo p2 = testMethod1.GetParameters()[1];
                var r1 = Randomizer.GetRandomizer(p1);
                var r2 = Randomizer.GetRandomizer(p2);
                Assert.That(r1, Is.SameAs(r2));
            }

            [Test]
            public static void ReturnsSameRandomizerForSameMethod()
            {
                var r1 = Randomizer.GetRandomizer(testMethod1);
                var r2 = Randomizer.GetRandomizer(testMethod1);
                Assert.That(r1, Is.SameAs(r2));
            }

            [Test]
            public static void ReturnsDifferentRandomizersForDifferentMethods()
            {
                var r1 = Randomizer.GetRandomizer(testMethod1);
                var r2 = Randomizer.GetRandomizer(testMethod2);
                Assert.That(r1, Is.Not.SameAs(r2));
            }

            static readonly MethodInfo testMethod1 =
                typeof(Repeatability).GetMethod("TestMethod1", BindingFlags.NonPublic | BindingFlags.Static);
            private static void TestMethod1(int x, int y)
            {
            }

            static readonly MethodInfo testMethod2 =
                typeof(Repeatability).GetMethod("TestMethod2", BindingFlags.NonPublic | BindingFlags.Static);
            private static void TestMethod2(int x, int y)
            {
            }
        }

        #endregion
    }
}


text:
const { Command } = require('discord.js-commando');
const music = require('../../structures/music.js');

module.exports = class Music_Stop extends Command {
    constructor(client) {
        super(client, {
            name: 'stop',
            group: 'music',
            memberName: 'stop',
            description: 'Stop what\'s playing and clears queue.',
            format: 'n/a'
        });
    }

    run(msg) {
        // if (!isAdmin(msg.member)) return msg.channel.send('You are not allowed to use this command.');
        if (!msg.guild.me.voiceChannel) msg.channel.send('Not in a voice channel.');

        const queue = music.getQueue(msg.guild.id);
        queue.splice(0, queue.length);
        msg.guild.me.voiceChannel.leave();
        msg.channel.send('Stopped playing and cleared queue list.');
    }
};


text:
"""
    FusionCompute create vm
"""

import re

from nova import exception
from nova.openstack.common import jsonutils
from nova.openstack.common.gettextutils import _

from nova.fusioncompute.virt.huaweiapi import ops_task_base
from nova.fusioncompute.virt.huaweiapi import constant
from nova.fusioncompute.virt.huaweiapi import exception as fc_exc
from nova.fusioncompute.virt.huaweiapi import utils
from nova.fusioncompute.virt.huaweiapi.utils import LOG
from nova.fusioncompute.virt.huaweiapi.fcinstance import FC_INSTANCE_MANAGER as FC_MGR

from FSComponentUtil import crypt

class VmCreateBase(ops_task_base.OpsTaskBase):
    """vm controller class"""
    def __init__(self, fc_client, task_ops, instance):
        super(VmCreateBase, self).__init__(fc_client, task_ops)
        self._instance = instance
        self._key_data = self._instance.get('key_data')
        self._metadata = self._instance.get('metadata')

        self._vm_create_body = {}
        self._volume_ops = None
        self._location = None
        self._vifs = []
        self._block_device_info = {}
        self._root_device_name = None
        self._image_meta = {}
        self._injected_files = []
        self._admin_password = None
        self._extra_specs = {}
        self._context = {}
        self._customization = {}

    def __call__(self, context, volume_ops, location,
                 vifs, block_device_info, image_meta,
                 injected_files, admin_password, extra_specs, customization):
        self._volume_ops = volume_ops
        self._location = location
        self._vifs = vifs
        self._block_device_info = block_device_info
        self._root_device_name = block_device_info.get('root_device_name')
        self._image_meta = image_meta
        self._injected_files = injected_files
        self._admin_password = admin_password
        self._extra_specs = extra_specs
        self._context = context
        self._customization = customization

    @property
    def image_properties(self):
        """
        image mate properties
        :return:
        """
        if self._image_meta:
            return self._image_meta.get('properties', {})
        else:
            return {}

    def check_input(self):
        """
        check function input params
        :return:
        """
        os_option = self.get_os_options()
        LOG.debug(_('os option: %s .'), jsonutils.dumps(os_option))
        if not (os_option['osType'] and os_option['osVersion']):
            LOG.error('Invalid os option for vm %s!', self._instance['name'])
            raise fc_exc.InvalidOsOption()

    def get_body_ext(self):
        """
        if body not enough, child class can extend
        :return:
        """
        raise NotImplementedError()

    def build_para(self):
        """build create body"""
        self._vm_create_body = {
            'name': self._instance['display_name'],
            'description': self._instance['name'],
            'group': constant.VM_GROUP_FLAG,
            'uuid': self._instance['uuid'],
            'location': self._location,
            'autoBoot': self.is_auto_boot(),
            'vmConfig': self.get_vm_config(),
            'osOptions': self.get_os_options(),
            'vmCustomization': self.get_vm_customization(),
            'publickey': self._key_data
        }
        self.get_body_ext()

    def extend_ops_before_start(self):
        """
        vm is created in stopped state, do something before start
        :return:
        """
        pass

    def create_and_boot_vm(self):
        """
        create vm interface func
        :return:
        """
        self.check_input()
        self.build_para()
        self.create_vm()

        # VM is created in stopped state in some cases,
        # do the extended ops in subclass and start it at last
        if not self.is_auto_boot():
            self.inject_files()

            #Other opeation when vm stoped
            self.extend_ops_before_start()
            self.start_vm()

    def get_cpu_info(self):
        """get vm cpu info"""
        cpu_info = {'quantity': self._instance['vcpus']}
        cpu_qos = utils.dict_filter_and_convert(self._extra_specs,
                                                constant.CPU_QOS_NOVA_KEY,
                                                constant.CPU_QOS_FC_KEY)
        cpu_info = utils.dict_add(cpu_info, cpu_qos)
        return cpu_info

    def get_memory_info(self):
        """get vm memory info"""
        return {
            'quantityMB': self._instance['memory_mb']
        }

    def get_disks_info(self):
        """get vm disk specific info"""
        raise NotImplementedError()

    def get_nic_info(self):
        """get vm nic info"""
        return [
            {
                'name': vif['network_info']['id'],
                'portId': vif['network_info']['id'],
                'mac': vif['network_info']['address'],
                'portGroupUrn': vif['pg_urn'],
                'sequenceNum': vif['sequence_num']
            }
            for vif in self._vifs
        ]

    def get_fc_os_options(self, os_type, os_version):
        """
        get fc options
        :param os_type:
        :param os_version:
        :return:
        """
        try:
            fc_os_type = constant.HUAWEI_OS_TYPE_MAP[os_type.lower()]
            fc_os_version = \
                constant.HUAWEI_OS_VERSION_INT[os_type][os_version.lower()]
        #ignore pylint:disable=W0703
        except Exception as excp:
            LOG.warn(_("use default os type and version %s."), excp)
            fc_os_type, fc_os_version = constant.DEFAULT_HUAWEI_OS_CONFIG

        return {
            'osType': fc_os_type,
            'osVersion': fc_os_version
        }

    def get_os_options(self):
        """
        get vm os info
        get os Type from mata
        :return:
        """
        os_type = self._metadata.get(constant.HUAWEI_OS_TYPE)
        os_version = self._metadata.get(constant.HUAWEI_OS_VERSION)
        return self.get_fc_os_options(os_type, os_version)

    def get_properties(self):
        """get vm property"""
        return {
            'bootOption': utils.get_boot_option_from_metadata(self._metadata)
        }

    def get_vm_config(self):
        """get vm config info"""
        vm_config_body = {
            'cpu': self.get_cpu_info(),
            'memory': self.get_memory_info(),
            'disks': self.get_disks_info(),
            'nics': self.get_nic_info(),
            'properties': self.get_properties()
        }
        return vm_config_body

    def _get_vm_customization_nics(self):
        """get vm customization nics"""
        cus_nics = []
        for vif in self._vifs:
            if vif['enable_dhcp']:
                cus_nic = {
                    'sequenceNum': vif['sequence_num'] + 1
                }
                cus_nics.append(cus_nic)
                continue

            network = vif['network_info']['network']
            subnet_ipv4_list = [s for s in network['subnets']
                                if s['version'] == constant.IPV4_VERSION]
            if len(subnet_ipv4_list) > 0:
                ip_ipv4 = None

                dns = [None, None]
                if len(subnet_ipv4_list[0]['ips']) > 0:
                    ip_ipv4 = subnet_ipv4_list[0]['ips'][0]

                dns_len = len(subnet_ipv4_list[0]['dns'])
                for index in range(0, min(2, dns_len)):
                    dns[index] = subnet_ipv4_list[0]['dns'][index]['address']

                netmask_ipv4 = str(subnet_ipv4_list[0].as_netaddr().netmask)
                gateway_ipv4 = subnet_ipv4_list[0]['gateway']['address']

                cus_nic = {'sequenceNum': vif['sequence_num'] + 1,
                           'ip':  ip_ipv4 and ip_ipv4['address'] or '',
                           'gateway': gateway_ipv4,
                           'netmask': netmask_ipv4,
                           'ipVersion': constant.IPV4_VERSION,
                           'setdns': dns[0],
                           'adddns': dns[1]}
                cus_nics.append(cus_nic)

        LOG.debug(_('cus_nic: %s.'), jsonutils.dumps(cus_nics))
        return cus_nics

    def _validate_customization(self, customization):
        """

        :return:
        """

        valid_customizations = [
            'hostname',
            'workgroup',
            'domain',
            'domainName',
            'domainPassword',
            'ouName'
        ]

        for key in customization.keys():
            if key not in valid_customizations:
                msg = _("Invalid key: %s") % key
                raise fc_exc.InvalidCustomizationInfo(reason=msg)

    def get_vm_customization(self):
        """get vm custom info"""
        if self.get_os_options()['osType'] == 'Other':
            return None

        vm_custom_body = {
            'osType': self.get_os_options()['osType'],
            'password': self._admin_password,
            'nicSpecification': self._get_vm_customization_nics()
        }

        self._validate_customization(self._customization)
        for key in self._customization.keys():
            vm_custom_body[key] = self._customization[key]

        return vm_custom_body

    def is_auto_boot(self):
        """get auto boot"""
        if len(self._injected_files):
            return False
        else:
            return True

    def inject_files(self):
        """

        :return:
        """

        fc_vm = FC_MGR.get_vm_by_uuid(self._instance)
        for (path, contents) in self._injected_files:
            body = {
                'fileName': path,
                'vmData': contents
            }
            self.post(fc_vm.get_vm_action_uri('set_vm_data'), data=body)
            LOG.debug(_('inject file %s succeed.') % path)

    def create_vm(self):
        """
        create vm interface
        :return:
        """
        raise NotImplementedError()

    def start_vm(self):
        """

        :return:
        """
        fc_vm = FC_MGR.get_vm_by_uuid(self._instance)
        self.post(fc_vm.get_vm_action_uri('start'),
                  excp=exception.InstancePowerOnFailure)

class VmCreateByImport(VmCreateBase):
    """
    create vm use import vm interface
    """
    def get_protocol(self):
        """get nfs or null"""
        raise NotImplementedError()

    def create_vm(self):
        """
        create vm by import interface
        :return:
        """
        self.post(self.site.import_vm_uri, data=self._vm_create_body,
                  excp=fc_exc.FusionComputeReturnException)

    def get_body_ext(self):
        """
        import vm extend params
        :return:
        """
        self._vm_create_body['protocol'] = self.get_protocol()

class VmCreateWithVolume(VmCreateByImport):
    """create vm with volume"""

    def get_protocol(self):
        """get null"""
        return "null"

    def get_disks_info(self):
        """override get vm disk specific info"""

        LOG.debug(_('prepare volume'))

        disks_info = []
        for disk in self._volume_ops.ensure_volume(self._block_device_info):
            disk_info = {
                'pciType': disk['pci'],
                'volumeUrn': disk['urn'],
                'isThin': constant.FC_DRIVER_JOINT_CFG['volume_is_thin']
            }

            if disk['mount_device'] == self._root_device_name:
                disk_info['sequenceNum'] = 1
            else:
                disk_info['sequenceNum'] = \
                    constant.MOUNT_DEVICE_SEQNUM_MAP[disk['mount_device']]

            disks_info.append(disk_info)
        return disks_info

    def get_os_options(self):
        """get vm os info"""
        # get os Type from mata
        meta_data = self._volume_ops.\
            get_block_device_meta_data(self._context, self._block_device_info)
        if meta_data:
            volume_meta_data = meta_data.get('volume_image_metadata')
            if volume_meta_data:
                os_type = volume_meta_data.get(constant.HUAWEI_OS_TYPE)
                os_version = volume_meta_data.get(constant.HUAWEI_OS_VERSION)
                if os_type:
                    return self.get_fc_os_options(os_type, os_version)

        return super(VmCreateWithVolume, self).get_os_options()

class VmCreateWithImage(VmCreateByImport):
    """create vm with image"""

    def get_protocol(self):
        """default protocol is glance"""
        return "glance"

    def get_os_options(self):
        """get vm os info"""

        # get os Type from mata
        os_type = self.image_properties.get(constant.HUAWEI_OS_TYPE)
        os_version = self.image_properties.get(constant.HUAWEI_OS_VERSION)
        if os_type:
            return self.get_fc_os_options(os_type, os_version)
        else:
            return super(VmCreateWithImage, self).get_os_options()

    def _get_image_size(self):
        """get image size info"""
        image_size = self._image_meta.get('size')
        if image_size:
            return utils.image_size_to_gb(image_size)
        else:
            return 0

    def check_input(self):
        """
        create vm image detail check
        :return:
        """
        super(VmCreateWithImage, self).check_input()

        disk_quantity_gb = self._instance['root_gb']
        image_size = self._get_image_size()
        if image_size > disk_quantity_gb:
            LOG.error(_("image is larger than sys-vol."))
            raise fc_exc.ImageTooLarge

    def get_disks_info(self):
        """get image disk detail info"""

        LOG.debug(_('prepare volume'))

        disks_info = []

        # sys vol info
        sys_disk_info = {
            'sequenceNum': 1,
            'quantityGB': self._instance['root_gb'],
            'isThin': constant.FC_DRIVER_JOINT_CFG['volume_is_thin']
        }
        disks_info.append(sys_disk_info)

        # user vol info
        for disk in self._volume_ops.ensure_volume(self._block_device_info):
            user_disk_info = {
                'pciType': disk['pci'],
                'volumeUrn': disk['urn'],
                'sequenceNum':
                    constant.MOUNT_DEVICE_SEQNUM_MAP[disk['mount_device']],
                'isThin': constant.FC_DRIVER_JOINT_CFG['volume_is_thin']
            }
            disks_info.append(user_disk_info)

        return disks_info

class VmCreateWithNfsImage(VmCreateWithImage):
    """create vm with nfs image"""

    def get_protocol(self):
        """get nfs protocol"""
        return "nfs"

    def _get_template_url(self):
        """get nfs location"""
        return self.image_properties[constant.HUAWEI_IMAGE_LOCATION]

    def get_body_ext(self):
        """
        create vm with image, extend url info
        :return:
        """
        super(VmCreateWithNfsImage, self).get_body_ext()
        self._vm_create_body['url'] = self._get_template_url()

class VmCreateWithUdsImage(VmCreateWithImage):
    """create vm with uds image"""

    """
    create vm use import vm interface
    """
    def __init__(self, fc_client, task_ops, instance):
        super(VmCreateWithUdsImage, self).__init__(fc_client, task_ops, instance)
        self.usd_image_server_ip = None
        self.usd_image_port = None
        self.usd_image_bucket_name = None
        self.usd_image_key = None

    def _get_uds_image_info(self, image_location):
        """
        :param image_location: {ip}:{port}:{buket name}:{key}
        192.168.0.1:5443:region1.glance:001
        """

        if image_location:
            uds_image_info = image_location.strip()
            str_array = re.split(":", uds_image_info)
            if len(str_array) == 4:
                return str_array[0], \
                       str_array[1], \
                       str_array[2], \
                       str_array[3]
        reason = _("Invalid uds image info,invalid image_location!")
        raise fc_exc.InvalidUdsImageInfo(reason=reason)

    def check_input(self):
        super(VmCreateWithUdsImage, self).check_input()

        properties = self._image_meta.get('properties')
        if properties:
            try:
                self.usd_image_server_ip,  \
                self.usd_image_port, \
                self.usd_image_bucket_name, \
                self.usd_image_key = \
                    self._get_uds_image_info\
                        (properties.get(constant.HUAWEI_IMAGE_LOCATION))
            except Exception:
                reason = _("Invalid uds image info,invalid loaction!")
                raise fc_exc.InvalidUdsImageInfo(reason=reason)

        if constant.CONF.fusioncompute.uds_access_key is '' \
                or constant.CONF.fusioncompute.uds_secret_key is '':
            reason = _("Invalid uds image info,invalid AK SK!")
            raise fc_exc.InvalidUdsImageInfo(reason=reason)

    def get_protocol(self):
        """get uds protocol"""
        return "uds"

    def get_body_ext(self):
        """
        create vm with image, extend uds info
        :return:
        """
        super(VmCreateWithUdsImage, self).get_body_ext()
        self._vm_create_body['s3Config'] = {
            'serverIp': self.usd_image_server_ip,
            'port': self.usd_image_port,
            'accessKey': crypt.decrypt(constant.CONF.fusioncompute.uds_access_key),
            'secretKey': crypt.decrypt(constant.CONF.fusioncompute.uds_secret_key),
            'bucketName': self.usd_image_bucket_name,
            'key': self.usd_image_key
        }

class VmCreateWithGlanceImage(VmCreateWithImage):
    """create vm with glance image"""

    def check_input(self):
        super(VmCreateWithGlanceImage, self).check_input()

        if constant.CONF.fusioncompute.glance_server_ip is '':
            reason = _("Invalid glance image info,invalid server ip!")
            raise fc_exc.InvalidGlanceImageInfo(reason=reason)

    def get_body_ext(self):
        """
        create vm with image, extend glance info
        :return:
        """
        super(VmCreateWithGlanceImage, self).get_body_ext()
        self._vm_create_body['glanceConfig'] = {
            'endPoint': ':'.join([str(constant.CONF.glance.host),
                                  str(constant.CONF.glance.port)]),
            'serverIp': constant.CONF.fusioncompute.glance_server_ip,
            'token': self._context.auth_token,
            'imageID': self._image_meta['id']
        }

class VmCreateByClone(VmCreateBase):
    """
    create vm use import vm interface
    """
    def __init__(self, fc_client, task_ops, instance):
        super(VmCreateByClone, self).__init__(fc_client, task_ops, instance)
        self._need_attach_user_vols = False
        self._cloned_source_vm_or_tpl = None

    def is_auto_boot(self):
        """

        :return:
        """
        if len(self._block_device_info.get('block_device_mapping')):
            self._need_attach_user_vols = True
            return False
        else:
            return super(VmCreateByClone, self).is_auto_boot()

    def get_os_options(self):
        """get vm os info"""

        # get os Type from mata
        os_type = self.image_properties.get(constant.HUAWEI_OS_TYPE)
        os_version = self.image_properties.get(constant.HUAWEI_OS_VERSION)
        if os_type:
            return self.get_fc_os_options(os_type, os_version)
        else:
            return super(VmCreateByClone, self).get_os_options()

    def get_disks_info(self):
        """
        FC itself will clone disks belonging to this tpl/vm(it should and
        must has only one sys volume).
        """
        LOG.debug(_('prepare volume'))
        disks_info = []
        disk_sequence = 1

        # sys vol info
        sys_disk_info = {
            'sequenceNum': disk_sequence,
            'quantityGB': self._instance['root_gb'],
            'isThin': constant.FC_DRIVER_JOINT_CFG['volume_is_thin']
        }
        disks_info.append(sys_disk_info)

        return disks_info

    def get_body_ext(self):
        """
        if body not enough, child class can extend
        :return:
        """
        if self._vm_create_body.has_key("uuid"):
            self._vm_create_body.pop("uuid")
        self._vm_create_body["clonedVmUUID"] = self._instance['uuid']

    def extend_ops_before_start(self):
        """
        create by clone, user vol should attach when vm stoped
        :return:
        """
        if self._need_attach_user_vols:
            self._attach_user_vols()

    def _attach_user_vols(self):
        """

        :return:
        """
        fc_vm = FC_MGR.get_vm_by_uuid(self._instance)
        for disk in self._volume_ops.ensure_volume(self._block_device_info):
            body = {
                'volUrn': disk['urn'],
                'sequenceNum':
                    constant.MOUNT_DEVICE_SEQNUM_MAP[disk['mount_device']]
            }
            LOG.debug(_("begin attach user vol: %s"), disk['urn'])
            self._volume_ops.attach_volume(fc_vm, vol_config=body)

    def create_vm(self):
        self.post(self._cloned_source_vm_or_tpl.get_vm_action_uri('clone'),
                  data=self._vm_create_body,
                  excp=fc_exc.InstanceCloneFailure)

class VmCreateWithTemplate(VmCreateByClone):
    """create vm with image"""

    def check_input(self):
        super(VmCreateWithTemplate, self).check_input()

        properties = self._image_meta.get('properties')
        if properties:
            try:
                self._cloned_source_vm_or_tpl = \
                    self._get_vm_by_template_url(
                        properties.get(constant.HUAWEI_IMAGE_LOCATION))
                self._validate_template(self._cloned_source_vm_or_tpl)
            except Exception:
                LOG.error(_("Invalid FusionCompute template !"))
                raise fc_exc.InstanceCloneFailure

    def get_body_ext(self):
        """
        if body not enough, child class can extend
        :return:
        """
        super(VmCreateWithTemplate, self).get_body_ext()
        self._vm_create_body['isTemplate'] = False

        is_link_clone = self._metadata.get(constant.HUAWEI_IS_LINK_CLONE)
        if is_link_clone:
            self._vm_create_body['isLinkClone'] = is_link_clone

    def _get_vm_by_template_url(self, template_url):
        """
        :param template_url: {vrm site id}:{vm id}
        239d8a8e:i-00000061
        """

        vm_id = None
        if template_url:
            url = template_url.strip()
            str_array = re.split(":", url)
            if len(str_array) == 2:
                vm_id = str_array[1]

        if vm_id is not None:
            return FC_MGR.get_vm_by_id(vm_id)
        return None

    def _validate_template(self, instance):
        """

        :param instance: fc vm
        :return:
        """
        if instance is not None and instance.isTemplate is not True:
            raise fc_exc.InstanceCloneFailure

        for disk in instance['vmConfig']['disks']:
            if disk['sequenceNum'] not in [0, 1]:
                raise fc_exc.InstanceCloneFailure

def get_vm_create(fc_client, task_ops, instance, image_meta=None):
    """get create vm object"""
    if instance.get('image_ref'):
        image_type = None
        if image_meta:
            properties = image_meta.get('properties')
            if properties:
                image_type = properties.get(constant.HUAWEI_IMAGE_TYPE)

        if image_type == 'nfs':
            vm_class = VmCreateWithNfsImage
        elif image_type == 'uds':
            vm_class = VmCreateWithUdsImage
        elif image_type == 'template':
            vm_class = VmCreateWithTemplate
        elif image_type == 'glance' or image_type == None:
            vm_class = VmCreateWithGlanceImage
        else:
            LOG.error(_("image type is error %s."), image_type)
            raise fc_exc.InvalidImageDir
    else:
        vm_class = VmCreateWithVolume

    return vm_class(fc_client, task_ops, instance)


text:
"""Unit tests."""

import mock
import pytest

from google.cloud import automl_v1beta1
from google.cloud.automl_v1beta1.proto import data_items_pb2
from google.cloud.automl_v1beta1.proto import prediction_service_pb2

class MultiCallableStub(object):
    """Stub for the grpc.UnaryUnaryMultiCallable interface."""

    def __init__(self, method, channel_stub):
        self.method = method
        self.channel_stub = channel_stub

    def __call__(self, request, timeout=None, metadata=None, credentials=None):
        self.channel_stub.requests.append((self.method, request))

        response = None
        if self.channel_stub.responses:
            response = self.channel_stub.responses.pop()

        if isinstance(response, Exception):
            raise response

        if response:
            return response

class ChannelStub(object):
    """Stub for the grpc.Channel interface."""

    def __init__(self, responses=[]):
        self.responses = responses
        self.requests = []

    def unary_unary(self, method, request_serializer=None, response_deserializer=None):
        return MultiCallableStub(method, self)

class CustomException(Exception):
    pass

class TestPredictionServiceClient(object):
    def test_predict(self):
        # Setup Expected Response
        expected_response = {}
        expected_response = prediction_service_pb2.PredictResponse(**expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = automl_v1beta1.PredictionServiceClient()

        # Setup Request
        name = client.model_path("[PROJECT]", "[LOCATION]", "[MODEL]")
        payload = {}

        response = client.predict(name, payload)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = prediction_service_pb2.PredictRequest(
            name=name, payload=payload
        )
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request

    def test_predict_exception(self):
        # Mock the API response
        channel = ChannelStub(responses=[CustomException()])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = automl_v1beta1.PredictionServiceClient()

        # Setup request
        name = client.model_path("[PROJECT]", "[LOCATION]", "[MODEL]")
        payload = {}

        with pytest.raises(CustomException):
            client.predict(name, payload)


text:
'use strict';

import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as objQuery from 'simple-object-query';
import * as Data from '../data/PolyGuruConfig';
import * as _orderBy from 'lodash.orderby';

import { FileParser } from '../parsers/FileParser';
import { HTMLFileParser } from '../parsers/HTMLFileParser';

export class CacheStorage {
  private static _instance: CacheStorage;
  public static get Instance() {
    return CacheStorage._instance || (CacheStorage._instance = new CacheStorage());
  }

  private _configWatcher: vscode.FileSystemWatcher;
  private _config: Data.PolyGuruConfig;

  public get config() {
    return this._config;
  }

  public static get configPath(): string {
    return path.join(vscode.workspace.rootPath, '.polymer-guru.json');
  }

  private _listAppComponents: HTMLFileParser[] = [];
  private _listAppComponentsOrdered: HTMLFileParser[] = null;
  private _listExtLibComponents: HTMLFileParser[] = [];
  private _listExtLibComponentsOrdered: HTMLFileParser[] = null;
  private _listOtherResources: FileParser[] = [];
  private _listFailedResources: { fileParser: FileParser, error: any }[] = [];

  public get appComponents(): HTMLFileParser[] {
    return this._listAppComponents;
  }

  public get appComponentsOrdered(): HTMLFileParser[] {
    if (!this._listAppComponentsOrdered) {
      this._listAppComponentsOrdered = _orderBy(this.appComponents, (d) => {
        return d.filePath.relativePath;
      });
    }
    return this._listAppComponentsOrdered;
  }

  public clearAppComponents() {
    this._listAppComponents = [];
    this.clearAppComponentsOrderedCacheList();
  }
  public clearAppComponentsOrderedCacheList() {
    this._listAppComponentsOrdered = null;
  }

  public get externalComponents(): HTMLFileParser[] {
    return this._listExtLibComponents;
  }
  public get externalComponentsOrdered(): HTMLFileParser[] {
    if (!this._listExtLibComponentsOrdered) {
      this._listExtLibComponentsOrdered = _orderBy(this.externalComponents, (d) => {
        return d.filePath.relativePath;
      });
    }
    return this._listExtLibComponentsOrdered;
  }
  public clearExternalComponents() {
    this._listExtLibComponents = [];
    this.clearExternalComponentsOrderedCacheList();
  }
  public clearExternalComponentsOrderedCacheList() {
    this._listExtLibComponentsOrdered = null;
  }

  public get otherResources(): FileParser[] {
    return this._listOtherResources;
  }
  public clearOtherResources() {
    this._listOtherResources = [];
  }

  public get failedResources(): { fileParser: FileParser, error: any }[] {
    return this._listFailedResources;
  }
  public clearFailedResources() {
    this._listFailedResources = [];
  }

  private constructor() {
  }

  public loadConfig(): void {
    try {
      var contentBuffer = fs.readFileSync(CacheStorage.configPath, 'utf-8');
      this._config = JSON.parse(contentBuffer) as Data.PolyGuruConfig;

      this._initConfigWatcher();
    } catch (e) {
      console.log((<Error>e));
    }
  }

  private _initConfigWatcher() {
    if (!this._configWatcher) {
      this._configWatcher = vscode.workspace.createFileSystemWatcher(CacheStorage.configPath, true, false, true);
      this._configWatcher.onDidChange(() => {
        this.loadConfig();
      });
    }
  }
}


text:
import sys

from setuptools import setup, find_packages

import kamboo

requires = ['kotocore']

if sys.version_info[:2] == (2, 6):
    # For python2.6 we have to require argparse since it
    # was not in stdlib until 2.7.
    requires.append('argparse>=1.1')

setup_options = dict(
    name='kamboo',
    version=kamboo.__version__,
    description='To build and distribute AMI images' +
    ' or EC2 snapshots across accounts and regions',
    long_description=open('README.rst').read(),
    author='Henry Huang',
    author_email='henry.s.huang@gmail.com',
    url='https://github.com/henrysher/kamboo',
    scripts=[],
    packages=find_packages('.', exclude=['tests*']),
    package_dir={'kamboo': 'kamboo'},
    package_data={'kamboo': []},
    install_requires=requires,
    license="Apache License 2.0",
    classifiers=(
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'Natural Language :: English',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
    ),
)

setup(**setup_options)


text:
var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open(function(err, db) {

    // Fetch a collection to insert document into
    db.collection("remove_all_documents_no_safe", function(err, collection) {

        // Insert a bunch of documents
        collection.insert([{a:1}, {b:2}, {hkon:3}], {w:1}, function(err, result) {
            assert.equal(null, err);

            // Fetch all results
            collection.find().toArray(function(err, items) {
                assert.equal(null, err);
                assert.equal(3, items.length);
            });

            // Remove all the document
            collection.remove();

            // Fetch all results
            collection.find().toArray(function(err, items) {
                assert.equal(null, err);
                assert.equal(0, items.length);
                db.close();
            });
        });
    })
});


text:
cd `dirname $0`
. _project.sh

echo "/nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn"
echo "...Calling the ReplaceSchema task"
echo "nnnnnnnnnn/"
sh $DBFLUTE_HOME/etc/cmd/_df-replace-schema.sh $MY_PROPERTIES_PATH
taskReturnCode=$?

if [ $taskReturnCode -ne 0 ];then
  exit $taskReturnCode;
fi


text:
package com.google.devtools.kythe.platform.shared;

/**
 * Allows different analysis drivers to plug-in different statistics collectors to the Kythe
 * analyzers.
 */
public interface StatisticsCollector {
  /** Increments the named counter by one. */
  void incrementCounter(String name);

  /** Increments the named counter by specified amount. */
  void incrementCounter(String name, int amount);
}


text:
package org.tll.canyon.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.tll.canyon.dao.AssetAccessRequestDao;
import org.tll.canyon.model.AssetAccessRequest;
import org.tll.canyon.model.viewwrappers.AssetAccessRequestSearchForm;
import org.tll.canyon.model.viewwrappers.AssetHitStatSearchForm;

public class AssetAccessRequestDaoHibernate extends BaseDaoHibernate implements AssetAccessRequestDao {

    /**
     * @see org.tll.canyon.dao.AssetAccessRequestDao#getAssetAccessRequests(org.tll.canyon.model.AssetAccessRequest)
     */
    @SuppressWarnings("unchecked")
    public List<AssetAccessRequest> getAssetAccessRequests(final AssetAccessRequest example) {
        // return getHibernateTemplate().find("from AssetAccessRequest");
        if (example == null) {
            return getHibernateTemplate().find("from AssetAccessRequest");
        } else {
            // filter on properties set in the assetRole
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {

                    Example ex = Example.create(example).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(AssetAccessRequest.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see org.tll.canyon.dao.AssetAccessRequestDao#getAssetAccessRequest(Long
     *      id)
     */
    public AssetAccessRequest getAssetAccessRequest(final Long id) {
        AssetAccessRequest assetAccessRequest = (AssetAccessRequest) getHibernateTemplate()
                .get(AssetAccessRequest.class, id);
        if (assetAccessRequest == null) {
            log.warn("uh oh, assetAccessRequest with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(AssetAccessRequest.class, id);
        }

        return assetAccessRequest;
    }

    /**
     * @see org.tll.canyon.dao.AssetAccessRequestDao#saveAssetAccessRequest(AssetAccessRequest
     *      assetAccessRequest)
     */
    public void saveAssetAccessRequest(final AssetAccessRequest assetAccessRequest) {
        getHibernateTemplate().saveOrUpdate(assetAccessRequest);
    }

    /**
     * @see org.tll.canyon.dao.AssetAccessRequestDao#removeAssetAccessRequest(Long
     *      id)
     */
    public void removeAssetAccessRequest(final Long id) {
        getHibernateTemplate().delete(getAssetAccessRequest(id));
    }

    /**
     * @see org.tll.canyon.dao.AssetAccessRequestDao#getAssetAccessRequestsBySearch(AssetHitStatSearchForm)
     */
    @SuppressWarnings("unchecked")
    public List<AssetAccessRequest> getAssetAccessRequestsBySearch(
            final AssetAccessRequestSearchForm assetAccessRequestSearchForm) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(AssetAccessRequest.class);

                if (assetAccessRequestSearchForm.getStartCompleteDate() != null
                        && assetAccessRequestSearchForm.getEndCompleteDate() != null) {
                    criteria.add(Restrictions.between("completeDate", assetAccessRequestSearchForm.getStartCompleteDate(),
                            assetAccessRequestSearchForm.getEndCompleteDate()));
                }

                if (assetAccessRequestSearchForm.getAssetAdministrationEmail() != null) {
                    criteria.add(Restrictions.ilike("assetAdministrationEmail", assetAccessRequestSearchForm.getAssetAdministrationEmail(),
                            MatchMode.ANYWHERE));
                }
                if (assetAccessRequestSearchForm.getEmployeeUserId() != null) {
                    criteria.add(Restrictions.ilike("employeeUserId", assetAccessRequestSearchForm.getEmployeeUserId(),
                            MatchMode.ANYWHERE));
                }
                if (assetAccessRequestSearchForm.isComplete() != null) {
                    criteria.add(Restrictions.eq("complete", assetAccessRequestSearchForm.isComplete()));
                }
                //
                if (assetAccessRequestSearchForm.getAssetRole() != null
                        && assetAccessRequestSearchForm.getAssetName() != null) {

                    criteria.createCriteria("assetRole").add(
                            Restrictions.eq("name", assetAccessRequestSearchForm.getAssetRole())).createCriteria(
                            "assetDetail").add(Restrictions.eq("assetName", assetAccessRequestSearchForm.getAssetName()));
                } else if (assetAccessRequestSearchForm.getAssetName() != null) {
                    criteria.createCriteria("assetRole").createCriteria("assetDetail").add(
                            Restrictions.eq("assetName", assetAccessRequestSearchForm.getAssetName()));
                } else if (assetAccessRequestSearchForm.getAssetRole() != null) {
                    criteria.createCriteria("assetRole").add(
                            Restrictions.eq("name", assetAccessRequestSearchForm.getAssetRole()));
                }
                return criteria.list();
            }
        });
    }
}


text:
package org.thoughtslive.jenkins.plugins.jira.steps;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.spy;

import java.io.PrintStream;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.thoughtslive.jenkins.plugins.jira.Site;
import org.thoughtslive.jenkins.plugins.jira.api.Comment;
import org.thoughtslive.jenkins.plugins.jira.api.ResponseData;
import org.thoughtslive.jenkins.plugins.jira.api.ResponseData.ResponseDataBuilder;
import org.thoughtslive.jenkins.plugins.jira.service.JiraService;

import hudson.AbortException;
import hudson.EnvVars;
import hudson.model.Run;
import hudson.model.TaskListener;

/**
 * Unit test cases for EditCommentStep class.
 *
 * @author Naresh Rayapati
 *
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({EditCommentStep.class, Site.class})
public class EditCommentStepTest {

	@Mock
	TaskListener taskListenerMock;
	@Mock
	Run<?, ?> runMock;
	@Mock
	EnvVars envVarsMock;
	@Mock
	PrintStream printStreamMock;
	@Mock
	JiraService jiraServiceMock;
	@Mock
	Site siteMock;

	EditCommentStep.Execution stepExecution;

	@Before
	public void setup() {

		// Prepare site.
		when(envVarsMock.get("JIRA_SITE")).thenReturn("LOCAL");
		when(envVarsMock.get("BUILD_URL")).thenReturn("http://localhost:8080/jira-testing/job/01");

		PowerMockito.mockStatic(Site.class);
		Mockito.when(Site.get(any())).thenReturn(siteMock);
		when(siteMock.getService()).thenReturn(jiraServiceMock);

		stepExecution = spy(new EditCommentStep.Execution());

		when(runMock.getCauses()).thenReturn(null);
		when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
		doNothing().when(printStreamMock).println();

		final ResponseDataBuilder<Comment> builder = ResponseData.builder();
		when(jiraServiceMock.updateComment(anyString(), anyInt(), anyString())).thenReturn(builder.successful(true).code(200).message("Success").build());

		stepExecution.listener = taskListenerMock;
		stepExecution.envVars = envVarsMock;
		stepExecution.run = runMock;

		doReturn(jiraServiceMock).when(stepExecution).getJiraService(any());
	}

	@Test
	public void testWithZeroComponentIdThrowsAbortException() throws Exception {
		final EditCommentStep step = new EditCommentStep("TEST-1", 0, "test comment");
		stepExecution.step = step;

		// Execute and assert Test.
		assertThatExceptionOfType(AbortException.class).isThrownBy(() -> {
			stepExecution.run();
		}).withMessage("commentId less than or equals to zero.").withStackTraceContaining("AbortException").withNoCause();
	}

	@Test
	public void testWithNegativeComponentIdThrowsAbortException() throws Exception {
		final EditCommentStep step = new EditCommentStep("TEST-1", -100, "test comment");
		stepExecution.step = step;

		// Execute and assert Test.
		assertThatExceptionOfType(AbortException.class).isThrownBy(() -> {
			stepExecution.run();
		}).withMessage("commentId less than or equals to zero.").withStackTraceContaining("AbortException").withNoCause();
	}

	@Test
	public void testWithEmptyIdOrKeyThrowsAbortException() throws Exception {
		final EditCommentStep step = new EditCommentStep("", 1000, "test comment");
		stepExecution.step = step;

		// Execute and assert Test.
		assertThatExceptionOfType(AbortException.class).isThrownBy(() -> {
			stepExecution.run();
		}).withMessage("idOrKey is empty or null.").withStackTraceContaining("AbortException").withNoCause();
	}

	@Test
	public void testWithEmptyCommentThrowsAbortException() throws Exception {
		final EditCommentStep step = new EditCommentStep("TEST-1", 1000, "");
		stepExecution.step = step;

		// Execute and assert Test.
		assertThatExceptionOfType(AbortException.class).isThrownBy(() -> {
			stepExecution.run();
		}).withMessage("comment is empty or null.").withStackTraceContaining("AbortException").withNoCause();
	}

	@Test
	public void testSuccessfulEditComment() throws Exception {
		final EditCommentStep step = new EditCommentStep("TEST-1", 1000, "test comment");
		stepExecution.step = step;

		// Execute Test.
		stepExecution.run();

		// Assert Test
		verify(jiraServiceMock, times(1)).updateComment("TEST-1", 1000,
				"test comment\n{panel}Automatically created by: [~anonymous] from [Build URL|http://localhost:8080/jira-testing/job/01]{panel}");
		assertThat(stepExecution.step.isFailOnError()).isEqualTo(true);
	}
}