text:
var util = require("util");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
var steamlogin = require('steam-login');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var fsp = require('filendir')
var fs = require('fs');
var bodyParser = require('body-parser');
var request = require('request');
var qs = require('qs');
var cloneDeep=require('lodash.clonedeep');
var stringify = require('json-stringify-safe');
/* WebUI. Does not respond to *any* input on *any* chat. It simply provides an API and default browser client for changing bot settings, such as name, etc. Pull requests are welcome.
admins        = Array     - []                        - Array of steamids of those allowed to access the webui. You can also whitelist an ip address by putting it here (127.0.0.1 is good)
apikey        = string    -                           - steam api key. Unsure if required, will be used if given. Can also be given in chatbot constructor as steamapikey.
secret        = string    - random string (changes)   - You'll want to set this to something, it's the session key. If you don't save it the *first* time, it'll be initialized to a 64byte hex string.
secretFile    = string    - botName/trigname.secret   - Overrides above after first use. Delete to change secret.
sessionStore  = string    - botName/trigname.sessions - Where are the sessions saved?
public        = string    -                           - public path to the options.web directory (including the webUI bit), required for the steam servers to redirect you properly.
cookieName    = string    - "connect.sid"             - name of the cookie used by session middleware. Not sure why you'd want to change it, but whatever

*/

var WebUI = function() {
	WebUI.super_.apply(this, arguments);
};

util.inherits(WebUI, BaseTrigger);

var type = "WebUI";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new WebUI(type, name, chatBot, options);
	trigger.options.admins        = options.admins        || [];
	trigger.options.web           = options.web           || "/api";
	trigger.options.secretFile    = options.secretFile    || chatBot.name+"/"+type+"/"+name+".secret";
	trigger.options.sessionStore  = options.sessionStore  || chatBot.name+"/"+type+"/"+name+".sessions";
	trigger.options.apikey        = options.apikey        || chatBot.options.steamapikey||false;
	trigger.options.apikeyStore   = options.apikeyStore   || chatBot.name+"/"+type+"/"+name+".apikeys";
	trigger.options.public        = trigger.options.public|| false;
	trigger.serverStarted = !options.web; //leftover from webUI origins, keep using?
	trigger.allowMessageTriggerAfterResponse = true;
	return trigger;
};

