text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.06 at 03:13:54 오후 KST
//

package net.herit.iot.onem2m.resource;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

import net.herit.iot.message.onem2m.OneM2mRequest.OPERATION;
import net.herit.iot.message.onem2m.OneM2mResponse.RESPONSE_STATUS;
import net.herit.iot.onem2m.core.util.OneM2MException;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <extension base="{http://www.onem2m.org/xml/protocols}announceableResource">
 *       <sequence>
 *         <element name="appName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="App-ID" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="AE-ID" type="{http://www.onem2m.org/xml/protocols}ID"/>
 *         <element name="pointOfAccess" type="{http://www.onem2m.org/xml/protocols}poaList" minOccurs="0"/>
 *         <element name="ontologyRef" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
 *         <element name="nodeLink" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
 *         <element name="requestReachability" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *         <element name="contentSerialization" type="{http://www.onem2m.org/xml/protocols}serializations" minOccurs="0"/>
 *         <choice minOccurs="0">
 *           <element name="childResource" type="{http://www.onem2m.org/xml/protocols}childResourceRef" maxOccurs="unbounded"/>
 *           <choice maxOccurs="unbounded">
 *             <element ref="{http://www.onem2m.org/xml/protocols}container"/>
 *             <element ref="{http://www.onem2m.org/xml/protocols}group"/>
 *             <element ref="{http://www.onem2m.org/xml/protocols}accessControlPolicy"/>
 *             <element ref="{http://www.onem2m.org/xml/protocols}subscription"/>
 *             <element ref="{http://www.onem2m.org/xml/protocols}pollingChannel"/>
 *             <element ref="{http://www.onem2m.org/xml/protocols}schedule"/>
 *           </choice>
 *         </choice>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "appName",
    "appID",
    "aeid",
    "pointOfAccess",
    "ontologyRef",
    "nodeLink",
    "requestReachability",
    "contentSerialization",
    "e2ESecInfo",
    "childResource",
    "containerOrGroupOrAccessControlPolicy"
})
//@XmlRootElement(name = "m2m:ae")
@XmlRootElement(name = Naming.AE_SN)
public class AE
    extends AnnounceableResource
{
//	public final static String SCHEMA_LOCATION = "CDT-AE-v1_2_0.xsd";
//	public final static String SCHEMA_LOCATION = "CDT-AE-v1_6_0.xsd";
	public final static String SCHEMA_LOCATION = "CDT-AE-v2_7_0.xsd";

//	String[] CREATE_MA = {"appID", "requestReachability"};
//	String[] CREATE_NP = {"resourceName","resourceType","resourceID","parentID","creationTime",
//							"lastModifiedTime","aeid","nodeLink"};
//	String[] UPDATE_MA = {};
//	String[] UPDATE_NP = {"resourceName","resourceType","resourceID","parentID","creationTime",
//							"lastModifiedTime","aeid","nodeLink", "appID"};
//	String[] RESPONSE_MA = {"resourceType", "resourceID", "resourceName", "parentID", "expireationTime",
//							"creationTime", "lastModifiedTime"};
//	String[] RESPONSE_NP = {};

	@XmlElement(name = Naming.APPNAME_SN) //"apn")
    protected String appName;
    //@XmlElement(name = "App-ID", required = true)
	//@XmlElement(name = "api", required = true)
	@XmlElement(name = Naming.APPID_SN) //"api")
    protected String appID;
    //@XmlElement(name = "AE-ID", required = true)
    //@XmlElement(name = "aei", required = true)
	@XmlElement(name = Naming.AEID_SN) //"aei")
    protected String aeid;
    @XmlList
    @XmlElement(name = Naming.POINTOFACCESS_SN) //"poa")
    protected List<String> pointOfAccess;
    @XmlSchemaType(name = "anyURI")
    @XmlElement(name = Naming.ONTOLOGYREF_SN) //"or")
    protected String ontologyRef;
    @XmlSchemaType(name = "anyURI")
    @XmlElement(name = Naming.NODELINK_SN) //"nl")
    protected String nodeLink;
    @XmlElement(name = Naming.REQUESTREACHABILITY_SN) //"rr")
    //protected boolean requestReachability;
    protected Boolean requestReachability;

    @XmlList
    @XmlElement(name = Naming.CONTENTSERIALIZATION_SN) //"csz")
    protected List<PermittedMediaTypes> contentSerialization;  // added in XSD-1.6.0

    @XmlElement(name = Naming.E2ESECINFO_SN)
    protected E2ESecInfo e2ESecInfo;				// added in XSD-2.7.0

    @XmlElement(name = Naming.CHILDRESOURCE_SN) //"ch")
    protected List<ChildResourceRef> childResource;
    @XmlElements({
        @XmlElement(name = "group", namespace = "http://www.onem2m.org/xml/protocols", type = Group.class),
        @XmlElement(name = "container", namespace = "http://www.onem2m.org/xml/protocols", type = Container.class),
        @XmlElement(name = "schedule", namespace = "http://www.onem2m.org/xml/protocols", type = Schedule.class),
        @XmlElement(name = "pollingChannel", namespace = "http://www.onem2m.org/xml/protocols", type = PollingChannel.class),
        @XmlElement(name = "subscription", namespace = "http://www.onem2m.org/xml/protocols", type = Subscription.class),
        @XmlElement(name = "accessControlPolicy", namespace = "http://www.onem2m.org/xml/protocols", type = AccessControlPolicy.class),
        @XmlElement(name = "semanticDescriptor", namespace = "http://www.onem2m.org/xml/protocols", type = SemanticDescriptor.class),
        @XmlElement(name = "timeSeries", namespace = "http://www.onem2m.org/xml/protocols", type = TimeSeries.class),
        @XmlElement(name = "trafficPattern", namespace = "http://www.onem2m.org/xml/protocols", type = TrafficPattern.class),
        @XmlElement(name = "sg_flexContainerResource", namespace = "http://www.onem2m.org/xml/protocols", type = FlexContainerResource.class)
    })
    protected List<Resource> containerOrGroupOrAccessControlPolicy;

    /**
     * Gets the value of the appName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAppName() {
        return appName;
    }

    /**
     * Sets the value of the appName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAppName(String value) {
        this.appName = value;
    }

    /**
     * Gets the value of the appID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAppID() {
        return appID;
    }

    /**
     * Sets the value of the appID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAppID(String value) {
        this.appID = value;
    }

    /**
     * Gets the value of the aeid property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAEID() {
        return aeid;
    }

    /**
     * Sets the value of the aeid property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAEID(String value) {
        this.aeid = value;
    }

    /**
     * Gets the value of the pointOfAccess property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the pointOfAccess property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getPointOfAccess().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link String }
     *
     *
     */
    public List<String> getPointOfAccess() {
//        if (pointOfAccess == null) {
//            pointOfAccess = new ArrayList<String>();
//        }
        return this.pointOfAccess;
    }

    public void addPointOfAccess(String poa) {
    	if (pointOfAccess == null) {
    		pointOfAccess = new ArrayList<String>();
    	}
    	this.pointOfAccess.add(poa);
    }
    /**
     * Gets the value of the ontologyRef property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getOntologyRef() {
        return ontologyRef;
    }

    /**
     * Sets the value of the ontologyRef property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOntologyRef(String value) {
        this.ontologyRef = value;
    }

    /**
     * Gets the value of the nodeLink property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getNodeLink() {
        return nodeLink;
    }

    /**
     * Sets the value of the nodeLink property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setNodeLink(String value) {
        this.nodeLink = value;
    }

    /**
     * Gets the value of the requestReachability property.
     *
     */
    public Boolean isRequestReachability() {
        return requestReachability;
    }

    /**
     * Sets the value of the requestReachability property.
     *
     */
    public void setRequestReachability(Boolean value) {
        this.requestReachability = value;
    }

    /**
     * XSD-1.6.0
     * Gets the value of the contentSerialization property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the contentSerialization property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getContentSerialization().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link PermittedMediaTypes }
     *
     *
     */
    public List<PermittedMediaTypes> getContentSerialization() {
//        if (contentSerialization == null) {
//            contentSerialization = new ArrayList<PermittedMediaTypes>();
//        }
        return this.contentSerialization;
    }

    public void addContentSerialization(PermittedMediaTypes pmt) {
    	 if (contentSerialization == null) {
             contentSerialization = new ArrayList<PermittedMediaTypes>();
         }
    	 contentSerialization.add(pmt);
    }

    /**
     * Gets the value of the e2ESecInfo property.
     *
     * @return
     *     possible object is
     *     {@link E2ESecInfo }
     *
     */
    public E2ESecInfo getE2ESecInfo() {
        return e2ESecInfo;
    }

    /**
     * Sets the value of the e2ESecInfo property.
     *
     * @param value
     *     allowed object is
     *     {@link E2ESecInfo }
     *
     */
    public void setE2ESecInfo(E2ESecInfo value) {
        this.e2ESecInfo = value;
    }

    /**
     * Gets the value of the childResource property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the childResource property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getChildResource().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ChildResourceRef }
     *
     *
     */
    public List<ChildResourceRef> getChildResource() {
//        if (childResource == null) {
//            childResource = new ArrayList<ChildResourceRef>();
//        }
        return this.childResource;
    }

    public void addChildResource(ChildResourceRef ch) {
    	if (childResource == null) {
    		childResource = new ArrayList<ChildResourceRef>();
    	}
    	this.childResource.add(ch);
    }

    /**
     * Gets the value of the containerOrGroupOrAccessControlPolicy property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the containerOrGroupOrAccessControlPolicy property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getContainerOrGroupOrAccessControlPolicy().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Group }
     * {@link Container }
     * {@link Schedule }
     * {@link PollingChannel }
     * {@link Subscription }
     * {@link AccessControlPolicy }
     *
     *
     */
    public List<Resource> getContainerOrGroupOrAccessControlPolicy() {
//        if (containerOrGroupOrAccessControlPolicy == null) {
//            containerOrGroupOrAccessControlPolicy = new ArrayList<Resource>();
//        }
        return this.containerOrGroupOrAccessControlPolicy;
    }

    public void addContainerOrGroupOrAccessControlPolicy(Resource res) {
    	if (containerOrGroupOrAccessControlPolicy == null) {
    		containerOrGroupOrAccessControlPolicy = new ArrayList<Resource>();
    	}
    	this.containerOrGroupOrAccessControlPolicy.add(res);
    }

    @Override
	public void validate(OPERATION operation) throws OneM2MException {

		if (operation.equals(OPERATION.CREATE)) {	// create 요청에 의해 생성된 리소스에 대한 유효성 체크 (DB저장전)
			if (this.appID == null || this.appID.length() == 0) {
				throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'appID' is M on CREATE operation" );
			}
			// v1.0.1 - TBD
			//if (this.requestReachability == null) {
			//	throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'requestReachability' is M onCREATE operation");
			//}
			// requestReachability is Mandatory in CDT-2.7.0 and updated in 2016-10-17
			if (this.requestReachability == null) {
				throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'requestReachability' is M onCREATE operation");
			}
			if (this.aeid != null) {
				throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'aeid' is NP onCREATE operation");
			}
			// nodeLink is Optional in CDT-2.7.0 and blocked in 2016-10-17
			//if (this.nodeLink != null) {
			//	throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'nodeLink' is NP onCREATE operation");
			//}

		} else if (operation.equals(OPERATION.UPDATE)) {	// update 요청에 의해 생성된 리소스에 대한 유효성 체크 (DB저장전)

			if (this.appID != null) {
				throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'appID' is NP on UPDATE operation");
			}
			if (this.aeid != null) {
				throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'aeid' is NP on UPDATE operation");
			}
			//nodeLink is Optional in CDT-2.7.0 and blocked in 2016-10-17
			//if (this.nodeLink != null) {
			//	throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "'aeid' is NP on UPDATE operation");
			//}
		}

		super.validate(operation);

	}

	public String toString() {

		StringBuilder sbld = new StringBuilder();

		sbld.append("[AE]").append(NL);
		sbld.append("AE_ID:").append(aeid).append(NL);
		sbld.append("App_ID:").append(appID).append(NL);
		sbld.append("appName:").append(appName).append(NL);
		sbld.append("pointOfAccess:").append(pointOfAccess).append(NL);
		sbld.append("ontologyRef:").append(ontologyRef).append(NL);
		sbld.append("nodeLink:").append(nodeLink).append(NL);
		sbld.append(NL).append(super.toString());

		return sbld.toString();
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<StringCodeDatabase Version="2" ItemsCount="5"><StringCode SourceType="DLLRC:"><StringId>@{xepdocumentmfc.2eexception.2edisconnectui}</StringId>
		<SourceDll>XEP_DocumentFrameworkMFC.2edll</SourceDll>
		<ResourceId>10174</ResourceId>
	</StringCode>
	<StringCode SourceType="DLLRC:"><StringId>@{xepdocumentmfc.2eexception.2eviewupdate}</StringId>
		<SourceDll>XEP_DocumentFrameworkMFC.2edll</SourceDll>
		<ResourceId>10170</ResourceId>
	</StringCode>
	<StringCode SourceType="DLLRC:"><StringId>@{xepdocumentmfc.2eexception.2eclosedocument}</StringId>
		<SourceDll>XEP_DocumentFrameworkMFC.2edll</SourceDll>
		<ResourceId>10174</ResourceId>
	</StringCode>
	<StringCode SourceType="DLLRC:"><StringId>@{xepdocumentmfc.2eexception.2enavigator.2eredraw}</StringId>
		<SourceDll>XEP_DocumentFrameworkMFC.2edll</SourceDll>
		<ResourceId>10308</ResourceId>
	</StringCode>
	<StringCode SourceType="DLLRC:"><StringId>@{xepdocumentmfc.2eexception.2eviewpagination}</StringId>
		<SourceDll>XEP_DocumentFrameworkMFC.2edll</SourceDll>
		<ResourceId>10169</ResourceId>
	</StringCode>
</StringCodeDatabase>

redpajama_set_name: RedPajamaGithub


text:
module Network.Transport.InMemory
  ( createTransport
  , createTransportExposeInternals
  -- * For testing purposes
  , TransportInternals(..)
  , breakConnection
  ) where

import Network.Transport
import Network.Transport.InMemory.Internal
import Network.Transport.InMemory.Debug

-- | Create a new Transport.
--
-- Only a single transport should be created per Haskell process
-- (threads can, and should, create their own endpoints though).
createTransport :: IO Transport
createTransport = fmap fst createTransportExposeInternals


text:
'use strict';

var util = require('util');
var path = require('path');
var npmLatest = require('npm-latest');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
  },

  askForProjectInfo: function () {
    var cb = this.async();
    var log = this.log;

    log(yosay('Hello, and welcome to the hapi composer generator. Let\'s be awesome together!'));

    var prompts = [{
      name: 'name',
      message: 'Project Name',
      default: path.basename(process.cwd())
    }, {
      name: 'description',
      message: 'Description',
      default: 'The best project ever.'
    }, {
      name: 'homepage',
      message: 'Homepage'
    }, {
      name: 'license',
      message: 'License',
      default: 'MIT',
      store: true
    }, {
      name: 'githubUsername',
      message: 'GitHub username',
      store: true
    }, {
      name: 'authorName',
      message: 'Author\'s Name',
      store: true
    }, {
      name: 'authorEmail',
      message: 'Author\'s Email',
      store: true
    }, {
      name: 'authorUrl',
      message: 'Author\'s Homepage',
      store: true
    }];

    this.currentYear = (new Date()).getFullYear();

    this.prompt(prompts, function (answers) {
      this.slugname = this._.slugify(answers.name);
      this.safeSlugname = this.slugname.replace(
          /-+([a-zA-Z0-9])/g,
          function (g) {
            return g[1].toUpperCase();
          }
      );

      if (answers.homepage) {
        answers.homepage = answers.homepage.trim();
      }
      if (answers.license) {
        answers.license = answers.license.trim() || 'MIT';
      }
      if (answers.authorName) {
        answers.authorName = answers.authorName.trim();
      }
      if (answers.authorEmail) {
        answers.authorEmail = answers.authorEmail.trim();
      }
      if (answers.authorUrl) {
        answers.authorUrl = answers.authorUrl.trim();
      }

      if (answers.githubUsername && answers.githubUsername.trim()) {
        this.repoUrl = 'https://github.com/' + answers.githubUsername + '/' + this.slugname;
      } else {
        this.repoUrl = 'user/repo';
        answers.githubUsername = 'user';
      }

      if (!answers.homepage) {
        answers.homepage = this.repoUrl;
      }

      this.props = answers;

      cb();
    }.bind(this));
  },

  askForDevModules: function () {
    var cb = this.async();

    var prompts = [{
      type: 'checkbox',
      name: 'devModules',
      message: 'Which modules would you like to include?',
      store: true,
      choices: [{
          value: 'gulp-jscs',
          name: 'jscs (JavaScript Code Style checker)',
          checked: true
        }, {
          value: 'gulp-bump',
          name: 'release (Bump npm versions with Gulp)',
          checked: true
        }
      ]
    }];

    this.prompt(prompts, function (answers) {

      var hasMod = function (mod) {
        return answers.devModules.indexOf(mod) !== -1;
      };

      this.gulpJscs = hasMod('gulp-jscs');
      this.gulpBump = hasMod('gulp-bump');
      this.coverallsModule = true;

      cb();

    }.bind(this));
  },

  askForHapiPlugins: function () {
    var cb = this.async();

    var prompts = [{
      type: 'checkbox',
      name: 'hapiPlugins',
      message: 'Which hapi plugins would you like to include?',
      choices: []
    }];

    var defaultPlugins = [
      {name: 'lout', description: 'API documentation generator'},
      {name: 'hapi-auth-cookie', description: 'Cookie authentication plugin'},
      {name: 'bell', description: 'Third-party login plugin'},
      {name: 'hapi-auth-basic', description: 'Basic authentication plugin'},
      {name: 'tv', description: 'Interactive debug console'},
      {name: 'scooter', description: 'User-agent information plugin'},
      {name: 'poop', description: 'Plugin for handling uncaught exceptions'},
      {name: 'good', description: 'Server and process monitoring plugin'},
      {name: 'reptile', description: 'Plugin for creating a REPL'},
      {name: 'yar', description: 'Session plugin and cookie jar'},
      {name: 'crumb', description: 'CSRF crumb generation and validation'}
    ];

    var plugins = this.globalConfig.get('hapiPlugins');
    if (!plugins) {
      this.globalConfig.set('hapiPlugins', defaultPlugins);
      plugins = defaultPlugins;
    }

    plugins.forEach(function (pkg) {
      prompts[0].choices.push({
        value: pkg.name,
        name: util.format('%s (%s)', pkg.name, pkg.description),
        checked: pkg.checked || false
      });
    });

    this.prompt(prompts, function (answers) {
      var hasMod = function (mod) {
        return answers.hapiPlugins.indexOf(mod) !== -1;
      };

      this.hapiPlugins = {};
      plugins.forEach(function (dep) {
        if (hasMod(dep.name)) {
          this.hapiPlugins[dep.name] = 'latest';
        }
      }.bind(this));

      cb();

    }.bind(this));
  },

  askForCustomHapiPlugin: function () {
    var cb = this.async();

    var prompts = [{
      type: 'confirm',
      name: 'customHapiPlugin',
      message: 'Would you like to include a hapi plugin boilerplate?',
      default: false
    }];

    this.prompt(prompts, function (answers) {
      this.customHapiPlugin = answers.customHapiPlugin;
      cb();
    }.bind(this));
  },

  askForOtherNpmDependencies: function () {
    var cb = this.async();

    var prompts = [{
      type: 'checkbox',
      name: 'npmModules',
      message: 'Which other npm dependencies would you like to include?',
      choices: []
    }];

    var defaultNpmModules = [
      {name: 'joi', description: 'Object schema validation'},
      {name: 'boom', description: 'HTTP-friendly error objects'},
      {name: 'catbox', description: 'Multi-strategy object caching service'}
    ];

    var npmModules = this.globalConfig.get('npmModules');
    if (!npmModules) {
      this.globalConfig.set('npmModules', defaultNpmModules);
      npmModules = defaultNpmModules;
    }

    npmModules.forEach(function (pkg) {
      prompts[0].choices.push({
        value: pkg.name,
        name: util.format('%s (%s)', pkg.name, pkg.description),
        checked: pkg.checked || false
      });
    });

    this.prompt(prompts, function (answers) {

      var hasMod = function (mod) {
        return answers.npmModules.indexOf(mod) !== -1;
      };

      this.npmModules = {};
      npmModules.forEach(function (dep) {
        if (hasMod(dep.name)) {
          this.npmModules[dep.name] = 'latest';
        }
      }.bind(this));

      cb();

    }.bind(this));
  },

  mergeDependencies: function () {
    this.npmDependencies = util._extend(this.npmModules, this.hapiPlugins);
  },

  getLatestVersions: function () {
    var cb = this.async();
    var count = Object.keys(this.npmDependencies).length;

    if (count === 0) {
      return cb();
    }

    for (var packageName in this.npmDependencies) {
      npmLatest(packageName, {timeout: 1900}, function (err, result) {
        if (!err && result.name && result.version) {
          this.npmDependencies[result.name] = result.version;
        }
        if (!--count) {
          cb();
        }
      }.bind(this));
    }
  },

  resolveDependencies: function () {
    this.dependencies = '';
    for (var name in this.npmDependencies) {
      var version = this.npmDependencies[name];
      this.dependencies += util.format('\n    "%s": "%s",', name, version);
    }
    if (this.dependencies.length > 0) {
      this.dependencies = this.dependencies.replace('\n', '');
      this.dependencies = this.dependencies.substring(0, this.dependencies.length - 1);
    }
  },

  setupProject: function () {
    this.copy('jshintrc', '.jshintrc');
    this.copy('_gitignore', '.gitignore');
    this.copy('_travis.yml', '.travis.yml');
    this.copy('editorconfig', '.editorconfig');

    if (this.gulpJscs) {
      this.copy('jscs.json', '.jscs.json');
    }

    this.template('_README.md', 'README.md');
    this.template('_gulpfile.js', 'gulpfile.js');
    this.template('_package.json', 'package.json');

    this.mkdir('lib');
    this.template('lib/_index.js', 'lib/index.js');

    var _composerConfig = require(path.join(__dirname + '/templates/lib/_config.json'));
    if (this.customHapiPlugin) {
      _composerConfig.plugins["../../../lib/plugins/example"] = {};
      this.mkdir('lib/plugins');
      this.mkdir('lib/plugins/example');
      this.copy('lib/plugins/example/package.json', 'lib/plugins/example/package.json');
      this.copy('lib/plugins/example/index.js', 'lib/plugins/example/index.js');
    }

    if (this.hapiPlugins) {
      Object.keys(this.hapiPlugins).forEach(function(key) {
        _composerConfig.plugins[key] = {};
      });
    }

    this.write('lib/config.json', JSON.stringify(_composerConfig, null, 2));

    this.mkdir('test');
    this.template('test/name_test.js', 'test/' + this.slugname + '_test.js');
  },

  installNpm: function () {
    this.installDependencies({
      bower: false,
      skipInstall: this.options['skip-install']
    });
  }
});


text:
typedef struct hashmap {
	list_head_t	*buckets;
	unsigned 	nbuckets;
} hashmap_t;

hashmap_t *hashmap_create( unsigned n );
void hashmap_free( hashmap_t *map );

void *hashmap_add( hashmap_t *map, unsigned hash, void *val );
void *hashmap_get( hashmap_t *map, unsigned hash );
void hashmap_remove( hashmap_t *map, unsigned hash );

#endif


text:
package mods.bloxgate.bloxgatemod.client.container;

import mods.bloxgate.bloxgatemod.common.tileentity.TileEntityBlockDeployer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;

public class ContainerBlockDeployer extends Container
{
    private TileEntityBlockDeployer deployer;

    public ContainerBlockDeployer(InventoryPlayer invPlayer, TileEntityBlockDeployer entity)
    {
        this.deployer = entity;
    }

    @Override
    public boolean canInteractWith(EntityPlayer entityplayer)
    {
        return deployer.isUseableByPlayer(entityplayer);
    }
}


text:
var assert = require('assert');
var common = require('../common.js');

var spawn = require('child_process').spawn;

var child = spawn(process.execPath, [ '-i' ], {
  stdio: [null, null, 2]
});

var stdout = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(c) {
  process.stdout.write(c);
  stdout += c;
});