// I'd like to be able to run functions right before it's unloaded, but I can't get the code to work...
WebUI.prototype._onLoad = function(){
	this.logPrefix = this.chatBot.name+"/"+this.name+": "; //I'm tired of typing this out.
	if(!this.chatBot.options.disableWebServer && !this.serverStarted) {
		this.winston.debug(this.chatBot.name+"/"+this.name+": Starting webserver functions for webUI");
		this._startServer();
	}
	return true;
}
WebUI.prototype._startServer = function(){
	if(this.chatBot.options.disableWebServer || this.serverStarted) {
		this.winston.info(this.chatBot.name+"/"+this.name+": webUI webserver is disabled or already initialized. Not starting webserver functions");
		return false;
	}
	if(!this.chatBot.express) {
		this.winston.error(this.chatBot.name+"/"+this.name+": bot's webserver doesn't exist! I can't do crap!");
		return false;
	}
	this.winston.debug(this.chatBot.name+"/"+this.name+": Starting webserver functions for webUI");
	if(this.options.web===true) { //set default route
		this.options.web = "/api";
	}
	var that = this;
	try {
		this.options.secret = JSON.parse(fs.readFileSync(this.options.secretFile));
	} catch(err) {
		this.options.secret = require('crypto').randomBytes(64).toString('hex');
		fsp.ws(this.options.secretFile,this.options.secret);
	}
	try {
		this.apikeys = JSON.parse(fs.readFileSync(this.options.apikeyStore));
	} catch(err) {
		this.apikeys = {};
		fsp.ws(this.options.apikeyStore,JSON.stringify(this.apikeys));
	}
	var fslogfunc = function(log) {
		try {
			that.winston.info(this.logPrefix+log);
		} catch(err) {
			console.log(err.stack);
			fs.writeFileSync('error-webui-'+Date(),err.stack);
		}
	}
	var fsopts = {
		path:this.options.sessionStore,
		ttl:1800,
		logFn:fslogfunc
	}

	var sessionMiddleware = session({
		store: new FileStore(fsopts),
		secret: this.options.secret,
		resave: false,
		saveUninitialized: false
	})

	this.sockets = this._getSocket(this.options.web+"/client.ws");
	this.sockets.use(function(socket, next) { //enforce sessions for socket.io, found at http://stackoverflow.com/a/25618636/4856479
		sessionMiddleware(socket.request, socket.request.res, next);
	});

	var app = this._addRouter(this.options.web);
	app.use(sessionMiddleware);
	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({ extended: false }));
	app.use(steamlogin.middleware({
		realm: this.options.public,
		verify: this.options.public+'/verify',
		apiKey: this.options.apikey
	}));
	app.use(function(req, res, next) {
		var ip = that.chatBot._getClientIp(req); //special case to allow ip addresses (127.0.0.1)
		if(that.options.admins.indexOf(ip) > -1) { //steam login doesn't actually check the userid for validity, so this works
			req.user = ip;
		}
		if(req.user) {
			that.winston.silly(that.logPrefix+"User: "+JSON.stringify(req.user));
		} else {
			that.winston.silly(that.logPrefix+"NO USER!");
		}
		next();
	});
	app.get('/authenticate', steamlogin.authenticate('/api/'), function(req, res) {
		that.winston.silly(that.logPrefix+'user',JSON.stringify(req.user));
	});
	app.get('/login', steamlogin.authenticate('/api/'), function(req, res) {
		that.winston.silly(that.logPrefix+'user',JSON.stringify(req.user));
	});
	app.get('/verify', steamlogin.verify(), function(req, res) {
		that.winston.silly(that.logPrefix+'user',JSON.stringify(req.user));
//		res.send(JSON.stringify(req.user));
		if(that.options.admins.indexOf(req.user.steamid) === -1) {
			res.status(403).send("
Access Denied

"+req.user.username+"/"+req.user.steamid+" is not allowed access");
			req.logout();
		} else {
			res.redirect(that.options.web+"/client");
		}
	});

	app.get('/logout', steamlogin.enforceLogin('/api/'), function(req, res) {
		that.winston.silly(that.logPrefix+'user',JSON.stringify(req.user));
		req.logout();
		res.redirect('/api/login');
	});
	app.get('/test', steamlogin.enforceLogin('/api/'), function(req, res) {
		that.winston.silly(that.logPrefix+'user',JSON.stringify(req.user));
		res.send(JSON.stringify(req.user));
	});
	app.get('/client', steamlogin.enforceLogin('/api/'), function(req, res) {
		if(that.options.admins.indexOf(req.user.steamid) === -1) {
			res.status(403).send("
Access Denied

"+req.user.username+"/"+req.user.steamid+" is not allowed access");
			req.logout();
			res.redirect("/api/login");
		} else {
			res.sendFile(__dirname+'/WebUI/index.html');
		}
	});
	app.post('/client', function(req,res){
		that.winston.info('###########\n###########\nCLIENT POST\n###########\n###########');
		that.winston.silly(that.logPrefix+'user',JSON.stringify(req.user));
		message = req.user == null ? 'not logged in' : 'hello ' + req.user.username;
		if(that.options.admins.indexOf(req.user.steamid) === -1) {
			that.winston.info('User not allowed access!');
			res.json({error:req.user.username+"/"+req.user.steamid+" is not allowed access"});
		} else {
			that.winston.info('User '+req.user.username+'/'+req.user.steamid+' allowed access to endpoint!');
			that._endpoint(req,res);
		}
	});
	app.get('/webui.js', steamlogin.enforceLogin('/api/'), function(req, res) {
		if(that.options.admins.indexOf(req.user.steamid) === -1) {
			res.status(403).send("
Access Denied

"+req.user.username+"/"+req.user.steamid+" is not allowed access");
			req.logout();
		} else {
			res.set('Content-Type', 'text/javascript');
			res.sendFile(__dirname+'/WebUI/webui.js');
		}
	});
	app.get('/styles.css', steamlogin.enforceLogin('/api/'), function(req, res) {
		if(that.options.admins.indexOf(req.user.steamid) === -1) {
			res.status(403).send("
Access Denied

"+req.user.username+"/"+req.user.steamid+" is not allowed access");
			req.logout();
		} else {
			res.set('Content-Type', 'text/css');
			res.sendFile(__dirname+'/WebUI/styles.css');
		}
	});
	this.sockets.on('connection', function(socket) {
		socket.emit('USERS',JSON.stringify(that.chatBot.users()));
		socket.emit('ROOMS',JSON.stringify(that.chatBot.rooms()));
		socket.emit('FRIENDS',JSON.stringify(that.chatBot.friends()));
		socket.emit('GROUPS',JSON.stringify(that.chatBot.groups()));
		socket.emit('STATS',JSON.stringify(that._getStats()));
		socket.emit('IGNORES',JSON.stringify(that.chatBot.ignores));
		socket.emit('TRIGGERS',stringify(that._getTriggers()));
		socket.on('USERS', function(data) {
			socket.emit('USERS',JSON.stringify(that.chatBot.users()));
		});
		socket.on('ROOMS', function(data) {
			socket.emit('ROOMS',JSON.stringify(that.chatBot.rooms()));
		});
		socket.on('FRIENDS', function(data) {
			socket.emit('FRIENDS',JSON.stringify(that.chatBot.friends()));
		});
		socket.on('GROUPS', function(data) {
			socket.emit('GROUPS',JSON.stringify(that.chatBot.groups()));
		});
		socket.on('STATS', function(data) {
			socket.emit('STATS',JSON.stringify(that._getStats()));
		});
		socket.on('TRIGGERS', function(data) {
			socket.emit('TRIGGERS',JSON.stringify(that._getTriggers()));
		});
		socket.on('IGNORES', function(data){
			socket.emit('IGNORES',JSON.stringify(that.chatBot.ignores));
		});
		that.chatBot.winston.on('logging', function(transport, level, msg, meta){
			socket.emit('log',JSON.stringify({level:level,msg:msg,meta:JSON.stringify(meta)}));
		});
	});
//	setInterval(function(){that._sendStats(that)},5000);
//	setInterval(function(){that._sendTriggers(that)},5000);
}
WebUI.prototype._respondToEnteredMessage = function(roomId,userId) {
	this.sockets.emit('USERS',JSON.stringify(this.chatBot.users()));
	return false;
}
WebUI.prototype._respondToDisconnect = function(roomId,userId) {
	this.sockets.emit('USERS',JSON.stringify(this.chatBot.users()));
	return false;
}
WebUI.prototype._respondToLeftMessage = function(roomId, userId) {
	this.sockets.emit('USERS',JSON.stringify(this.chatBot.users()));
	return false;
}
WebUI.prototype._respondToKick = function(roomId,kickedId,kickerId) {
	this.sockets.emit('USERS',JSON.stringify(this.chatBot.users()));
	return false;
}
WebUI.prototype._endpoint = function(req,res) {
//	this.sockets.emit('REQUEST',req.body);
	var validTypes = ['send','join','leave','name','kick','ban','lock'
		,'unlock','mod','unmod','status','announce','loadTrigger'
		,'unloadTrigger','removeIgnore','addIgnore'];
	if(validTypes.indexOf(req.body.type)>-1) {
		var err = this['_'+req.body.type](req.body);
		if(err && err instanceof Object) {
			res.json(err);
		} else if(err) {
			res.json({error:err});
		} else {
			res.json({error:false,body:req.body});
		}
	} else {
		res.json({error:"Invalid endpoint",body:req.body});
	}
}
WebUI.prototype.addApiKey = function(userid) {
	var apikey = hat();
	this.apiKeys[apikey] = userid;
	return apikey;
}
WebUI.prototype.checkApiKey = function(key) {
	if(key in this.apiKeys) {
		return this.apiKeys[key];
	}
	return false;
}
WebUI.prototype.getApiKey = function(userid) {
	for(var key in this.apikeys) {
		if(this.apikeys[key]===userid) {
			return key;
		}
	}
}
WebUI.prototype._send = function(body){
	this.winston.silly(body);
	if(!body.target) { return "No chat specified"; }
	if(!body.message) { return "No messages specified"; }
	try {
		this.winston.info(body.target);
		this._sendMessageAfterDelay(body.target, body.message);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._join = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No chat specified"; }
	try {
		this.chatBot.joinChat(body.target);
		if(body.message) {
			this._sendMessageAfterDelay(body.target, body.message);
		}
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._leave = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No chat specified"; }
	try {
		if(message) {
			this._sendMessageAfterDelay(body.target, message);
		}
		this.chatBot.leaveChat(body.target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._name = function(body) {
	this.winston.silly(body);
	if(!body.name||body.name==="") { return "No name specified"; }
	try {
		this.chatBot.setPersonaName(body.name);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._kick = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No user specified"; }
	if(!body.room) { return "No chat specified"; }
	try {
		this.chatBot.kick(body.room, body.target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._ban = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No users specified"; }
	if(!body.rooms) { return "No chat specified"; }
	try {
		this.chatBot.ban(body.room, body.target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._unban = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No user specified"; }
	if(!body.room) { return "No chat specified"; }
	try {
		this.chatBot.unban(body.room,target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._lock = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No chat specified"; }
	try {
		this.chatBot.lockChat(body.target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._unlock = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No chat specified"; }
	try {
		this.chatBot.unlockChat(body.target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._mod = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No chat specified"; }
	try {
		this.chatBot.setModerated(body.target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._unmod = function(body) {
	this.winston.silly(body);
	if(!body.target) { return "No chat specified"; }
	try {
		this.chatBot.setUnmoderated(body.target);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._status = function(body) {
	this.winston.silly(body);
	try {
		var statint = parseInt(body.status);
		if(!body.status || statint.toString!==body.status || statint>6 || statint<0) {
			var ret =  {error:"invalid status",validStatuses:{offline:0,online:1,busy:2,away:3,snooze:4,trade:5,play:6}};
		}
		this.chatBot.setPersonaState(statint);
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._loadTrigger = function(body){
	if(this.chatBot.triggers[body.name]) {
		return "this trigger already exists!";
	}
	if(!body.name || !body.options || !body.trigtype) {
		return "Invalid syntax: 'name, 'type', options{} required";
	}
	try {
		var options = JSON.parse(body.options);
	} catch(err) {
		var options = cloneDeep(body.options);
		console.log(options);
		this.winston.error(err.stack);
//		return "Invalid options!";
	}
	try {
		this.chatBot.addTrigger(body.name, body.trigtype, options)
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. See log";
	}
//	this.sockets.emit('TRIGGERS',this._getTriggers());
}

WebUI.prototype._unloadTrigger = function(body){
	if(!body.name || !this.chatBot.triggers[body.name]) {
		return "Please specify a valid trigger";
	}
	try {
		this.chatBot.removeTrigger(body.name)
	} catch(err) {
		this.winston.error(err.stack);
		return "Unknown error. See log";
	}
//	this.sockets.emit('TRIGGERS',this._getTriggers());
}
WebUI.prototype._addIgnore = function(body){
	if(!body.id||typeof body.id!==string) {
		return "Invalid ID!"
	}
	this.chatBot.ignores[this.chatBot.ignores.length]=body.id;
//	this.sockets.emit('IGNORES',this.chatBot.ignores);
}
WebUI.prototype._removeIgnore = function(body) {
	if(!body.id||typeof body.id!==string) {
		return "Invalid ID!"
	}
	var i = this.chatBot.ignores.indexOf(body.id);
	if(i===0) {
		return "Not ignored!"
	}
	this.chatBot.ignores.splice(i,1);
//	this.sockets.emit('IGNORES',this.chatBot.ignores);
}

WebUI.prototype.makeAnnouncement = function(target, head, body, source) {
	var that = this;
	var post_data = qs.stringify({
		"sessionID" : that.chatBot.steamTrade.sessionID,
		"action" : "post",
		"headline" : head,
		"body" : body
	});
	var post_options = {
		host: "steamcommunity.com",
		port: "80",
		path: "/groups/"+target+"/announcements/create",
		method: "POST",
		headers: {
			"Content-Type" : "application/x-www-form-urlencoded",
			"Content-Length" : post_data.length,
			"cookie" : that.chatBot.cookie
		}
	};
	var post_req = http.request(post_options, function(res) {
		res.setEncoding("utf8");
		res.on("data", function(chunk) {
			that.winston.info("Announcement created: " + head);
			if(source) {
				that.sendMessageAfterDelay(source, "Announcement created: " + head);
			} else {
				return head;
			}
		});
	});
	post_req.write(post_data);
	post_req.end();
	this.winston.debug(post_data)
	this.winston.debug(post_options);
}
/*
WebUI.prototype._announce = function(body) {
	this.winston.silly(body);
	try {
		var success = this._makeAnnouncement(body.target,body.headline,body.body,body.source);
		console.log(success);
	} catch(err) {
		return "Unknown error. Please check logs";
	}
}
WebUI.prototype._makeAnnouncement = function(target, head, body, source) {
	var that = this;
	try {
		var uri = 'https://steamcommunity.com/groups/'+target+'/announcements/create';
		var post_data = {
			"sessionid" : that.chatBot.steamTrade.sessionID,
//			"sessionID" : that.chatBot.steamTrade.sessionID,
			"action" : "post",
			"headline" : head,
			"body" : body
		}
		that.winston.debug('POSTING announcement');
		return request({method:'POST', url:uri, jar:that.chatBot.steamTrade._j}, function(error, response, body){
			try {
				that.winston.info("Announcement created: " + head);
//				if(source) {
//					that.sendMessageAfterDelay(source, "Announcement created: " + head);
//				} else {
					console.log(head);
//				}
				console.log('error',error);
				console.log('response',response);
				console.log('body',body);
				fs.writeFileSync('response'+(Date())+'.txt',JSON.stringify(response));
			}catch(err){
				console.log(err.stack);
			}
		});
	}catch(err){
		console.log(err.stack);
	}
}
*/
WebUI.prototype._getStats = function() {
	var meminfo = process.memoryUsage();
	var stats = {
		startTime: this.chatBot.startTime,
		connected: this.chatBot.connected,
		muted: this.chatBot.muted,
		sinceStart: process.hrtime(this.chatBot.startTime),
		platform: process.platform,
		arch: process.arch,
		heapUsed: meminfo.heapUsed,
		heapTotal: meminfo.heapTotal,
		rss: meminfo.rss,
		botVersion: this.chatBot.version,
		nodeVersion: process.version
	}
	if(this.chatBot.logonTime) {
		stats.logonTime = this.chatBot.logonTime;
		stats.sinceLogon = process.hrtime(this.chatBot.logonTime);
	}
	if(this.chatBot.logoffTime) {
		stats.logoffTime = this.chatBot.logoffTime,
		stats.sinceLogoff = process.hrtime(this.chatBot.logoffTime);
	}
	return stats;
}
WebUI.prototype._getTriggers = function(){
	var triggers = {};
	for(var trigger in this.chatBot.triggers) {
		var trig = this.chatBot.triggers[trigger];
		triggers[trigger] = { type:trig.type, name:trig.name, options:{}}
		for(var option in trig.options){
			if(option.toLowerCase().indexOf('apikey')===-1 &&
				option.toLowerCase().indexOf('secret')===-1 &&
				option.toLowerCase().indexOf('pass')===-1 &&
				option.toLowerCase().indexOf('client')===-1 &&
				!(trig.options[option] instanceof Function)
			){
				triggers[trigger].options[option] = trig.options[option];
			}
		}
	}
	return triggers;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PololuMaestroServiceState xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                           xmlns:d="http://schemas.microsoft.com/xw/2004/10/dssp.html"
                           xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
                           xmlns="http://schemas.trackroamer.com/2012/02/pololumaestroservice.html">
  <SafePositions>
    <SafePosition>
      <channel>4</channel>
      <positionUs>1000</positionUs>
    </SafePosition>
    <SafePosition>
      <channel>5</channel>
      <positionUs>1000</positionUs>
    </SafePosition>
  </SafePositions>
</PololuMaestroServiceState>

redpajama_set_name: RedPajamaGithub


text:
package com.happydroids.server;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.happydroids.HappyDroidConsts;

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class GameUpdateCollection extends HappyDroidServiceCollection<GameUpdate> {
  public GameUpdateCollection() {
    super();
  }

  @Override
  public String getBaseResourceUri() {
    return HappyDroidConsts.HAPPYDROIDS_URI + "/api/v1/gameupdate/";
  }

  @Override
  protected boolean requireAuthentication() {
    return false;
  }
}


text:
#import <OfficeImport/MFPhoneBrush.h>

@class MFPhoneBitmap;

// Not exported
@interface MFPhonePatternBrush : MFPhoneBrush
{
    MFPhoneBitmap *m_pattern;
    _Bool m_usePaletteForBilevel;
}

+ (id)patternBrushWithBitmap:(id)arg1 usePaletteForBilevel:(_Bool)arg2;
- (void)fillPath:(id)arg1:(id)arg2;
- (void)dealloc;
- (id)initWithBitmap:(id)arg1 usePaletteForBilevel:(_Bool)arg2;

@end


text:
require File.dirname(__FILE__) + '/spec_helper.rb'

describe Rack::Webauth::XML do

  describe "-- parsing a sucessful webauth payload" do
    before(:each) do
      xml_text = File.read("spec/support/webauth_good_payload.xml")
      @xml = Rack::Webauth::XML.parse(xml_text)
    end

    it "should be a good response" do
      @xml.should be_good_response
    end

    it "should be a successful authentication" do
      @xml.should be_auth_success
    end

    it "should be valid" do
      @xml.should be_valid
    end

    it "should have the correct number of attributes" do
      @xml.attributes.should have(6).items
    end
  end

  describe "-- parsing a failed webauth payload" do
    before(:each) do
      xml_text = File.read("spec/support/webauth_failed_payload.xml")
      @xml = Rack::Webauth::XML.parse(xml_text)
    end

    it "should be a good response" do
      @xml.should be_good_response
    end

    it "should not be a successful authentication" do
      @xml.should_not be_auth_success
    end

    it "should not be valid" do
      @xml.should_not be_valid
    end

  end

  describe "-- parsing a random XML document" do
    before(:each) do
      xml_text = "<xml><document name=\"foo\">Bar!</document></xml>"
      @xml = Rack::Webauth::XML.parse(xml_text)
    end

    it "should not be a good response" do
      @xml.should_not be_good_response
    end

    it "should not be valid" do
      @xml.should_not be_valid
    end

  end

end


text:
package dm.kafka.consumer;

public interface DataTransformer {

	public String alter(String data);

	public void close();
}


text:
Let capistrano take care of all your server setup. Upload stage specific config files and automated setup of nxing, puma, unicorn and sidekiq.

## Installation

Add this to your application's `Gemfile`:

```ruby
group :development do
  gem 'capistrano'
  gem 'capistrano-generals'
end
```

And then execute:

    $ bundle install

Create the capistrano `Capfile` if neccecary:

    $ bundle exec cap install

And add this to the `Capfile`:

```ruby
require 'capistrano/generals'
```

## Usage
When the generals package is added to the `Capfile`, the user can specify the required tasks.
In your `config/deploy.rb` you can add the taks by adding them to the deploy namespace like this:

```ruby
namespace :deploy do
  before :deploy,   'git:push'
  before :deploy,   'deploy:symlink:upload_linked_files'
  before :deploy,   'setup'
end
```

### Setup linked files
There are some tasks for linking configuration files to the system. It is
possible to use stage specific files like `config/nginx.staging.conf`. It will
then link this file to the system. If the stage specific file is not present,
it will look for the `config/nginx.conf` file. If that is absent as well it will
raise an error.
```ruby
cap <stage> setup:symlink:nginx    # Adds config/nginx.stage.conf to enabled nginx sites
cap <stage> setup:symlink:unicorn  # Adds config/unicorn_init.stage.sh to /etc/init.d scripts and add run at startup
cap <stage> setup:symlink:sidekiq  # Adds config/sidekiq_init.stag.sh to /etc/init.d scipts and add run at startup
```

### Git push
This first checks if there are no local changes that has not been committed.
If all changes are committed, they are pushed.

Options:

* IGNORE_DEPLOY_RB=true: This ignores changes in deploy.rb, for testing only!
* FORCE=true: Force push changes

### Upload linked files
This uploads the linked files. It first checks for a stage specific file so for
example you want to upload `database.yml` to the `staging` environment,
the system first searches for `database.staging.yml` and if it cannot find that
it will fall back to the original.

### Setup
TODO: Create docs. It creates config files and startup scripts for nginx, unicorn and sidekiq.

### Restart
This will upgrade the unicorn workers and restart nginx.

## Contributing

1. Fork it ( https://github.com/StefSchenkelaars/capistrano-generals/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## Disclaimer
With ideas from:
* https://github.com/capistrano-plugins/capistrano-unicorn-nginx
* https://exceptiontrap.com/blog/11-create-and-install-ssl-certificates-with-ease-capistrano-recipe


text:
import {CHANGE_VISIBILITY} from '../constants/Visibility'

export default function visibilityFilter(state = 'all', action) {
    switch (action.type) {
        case CHANGE_VISIBILITY:
            return action.payload;
        default:
            return state;
    }
}


text:
// -------------------------------------------------------------------------- \\
// File: LocalFile.js                                                         \\
// Module: API                                                                \\
// Requires: connections.js                                                   \\
// -------------------------------------------------------------------------- \\

/*global O, JMAP */

'use strict';

( function ( JMAP ) {

const isDestroyed = O.isDestroyed;
const Class = O.Class;
const Obj = O.Object;
const RunLoop = O.RunLoop;
const HttpRequest = O.HttpRequest;

const upload = JMAP.upload;
const auth = JMAP.auth;

// ---

const LocalFile = Class({

    Extends: Obj,

    nextEventTarget: upload,

    init: function ( file, accountId ) {
        this.file = file;
        this.accountId = accountId;
        this.blobId = '';

        // Using NFC form for the filename helps when it uses a combining
        // character that's not in our font. Firefox renders this badly, so
        // does Safari (but in a different way). By normalizing, the whole
        // replacement character will be drawn from the fallback font, which
        // looks much better. (Chrome does this by default anyway.)
        // See PTN425984
        var name = file.name;
        if ( name && name.normalize ) {
            name = name.normalize( 'NFC' );
        }
        // If the OS doesn't have a MIME type for a file (e.g. .ini files)
        // it will give an empty string for type. Attaching .mhtml files may
        // give a bogus "multipart/related" MIME type. The OS may have a bogus
        // content type (e.g. sketchup was (is?) settings "SKP" as the content
        // type on Windows); if there's no slash, ignore the type.
        var type = file.type;
        if ( !type || type.startsWith( 'multipart/' ) ||
                !type.contains( '/' ) ) {
            type = 'application/octet-stream';
        }
        this.name = name ||
            ( 'image.' + ( /\w+$/.exec( file.type ) || [ 'png' ] )[0] );
        this.type = type;
        this.size = file.size;

        this.isTooBig = false;
        this.isUploaded = false;

        this.response = null;
        this.progress = 0;
        this.loaded = 0;

        this._backoff = 500;

        LocalFile.parent.constructor.call( this );
    },

    destroy: function () {
        var request = this._request;
        if ( request ) {
            upload.abort( request );
        }
        LocalFile.parent.destroy.call( this );
    },

    upload: function ( obj, key ) {
        if ( obj && key ) {
            obj.removeObserverForKey( key, this, 'upload' );
        }
        if ( !isDestroyed( this ) ) {
            upload.send(
                this._request = new HttpRequest({
                    nextEventTarget: this,
                    method: 'POST',
                    url: auth.get( 'uploadUrl' ).replace(
                        '{accountId}', encodeURIComponent( this.accountId ) ),
                    headers: {
                        'Authorization': auth.get( 'accessToken' ),
                    },
                    responseType: 'json',
                    data: this.file,
                })
            );
        }
        return this;
    },

    _uploadDidProgress: function ( event ) {
        const loaded = event.loaded;
        const total = event.total;
        const delta = loaded - this.get( 'loaded' );
        const progress = ~~( 100 * loaded / total );
        this.set( 'progress', progress )
            .set( 'loaded', loaded )
            .fire( 'localfile:progress', {
                loaded: loaded,
                total: total,
                delta: delta,
                progress: progress,
            });
    }.on( 'io:uploadProgress' ),

    _uploadDidSucceed: function ( event ) {
        var response = event.data;

        // Was there an error?
        if ( !response ) {
            return this.uploadDidFail();
        }

        this.beginPropertyChanges()
            .set( 'response', response )
            .set( 'blobId', response.blobId )
            .set( 'progress', 100 )
            .set( 'isUploaded', true )
            .endPropertyChanges()
            .uploadDidSucceed();
    }.on( 'io:success' ),

    _uploadDidFail: function ( event ) {
        this.set( 'progress', 0 );

        switch ( event.status ) {
        // case 400: // Bad Request
        // case 403: // Forbidden
        // case 415: // Unsupported Media Type
        //     break;
        case 401: // Unauthorized
            auth.didLoseAuthentication()
                .addObserverForKey( 'isAuthenticated', this, 'upload' );
            break;
        case 404: // Not Found
            auth.fetchSession()
                .addObserverForKey( 'uploadUrl', this, 'upload' );
            break;
        case 413: // Request Entity Too Large
            this.set( 'isTooBig', true );
            break;
        case 0:   // Connection failed
        case 429: // Rate limited
        case 502: // Bad Gateway
        case 503: // Service Unavailable
        case 504: // Gateway Timeout
            RunLoop.invokeAfterDelay( this.upload, this._backoff, this );
            this._backoff = Math.min( this._backoff * 2, 30000 );
            return;
        }

        this.uploadDidFail();
    }.on( 'io:failure' ),

    _uploadDidEnd: function ( event ) {
        var request = event.target;
        request.destroy();
        if ( this._request === request ) {
            this._request = null;
        }
    }.on( 'io:end' ),

    uploadDidSucceed: function () {
        this.fire( 'localfile:success' );
    },

    uploadDidFail: function () {
        this.fire( 'localfile:failure' );
    },
});

// --- Export

JMAP.LocalFile = LocalFile;

}( JMAP ) );


text:
<?php

namespace qwertyrrr\callback;

use yii;

class Module extends \yii\base\Module
{
	public $adminRoles = ['admin', 'superadmin'];
	/* Delivery settings */
	public $email = null;
	public $subject = 'Callback requested';
	public $mailTemplate = '/mails/callbackMail';

	/* View settigns */
	public $openButtonTitle = "Обратный звонок";
	public $formTitle = "Заказать звонок";
	public $nameTitle = "Ваше имя";
	public $namePlaceholder = "Анатолий";
	public $phoneTitle = "Ваш телефон";
	public $phonePlaceholder = "88005553535";
	public $messageTitle = "Сообщение";
	public $messagePlaceholder = "Текст...";
	public $timeTitle = "Время для звонка: ";
	public $times = [
		'10:30-12:30' => '10:30-12:30',
		'14:00-18:30' => '14:00-18:30',
	];
	public $buttonTitle = "Отправить";

	/* validation settings */
	public $requireMessage = "Заполните поле {attribute}";

	public function init()
	{
		parent::init();

		return true;
	}
}


text:
"use strict";

if (typeof Promise === "undefined") {
  // Rejection tracking prevents a common issue where React gets into an
  // inconsistent state due to an error, but it gets swallowed by a Promise,
  // and the user has no idea what causes React's erratic future behavior.
  require("promise/lib/rejection-tracking").enable();
  window.Promise = require("promise/lib/es6-extensions.js");
}

// fetch() polyfill for making API calls.
require("whatwg-fetch");

// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require("object-assign");

window.matchMedia =
  window.matchMedia ||
  function() {
    return {
      matches: false,
      addListener: function() {},
      removeListener: function() {}
    };
  };


text:
package net.bluemix.connectors.core.creator;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openstack4j.api.client.IOSClientBuilder.V3;
import org.springframework.cloud.service.ServiceConnectorConfig;

import net.bluemix.connectors.core.info.IBMObjectStorageServiceInfo;

public class V3InstanceCreatorTest {

  private V3InstanceCreator creator;

  @Before
  public void setUp() throws Exception {
    this.creator = new V3InstanceCreator();
  }

  @After
  public void tearDown() throws Exception {
    this.creator = null;
  }

  @Test
  public void testCreate() {
    IBMObjectStorageServiceInfo serviceInfo = new IBMObjectStorageServiceInfo("id", "authUrl", "domainId", "domainName", "password", "project",
            "projectId", "region", "userId", "username");
    assertTrue(creator.create(serviceInfo, new ServiceConnectorConfig(){}) instanceof V3);
  }

}


text:
<?php

namespace Drupal\Core\Menu;

use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;

/**
 * Manages discovery and instantiation of menu local task plugins.
 *
 * This manager finds plugins that are rendered as local tasks (usually tabs).
 * Derivatives are supported for modules that wish to generate multiple tabs on
 * behalf of something else.
 */
interface LocalTaskManagerInterface extends PluginManagerInterface {

  /**
   * Gets the title for a local task.
   *
   * @param \Drupal\Core\Menu\LocalTaskInterface $local_task
   *   A local task plugin instance to get the title for.
   *
   * @return string
   *   The localized title.
   */
  public function getTitle(LocalTaskInterface $local_task);

  /**
   * Find all local tasks that appear on a named route.
   *
   * @param string $route_name
   *   The route for which to find local tasks.
   *
   * @return array
   *   Returns an array of task levels. Each task level contains instances
   *   of local tasks (LocalTaskInterface) which appear on the tab route.
   *   The array keys are the depths and the values are arrays of plugin
   *   instances.
   */
  public function getLocalTasksForRoute($route_name);

  /**
   * Gets the render array for all local tasks.
   *
   * @param string $current_route_name
   *   The route for which to make renderable local tasks.
   * @param \Drupal\Core\Cache\RefinableCacheableDependencyInterface $cacheability
   *   The cacheability metadata for the local tasks.
   *
   * @return array
   *   A render array as expected by menu-local-tasks.html.twig.
   */
  public function getTasksBuild($current_route_name, RefinableCacheableDependencyInterface &$cacheability);

  /**
   * Collects the local tasks (tabs) for the current route.
   *
   * @param string $route_name
   *   The route for which to make renderable local tasks.
   * @param int $level
   *   The level of tasks you ask for. Primary tasks are 0, secondary are 1.
   *
   * @return array
   *   An array containing
   *   - tabs: Local tasks render array for the requested level.
   *   - route_name: The route name for the current page used to collect the
   *     local tasks.
   *
   * @see hook_menu_local_tasks_alter()
   */
  public function getLocalTasks($route_name, $level = 0);

}


text:
add_comp_wordbreak_char() {
    [[ "${COMP_WORDBREAKS//[^$1]}" ]] || COMP_WORDBREAKS+=$1
} # add_comp_wordbreak_char()

# Diff environment files to detect if environment is unmodified
# @param $1  File 1
# @param $2  File 2
# @param $3  Additional sed script
diff_env() {
    diff "$1" "$2" | sed -e "
# Remove diff line indicators
        /^[0-9,]\{1,\}[acd]/d
# Remove diff block separators
        /---/d
# Remove underscore variable
        /[<>] _=/d
# Remove PPID bash variable
        /[<>] PPID=/d
# Remove BASH_REMATCH bash variable
        /[<>] BASH_REMATCH=/d
# Remove functions starting with underscore
        /[<>] declare -f _/d
        $3"
} # diff_env()

# Output array elements, sorted and separated by newline
# Unset variable after outputting.
# @param $1  Name of array variable to process
echo_array() {
    local name=$1[@]
    printf "%s\n" "${!name}" | sort
} # echo_array()


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">

    <link rel="stylesheet" href="assets/css/plugins.css"/>

    <link rel="stylesheet" href="{{site.baseurl}}/style.css">

    <link rel="stylesheet" href="assets/css/responsive.css"/>

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                        data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>

                        D R Diagnostix

Home(current)

Service

About

Doctor Portfolio

Academic

FAQ

Contact Us

+91-9899917501, +91-0129-2282400 | Email :  info@drdiagnostix.com

FOR THE FIRST TIME IN NCR

                            INTRODUCING A NEW ERA IN DIGITAL RADIOGRAPHY DENTISTRY WITH
                            3D CONE BEAM CT (CBCT)

                            <button class="btn btn-primary">Request An Appointment
                            </button>

WHAT WE DO

WEB DESIGN

                                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
                                eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
                                qui officia deserunt mollit anim id est. laboru

                            <button class="btn pt-btn btn-primary">View More</button>

SEARCH ENGINE OPTIMIZATION

                                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
                                eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
                                qui officia deserunt mollit anim id est. laboru

                            <button class="btn pt-btn btn-primary">View More</button>

AFFILIATE MARKETING

                                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
                                eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
                                qui officia deserunt mollit anim id est. laboru

                            <button class="btn pt-btn btn-primary">View More</button>

HOW WE WORK

Our Features

Visual Composer

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Responsive

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Retina Ready

orem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                            labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ulla

Our Packages

Basic

5 web sites

5 e-mails

5 MySQL databases

5 MySQL databases

10 GB storage

$5/mo.

ORDER NOW

Standard

5 web sites

5 e-mails

5 MySQL databases

5 MySQL databases

10 GB storage

$12/mo.

ORDER NOW

Premium

5 web sites

5 e-mails

5 MySQL databases

5 MySQL databases

10 GB storage

$19/mo.

ORDER NOW

Our History

                                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
                                eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
                                qui officia deserunt mollit anim id est. laboru

                                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                                exercitation ullamco laboris nisi ut aliquip ex ea commodo
                                consequat.

                                <button class="btn btn-primary">BROWSE OUR HISTORY</button>

Our Business Project

TECHNICAL AID

SECURE ACCESS

MARKET RESERCH

CREDIT RESERCH

TECHNICAL AID

TECHNICAL AID

TECHNICAL AID

TECHNICAL AID

Our Team

Dr Lovekesh

MD, MS

Dr Lovekesh

MD,MS

Dr Lovekesh

MD, MS

Dr Lovekesh

MD, MS

Updates & Support

                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                        labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
                        laboris nisi ut aliquip ex ea commodo
                        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
                        fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
                        deserunt mollit anim id est. laboru

                        <button class="btn btn-primary">SUPPORT CENTER</button>

NEED ACCURATE REPORTS?

                            <button class="btn hire-btn btn-primary">Get In Touch</button>

PORTFOLIO

Services

Doctor Profile

FAQ

Print

User Interface

ABOUT

D R Diagnostix

History

Vision

CONTACT

Basic Info

Map

Contact Form

&copy D R Diagnostix. All rights reserved.


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Verify\V1\Service;

use Twilio\Page;

/**
 * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
 */
class VerificationPage extends Page {
    public function __construct($version, $response, $solution) {
        parent::__construct($version, $response);

        // Path Solution
        $this->solution = $solution;
    }

    public function buildInstance(array $payload) {
        return new VerificationInstance($this->version, $payload, $this->solution['serviceSid']);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        return '[Twilio.Verify.V1.VerificationPage]';
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
    </parent>

	<artifactId>wrdoclet-demosite</artifactId>
	<version>1.1.1-SNAPSHOT</version>
	<description>demo site for wrdoclet</description>
	<properties>
		<spring.version>5.3.5</spring.version>
		<jackson-version>2.12.2</jackson-version>
		<wrdoclet.systemname>demosite</wrdoclet.systemname>
		<wrdoclet.branchname>master</wrdoclet.branchname>
		<wrdoclet.buildid>time</wrdoclet.buildid>
		<wrdoclet.output>${project.basedir}/target/apidocs-demosite</wrdoclet.output>
	</properties>
	<build>
		<plugins>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.0.5.v20130815</version>
				<configuration>
			      <webAppConfig>
			        <allowDuplicateFragmentNames>true</allowDuplicateFragmentNames>
			      </webAppConfig>
    			</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.0</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.10.3</version>
				<configuration>
					<doclet>net.winroad.wrdoclet.HtmlDoclet</doclet>
					<docletArtifact>
						<groupId>net.winroad</groupId>
						<artifactId>wrdoclet</artifactId>
						<version>1.2.3</version>
					</docletArtifact>
					<useStandardDocletOptions>false</useStandardDocletOptions><!-- important ! -->
					<additionalparam>
						-systemname ${wrdoclet.systemname}
						-branchname ${wrdoclet.branchname}
						-buildid ${wrdoclet.buildid}
						-d ${wrdoclet.output}
						-charset utf-8
						-springcontextconfigpath ${project.basedir}/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml
						-excludedurlsxpath //:beans/mvc:interceptors/mvc:interceptor/:bean/:property/:list/:value
						-showannotationlist net.winroad.Models.LoginAuthority,org.springframework.web.bind.annotation.RequestMapping
						-authkeyword REQUEST_COOKIE_AUTH,REQUEST_BODY_AUTH
						-noauthkeyword NO_AUTH,OPTIONAL_AUTH
						-cmzfieldexclude net.winroad.config.JsonResult.exclude
						-cmzfieldinclude net.winroad.config.JsonResult.include
					</additionalparam>
					<sourcepath>${project.basedir}/../wrdoclet-beans/src/main/java;${project.basedir}/src/main/java</sourcepath>
					<subpackages>net.winroad.Controller:net.winroad.MQ</subpackages>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
		   <groupId>org.hibernate</groupId>
		   <artifactId>hibernate-validator</artifactId>
		   <version>5.3.6.Final</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>net.winroad</groupId>
			<artifactId>wrdoclet-beans</artifactId>
			<version>1.1.1-SNAPSHOT</version>
		</dependency>

		<!-- Jackson JSON Mapper -->

		<dependency>
		  	<groupId>com.fasterxml.jackson.core</groupId>
		  	<artifactId>jackson-core</artifactId>
		  	<version>${jackson-version}</version>
		</dependency>

		<dependency>
  			<groupId>com.fasterxml.jackson.core</groupId>
  			<artifactId>jackson-annotations</artifactId>
  			<version>${jackson-version}</version>
		</dependency>

         <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
             <version>${jackson-version}</version>
         </dependency>

		<dependency>
			<groupId>com.google.code.findbugs</groupId>
			<artifactId>annotations</artifactId>
			<version>3.0.1</version>
		</dependency>

<!-- 		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.36</version>
		</dependency>
		 -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.16</version>
		</dependency>

		<dependency>
		    <groupId>com.alibaba.rocketmq</groupId>
		    <artifactId>rocketmq-client</artifactId>
		    <version>3.2.6</version>
		</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
	</dependencies>
</project>


text:
use alloc::raw_vec::RawVec;

/// Alternative way to allocate memory, requiring unstable RawVec.
pub fn allocate_boxed_slice(cap: usize) -> Box<[u8]> {
    let raw = RawVec::with_capacity(cap);
    unsafe {
        raw.into_box()
    }
}


text:
<?php

/**
 * Grid column widget for rendering grid cells that contains mapped values
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Options
    extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Text
{
    /**
     * Render a grid cell as options
     *
     * @param Varien_Object $row
     * @return string
     */
    public function render(Varien_Object $row)
    {
        $options = $this->getColumn()->getOptions();
        $showMissingOptionValues = (bool)$this->getColumn()->getShowMissingOptionValues();
        if (!empty($options) && is_array($options)) {
            $value = $row->getData($this->getColumn()->getIndex());
            if (is_array($value)) {
                $res = array();
                foreach ($value as $item) {
                    if (isset($options[$item])) {
                        $res[] = $this->escapeHtml($options[$item]);
                    }
                    elseif ($showMissingOptionValues) {
                        $res[] = $this->escapeHtml($item);
                    }
                }
                return implode(', ', $res);
            } elseif (isset($options[$value])) {
                return $this->escapeHtml($options[$value]);
            } elseif (in_array($value, $options)) {
                return $this->escapeHtml($value);
            }
        }
    }
}


text:
"""Tests the core implementation of Guided IG."""
import unittest

from . import guided_ig
from .base import INPUT_OUTPUT_GRADIENTS
import numpy as np

class GuidedIGTest(unittest.TestCase):
  """To run: "python -m unittest saliency.core.guided_ig_test" from the top-level directory."""

  def _linear_test_func(self, x_value_batch, call_model_args, expected_keys):
    """Returns gradient of a linear function 2 * x1 + x2.

    Guided IG for linear function produces tha same attribution as Integrated
    Gradients regardless of the parameters.
    """
    self.assertListEqual(expected_keys, [INPUT_OUTPUT_GRADIENTS])
    self.assertEqual(call_model_args, 'airplane')
    return {INPUT_OUTPUT_GRADIENTS: [[2.0, 1.0]]}

  def _quadratic_indep_test_func(self, x_value_batch, call_model_args,
      expected_keys):
    """Returns gradient of a quadratic function 2 * x1^2 + x2^2.

    The partial derivatives of the function with respect to x1 and x2 are
    independent from each other. For such functions, the Guided IG result
    should be equivalent to regular Integrated Gradients.
    """
    self.assertListEqual(expected_keys, [INPUT_OUTPUT_GRADIENTS])
    return {INPUT_OUTPUT_GRADIENTS: [
        [4 * x_value_batch[0, 0], 2 * x_value_batch[0, 1]]]}

  def _quadratic_dep_test_func(self, x_value_batch, call_model_args,
      expected_keys):
    """Returns gradient of a quadratic function (2 * x1 + x2)^2.

    The partial derivatives of the function with respect to x1 and x2 depend on
    each other. For such functions, the Guided IG produces different result
    than Integrated Gradients. TYhe difference depends on the max_dist that
    Guided IG can deviate from the IG path.
    """
    self.assertListEqual(expected_keys, [INPUT_OUTPUT_GRADIENTS])
    return {INPUT_OUTPUT_GRADIENTS: [
        [8 * x_value_batch[0, 0] + 4 * x_value_batch[0, 1],
         4 * x_value_batch[0, 0] + 2 * x_value_batch[0, 1]]]}

  def testGuidedIGLinearWithBaseline(self):
    """Tests attributions of the linear function with provided baseline.

    The expected result should be equal to the regular Integrated Gradients
    attribution.
    """
    gig = guided_ig.GuidedIG()
    mask = gig.GetMask(x_value=[10.0, 5.0],
                       call_model_function=self._linear_test_func,
                       call_model_args='airplane',
                       x_baseline=[-1.0, -3.0],
                       x_steps=10,
                       fraction=0.1,
                       max_dist=0.5)
    np.testing.assert_allclose(mask, [22.0, 8.0])

  def testLinearWithoutBaseline(self):
    """Tests attributions of the linear function with default baseline.

    The expected result should be equal to the regular Integrated Gradients
    attribution.
    """
    gig = guided_ig.GuidedIG()
    mask = gig.GetMask(x_value=[10, 5],
                       call_model_function=self._linear_test_func,
                       call_model_args='airplane',
                       x_steps=10,
                       fraction=0.1,
                       max_dist=0.5)
    np.testing.assert_allclose(mask, [20.0, 5.0])

  def testIndependentQuadratic(self):
    """Tests attributions of the quadratic function with independent partials.

    The expected result should be equal to the regular Integrated Gradients
    attribution regardless of the parameters.
    """
    gig = guided_ig.GuidedIG()
    mask = gig.GetMask(x_value=[3, 3],
                       call_model_function=self._quadratic_indep_test_func,
                       x_steps=1000,
                       fraction=0.1,
                       max_dist=0.4)
    np.testing.assert_allclose(mask, [18.0, 9.0], rtol=0.01)

  def testIndependentQuadraticInputIsLessThanBaseline(self):
    """Tests attributions of the quadratic function with independent partials.

    The expected result should be equal to the regular Integrated Gradients
    attribution regardless of the parameters. This method tests the case when
    the baseline values are higher than the input.
    """
    gig = guided_ig.GuidedIG()
    mask = gig.GetMask(x_value=[0, 0],
                       call_model_function=self._quadratic_indep_test_func,
                       x_baseline=[3, 3],
                       x_steps=1000,
                       fraction=0.1,
                       max_dist=0.4)
    np.testing.assert_allclose(mask, [-18.0, -9.0], rtol=0.01)

  def testDependentQuadraticIG(self):
    """Tests attributions of the quadratic function with dependent partials.

    The test sets such parameters that produce attribution equal to
    Integrated Gradients, namely, by setting zero deviation from the
    straight-line path or changing all features at every integration step.
    """
    gig = guided_ig.GuidedIG()
    # Setting max_dist to 0.0 reduces Guided IG to regular IG.
    mask = gig.GetMask(x_value=[3, 3],
                       call_model_function=self._quadratic_dep_test_func,
                       x_steps=1000,
                       fraction=0.1,
                       max_dist=0.0)
    np.testing.assert_allclose(mask, [54.0, 27.0], rtol=0.01)

    # Setting fraction to 1.0 also reduces Guided IG to regular IG.
    mask = gig.GetMask(x_value=[3, 3],
                       call_model_function=self._quadratic_dep_test_func,
                       x_steps=1000,
                       fraction=1.0,
                       max_dist=0.5)
    np.testing.assert_allclose(mask, [54.0, 27.0], rtol=0.01)

  def testDependentQuadraticUnbound(self):
    """Tests unbounded Guided IG with quadratic function and dependent partials.
    """
    gig = guided_ig.GuidedIG()
    mask = gig.GetMask(x_value=[3, 3],
                       call_model_function=self._quadratic_dep_test_func,
                       x_steps=1000,
                       fraction=0.1,
                       max_dist=1.0)
    np.testing.assert_allclose(mask, [72.0, 9.0], rtol=0.01)

  def testDependentQuadratic(self):
    """Tests bounded Guided IG with quadratic function and dependent partials.

    The expected result should be between attributions of Integrated Gradients
    and unbounded IG. The test checks that the result attribution satisfies the
    completeness axiom.
    """
    gig = guided_ig.GuidedIG()
    mask = gig.GetMask(x_value=[3, 3],
                       call_model_function=self._quadratic_dep_test_func,
                       x_steps=1000,
                       fraction=0.1,
                       max_dist=0.2)
    # Check the result satisfy completeness.
    self.assertAlmostEqual(mask.sum(), 81.0, delta=0.1)
    # Check that the result is between unbounded Guided IG and IG.
    self.assertTrue(55.0 < mask[0] < 71.0)
    self.assertTrue(10.0 < mask[1] < 26.0)

if __name__ == '__main__':
  unittest.main()