child.stdin.write = function(original) { return function(c) {
  process.stderr.write(c);
  return original.call(child.stdin, c);
}}(child.stdin.write);

child.stdout.once('data', function() {
  child.stdin.write('var throws = 0;');
  child.stdin.write('process.on("exit",function(){console.log(throws)});');
  child.stdin.write('function thrower(){console.log("THROW",throws++);XXX};');
  child.stdin.write('setTimeout(thrower);""\n');

  setTimeout(fsTest, 50);
  function fsTest() {
    var f = JSON.stringify(__filename);
    child.stdin.write('fs.readFile(' + f + ', thrower);\n');
    setTimeout(eeTest, 50);
  }

  function eeTest() {
    child.stdin.write('setTimeout(function() {\n' +
                      '  var events = require("events");\n' +
                      '  var e = new events.EventEmitter;\n' +
                      '  process.nextTick(function() {\n' +
                      '    e.on("x", thrower);\n' +
                      '    setTimeout(function() {\n' +
                      '      e.emit("x");\n' +
                      '    });\n' +
                      '  });\n' +
                      '});"";\n');

    setTimeout(child.stdin.end.bind(child.stdin), 50);
  }
});

child.on('close', function(c) {
  assert(!c);
  // make sure we got 3 throws, in the end.
  var lastLine = stdout.trim().split(/\r?\n/).pop();
  assert.equal(lastLine, '> 3');
});


text:
<?php

namespace FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        $topDeals = $this->get('deal.manager')->findTopDeals();

        $featuredBrands = [];
        $featuredBrands[] = $this->get('business.manager')->findBySlug('xenote-restaurant');
        $featuredBrands[] = $this->get('business.manager')->findBySlug('tito-s-playland');
        $featuredBrands[] = $this->get('business.manager')->findBySlug('maz-fresco');

        return $this->render('FrontendBundle:Default:index.html.twig',
            array(
                'name' => 'Dear Public User',
                'last_username' => $lastUsername,
                'error' => $error,
                'deals' => $topDeals,
                'featured_brands' => $featuredBrands
            )
        );
    }

    public function logedInAction()
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        $topDeals = $this->get('deal.manager')->findTopDeals();

        return $this->render('FrontendBundle:Default:index.html.twig',
            array(
                'name' => 'Loged In User',
                'last_username' => $lastUsername,
                'error' => $error,
                'deals' => $topDeals,
            )
        );
    }

    public function staticPageAction($name)
    {
        return $this->render("FrontendBundle:Static:" . $name . ".html.twig");
    }

    /**
     * Displays robots.txt.
     */
    public function robotsAction($template = null)
    {
        $response = new Response();
        $response->headers->set('Content-Type', 'text/plain');

        return $this->render($template ?: sprintf(
            "FrontendBundle:Static:robots_%s.txt.twig",
            $this->container->getParameter('kernel.environment')
        ), array(), $response);
    }

    /**
     * Handles the logic of the mall map page
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     * @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException
     */
    public function mapAction(Request $request, $hl = null)
    {
        $businesses = $this->get('business.manager')->findAll();

        $encoder = new JsonEncoder();
        $normalizer = new ObjectNormalizer();
        $normalizer->setIgnoredAttributes([
            'categories',
            'deals',
            'customers',
            'openings',
        ]);

        if($hl !== null){
            $businessData = $this->get('business.manager')->findBySlug($hl);
        } else {
            $businessData = null;
        }

        $serializer = new Serializer([$normalizer], [$encoder]);

        return $this->render('@Frontend/map.html.twig', [
            'businesses' => $serializer->serialize($businesses, 'json'),
            'highlight' => $hl,
            'businessData' => $businessData
        ]);
    }

    /**
     * Displays Job Fair Page
     */
    public function jobfairAction(Request $request)
    {
        $openings = $this->get('opening.manager')->findMatchingOpenings()->getQuery()->execute();

        return $this->render("FrontendBundle:Static:jobfair.html.twig", [
            'openings' => $openings
        ]);
    }
}


text: export { default } from 'ember-data-twitch/adapters/twitch-video';


text:
namespace DocumentSystem
{
    using System;
    using System.Linq;

    abstract class EncryptableDocument : BinaryDocument, IEncryptable
    {
        public bool IsEncrypted { get; private set; }

        public void Encrypt()
        {
            this.IsEncrypted = true;
        }

        public void Decrypt()
        {
            this.IsEncrypted = false;
        }

        public override string ToString()
        {
            if (this.IsEncrypted)
            {
                return this.GetType().Name + "[encrypted]";
            }
            else
            {
                return base.ToString();
            }
        }
    }
}


text:
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
         xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.nicmarti.redis</groupId>
    <artifactId>redis-sample</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <name>Redis samples in Java</name>

      <prerequisites>
    <maven>3.0.4</maven>
  </prerequisites>

    <dependencies>
        <dependency>
            <!-- home page https://github.com/xetorthio/jedis -->
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.4.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
    <dependency>
      <groupId>org.easytesting</groupId>
      <artifactId>fest-assert-core</artifactId>
      <version>2.0M10</version>
    </dependency>
    <dependency>
      <groupId>org.easytesting</groupId>
      <artifactId>fest-reflect</artifactId>
      <version>1.4.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>14.0</version>
    </dependency>
    <dependency>
      <groupId>org.easytesting</groupId>
      <artifactId>fest-guava-assert</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.0.9</version>
    </dependency>
    <dependency>
      <groupId>org.easytesting</groupId>
      <artifactId>fest-joda-time-assert</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

   <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <encoding>${project.build.sourceEncoding}</encoding>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
          <encoding>${project.build.sourceEncoding}</encoding>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12</version>
        <configuration>
          <includes>
            <include>**/*Sample.java</include>
          </includes>
          <argLine>-Xms128m -Xmx512m</argLine>
        </configuration>
      </plugin>

    </plugins>
  </build>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>


text:
name             'octohost'
maintainer       'Darron Froese'
maintainer_email 'darron@froese.org'
license          'Apache 2.0'
description      'Installs/configures octohost'
version          '1.0.10'
recipe           'octohost::default', 'Installs/configures octohost'
issues_url       'https://github.com/octohost/octohost-cookbook/issues'
source_url       'https://github.com/octohost/octohost-cookbook'

depends 'chef-sugar'
depends 'apt'
depends 'ubuntu_base'
depends 'octobase'
depends 'docker'
depends 'gitreceive'
depends 'sysdig'
depends 'firewall'
depends 'logrotate'
depends 'rsyslog', '2.2.0'
depends 'packagecloud'
depends 'python'
depends 'zfs_linux'


text:
layout: page
title: PHP 2511: Applied Regression Analysis
---

Introduction to R Programming for Biostatistics

Data Management, Regression Modeling and Survival Analysis

Course Evaluation

Adam Sullivan, Assistant Professor of Biostatistics, Brown University

Joseph Hogan, Professor of Biostatistics, Brown University

Ann Mwangi, Senior Lecturer, Moi University School of Medicine

Get R Now!

  The Schedule

19-22 June 2017

AMPATH / Moi University School of Medicine

Noble Conference Center

Eldoret, Kenya


text:
#ifndef _ASM_IA64_CACHEFLUSH_H
#define _ASM_IA64_CACHEFLUSH_H

#include <linux/page-flags.h>

#include <asm/bitops.h>
#include <asm/page.h>

/*
 * Cache flushing routines.  This is the kind of stuff that can be very expensive, so try
 * to avoid them whenever possible.
 */

#define flush_cache_all()			do { } while (0)
#define flush_cache_mm(mm)			do { } while (0)
#define flush_cache_dup_mm(mm)			do { } while (0)
#define flush_cache_range(vma, start, end)	do { } while (0)
#define flush_cache_page(vma, vmaddr, pfn)	do { } while (0)
#define flush_icache_page(vma,page)		do { } while (0)
#define flush_cache_vmap(start, end)		do { } while (0)
#define flush_cache_vunmap(start, end)		do { } while (0)

#define flush_dcache_page(page)			\
do {						\
	clear_bit(PG_arch_1, &(page)->flags);	\
} while (0)

#define flush_dcache_mmap_lock(mapping)		do { } while (0)
#define flush_dcache_mmap_unlock(mapping)	do { } while (0)

extern void flush_icache_range (unsigned long start, unsigned long end);

#define flush_icache_user_range(vma, page, user_addr, len)					\
do {												\
	unsigned long _addr = (unsigned long) page_address(page) + ((user_addr) & ~PAGE_MASK);	\
	flush_icache_range(_addr, _addr + (len));						\
} while (0)

#define copy_to_user_page(vma, page, vaddr, dst, src, len) \
do { memcpy(dst, src, len); \
     flush_icache_user_range(vma, page, vaddr, len); \
} while (0)
#define copy_from_user_page(vma, page, vaddr, dst, src, len) \
	memcpy(dst, src, len)

#endif /* _ASM_IA64_CACHEFLUSH_H */


text:
import { Container, interfaces } from "inversify";
import { TYPES } from "../types";

export interface ViewerOptions {
    baseDiv: string
    baseClass: string
    hiddenDiv: string
    hiddenClass: string
    popupDiv: string
    popupClass: string
    popupClosedClass: string
    needsClientLayout: boolean
    needsServerLayout: boolean
    popupOpenDelay: number
    popupCloseDelay: number
}

export const defaultViewerOptions = () => (<ViewerOptions>{
    baseDiv: 'sprotty',
    baseClass: 'sprotty',
    hiddenDiv: 'sprotty-hidden',
    hiddenClass: 'sprotty-hidden',
    popupDiv: 'sprotty-popup',
    popupClass: 'sprotty-popup',
    popupClosedClass: 'sprotty-popup-closed',
    needsClientLayout: true,
    needsServerLayout: false,
    popupOpenDelay: 1000,
    popupCloseDelay: 300
});

/**
 * Utility function to partially set viewer options. Default values (from `defaultViewerOptions`) are used for
 * options that are not specified.
 */
export function configureViewerOptions(context: { bind: interfaces.Bind, isBound: interfaces.IsBound, rebind: interfaces.Rebind },
        options: Partial<ViewerOptions>): void {
    const opt: ViewerOptions = {
        ...defaultViewerOptions(),
        ...options
    };
    if (context.isBound(TYPES.ViewerOptions))
        context.rebind(TYPES.ViewerOptions).toConstantValue(opt);
    else
        context.bind(TYPES.ViewerOptions).toConstantValue(opt);
}

/**
 * Utility function to partially override the currently configured viewer options in a DI container.
 */
export function overrideViewerOptions(container: Container, options: Partial<ViewerOptions>): ViewerOptions {
    const opt = container.get<ViewerOptions>(TYPES.ViewerOptions);
    for (const p in options) {
        if (options.hasOwnProperty(p))
            (opt as any)[p] = (options as any)[p];
    }
    return opt;
}


text:
import ipaddress
import unicodedata

from django.db.models import Q
from django.db.models.query import QuerySet

from devices.crypto.cisco import MAGIC as CISCO_MAGIC
from net.models import Connection
from peering.enums import IPFamily
from peering.models.abstracts import BGPSession
from peering.models.models import (
    AutonomousSystem,
    BGPGroup,
    DirectPeeringSession,
    InternetExchange,
    InternetExchangePeeringSession,
    Router,
)
from utils.models import TaggableModel

def ipv4(value):
    """
    Parses the value as an IPv4 address and returns it.
    """
    try:
        return ipaddress.IPv4Address(value)
    except ValueError:
        pass

    try:
        return ipaddress.IPv4Interface(value)
    except ValueError:
        pass

    return None

def ipv6(value):
    """
    Parses the value as an IPv6 address and returns it.
    """
    try:
        return ipaddress.IPv6Address(value)
    except ValueError:
        pass

    try:
        return ipaddress.IPv6Interface(value)
    except ValueError:
        pass

    return None

def ip(value):
    """
    Returns the remote IP of a BGP session.
    """
    if not isinstance(value, BGPSession):
        raise ValueError("value is not a bgp session")

    ip = value.ip_address
    if type(ip) in (ipaddress.IPv4Interface, ipaddress.IPv6Interface):
        return str(ip.ip)
    elif type(ip) in (ipaddress.IPv4Address, ipaddress.IPv6Address):
        return str(ip)
    else:
        return ip

def ip_version(value):
    """
    Returns the IP version of a BGP session.
    """
    if not isinstance(value, BGPSession):
        raise ValueError("value is not a bgp session")

    if ipv6(value.ip_address):
        return 6
    if ipv4(value.ip_address):
        return 4

    raise ValueError("ip address for session is invalid")

def max_prefix(value):
    """
    Returns the max prefix value for a BGP session.
    """
    if not isinstance(value, BGPSession):
        raise ValueError("value is not a bgp session")

    if ipv6(value.ip_address):
        return value.autonomous_system.ipv6_max_prefixes
    else:
        return value.autonomous_system.ipv4_max_prefixes

def cisco_password(password):
    """
    Returns a Cisco type 7 password without the magic word.
    """
    if password.startswith(CISCO_MAGIC):
        return password[2:]
    else:
        return password

def filter(value, **kwargs):
    """
    Returns a filtered queryset or iterable based on provided criteria.
    """
    if type(value) is QuerySet:
        return value.filter(**kwargs)

    try:
        iter(value)
    except TypeError:
        raise ValueError("value cannot be filtered (not iterable)")

    # Build a list with items matching all provided criteria
    # Fail validation of an item if it does not have one of the attributes
    filtered = []
    for i in value:
        valid = True
        for k, v in kwargs.items():
            try:
                valid = getattr(i, k, None) == v
            except AttributeError:
                valid = False

            if not valid:
                break

        if valid:
            filtered.append(i)

    return filtered

def get(queryset, **kwargs):
    """
    Returns a single object from a queryset and a filter. If more than one object
    matches the filterm a queryset will be return.
    """
    q = filter(queryset, **kwargs)

    if q.count() == 1:
        return q.get()
    else:
        return q

def iterate(value, field):
    """
    Yields the value of a given field of an item in an iteratable.

    If the item does not have the field, it will simply yield a null value.
    """
    for item in value:
        yield getattr(item, field, None)

def iter_export_policies(value, field="", family=-1):
    """
    Returns a list of policies to apply on export.

    An optional field can be passed as parameter to return only this field's value.
    An optional family can be passed to return only policies matching the address
    family.
    """
    if not hasattr(value, "export_policies"):
        raise AttributeError("{value} has not export policies")

    if type(field) is not str:
        raise AttributeError(f"field must be a string'")

    policies = value.export_policies()
    if family in IPFamily.values:
        policies = filter(policies, address_family__in=[0, family])

    if field:
        return [getattr(p, field) for p in policies]

    return list(policies)

def iter_import_policies(value, field="", family=-1):
    """
    Returns a list of policies to apply on import.

    An optional field can be passed as parameter to return only this field's value.
    An optional family can be passed to return only policies matching the address
    family.
    """
    if not hasattr(value, "import_policies"):
        raise AttributeError("{value} has not import policies")

    if type(field) is not str:
        raise AttributeError(f"field must be a string'")

    policies = value.import_policies()
    if family in IPFamily.values:
        policies = filter(policies, address_family__in=[0, family])

    if field:
        return [getattr(p, field) for p in policies]

    return list(policies)

def communities(value, field=""):
    """
    Returns a list of communities applied to an AS, a group, an IXP or a session.
    """
    c = None

    if type(value) is InternetExchangePeeringSession:
        c = value.ixp_connection.internet_exchange_point.communities
    if type(value) is DirectPeeringSession:
        c = value.bgp_group.communities
    if hasattr(value, "communities"):
        c = value.communities

    if c:
        if field:
            return [getattr(i, field) for i in c]
        return c.all()

    return []

def merge_communities(value):
    """
    Merges and returns communities.
    """
    if not hasattr(value, "merged_communities"):
        raise AttributeError("{value} has not merged communities")

    return value.merged_communities()

def length(value):
    """
    Returns the number of items in a queryset or an iterable.
    """
    if type(value) is QuerySet:
        return value.count()

    # Fallback to python's len()
    return len(value)

def merge_export_policies(value, order=""):
    """
    Merges and returns policy list for export.

    If duplicates are found, only the most specific one will be kept.
    """
    if not hasattr(value, "merged_export_policies"):
        raise AttributeError("{value} has not merged export policies")

    return value.merged_export_policies(order == "reverse")

def merge_import_policies(value, order=""):
    """
    Merges and returns policy list for import.

    If duplicates are found, only the most specific one will be kept.
    """
    if not hasattr(value, "merged_import_policies"):
        raise AttributeError("{value} has not merged import policies")

    return value.merged_import_policies(order == "reverse")

def connections(value):
    if not hasattr(value, "get_connections"):
        raise AttributeError(f"{value} has no connections")
    return value.get_connections()

def local_ips(value, family=0):
    """
    Returns local IP addresses for a BGP session or an IXP.
    """
    if isinstance(value, DirectPeeringSession):
        return value.local_ip_address

    if isinstance(value, InternetExchangePeeringSession):
        if value.ip_address.version == 6:
            return value.ixp_connection.ipv6_address
        else:
            return value.ixp_connection.ipv4_address

    if isinstance(value, InternetExchange):
        ips = []
        for c in Connection.objects.filter(internet_exchange_point=value):
            if c.ipv4_address and family != 6:
                ips.append(c.ipv4_address)
            if c.ipv6_address and family != 4:
                ips.append(c.ipv6_address)
        return ips

    return None

def direct_sessions(value, family=0, group=None):
    """
    Returns a queryset of direct peering sessions.

    If family is set to 4 or 6, only the sessions matching the IP address
    family will be returned. If family is not set all sessions matching all address
    families will be returned.
    """
    if not hasattr(value, "get_direct_peering_sessions"):
        raise AttributeError(f"{value} has no direct peering sessions, try `sessions`")

    s = value.get_direct_peering_sessions(bgp_group=group)

    if family not in (4, 6):
        return s
    else:
        return s.filter(ip_address__family=family)

def ixp_sessions(value, family=0, ixp=None):
    """
    Returns a queryset of IXP peering sessions.

    If family is set to 4 or 6, only the sessions matching the IP address
    family will be returned. If family is not set all sessions matching all address
    families will be returned.

    If ixp is set, only sessions for the given IXP will be returned. If ixp is not set
    all IXP sessions will be returned.
    """
    if not hasattr(value, "get_ixp_peering_sessions"):
        raise AttributeError(f"{value} has no ixp peering sessions, try `sessions`")

    s = value.get_ixp_peering_sessions(internet_exchange_point=ixp)

    if family not in (4, 6):
        return s
    else:
        return s.filter(ip_address__family=family)

def sessions(value, family=0):
    """
    Returns a queryset of peering sessions, they can be direct or IXP but not both.

    If family is set to 4 or 6, only the sessions matching the IP address family will
    be returned. If family is not set all sessions matching all address families will
    be returned.
    """
    if not hasattr(value, "get_peering_sessions"):
        raise AttributeError(
            f"{value} has no generic peering sessions, try `direct_sessions` or `ixp_sessions`"
        )

    if family not in (4, 6):
        return value.get_peering_sessions()
    else:
        return value.get_peering_sessions().filter(ip_address__family=family)

def route_server(value, family=0):
    """
    Returns a queryset listing all route server sessions for an IXP.
    """
    if type(value) is not InternetExchange:
        raise ValueError("value is not an internet exchange")

    return sessions(value, family=family).filter(is_route_server=True)

def direct_peers(value, group=""):
    """
    Returns a queryset of all autonomous systems peering directly with a router.

    An optional group can be used for filtering, always as a slug.
    """
    if type(value) is not Router:
        raise ValueError("value is not a router")

    g = None
    if group:
        try:
            g = BGPGroup.objects.get(slug=group)
        except BGPGroup.DoesNotExist:
            pass

    return value.get_direct_autonomous_systems(bgp_group=g)

def ixp_peers(value, ixp=""):
    """
    Returns a queryset of all autonomous systems peering over IXPs with a router.
    """
    if type(value) is not Router:
        raise ValueError("value is not a router")

    i = None
    if ixp:
        try:
            i = InternetExchange.objects.get(slug=ixp)
        except InternetExchange.DoesNotExist:
            pass

    return value.get_ixp_autonomous_systems(internet_exchange_point=i)

def ixps(value, other):
    """
    Returns all IXPs on which both AS are peering together.
    """
    return value.get_internet_exchange_points(other)

def shared_ixps(value, other):
    """
    Returns shared IXPs where both ASNs are present without a bilateral session.
    """
    return value.get_shared_internet_exchange_points(other)

def missing_sessions(value, other, ixp=None):
    """
    Returns all missing sessions between two ASNs, optionally on an IXP.
    """
    return value.get_missing_peering_sessions(other, internet_exchange_point=ixp)

def prefix_list(value, family=0):
    """
    Returns the prefixes for the given AS.
    """
    if type(value) is not AutonomousSystem:
        raise ValueError("value is not an autonomous system")

    return value.get_irr_as_set_prefixes(family)

def safe_string(value):
    """
    Returns a safe string (retaining only ASCII characters).
    """
    return unicodedata.normalize("NFKD", value).encode("ASCII", "ignore").decode()

def tags(value):
    """
    Returns an iterable containing tags associated with an object."
    """
    if not isinstance(value, TaggableModel):
        raise AttributeError("object has no tags")
    return value.tags.all()

def has_tag(value, tag):
    """
    Returns a boolean indicating if an objects has the given tag.
    """
    if not isinstance(value, TaggableModel):
        raise AttributeError("object has no tags")

    return value.tags.filter(Q(name=tag) | Q(slug=tag)).count() > 0

def has_not_tag(value, tag):
    """
    Returns a boolean indicating if an objects has the given tag.
    """
    if not isinstance(value, TaggableModel):
        raise AttributeError("object has no tags")

    return value.tags.filter(Q(name=tag) | Q(slug=tag)).count() == 0

FILTER_DICT = {
    # Generics
    "safe_string": safe_string,
    "tags": tags,
    "has_tag": has_tag,
    "has_not_tag": has_not_tag,
    # IP address utilities
    "ipv4": ipv4,
    "ipv6": ipv6,
    # Length filter and synonyms
    "length": length,
    "len": length,
    "count": length,
    # Filtering
    "filter": filter,
    "get": get,
    "iterate": iterate,
    # Autonomous system
    "ixps": ixps,
    "shared_ixps": shared_ixps,
    "missing_sessions": missing_sessions,
    "prefix_list": prefix_list,
    "direct_sessions": direct_sessions,
    # BGP groups
    "local_ips": local_ips,
    # BGP sessions
    "direct_sessions": direct_sessions,
    "ixp_sessions": ixp_sessions,
    "sessions": sessions,
    "route_server": route_server,
    "ip": ip,
    "ip_version": ip_version,
    "max_prefix": max_prefix,
    "cisco_password": cisco_password,
    # Connections
    "connections": connections,
    # Routers
    "direct_peers": direct_peers,
    "ixp_peers": ixp_peers,
    # Communities
    "communities": communities,
    "merge_communities": merge_communities,
    # Routing policies
    "iter_export_policies": iter_export_policies,
    "iter_import_policies": iter_import_policies,
    "merge_export_policies": merge_export_policies,
    "merge_import_policies": merge_import_policies,
}

__all__ = ("FILTER_DICT",)


text:
import { Meteor } from "meteor/meteor";
import { Roles } from "meteor/alanning:roles";

import { Courses } from "/imports/api/courses/courses";

Meteor.users.helpers({
  emailAddress() {
    return this.emails[0].address;
  },

  fullName() {
    return this.preferredName || this.legalName();
  },

  legalName() {
    return (
      (this.services && this.services.google && this.services.google.name) ||
      (this.services && this.services.saml && this.services.saml.displayName) ||
      this.emailAddress().split("@")[0]
    );
  },

  firstName() {
    if (this.preferredName) return this.preferredName.split(" ")[0];

    const firstName =
      (this.services &&
        this.services.google &&
        this.services.google.given_name) ||
      this.fullName().split(" ")[0];

    return firstName;
  },

  initials() {
    let initials = "";
    const fullName = this.fullName();

    let parts = fullName.split(" ");
    if (parts.length < 2) parts = fullName.split("_");

    if (parts.length >= 2) {
      initials = parts[0][0] + parts[parts.length - 1][0];
    } else {
      initials = parts[0].substring(0, 2);
    }

    return initials.toUpperCase();
  },

  courses() {
    if (Roles.userIsInRole(this._id, ["admin", "mta"])) {
      return Courses.find({ active: true }, { sort: { name: 1 } });
    }

    const htaCourseIds = Roles.getGroupsForUser(this._id, "hta");
    const taCourseIds = Roles.getGroupsForUser(this._id, "ta");
    return Courses.find(
      { _id: { $in: htaCourseIds.concat(taCourseIds) }, active: true },
      { sort: { name: 1 } }
    );
  },

  htaCourses() {
    const htaCourseIds = Roles.getGroupsForUser(this._id, "hta");
    return Courses.find({ _id: { $in: htaCourseIds }, active: true });
  },

  isTAOrAbove() {
    return this.courses().count() > 0;
  },

  profilePictureUrl() {
    return (
      this.services && this.services.google && this.services.google.picture
    );
  }
});


text:
//
using System;

namespace Alachisoft.NosDB.Common.Configuration
{
    [AttributeUsage(AttributeTargets.Property)]
    public class ConfigurationSectionAttribute : ConfigurationAttributeBase
    {
        private string _sectionName;

        public ConfigurationSectionAttribute(string sectionName)
            : base(false, false)
        {
            _sectionName = sectionName;
        }

        public ConfigurationSectionAttribute(string sectionName, bool isRequired, bool isCollection)
            : base(isRequired, isCollection)
        {
            _sectionName = sectionName;
        }

        /// <summary>
        /// Gets the section name.
        /// </summary>
        public string SectionName
        {
            get { return _sectionName; }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Vampola & Pouzar, Czech Mycol. 48(4): 316 (1996)

#### Original name
Ceriporia herinkii Vampola

### Remarks
null


text:
"""Timeseries metrics."""

from collections import defaultdict
import logging

from components import utils
import gae_ts_mon

from server import bot_management
from server import task_result

# - android_devices is a side effect of the health of each Android devices
#   connected to the bot.
# - caches has an unbounded matrix.
# - server_version is the current server version. It'd be good to have but the
#   current monitoring pipeline is not adapted for this.
# - id is unique for each bot.
# - temp_band is android specific.
# Keep in sync with ../swarming_bot/bot_code/bot_main.py
_IGNORED_DIMENSIONS = ('android_devices', 'caches', 'id', 'server_version',
                       'temp_band')

# Override default target fields for app-global metrics.
_TARGET_FIELDS = {
    'job_name': '',  # module name
    'hostname': '',  # version
    'task_num': 0,  # instance ID
}

### All the metrics.

# Custom bucketer with 12% resolution in the range of 1..10**5. Used for job
# cycle times.
_bucketer = gae_ts_mon.GeometricBucketer(growth_factor=10**0.05,
                                         num_finite_buckets=100)

# Custom bucketer with 2% resolution in the range of 100ms...100s. Used for
# pubsub latency measurements.
# Roughly speaking measurements range between 150ms and 300ms. However timeout
# for pubsub notification is 10s.
_pubsub_bucketer = gae_ts_mon.GeometricBucketer(growth_factor=10**0.01,
                                                num_finite_buckets=300,
                                                scale=10)

# Custom bucketer with 2% resolution in the range of 100ms...100000s. Used for
# task scheduling latency measurements.
_scheduler_bucketer = gae_ts_mon.GeometricBucketer(growth_factor=10**0.01,
                                                   num_finite_buckets=600,
                                                   scale=100)

# Custom bucketer with 2% resolution in the range of 100ms...100000s. Used for
# task dead detection latency.
# cron job runs every 60s, but can also fail for a few hours.
_detection_bucketer = gae_ts_mon.GeometricBucketer(growth_factor=10**0.01,
                                                   num_finite_buckets=600,
                                                   scale=100)

# Regular (instance-local) metrics: jobs/completed and jobs/durations.
# Both have the following metric fields:
# - project_id: e.g. 'chromium'.
# - subproject_id: e.g. 'blink'. Set to empty string if not used.
# - pool: e.g. 'Chrome'.
# - spec_name: name of a job specification.
# - result: one of 'success', 'failure', or 'infra-failure'.
_jobs_completed = gae_ts_mon.CounterMetric(
    'jobs/completed',
    'Number of completed jobs.', [
        gae_ts_mon.StringField('spec_name'),
        gae_ts_mon.StringField('project_id'),
        gae_ts_mon.StringField('subproject_id'),
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.StringField('result'),
        gae_ts_mon.StringField('status'),
    ])

_jobs_durations = gae_ts_mon.CumulativeDistributionMetric(
    'jobs/durations',
    'Cycle times of completed jobs, in seconds.', [
        gae_ts_mon.StringField('spec_name'),
        gae_ts_mon.StringField('project_id'),
        gae_ts_mon.StringField('subproject_id'),
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.StringField('result'),
    ],
    bucketer=_bucketer)

# Similar to jobs/completed and jobs/duration, but with a dedup field.
# - project_id: e.g. 'chromium'
# - subproject_id: e.g. 'blink'. Set to empty string if not used.
# - pool: e.g. 'Chrome'
# - spec_name: name of a job specification.
# - deduped: boolean describing whether the job was deduped or not.
_jobs_requested = gae_ts_mon.CounterMetric(
    'jobs/requested',
    'Number of requested jobs over time.', [
        gae_ts_mon.StringField('spec_name'),
        gae_ts_mon.StringField('project_id'),
        gae_ts_mon.StringField('subproject_id'),
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.BooleanField('deduped'),
    ])

# Swarming-specific metric. Metric fields:
# - project_id: e.g. 'chromium'.
# - subproject_id: e.g. 'blink'. Set to empty string if not used.
# - pool: e.g. 'Chrome'.
# - spec_name: name of a job specification.
# - priority: priority of a task.
_tasks_expired = gae_ts_mon.CounterMetric(
    'swarming/tasks/expired', 'Number of expired tasks', [
        gae_ts_mon.StringField('spec_name'),
        gae_ts_mon.StringField('project_id'),
        gae_ts_mon.StringField('subproject_id'),
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.IntegerField('priority'),
    ])

# Swarming-specific metric. Metric fields:
# - project_id: e.g. 'chromium-swarm'
_tasks_expiration_delay = gae_ts_mon.CumulativeDistributionMetric(
    'swarming/tasks/expiration_delay',
    'Delay of task expiration, in seconds.', [
        gae_ts_mon.StringField('project_id'),
    ])

# Swarming-specific metric. Metric fields:
# - project_id: e.g. 'chromium-swarm'
_tasks_slice_expiration_delay = gae_ts_mon.CumulativeDistributionMetric(
    'swarming/tasks/slice_expiration_delay',
    'Delay of task slice expiration, in seconds.',
    [
        gae_ts_mon.StringField('project_id'),
        gae_ts_mon.IntegerField('slice_index'),
    ],
    bucketer=gae_ts_mon.FixedWidthBucketer(width=30),
)

# Global metric. Metric fields:
# - project_id: e.g. 'chromium'.
# - subproject_id: e.g. 'blink'. Set to empty string if not used.
# - pool: e.g. 'Chrome'.
# - spec_name: name of a job specification.
# - status: 'pending' or 'running'.
_jobs_active = gae_ts_mon.GaugeMetric(
    'jobs/active', 'Number of running, pending or otherwise active jobs.', [
        gae_ts_mon.StringField('spec_name'),
        gae_ts_mon.StringField('project_id'),
        gae_ts_mon.StringField('subproject_id'),
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.StringField('status'),
    ])

# Global metric. Target field: hostname = 'autogen:<executor_id>' (bot id).
_executors_pool = gae_ts_mon.StringMetric(
    'executors/pool',
    'Pool name for a given job executor.',
    None)

# Global metric. Target fields:
# - hostname = 'autogen:<executor_id>' (bot id).
# Status value must be 'ready', 'running', or anything else, possibly
# swarming-specific, when it cannot run a job. E.g. 'quarantined' or
# 'dead'.
_executors_status = gae_ts_mon.StringMetric(
    'executors/status',
    'Status of a job executor.',
    None)

# Instance metric. Metric fields:
# - auth_method = one of 'luci_token', 'service_account', 'ip_whitelist'.
# - condition = depends on the auth method (e.g. email for 'service_account').
_bot_auth_successes = gae_ts_mon.CounterMetric(
    'swarming/bot_auth/success',
    'Number of successful bot authentication events', [
        gae_ts_mon.StringField('auth_method'),
        gae_ts_mon.StringField('condition'),
    ])

# Instance metric. Metric fields:
# - pool: e.g. 'skia'.
# - status: e.g. 'User canceled'.
# - http_status_code: e.g. 404.
_task_state_change_pubsub_notify_latencies = \
  gae_ts_mon.CumulativeDistributionMetric(
    'swarming/tasks/state_change_pubsub_notify_latencies',
    'Latency (in ms) of PubSub notification when backend receives task_update',
    [
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.StringField('status'),
        gae_ts_mon.IntegerField('http_status_code')
    ],
    bucketer=_pubsub_bucketer,
)

# Instance metric. Measures the latency for Swarming to recognise a task
# death (KILLED or BOT_DIED) and commit the state to storage.
# Metric fields:
# - pool: e.g. 'skia'.
# - cron: e.g. True if dead task was initiated by cron job, False otherwise
_dead_task_detection_latencies = \
  gae_ts_mon.CumulativeDistributionMetric(
    'swarming/tasks/dead_task_detection_latencies',
    'Latency (in ms) of task scheduling request',
    [
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.BooleanField('cron'),
    ],
    bucketer=_detection_bucketer,
)

# Instance metric. Metric fields:
# - pool: e.g. 'skia'.
# - spec_name: 'linux_chromium_tsan_rel_ng'
# - status: e.g. 'No resource available'.
_task_state_change_schedule_latencies = \
  gae_ts_mon.CumulativeDistributionMetric(
    'swarming/tasks/state_change_scheduling_latencies',
    'Latency (in ms) of task scheduling request',
    [
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.StringField('spec_name'),
        gae_ts_mon.StringField('status'),
        gae_ts_mon.StringField('device_type'),
    ],
    bucketer=_scheduler_bucketer,
)

# Instance metric. Metric fields:
# - pool: e.g. 'skia'.
# - queue_count: number of queues scanned in parallel (up to 30).
_scheduler_scans = gae_ts_mon.CounterMetric(
    'swarming/scheduler/scans', 'Number of queue scans', [
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.IntegerField('queue_count'),
    ])

# Instance metric. Metric fields:
# - pool: e.g. 'skia'.
# - status: 'claimed', 'expired', etc.
_scheduler_visits = gae_ts_mon.CumulativeDistributionMetric(
    'swarming/scheduler/visits',
    'Distribution of TaskToRunShard visited per scan', [
        gae_ts_mon.StringField('pool'),
        gae_ts_mon.StringField('status'),
    ],
    bucketer=gae_ts_mon.FixedWidthBucketer(width=5))

# Number of timeouts. Metric fields:
# - endpoint: e.g. 'bot/poll'
# - stage: e.g. 'assert_bot_async'
# - exception: e.g. 'DeadlineExceededError'
_handler_timeouts = gae_ts_mon.CounterMetric(
    'swarming/api/timeouts', 'Number of timeout events in API handlers.', [
        gae_ts_mon.StringField('endpoint'),
        gae_ts_mon.StringField('stage'),
        gae_ts_mon.StringField('exception'),
    ])

### Private stuff.

def _pool_from_dimensions(dimensions):
  """Return a canonical string of flattened dimensions."""
  pairs = []
  for key, values in dimensions.items():
    if key in _IGNORED_DIMENSIONS:
      continue
    # Strip all the prefixes of other values. values is already sorted.
    for i, value in enumerate(values):
      if not any(v.startswith(value) for v in values[i+1:]):
        pairs.append(u'%s:%s' % (key, value))
  return u'|'.join(sorted(pairs))

def _set_jobs_metrics():
  state_map = {
      task_result.State.RUNNING: 'running',
      task_result.State.PENDING: 'pending'
  }
  jobs_counts = defaultdict(lambda: 0)
  jobs_total = 0

  q = task_result.get_result_summaries_query(start=None,
                                             end=None,
                                             sort='created_ts',
                                             state='pending_running',
                                             tags=None)
  cursor = None
  more = True
  while more:
    summaries, cursor, more = q.fetch_page(5000, start_cursor=cursor)
    for summary in summaries:
      jobs_total += 1
      status = state_map.get(summary.state, '')
      tags_dict = _tags_to_dict(summary.tags)
      fields = _extract_job_fields(tags_dict)
      fields['status'] = status

      key = tuple(sorted(fields.items()))
      jobs_counts[key] += 1

      fields['device_type'] = tags_dict.get('device_type', '')
      key = tuple(sorted(fields.items()))

    logging.debug('_set_jobs_metrics: processed %d jobs', jobs_total)

  target_fields = dict(_TARGET_FIELDS)

  for key, count in jobs_counts.items():
    _jobs_active.set(count, target_fields=target_fields, fields=dict(key))

def _set_executors_metrics():
  executors_count = 0

  q = bot_management.BotInfo.query()
  cursor = None
  more = True
  while more:
    bots, cursor, more = q.fetch_page(5000, start_cursor=cursor)
    for bot_info in bots:
      executors_count += 1

      status = 'ready'
      if bot_info.task_id:
        status = 'running'
      elif bot_info.quarantined:
        status = 'quarantined'
      elif bot_info.is_dead:
        status = 'dead'
      elif bot_info.state and bot_info.state.get('maintenance', False):
        status = 'maintenance'

      target_fields = dict(_TARGET_FIELDS)
      target_fields['hostname'] = 'autogen:' + bot_info.id

      _executors_status.set(status, target_fields=target_fields)
      _executors_pool.set(_pool_from_dimensions(bot_info.dimensions),
                          target_fields=target_fields)

    logging.debug('_set_executors_metrics: processed %d bots', executors_count)

def _tags_to_dict(tags):
  """Converts list of string tags to dict.

  Args:
    tags (list of str): list of 'key:value' strings.
  """
  tags_dict = {}
  for tag in tags:
    try:
      key, value = tag.split(':', 1)
      tags_dict[key] = value
    except ValueError:
      pass
  return tags_dict

def _extract_given_job_fields(tags, tag_names):
  """Extracts job metric fields given by tag name from TaskResultSummary.

  Args:
    tags: list of tags.
    tags_names: list of tag names to extract.
  """
  tags_dict = _tags_to_dict(tags)
  fields = {}
  for tag in tag_names:
    fields[tag] = tags_dict.get(tag, '')
  return fields

def _extract_spec_name_field(tags_dict):
  """Extracts spec_name metric field from TaskResultSummary.

  Args:
    tags_dict: tags dictionary.
  """
  spec_name = tags_dict.get('spec_name')
  if not spec_name:
    spec_name = tags_dict.get('buildername', '')
    if tags_dict.get('build_is_experimental') == 'true':
      spec_name += ':experimental'
  return spec_name

def _extract_job_fields(tags_dict):
  """Extracts common job's metric fields from TaskResultSummary.

  Args:
    tags_dict: tags dictionary.
  """
  fields = {
      'project_id': tags_dict.get('project', ''),
      'subproject_id': tags_dict.get('subproject', ''),
      'pool': tags_dict.get('pool', ''),
      'spec_name': _extract_spec_name_field(tags_dict),
  }
  return fields

### Public API.

def on_task_requested(summary, deduped):
  """When a task is created."""
  fields = _extract_job_fields(_tags_to_dict(summary.tags))
  fields['deduped'] = deduped
  _jobs_requested.increment(fields=fields)

def on_task_completed(summary):
  """When a task is stopped from being processed."""
  fields = _extract_job_fields(_tags_to_dict(summary.tags))
  if summary.state == task_result.State.EXPIRED:
    fields['priority'] = summary.priority
    _tasks_expired.increment(fields=fields)
    return

  if summary.internal_failure:
    fields['result'] = 'infra-failure'
  elif summary.failure:
    fields['result'] = 'failure'
  else:
    fields['result'] = 'success'

  completed_fields = fields.copy()
  completed_fields['status'] = task_result.State.to_string(summary.state)
  _jobs_completed.increment(fields=completed_fields)
  if summary.duration is not None:
    _jobs_durations.add(summary.duration, fields=fields)

def on_task_expired(summary, task_to_run):
  """When a task slice is expired."""
  tags_dict = _tags_to_dict(summary.tags)
  fields = {'project_id': tags_dict.get('project', '')}

  # slice expiration delay
  _tasks_slice_expiration_delay.add(
      task_to_run.expiration_delay,
      fields=dict(fields, slice_index=task_to_run.task_slice_index))

  # task expiration delay
  if summary.expiration_delay:
    _tasks_expiration_delay.add(summary.expiration_delay, fields=fields)

def on_bot_auth_success(auth_method, condition):
  _bot_auth_successes.increment(fields={
      'auth_method': auth_method,
      'condition': condition,
  })

def set_global_metrics(kind):
  if kind == 'jobs':
    _set_jobs_metrics()
  elif kind == 'executors':
    _set_executors_metrics()
  else:
    logging.error('set_global_metrics(kind=%s): unknown kind.', kind)

def on_task_status_change_pubsub_latency(tags, state, http_status_code,
                                         latency):
  fields = _extract_given_job_fields(tags, [
      'pool',
  ])
  fields['status'] = task_result.State.to_string(state)
  fields['http_status_code'] = http_status_code
  logging.debug('Incrementing ts_mon PubSub notification count with fields=%s',
                fields)
  _task_state_change_pubsub_notify_latencies.add(latency, fields=fields)

def on_task_status_change_scheduler_latency(summary):
  fields = _extract_given_job_fields(summary.tags, [
      'pool', 'device_type',
  ])
  # device_type might not be supplied in the tags so try obtaining it directly
  # from the bot_dimensions
  if summary.bot_dimensions and fields['device_type'] == '':
    fields['device_type'] = summary.bot_dimensions.get('device_type', '')
  fields['spec_name'] = _extract_spec_name_field(_tags_to_dict(summary.tags))
  fields['status'] = task_result.State.to_string(summary.state)
  latency = summary.pending_now(utils.utcnow())
  _task_state_change_schedule_latencies.add(round(latency.total_seconds() *
                                                  1000),
                                            fields=fields)

def on_dead_task_detection_latency(tags, latency, cron):
  fields = _extract_given_job_fields(tags, [
      'pool',
  ])
  fields['cron'] = cron
  _dead_task_detection_latencies.add(round(latency.total_seconds() * 1000),
                                     fields=fields)

def on_scheduler_scan(pool, queue_count):
  _scheduler_scans.increment(
      fields={
          'pool': pool,
          'queue_count': 30 if queue_count > 30 else queue_count,
      })

def on_scheduler_visits(pool, claimed, mismatch, stale, total, visited):
  def add(key, val):
    _scheduler_visits.add(val, fields={'pool': pool, 'status': key})

  add('claimed', claimed)
  add('mismatch', mismatch)
  add('stale', stale)
  add('total', total)
  add('visited', visited)

def on_handler_timeout(endpoint, stage, exception):
  _handler_timeouts.increment(fields={
      'endpoint': endpoint,
      'stage': stage,
      'exception': exception,
  })

def initialize():
  # These metrics are the ones that are reset everything they are flushed.
  gae_ts_mon.register_global_metrics([
      _executors_pool,
      _executors_status,
      _jobs_active,
  ])


text:
"""Tests for the binary library functions."""

import unittest

from plaso.lib import binary

from tests import test_lib as shared_test_lib

class BinaryTests(shared_test_lib.BaseTestCase):
  """A unit test for the binary helper functions."""

  def setUp(self):
    """Makes preparations before running an individual test."""
    # String: "þrándur" - uses surrogate pairs to test four byte character
    # decoding.
    self._unicode_string_1 = (
        b'\xff\xfe\xfe\x00\x72\x00\xe1\x00\x6E\x00\x64\x00\x75\x00\x72\x00')

    # String: "What\x00is".
    self._ascii_string_1 = (
        b'\x57\x00\x68\x00\x61\x00\x74\x00\x00\x00\x69\x00\x73\x00')

    # String: "What is this?".
    self._ascii_string_2 = (
        b'\x57\x00\x68\x00\x61\x00\x74\x00\x20\x00\x69\x00\x73\x00'
        b'\x20\x00\x74\x00\x68\x00\x69\x00\x73\x00\x3F\x00')

  @shared_test_lib.skipUnlessHasTestFile([u'PING.EXE-B29F6629.pf'])
  def testReadUTF16Stream(self):
    """Test reading an UTF-16 stream from a file-like object."""
    test_file_path = self._GetTestFilePath([u'PING.EXE-B29F6629.pf'])

    with open(test_file_path, 'rb') as file_object:
      # Read a null char terminated string.
      file_object.seek(0x10)
      self.assertEqual(binary.ReadUTF16Stream(file_object), u'PING.EXE')

      # Read a fixed size string.
      file_object.seek(0x27f8)
      expected_string = u'\\DEVICE\\HARDDISKVOLUME'
      string = binary.ReadUTF16Stream(file_object, byte_size=44)
      self.assertEqual(string, expected_string)

      file_object.seek(0x27f8)
      expected_string = u'\\DEVICE\\HARDDISKVOLUME1'
      string = binary.ReadUTF16Stream(file_object, byte_size=46)
      self.assertEqual(string, expected_string)

      # Read another null char terminated string.
      file_object.seek(7236)
      self.assertEqual(
          binary.ReadUTF16Stream(file_object),
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\NTDLL.DLL')

  @shared_test_lib.skipUnlessHasTestFile([u'PING.EXE-B29F6629.pf'])
  def testUTF16StreamCopyToString(self):
    """Test copying an UTF-16 byte stream to a string."""
    test_file_path = self._GetTestFilePath([u'PING.EXE-B29F6629.pf'])

    with open(test_file_path, 'rb') as file_object:
      byte_stream = file_object.read()

      # Read a null char terminated string.
      self.assertEqual(
          binary.UTF16StreamCopyToString(byte_stream[0x10:]), u'PING.EXE')

      # Read a fixed size string.
      expected_string = u'\\DEVICE\\HARDDISKVOLUME'
      string = binary.UTF16StreamCopyToString(
          byte_stream[0x27f8:], byte_stream_size=44)
      self.assertEqual(string, expected_string)

      expected_string = u'\\DEVICE\\HARDDISKVOLUME1'
      string = binary.UTF16StreamCopyToString(
          byte_stream[0x27f8:], byte_stream_size=46)
      self.assertEqual(string, expected_string)

      # Read another null char terminated string.
      expected_string = (
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\NTDLL.DLL')

      string = binary.UTF16StreamCopyToString(byte_stream[7236:])
      self.assertEqual(string, expected_string)

  @shared_test_lib.skipUnlessHasTestFile([u'PING.EXE-B29F6629.pf'])
  def testArrayOfUTF16StreamCopyToString(self):
    """Test copying an array of UTF-16 byte streams to strings."""
    test_file_path = self._GetTestFilePath([u'PING.EXE-B29F6629.pf'])

    with open(test_file_path, 'rb') as file_object:
      byte_stream = file_object.read()

      strings_array = binary.ArrayOfUTF16StreamCopyToString(
          byte_stream[0x1c44:], byte_stream_size=2876)
      expected_strings_array = [
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\NTDLL.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\KERNEL32.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\APISETSCHEMA.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\KERNELBASE.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\LOCALE.NLS',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\PING.EXE',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\ADVAPI32.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSVCRT.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\SECHOST.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\RPCRT4.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\IPHLPAPI.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\NSI.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WINNSI.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\USER32.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\GDI32.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\LPK.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\USP10.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WS2_32.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\IMM32.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSCTF.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\EN-US\\PING.EXE.MUI',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\GLOBALIZATION\\SORTING\\'
          u'SORTDEFAULT.NLS',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSWSOCK.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WSHQOS.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WSHTCPIP.DLL',
          u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WSHIP6.DLL']

      self.assertEqual(strings_array, expected_strings_array)

  @shared_test_lib.skipUnlessHasTestFile([u'PING.EXE-B29F6629.pf'])
  def testArrayOfUTF16StreamCopyToStringTable(self):
    """Test copying an array of UTF-16 byte streams to a string table."""
    test_file_path = self._GetTestFilePath([u'PING.EXE-B29F6629.pf'])

    with open(test_file_path, 'rb') as file_object:
      byte_stream = file_object.read()

      string_table = binary.ArrayOfUTF16StreamCopyToStringTable(
          byte_stream[0x1c44:], byte_stream_size=2876)
      expected_string_table = {
          0: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\NTDLL.DLL',
          102: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\KERNEL32.DLL',
          210: (u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\'
                u'APISETSCHEMA.DLL'),
          326: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\KERNELBASE.DLL',
          438: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\LOCALE.NLS',
          542: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\PING.EXE',
          642: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\ADVAPI32.DLL',
          750: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSVCRT.DLL',
          854: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\SECHOST.DLL',
          960: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\RPCRT4.DLL',
          1064: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\IPHLPAPI.DLL',
          1172: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\NSI.DLL',
          1270: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WINNSI.DLL',
          1374: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\USER32.DLL',
          1478: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\GDI32.DLL',
          1580: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\LPK.DLL',
          1678: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\USP10.DLL',
          1780: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WS2_32.DLL',
          1884: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\IMM32.DLL',
          1986: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSCTF.DLL',
          2088: (u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\EN-US\\'
                 u'PING.EXE.MUI'),
          2208: (u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\GLOBALIZATION\\'
                 u'SORTING\\SORTDEFAULT.NLS'),
          2348: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSWSOCK.DLL',
          2454: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WSHQOS.DLL',
          2558: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WSHTCPIP.DLL',
          2666: u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WSHIP6.DLL'}

      self.assertEqual(string_table, expected_string_table)

  def testStringParsing(self):
    """Test parsing the ASCII string."""
    self.assertEqual(binary.ReadUTF16(self._ascii_string_1), u'Whatis')

    self.assertEqual(binary.ReadUTF16(self._ascii_string_2), u'What is this?')

    uni_text = binary.ReadUTF16(self._unicode_string_1)
    self.assertEqual(uni_text, u'þrándur')

  def testHex(self):
    """Test the hexadecimal representation of data."""
    hex_string_1 = binary.HexifyBuffer(self._ascii_string_1)
    hex_compare = (
        b'\\x57\\x00\\x68\\x00\\x61\\x00\\x74\\x00\\x00\\x00\\x69\\x00'
        b'\\x73\\x00')
    self.assertEqual(hex_string_1, hex_compare)

    hex_string_2 = binary.HexifyBuffer(self._unicode_string_1)
    hex_compare_unicode = (
        b'\\xff\\xfe\\xfe\\x00\\x72\\x00\\xe1\\x00\\x6e\\x00\\x64\\x00'
        b'\\x75\\x00\\x72\\x00')

    self.assertEqual(hex_string_2, hex_compare_unicode)

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


text:
<!--
  ~ Copyright (c) 2013 David Boissier
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>distribution</id>
    <formats>
        <format>zip</format>
    </formats>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/lib</outputDirectory>
            <excludes>
                <exclude>com.intellij:forms_rt</exclude>
                <exclude>com.intellij:openapi</exclude>
                <exclude>com.intellij:util</exclude>
                <exclude>commons-lang:commons-lang</exclude>
                <exclude>log4j:log4j</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
    <files>
        <file>
            <source>README.md</source>
            <outputDirectory>/</outputDirectory>
        </file>
        <file>
            <source>CHANGELOG.txt</source>
            <outputDirectory>/</outputDirectory>
        </file>
        <file>
            <source>LICENSE.txt</source>
            <outputDirectory>/</outputDirectory>
        </file>
    </files>
</assembly>