repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
peterayeni/rapidsms
rapidsms/contrib/locations/app.py
1529
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import re import logging from rapidsms.apps.base import AppBase from .models import Location logger = logging.getLogger(__name__) class App(AppBase): PATTERN = re.compile(r"^(.+)\b(?:at)\b(.+?)$") def __find_location(self, text): try: # check for a location code first return Location.objects.get(slug__iexact=text) # nothing else is supported, for now! except Location.DoesNotExist: return None def parse(self, msg): # if this message ends in "at SOMEWHERE", # we have work to do. otherwise, ignore it m = self.PATTERN.match(msg.text) if m is not None: # resolve the string into a Location object # (or None), and attach it to msg for other # apps to deal with text = m.group(2).strip() # split the text by space to find if it has a village # locCode,village = text.split() # location = self.__find_location(locCode) # location.village = village # msg.location = location msg.location = self.__find_location(text) # strip the location tag from the message, # so other apps don't have to deal with it msg.text = m.group(1) # we should probably log this crazy behavior... logger.info("Stripped Location code: %s" % text) logger.info("Message is now: %s" % msg.text)
bsd-3-clause
basnijholt/holoviews
holoviews/tests/plotting/matplotlib/testcallbacks.py
1284
from collections import deque import numpy as np from holoviews.core import DynamicMap from holoviews.element import Points, Curve from holoviews.streams import PointerXY, PointerX from .testplot import TestMPLPlot, mpl_renderer class TestCallbackPlot(TestMPLPlot): def test_dynamic_streams_refresh(self): stream = PointerXY(x=0, y=0) dmap = DynamicMap(lambda x, y: Points([(x, y)]), kdims=[], streams=[stream]) plot = mpl_renderer.get_plot(dmap) pre = mpl_renderer(plot, fmt='png') plot.state.set_dpi(72) stream.event(x=1, y=1) post = mpl_renderer(plot, fmt='png') self.assertNotEqual(pre, post) def test_stream_callback_single_call(self): def history_callback(x, history=deque(maxlen=10)): history.append(x) return Curve(list(history)) stream = PointerX(x=0) dmap = DynamicMap(history_callback, kdims=[], streams=[stream]) plot = mpl_renderer.get_plot(dmap) mpl_renderer(plot) for i in range(20): plot.state.set_dpi(72) stream.event(x=i) x, y = plot.handles['artist'].get_data() self.assertEqual(x, np.arange(10)) self.assertEqual(y, np.arange(10, 20))
bsd-3-clause
dodkoC/thesis-disassembler
testData/expectedResults/EmptyEnum.java
652
public final enum EmptyEnum extends java.lang.Enum<EmptyEnum> { public final static enum EmptyEnum A; public final static enum EmptyEnum B; private final static /* synthetic */ EmptyEnum[] $VALUES; public static EmptyEnum[] values() { return EmptyEnum.$VALUES.clone(); } public static EmptyEnum valueOf(java.lang.String name) { return java.lang.Enum.valueOf(EmptyEnum.class, name); } private EmptyEnum(java.lang.String arg0, int arg1) { super(arg0, arg1); } static void <clinit>() { EmptyEnum.A = new EmptyEnum("A", 0); EmptyEnum.B = new EmptyEnum("B", 1); EmptyEnum.$VALUES = new EmptyEnum[]{EmptyEnum.A, EmptyEnum.B}; } }
bsd-3-clause
NCIP/cagrid
cagrid/Software/core/caGrid/projects/websso-client-acegi/src/java/org/cagrid/websso/client/acegi/logout/SingleSignoutCallbackFilter.java
3043
package org.cagrid.websso.client.acegi.logout; import java.io.BufferedReader; import java.io.IOException; import java.net.URLDecoder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SingleSignoutCallbackFilter implements Filter, InitializingBean { private final Log log = LogFactory.getLog(getClass()); private String filterProcessesUrl; private ExpiredTicketCache expiredTicketCache; public void setFilterProcessesUrl(String s) { this.filterProcessesUrl = s; } public void setExpiredTicketCache(ExpiredTicketCache cache) { this.expiredTicketCache = cache; } public void afterPropertiesSet() throws Exception { Assert.hasLength(this.filterProcessesUrl, "filterProcessesUrl must be specified"); log.debug("filterProcessesUrl "+this.filterProcessesUrl); Assert.notNull(this.expiredTicketCache, "cache mandatory"); } public void init(FilterConfig config) throws ServletException { } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; if (processLogout(httpRequest)) { return; } chain.doFilter(request, response); } protected boolean processLogout(HttpServletRequest request) throws IOException { if (!request.getMethod().equalsIgnoreCase("POST")) { return false; } String uri = request.getRequestURI(); // strip everything after the first semi-colon int pathParamIndex = uri.indexOf(';'); if (pathParamIndex > 0) { uri = uri.substring(0, pathParamIndex); } if (!uri.endsWith(request.getContextPath() + this.filterProcessesUrl)) { return false; } String sTicket = null; BufferedReader reader = request.getReader(); String line = null; while ((line = reader.readLine()) != null) { line = URLDecoder.decode(line, "UTF-8"); if (line.startsWith("logoutRequest=")) { int start = line.indexOf("<samlp:SessionIndex>"); int end = line.indexOf("</samlp:SessionIndex>"); if (start > -1 && start < end) { sTicket = line.substring(start + "<samlp:SessionIndex>".length(), end); } } } reader.close(); if (sTicket != null) { log.info("expired Service ticket "+sTicket); this.expiredTicketCache.putTicketInCache(sTicket); } return true; } }
bsd-3-clause
edrlab/r2-streamer-js-dist
dist/es5/src/http/server-lcp-lsd-show.js
15229
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.serverLCPLSD_show = exports.serverLCPLSD_show_PATH = void 0; var tslib_1 = require("tslib"); var css2json = require("css2json"); var debug_ = require("debug"); var DotProp = require("dot-prop"); var express = require("express"); var jsonMarkup = require("json-markup"); var morgan = require("morgan"); var path = require("path"); var request = require("request"); var requestPromise = require("request-promise-native"); var lcp_1 = require("r2-lcp-js/dist/es5/src/parser/epub/lcp"); var lsd_1 = require("r2-lcp-js/dist/es5/src/parser/epub/lsd"); var serializable_1 = require("r2-lcp-js/dist/es5/src/serializable"); var UrlUtils_1 = require("r2-utils-js/dist/es5/src/_utils/http/UrlUtils"); var JsonUtils_1 = require("r2-utils-js/dist/es5/src/_utils/JsonUtils"); var BufferUtils_1 = require("r2-utils-js/dist/es5/src/_utils/stream/BufferUtils"); var json_schema_validate_1 = require("../utils/json-schema-validate"); var request_ext_1 = require("./request-ext"); var server_trailing_slash_redirect_1 = require("./server-trailing-slash-redirect"); var server_url_1 = require("./server-url"); var debug = debug_("r2:streamer#http/lcp-lsd-show"); exports.serverLCPLSD_show_PATH = "/lcp-lsd-show"; function serverLCPLSD_show(_server, topRouter) { var _this = this; var jsonStyle = "\n.json-markup {\n line-height: 17px;\n font-size: 13px;\n font-family: monospace;\n white-space: pre;\n}\n.json-markup-key {\n font-weight: bold;\n}\n.json-markup-bool {\n color: firebrick;\n}\n.json-markup-string {\n color: green;\n}\n.json-markup-null {\n color: gray;\n}\n.json-markup-number {\n color: blue;\n}\n"; var routerLCPLSD_show = express.Router({ strict: false }); routerLCPLSD_show.use(morgan("combined", { stream: { write: function (msg) { return debug(msg); } } })); routerLCPLSD_show.use(server_trailing_slash_redirect_1.trailingSlashRedirect); routerLCPLSD_show.get("/", function (_req, res) { var html = "<html><head>"; html += "<script type=\"text/javascript\">function encodeURIComponent_RFC3986(str) { " + "return encodeURIComponent(str).replace(/[!'()*]/g, (c) => { " + "return \"%\" + c.charCodeAt(0).toString(16); }); }" + "function go(evt) {" + "if (evt) { evt.preventDefault(); } var url = " + "location.origin +" + " '".concat(exports.serverLCPLSD_show_PATH, "/' +") + " encodeURIComponent_RFC3986(document.getElementById(\"url\").value);" + "location.href = url;}</script>"; html += "</head>"; html += "<body><h1>LCP / LSD examiner</h1>"; html += "<form onsubmit=\"go();return false;\">" + "<input type=\"text\" name=\"url\" id=\"url\" size=\"80\">" + "<input type=\"submit\" value=\"Go!\"></form>"; html += "</body></html>"; res.status(200).send(html); }); routerLCPLSD_show.param("urlEncoded", function (req, _res, next, value, _name) { req.urlEncoded = value; next(); }); routerLCPLSD_show.get("/:" + request_ext_1._urlEncoded + "(*)", function (req, res) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () { var reqparams, urlDecoded, isSecureHttp, rootUrl, failure, success, headers, needsStreamingResponse, response, err_1; var _this = this; return (0, tslib_1.__generator)(this, function (_a) { switch (_a.label) { case 0: reqparams = req.params; if (!reqparams.urlEncoded) { reqparams.urlEncoded = req.urlEncoded; } urlDecoded = reqparams.urlEncoded; debug(urlDecoded); isSecureHttp = req.secure || req.protocol === "https" || req.get("X-Forwarded-Proto") === "https"; rootUrl = (isSecureHttp ? "https://" : "http://") + req.headers.host; failure = function (err) { debug(err); res.status(500).send("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>"); }; success = function (response) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () { var isBadStatusCode, responseData, err_2, responseStr, responseJson, isStatusDoc, lcpOrLsd, lcpOrLsdJson, validationStr, doValidate, jsonSchemasRootpath, jsonSchemasNames, validationErrors, _i, validationErrors_1, err, val, valueStr, funk, css, jsonPretty; var _a; return (0, tslib_1.__generator)(this, function (_b) { switch (_b.label) { case 0: isBadStatusCode = response.statusCode && (response.statusCode < 200 || response.statusCode >= 300); if (isBadStatusCode) { failure("HTTP CODE " + response.statusCode); return [2]; } _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); return [4, (0, BufferUtils_1.streamToBufferPromise)(response)]; case 2: responseData = _b.sent(); return [3, 4]; case 3: err_2 = _b.sent(); debug(err_2); res.status(500).send("<html><body><p>Internal Server Error</p><p>" + err_2 + "</p></body></html>"); return [2]; case 4: responseStr = responseData.toString("utf8"); responseJson = JSON.parse(responseStr); isStatusDoc = responseJson.id && responseJson.status && responseJson.updated && responseJson.links; lcpOrLsd = isStatusDoc ? (0, serializable_1.TaJsonDeserialize)(responseJson, lsd_1.LSD) : (0, serializable_1.TaJsonDeserialize)(responseJson, lcp_1.LCP); lcpOrLsdJson = (0, serializable_1.TaJsonSerialize)(lcpOrLsd); doValidate = !reqparams.jsonPath || reqparams.jsonPath === "all"; if (doValidate) { jsonSchemasRootpath = path.join(process.cwd(), "misc", "json-schema"); jsonSchemasNames = [ isStatusDoc ? "lcp/status" : "lcp/license", "lcp/link", ]; validationErrors = (0, json_schema_validate_1.jsonSchemaValidate)(jsonSchemasRootpath, jsonSchemasNames, lcpOrLsdJson); if (validationErrors) { validationStr = ""; for (_i = 0, validationErrors_1 = validationErrors; _i < validationErrors_1.length; _i++) { err = validationErrors_1[_i]; debug("JSON Schema validation FAIL."); debug(err); val = err.jsonPath ? DotProp.get(lcpOrLsdJson, err.jsonPath) : ""; valueStr = (typeof val === "string") ? "".concat(val) : ((val instanceof Array || typeof val === "object") ? "".concat(JSON.stringify(val)) : ""); debug(valueStr); validationStr += "\n".concat(err.ajvMessage, ": ").concat(valueStr, "\n\n'").concat((_a = err.ajvDataPath) === null || _a === void 0 ? void 0 : _a.replace(/^\./, ""), "' (").concat(err.ajvSchemaPath, ")\n\n"); } } } funk = function (obj) { if ((obj.href && typeof obj.href === "string") || (obj.Href && typeof obj.Href === "string")) { var fullHref = obj.href ? obj.href : obj.Href; var isDataUrl = /^data:/.test(fullHref); var isMailUrl = /^mailto:/.test(fullHref); var notFull = !isDataUrl && !isMailUrl && !(0, UrlUtils_1.isHTTP)(fullHref); if (notFull) { fullHref = (0, UrlUtils_1.ensureAbsolute)(urlDecoded, fullHref); } if ((obj.type === "application/vnd.readium.license.status.v1.0+json" && obj.rel === "status") || (obj.type === "application/vnd.readium.lcp.license.v1.0+json" && obj.rel === "license")) { obj.__href__ = rootUrl + req.originalUrl.substr(0, req.originalUrl.indexOf(exports.serverLCPLSD_show_PATH + "/")) + exports.serverLCPLSD_show_PATH + "/" + (0, UrlUtils_1.encodeURIComponent_RFC3986)(fullHref); } else if (obj.type === "application/epub+zip" && obj.rel === "publication") { obj.__href__ = rootUrl + req.originalUrl.substr(0, req.originalUrl.indexOf(exports.serverLCPLSD_show_PATH + "/")) + server_url_1.serverRemotePub_PATH + "/" + (0, UrlUtils_1.encodeURIComponent_RFC3986)(fullHref); } else if (isDataUrl) { } else if (notFull && !isMailUrl) { obj.__href__ = fullHref; } } }; (0, JsonUtils_1.traverseJsonObjects)(lcpOrLsdJson, funk); css = css2json(jsonStyle); jsonPretty = jsonMarkup(lcpOrLsdJson, css); res.status(200).send("<html><body>" + "<h1>" + (isStatusDoc ? "LSD" : "LCP") + " JSON" + "</h1>" + "<h2><a href=\"" + urlDecoded + "\">" + urlDecoded + "</a></h2>" + "<hr>" + "<div style=\"overflow-x: auto;margin:0;padding:0;width:100%;height:auto;\">" + jsonPretty + "</div>" + (doValidate ? (validationStr ? ("<hr><p><pre>" + validationStr + "</pre></p>") : ("<hr><p>JSON SCHEMA OK.</p>")) : "") + "</body></html>"); return [2]; } }); }); }; headers = { "Accept": "application/json,application/xml", "Accept-Language": "en-UK,en-US;q=0.7,en;q=0.5", "User-Agent": "READIUM2", }; needsStreamingResponse = true; if (!needsStreamingResponse) return [3, 1]; request.get({ headers: headers, method: "GET", uri: urlDecoded, }) .on("response", function (res) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () { var successError_1; return (0, tslib_1.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4, success(res)]; case 1: _a.sent(); return [3, 3]; case 2: successError_1 = _a.sent(); failure(successError_1); return [2]; case 3: return [2]; } }); }); }) .on("error", failure); return [3, 7]; case 1: response = void 0; _a.label = 2; case 2: _a.trys.push([2, 4, , 5]); return [4, requestPromise({ headers: headers, method: "GET", resolveWithFullResponse: true, uri: urlDecoded, })]; case 3: response = _a.sent(); return [3, 5]; case 4: err_1 = _a.sent(); failure(err_1); return [2]; case 5: return [4, success(response)]; case 6: _a.sent(); _a.label = 7; case 7: return [2]; } }); }); }); topRouter.use(exports.serverLCPLSD_show_PATH, routerLCPLSD_show); } exports.serverLCPLSD_show = serverLCPLSD_show; //# sourceMappingURL=server-lcp-lsd-show.js.map
bsd-3-clause
mile-janev/vital-web
views/call/update.php
527
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\Call */ $this->title = 'Update Call: ' . ' ' . $model->id; $this->params['breadcrumbs'][] = ['label' => 'Calls', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = 'Update'; ?> <div class="call-update container"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
bsd-3-clause
NCIP/catissue-simple-query
src/test/java/edu/wustl/common/querysuite/QueryMetadataUtil.java
13095
/*L * Copyright Washington University in St. Louis * Copyright SemanticBits * Copyright Persistent Systems * Copyright Krishagni * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/catissue-simple-query/LICENSE.txt for details. */ package edu.wustl.common.querysuite; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.hibernate.HibernateException; import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException; import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException; import edu.wustl.common.querysuite.exceptions.MultipleRootsException; import edu.wustl.common.querysuite.exceptions.SqlException; import edu.wustl.common.util.dbmanager.DBUtil; /** * This class generates metadata for CP enhancements. * * @author deepti_shelar * */ public class QueryMetadataUtil { private static Connection connection = null; private static Statement stmt = null; private static HashMap<String, List<String>> entityNameAttributeNameMap = new HashMap<String, List<String>>(); private static HashMap<String, String> attributeColumnNameMap = new HashMap<String, String>(); private static HashMap<String, String> attributeDatatypeMap = new HashMap<String, String>(); public static void main(String[] args) throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException, MultipleRootsException, SqlException, HibernateException, SQLException, IOException { populateEntityAttributeMap(); populateAttributeColumnNameMap(); populateAttributeDatatypeMap(); connection = DBUtil.getConnection(); connection.setAutoCommit(true); stmt = connection.createStatement(); Set<String> keySet = entityNameAttributeNameMap.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String entityName = (String) iterator.next(); List<String> attributes = entityNameAttributeNameMap .get(entityName); for (String attr : attributes) { /*System.out.println("Adding attribute " + attr + "--" + entityName); */String sql = "select max(identifier) from dyextn_abstract_metadata"; ResultSet rs = stmt.executeQuery(sql); int nextIdOfAbstractMetadata = 0; if (rs.next()) { int maxId = rs.getInt(1); nextIdOfAbstractMetadata = maxId + 1; } int nextIdAttrTypeInfo = 0; sql = "select max(identifier) from dyextn_attribute_type_info"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdAttrTypeInfo = maxId + 1; } int nextIdDatabaseproperties = 0; sql = "select max(identifier) from dyextn_database_properties"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdDatabaseproperties = maxId + 1; } /*System.out.println(" generated ids"); System.out.println("dyextn_abstract_metadata : " + nextIdOfAbstractMetadata); System.out.println("dyextn_attribute_type_info :" + nextIdAttrTypeInfo); System.out.println("dyextn_database_properties :" + nextIdDatabaseproperties);*/ sql = "INSERT INTO dyextn_abstract_metadata values(" + nextIdOfAbstractMetadata + ",NULL,NULL,NULL,'" + attr + "',null)"; executeInsertSQL(sql); int entityId = getEntityIdByName(entityName); sql = "INSERT INTO dyextn_attribute values (" + nextIdOfAbstractMetadata + "," + entityId + ")"; executeInsertSQL(sql); sql = "insert into `dyextn_primitive_attribute` (`IDENTIFIER`,`IS_COLLECTION`,`IS_IDENTIFIED`,`IS_PRIMARY_KEY`,`IS_NULLABLE`)" + " values (" + nextIdOfAbstractMetadata + ",0,NULL,0,1)"; executeInsertSQL(sql); sql = "insert into `dyextn_attribute_type_info` (`IDENTIFIER`,`PRIMITIVE_ATTRIBUTE_ID`) values (" + nextIdAttrTypeInfo + "," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); String dataType = getDataTypeOfAttribute(attr); if (!dataType.equalsIgnoreCase("String")) { sql = "insert into `dyextn_numeric_type_info` (`IDENTIFIER`,`MEASUREMENT_UNITS`,`DECIMAL_PLACES`,`NO_DIGITS`) values (" + nextIdAttrTypeInfo + ",NULL,0,NULL)"; executeInsertSQL(sql); } if (dataType.equalsIgnoreCase("string")) { sql = "insert into `dyextn_string_type_info` (`IDENTIFIER`) values (" + nextIdAttrTypeInfo + ")"; } else if (dataType.equalsIgnoreCase("double")) { sql = "insert into dyextn_double_type_info (`IDENTIFIER`) values (" + nextIdAttrTypeInfo + ")"; } else if (dataType.equalsIgnoreCase("int")) { sql = "insert into dyextn_integer_type_info (`IDENTIFIER`) values (" + nextIdAttrTypeInfo + ")"; } executeInsertSQL(sql); String columnName = getColumnNameOfAttribue(attr); sql = "insert into `dyextn_database_properties` (`IDENTIFIER`,`NAME`) values (" + nextIdDatabaseproperties + ",'" + columnName + "')"; executeInsertSQL(sql); sql = "insert into `dyextn_column_properties` (`IDENTIFIER`,`PRIMITIVE_ATTRIBUTE_ID`) values (" + nextIdDatabaseproperties + "," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); } } addAssociation(false); addAssociation(true); } private static void addAssociation(boolean isSwap) throws SQLException { String sql = "select max(identifier) from dyextn_abstract_metadata"; ResultSet rs = stmt.executeQuery(sql); int nextIdOfAbstractMetadata = 0; if (rs.next()) { int maxId = rs.getInt(1); nextIdOfAbstractMetadata = maxId + 1; } int nextIdOfDERole = 0; sql = "select max(identifier) from dyextn_role"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdOfDERole = maxId + 1; } int nextIdOfDBProperties = 0; sql = "select max(identifier) from dyextn_database_properties"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdOfDBProperties = maxId + 1; } int nextIDintraModelAssociation = 0; sql = "select max(ASSOCIATION_ID) from intra_model_association"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIDintraModelAssociation = maxId + 1; } int nextIdPath = 0; sql = "select max(PATH_ID) from path"; rs = stmt.executeQuery(sql); if (rs.next()) { int maxId = rs.getInt(1); nextIdPath = maxId + 1; } int entityId = 0; String entityName = "edu.wustl.catissuecore.domain.CollectionProtocol"; sql = "select identifier from dyextn_abstract_metadata where name like '" + entityName + "'"; rs = stmt.executeQuery(sql); if (rs.next()) { entityId = rs.getInt(1); } if (entityId == 0) { System.out.println("Entity not found of name "); } /*System.out.println(" generated ids"); System.out.println("Fount entity id is :" + entityId); System.out.println("dyextn_abstract_metadata : " + nextIdOfAbstractMetadata); System.out.println("nextIdOfDERole : " + nextIdOfDERole); System.out.println("nextIdOfDBProperties : " + nextIdOfDBProperties); System.out.println("nextIDintraModelAssociatio : " + nextIDintraModelAssociation);*/ /* System.out.println("nextIdDEAssociation : " + nextIdDEAssociation);*/ sql = "insert into dyextn_abstract_metadata values (" + nextIdOfAbstractMetadata + ",null,null,null,'collectionProtocolSelfAssociation',null)"; executeInsertSQL(sql); sql = "insert into dyextn_attribute values (" + nextIdOfAbstractMetadata + "," + entityId + ")"; executeInsertSQL(sql); sql = "insert into dyextn_role values (" + nextIdOfDERole + ",'ASSOCIATION',2,0,'childCollectionProtocolCollection')"; executeInsertSQL(sql); int roleId = nextIdOfDERole + 1; sql = "insert into dyextn_role values (" + roleId + ",'ASSOCIATION',1,0,'parentCollectionProtocol')"; executeInsertSQL(sql); if (!isSwap) { sql = "insert into dyextn_association values (" + nextIdOfAbstractMetadata + ",'BI_DIRECTIONAL'," + entityId + "," + roleId + "," + nextIdOfDERole + ",1)"; } else { sql = "insert into dyextn_association values (" + nextIdOfAbstractMetadata + ",'BI_DIRECTIONAL'," + entityId + "," + nextIdOfDERole + "," + roleId + ",1)"; } executeInsertSQL(sql); sql = "insert into dyextn_database_properties values (" + nextIdOfDBProperties + ",'collectionProtocolSelfAssociation')"; executeInsertSQL(sql); sql = "insert into dyextn_constraint_properties values(" + nextIdOfDBProperties + ",'PARENT_CP_ID',null," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); sql = "insert into association values(" + nextIDintraModelAssociation + ",2)"; executeInsertSQL(sql); sql = "insert into intra_model_association values(" + nextIDintraModelAssociation + "," + nextIdOfAbstractMetadata + ")"; executeInsertSQL(sql); sql = "insert into path values (" + nextIdPath + "," + entityId + "," + nextIDintraModelAssociation + "," + entityId + ")"; executeInsertSQL(sql); } private static String getColumnNameOfAttribue(String attr) { return attributeColumnNameMap.get(attr); } private static String getDataTypeOfAttribute(String attr) { return attributeDatatypeMap.get(attr); } private static void populateEntityAttributeMap() { List<String> attributes = new ArrayList<String>(); attributes.add("offset"); entityNameAttributeNameMap.put( "edu.wustl.catissuecore.domain.SpecimenCollectionGroup", attributes); attributes = new ArrayList<String>(); attributes.add("offset"); entityNameAttributeNameMap.put( "edu.wustl.catissuecore.domain.CollectionProtocolRegistration", attributes); attributes = new ArrayList<String>(); attributes.add("type"); attributes.add("sequenceNumber"); attributes.add("studyCalendarEventPoint"); entityNameAttributeNameMap.put( "edu.wustl.catissuecore.domain.CollectionProtocol", attributes); } private static void populateAttributeColumnNameMap() { attributeColumnNameMap.put("offset", "DATE_OFFSET"); attributeColumnNameMap.put("type", "CP_TYPE"); attributeColumnNameMap.put("sequenceNumber", "SEQUENCE_NUMBER"); attributeColumnNameMap.put("studyCalendarEventPoint", "STUDY_CALENDAR_EVENT_POINT"); } private static void populateAttributeDatatypeMap() { attributeDatatypeMap.put("offset", "int"); attributeDatatypeMap.put("type", "string"); attributeDatatypeMap.put("sequenceNumber", "int"); attributeDatatypeMap.put("studyCalendarEventPoint", "double"); } private static int executeInsertSQL(String sql) throws SQLException { int b; System.out.println(sql+";"); b = stmt.executeUpdate(sql); return b; } private static int getEntityIdByName(String entityName) throws SQLException { ResultSet rs; int entityId = 0; String sql = "select identifier from dyextn_abstract_metadata where name like '" + entityName + "'"; rs = stmt.executeQuery(sql); if (rs.next()) { entityId = rs.getInt(1); } if (entityId == 0) { System.out.println("Entity not found of name "); } return entityId; } } /* * insert into dyextn_abstract_metadata values * (1224,null,null,null,'collectionProtocolSelfAssociation',null) insert * into dyextn_attribute values (1224,177); insert into dyextn_role * values (897,'ASSOCIATION',2,0,'childCollectionProtocolCollection'); * insert into dyextn_role values * (898,'ASSOCIATION',1,0,'parentCollectionProtocol'); insert into * dyextn_association values (1224,'BI_DIRECTIONAL',177,898,897,1) * insert into dyextn_database_properties values * (1222,'collectionProtocolSelfAssociation'); insert into * dyextn_constraint_properties values(1222,'PARENT_CP_ID',null,1224); * insert into intra_model_association values(664,1224) insert into path * values (985340,177,664,177); * * insert into dyextn_abstract_metadata values * (1225,null,null,null,'collectionProtocolSelfAssociation',null) insert * into dyextn_attribute values (1225,177); insert into dyextn_role * values (899,'ASSOCIATION',2,0,'childCollectionProtocolCollection'); * insert into dyextn_role values * (900,'ASSOCIATION',1,0,'parentCollectionProtocol'); insert into * dyextn_association values (1225,'BI_DIRECTIONAL',177,900,899,1) * insert into dyextn_database_properties values * (1223,'collectionProtocolSelfAssociation'); insert into * dyextn_constraint_properties values(1223,'PARENT_CP_ID',null,1225); * insert into intra_model_association values(665,1225) insert into path * values (985340,177,666,177); */
bsd-3-clause
juliangut/body-parser
tests/bootstrap.php
299
<?php /* * body-parser (https://github.com/juliangut/body-parser). * PSR7 body parser middleware. * * @license BSD-3-Clause * @link https://github.com/juliangut/body-parser * @author Julián Gutiérrez <juliangut@gmail.com> */ session_start(); require __DIR__ . '/../vendor/autoload.php';
bsd-3-clause
xuhuan/generator-zfis
app/index.js
2686
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var yosay = require('yosay'); var ZfisGenerator = yeoman.generators.Base.extend({ initializing: function() { this.pkg = require('../package.json'); }, prompting: function() { var done = this.async(); // Have Yeoman greet the user. this.log(yosay( 'Welcome to the doozie Zfis generator!' )); var prompts = [{ name: 'appName', message: 'app name', default: 'app' }, { name: 'version', message: 'version', default: '0.0.1' }, { type: "checkbox", message: "bower dependencies", name: "bower_dependencies", choices: [{ name: "jquery", checked: true }, { name: "bootstrap", checked: true }, { name: "json3", checked: true }, { name: "es5-shim", checked: true }, { name: "angular" }, { name: "angular-resource" }, { name: "angular-cookies" }, { name: "angular-sanitize" }, { name: "angular-animate" }, { name: "angular-touch" }, { name: "angular-route" }, { name: "angular-ui-router" }] }, { type: "checkbox", message: "package dependencies", name: "package_dependencies", choices: [{ name: "karma", checked: false }] }]; this.prompt(prompts, function(props) { this.appName = props.appName; this.version = props.version; var _bower_dependencies = {}; props.bower_dependencies.forEach(function(e, i, a) { _bower_dependencies[e] = "*"; }); var _package_dependencies = {}; props.package_dependencies.forEach(function(e, i, a) { _package_dependencies[e] = "*"; }); this.bower_dependencies = JSON.stringify(_bower_dependencies, null, '\r'); this.package_dependencies = JSON.stringify(_package_dependencies, null, '\r'); this.bower_dev_dependencies = JSON.stringify({}, null, '\r'); this.package_dev_dependencies = JSON.stringify({}, null, '\r'); this.template('_bower.json', 'bower.json'); this.template('_package.json', 'package.json'); // this.write('bower.json', JSON.stringify(bower, null, 2)); done(); }.bind(this)); }, writing: { app: function() { this.dest.mkdir('app'); this.dest.mkdir('app/templates'); this.dest.mkdir('static'); this.dest.mkdir('static/css'); this.dest.mkdir('static/images'); this.dest.mkdir('static/js'); this.dest.mkdir('src'); this.dest.mkdir('test'); }, projectfiles: function() { this.src.copy('editorconfig', '.editorconfig'); this.src.copy('jshintrc', '.jshintrc'); } }, end: function() { this.installDependencies(); } }); module.exports = ZfisGenerator;
bsd-3-clause
uwcirg/cpro
app/webroot/js/cpro.js
7108
/** * * Copyright 2013 University of Washington, School of Nursing. * http://opensource.org/licenses/BSD-3-Clause * * Main file for storing jquery functions that are called throughout the * codebase. * */ // AJAX to change language for currently logged in user or before login that // will then be saved to their record after login function changeLanguageSelf(lang) { $.ajax ({ type: "POST", url: appRoot + 'users/setLanguageForSelf', async: false, dataType: 'json', data: {"data[User][locale]" : lang , "data[AppController][AppController_id]" : acidValue} }).done(function(){ window.location.reload(); }).fail(function(){ alert("There was a problem updating the language." + appRoot) }); } // Show UW NetID login when "shift", "u" and "w" are typed at the same time // Used for instances that have UWNETID_LOGIN as false. (if "true" it always is // shown so this isn't need. function typeForNetId() { var map = {16: false, 85: false, 87: false}; $(document).keydown(function(e) { if (e.keyCode in map) { map[e.keyCode] = true; if (map[16] && map[85] && map[87]) { $("#uwLogin").fadeIn('slowUW'); } } }).keyup(function(e) { if (e.keyCode in map) { map[e.keyCode] = false; } }); } $(document).ready(function() { // Generic hide/show a section - used in patient edit. Specify the element(s) // to hide/show with the data-hide attribute on button $('.minimize-section').on("click", function(){ var minLink = $(this); var toHide = $(minLink).attr('data-hide'); $(toHide).toggle(0, function(){ $(minLink).toggleClass('section-hidden'); if($(toHide).is(":visible")) { $(minLink).html('<i class="icon-chevron-up"></i> Hide'); } else { $(minLink).html('<i class="icon-chevron-down"></i> Show'); } }); }) // Language switch - open confirmation modal $('#langSwitch').on('click', function() { var langChoice = $(this).attr('name'); $("#langSwitchModal").modal(); return false; }); // Language switch function on click. After AJAX is passed, the page will // reload with the new language. $('#langSwitchConfirm').on('click', function() { var langChoice = $(this).attr('name'); changeLanguageSelf(langChoice); return false; }); // Enable Bootstrap popovers and add functionality $("[rel=popover]").popover({ trigger: 'click', placement: 'top' }); // Adds a close button to popover title when created function addPopoverClose() { $(".popover-title").append('<button type="button" id="closePopover" class="close">&times;</button>'); } // Function to close any other popovers when clicking on a new one // Based on: http://stackoverflow.com/questions/12116725/executing-functions-before-bootstrap-popover-is-displayed var $visiblePopover; function popoverMgr($this) { // check if the one clicked is now shown if ($this.data('popover').tip().hasClass('in')) { // if another was showing, hide it $visiblePopover && $visiblePopover.popover('hide'); // then store the current popover $visiblePopover = $this; addPopoverClose(); } else { // if it was hidden, then nothing must be showing $visiblePopover = ''; } } // Execute popoverMgr $('body').on('click', '[rel="popover"]', function() { var $this = $(this); popoverMgr($this); return false; // Prevents page moving up if href="#" is in <a> tag. }); // Clicking on close button mimics a click on the original link $('body').on('click', '#closePopover', function() { $(this).closest("div").prev('[rel="popover"]').trigger('click'); }); // Enable Bootstrap tooltips $("[rel=tooltip]").tooltip(); // Scroll to point on page based on href. This method allows an affixed // column to move on clicks within page (uses Bootstrap affix) $(".scroll-on-page").on('click', function() { $('html,body').animate({scrollTop: $($(this).attr("href")).offset().top},{duration: 500, easing: "swing"}); return false; }); // Change date format to preferred dd/mm/yyyy $('input.datep').each(function(){ var serverFormat = $(this).val(); // if there's already a date and that date is in the YYYY-MM-DD (as // found by having one or more dashes in serverFormat) if (serverFormat && (serverFormat.indexOf("-") != -1)) { if (serverFormat && serverFormat != '') { var serverFormatArray = serverFormat.split("-"); var newFormat = serverFormatArray[1]+"/"+serverFormatArray[2]+"/"+serverFormatArray[0]; } $(this).val(newFormat); } }); }); // Make height of left sidebar fill the entire window function resizeSide() { var windowsize = $(window).width(); if (windowsize > 767) { // If window is wider than 767 then calculature which is taller - the // overall window or the main container (span10). Then set the left // height based on that. var headerHeight = $(".esrac-header.row").height(); var contOffset, mainHeight, contToChange; // container is named differently in survye layout vs. default if ($("body").hasClass('survey')) { contOffset = $(".survey-container").position().top; mainHeight = $(".survey-container").height(); contToChange = "#surveySidebar"; } else { contOffset = $(".intervention-container").position().top; mainHeight = $(".intervention-container").height(); contToChange = ".intervention-container > .row > .span2"; } if ($(window).height() > (mainHeight + headerHeight)) { //console.log("window is bigger "); var currentHeight = $(window).height() - contOffset; } else { //console.log("div is bigger "); var currentHeight = mainHeight; } $(contToChange).css("height", currentHeight + "px"); } else { // If window is less than 767 wide, the nav is no longer on left - // everything is in the single column, so we don't want any extra height $(".intervention-container > .row > .span2").css("height", ""); $("#surveySidebar").css("height", ""); } } $(window).load(function(){ // Fire resize when window finishes loading resizeSide(); $(window).resize(function() { // Fire resize if browser window size changes. Delay by 200ms to avoid // too many firings as user drags browser window clearTimeout(this.id); this.id = setTimeout(resizeSide, 200); }); //$(window).bind('resize', resizeSide); });
bsd-3-clause
genail/gear
src/gfx/race/ui/RaceUITimeTrail.cpp
4322
/* * Copyright (c) 2009-2010, Piotr Korzuszek * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "RaceUITimeTrail.h" #include "gfx/Stage.h" #include "gfx/race/ui/Label.h" #include "logic/race/GameLogicTimeTrailOnline.h" #include "math/Time.h" #include "ranking/RankingEntry.h" namespace Gfx { class RaceUITimeTrailImpl { public: RaceUITimeTrail *m_parent; const Race::GameLogicTimeTrailOnline &m_logic; Label m_bestOnlineTimeTitleLabel; Label m_bestOnlineTimeLabel; RaceUITimeTrailImpl( RaceUITimeTrail *p_parent, const Race::GameLogicTimeTrailOnline *p_logic); void positionLapTimeLabels(); ~RaceUITimeTrailImpl(); void load(CL_GraphicContext &p_gc); void draw(CL_GraphicContext &p_gc); }; RaceUITimeTrail::RaceUITimeTrail(const Race::GameLogicTimeTrailOnline *p_logic) : m_impl(new RaceUITimeTrailImpl(this, p_logic)) { // empty } RaceUITimeTrailImpl::RaceUITimeTrailImpl( RaceUITimeTrail *p_parent, const Race::GameLogicTimeTrailOnline *p_logic) : m_parent(p_parent), m_logic(*p_logic), m_bestOnlineTimeTitleLabel(CL_Pointf(), _("Best Online Lap"), Label::F_BOLD, 22), m_bestOnlineTimeLabel(CL_Pointf(), "", Label::F_REGULAR, 22) { positionLapTimeLabels(); m_bestOnlineTimeTitleLabel.setShadowVisible(true); m_bestOnlineTimeLabel.setShadowVisible(true); } void RaceUITimeTrailImpl::positionLapTimeLabels() { const int BOTTOM_MARGIN = 20; const int RIGHT_MARGIN = 20; const int ENTRY_HEIGHT = 25; const int stageWidth = Stage::getWidth(); const int stageHeight = Stage::getHeight(); m_bestOnlineTimeLabel.setAttachPoint(Label::AP_RIGHT | Label::AP_BOTTOM); m_bestOnlineTimeLabel.setPosition( CL_Pointf(stageWidth - RIGHT_MARGIN, stageHeight - BOTTOM_MARGIN)); m_bestOnlineTimeTitleLabel.setAttachPoint(Label::AP_RIGHT | Label::AP_BOTTOM); m_bestOnlineTimeTitleLabel.setPosition( CL_Pointf(stageWidth - RIGHT_MARGIN, stageHeight - BOTTOM_MARGIN - ENTRY_HEIGHT)); } RaceUITimeTrail::~RaceUITimeTrail() { // empty } RaceUITimeTrailImpl::~RaceUITimeTrailImpl() { // empty } void RaceUITimeTrail::load(CL_GraphicContext &p_gc) { m_impl->load(p_gc); } void RaceUITimeTrailImpl::load(CL_GraphicContext &p_gc) { m_bestOnlineTimeLabel.load(p_gc); m_bestOnlineTimeTitleLabel.load(p_gc); } void RaceUITimeTrail::draw(CL_GraphicContext &p_gc) { m_impl->draw(p_gc); } void RaceUITimeTrailImpl::draw(CL_GraphicContext &p_gc) { if (m_logic.hasFirstPlaceRankingEntry()) { const RankingEntry &rankingEntry = m_logic.getFirstPlaceRankingEntry(); Math::Time bestTime(rankingEntry.timeMs); m_bestOnlineTimeLabel.setText( cl_format("%1 by %2", bestTime.raceFormat(), rankingEntry.name)); } else { m_bestOnlineTimeLabel.setText("--:--:---"); } m_bestOnlineTimeTitleLabel.draw(p_gc); m_bestOnlineTimeLabel.draw(p_gc); } }
bsd-3-clause
mogoweb/chromium-crosswalk
chrome/browser/chromeos/extensions/file_manager/private_api_util.cc
7545
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/extensions/file_manager/private_api_util.h" #include "base/files/file_path.h" #include "chrome/browser/chromeos/drive/drive.pb.h" #include "chrome/browser/chromeos/drive/file_errors.h" #include "chrome/browser/chromeos/drive/file_system_interface.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/file_manager/fileapi_util.h" #include "chrome/browser/chromeos/fileapi/file_system_backend.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "ui/shell_dialogs/selected_file_info.h" #include "webkit/browser/fileapi/file_system_context.h" #include "webkit/browser/fileapi/file_system_url.h" using content::BrowserThread; namespace file_manager { namespace util { namespace { // The struct is used for GetSelectedFileInfo(). struct GetSelectedFileInfoParams { GetSelectedFileInfoLocalPathOption local_path_option; GetSelectedFileInfoCallback callback; std::vector<base::FilePath> file_paths; std::vector<ui::SelectedFileInfo> selected_files; }; // Forward declarations of helper functions for GetSelectedFileInfo(). void ContinueGetSelectedFileInfo(Profile* profile, scoped_ptr<GetSelectedFileInfoParams> params, drive::FileError error, const base::FilePath& local_file_path, scoped_ptr<drive::ResourceEntry> entry); // Part of GetSelectedFileInfo(). void GetSelectedFileInfoInternal(Profile* profile, scoped_ptr<GetSelectedFileInfoParams> params) { DCHECK(profile); drive::FileSystemInterface* file_system = drive::util::GetFileSystemByProfile(profile); for (size_t i = params->selected_files.size(); i < params->file_paths.size(); ++i) { const base::FilePath& file_path = params->file_paths[i]; if (!drive::util::IsUnderDriveMountPoint(file_path)) { params->selected_files.push_back( ui::SelectedFileInfo(file_path, base::FilePath())); } else { // |file_system| is NULL if Drive is disabled. if (!file_system) { ContinueGetSelectedFileInfo(profile, params.Pass(), drive::FILE_ERROR_FAILED, base::FilePath(), scoped_ptr<drive::ResourceEntry>()); return; } // When the caller of the select file dialog wants local file paths, // we should retrieve Drive files onto the local cache. switch (params->local_path_option) { case NO_LOCAL_PATH_RESOLUTION: params->selected_files.push_back( ui::SelectedFileInfo(file_path, base::FilePath())); break; case NEED_LOCAL_PATH_FOR_OPENING: file_system->GetFileByPath( drive::util::ExtractDrivePath(file_path), base::Bind(&ContinueGetSelectedFileInfo, profile, base::Passed(&params))); return; // Remaining work is done in ContinueGetSelectedFileInfo. case NEED_LOCAL_PATH_FOR_SAVING: file_system->GetFileByPathForSaving( drive::util::ExtractDrivePath(file_path), base::Bind(&ContinueGetSelectedFileInfo, profile, base::Passed(&params))); return; // Remaining work is done in ContinueGetSelectedFileInfo. } } } params->callback.Run(params->selected_files); } // Part of GetSelectedFileInfo(). void ContinueGetSelectedFileInfo(Profile* profile, scoped_ptr<GetSelectedFileInfoParams> params, drive::FileError error, const base::FilePath& local_file_path, scoped_ptr<drive::ResourceEntry> entry) { DCHECK(profile); const int index = params->selected_files.size(); const base::FilePath& file_path = params->file_paths[index]; base::FilePath local_path; if (error == drive::FILE_ERROR_OK) { local_path = local_file_path; } else { DLOG(ERROR) << "Failed to get " << file_path.value() << " with error code: " << error; } params->selected_files.push_back(ui::SelectedFileInfo(file_path, local_path)); GetSelectedFileInfoInternal(profile, params.Pass()); } } // namespace // Returns string representaion of VolumeType. std::string VolumeTypeToStringEnum(VolumeType type) { switch (type) { case VOLUME_TYPE_GOOGLE_DRIVE: return "drive"; case VOLUME_TYPE_DOWNLOADS_DIRECTORY: return "downloads"; case VOLUME_TYPE_REMOVABLE_DISK_PARTITION: return "removable"; case VOLUME_TYPE_MOUNTED_ARCHIVE_FILE: return "archive"; } NOTREACHED(); return ""; } int32 GetTabId(ExtensionFunctionDispatcher* dispatcher) { if (!dispatcher) { LOG(WARNING) << "No dispatcher"; return 0; } if (!dispatcher->delegate()) { LOG(WARNING) << "No delegate"; return 0; } content::WebContents* web_contents = dispatcher->delegate()->GetAssociatedWebContents(); if (!web_contents) { LOG(WARNING) << "No associated tab contents"; return 0; } return ExtensionTabUtil::GetTabId(web_contents); } base::FilePath GetLocalPathFromURL( content::RenderViewHost* render_view_host, Profile* profile, const GURL& url) { DCHECK(render_view_host); DCHECK(profile); scoped_refptr<fileapi::FileSystemContext> file_system_context = util::GetFileSystemContextForRenderViewHost( profile, render_view_host); const fileapi::FileSystemURL filesystem_url( file_system_context->CrackURL(url)); base::FilePath path; if (!chromeos::FileSystemBackend::CanHandleURL(filesystem_url)) return base::FilePath(); return filesystem_url.path(); } void GetSelectedFileInfo(content::RenderViewHost* render_view_host, Profile* profile, const std::vector<GURL>& file_urls, GetSelectedFileInfoLocalPathOption local_path_option, GetSelectedFileInfoCallback callback) { DCHECK(render_view_host); DCHECK(profile); scoped_ptr<GetSelectedFileInfoParams> params(new GetSelectedFileInfoParams); params->local_path_option = local_path_option; params->callback = callback; for (size_t i = 0; i < file_urls.size(); ++i) { const GURL& file_url = file_urls[i]; const base::FilePath path = GetLocalPathFromURL( render_view_host, profile, file_url); if (!path.empty()) { DVLOG(1) << "Selected: file path: " << path.value(); params->file_paths.push_back(path); } } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&GetSelectedFileInfoInternal, profile, base::Passed(&params))); } } // namespace util } // namespace file_manager
bsd-3-clause
fu-tao/meelier_c2.0
common/libs/Pay.php
2334
<?php namespace Apps\Common\Libs; use Apps\Common\Models\UserOrder; use Apps\Common\Models\UserOrderGoods; use PhalconPlus\Common\Component; use PhalconPlus\Common\Util; use WeiXin\Pay as WeiXinPay; class Pay extends Component { public function weiXinUnifiedOrderByApp($orderId=0, $orderLongId=0) { $orderInfo = null; if($orderId > 0){ $orderInfo = UserOrder::findFirst('order_id = ' . $orderId); } elseif($orderLongId > 0) { $orderInfo = UserOrder::findFirst('order_long_id = ' . $orderLongId); } if(!$orderInfo) { return false; } $orderId = $orderInfo->order_id; $orderLongId = $orderInfo->order_long_id; $totalFee = $orderInfo->order_money; $titleArr = []; // 商品信息 $goods = UserOrderGoods::query() ->columns('service_name name') ->where('order_id = :oid:', ['oid' => $orderId]) ->leftJoin('Apps\Common\Models\BeautyParlorService', 'service_id = goods_id', 'bps') ->execute(); foreach($goods as $d) { $titleArr[] = $d->name; } $title = implode(',', $titleArr); $payConfig = include APP_COMMON_PATH . "base-config/pay.php"; $wxPay = new WeiXinPay($payConfig['weixin']); $info = $wxPay->unifiedOrder($orderLongId, $title, $totalFee, 'APP'); if($info == false) { return false; } return $info['prepayId']; } public function weiXin2AppPay($orderId=0, $orderLongId=0) { $perpayid = $this->weiXinUnifiedOrderByApp($orderId, $orderLongId); if($perpayid == false) { return false; } $payConfig = include APP_COMMON_PATH . "base-config/pay.php"; $weixinConfig = $payConfig['weixin']; $params = [ 'appid' => $weixinConfig['appId'], 'partnerid' => $weixinConfig['mchId'], 'prepayid' => $perpayid, 'package' => 'Sign=WXPay', 'noncestr' => Util::RandStr(10), 'timestamp' => time() ]; $pay = new \WeiXin\Pay($weixinConfig); $params['sign'] = $pay->getSign($params); $params['_package'] = $params['package']; unset($params['package']); return $params; } }
bsd-3-clause
DemocracyClub/UK-Polling-Stations
polling_stations/apps/data_importers/tests/stubs/__init__.py
1386
from django.contrib.gis.geos import Point, GEOSGeometry from data_importers.base_importers import BaseCsvStationsKmlDistrictsImporter from data_importers.management.commands import BaseCsvStationsJsonDistrictsImporter class BaseStubCsvStationsJsonDistrictsImporter(BaseCsvStationsJsonDistrictsImporter): council_id = "AAA" def district_record_to_dict(self, record): properties = record["properties"] return { "council": self.council, "internal_council_id": properties["id"], "name": properties["name"], } def station_record_to_dict(self, record): location = Point(float(record.lng), float(record.lat), srid=self.get_srid()) return { "council": self.council, "internal_council_id": record.internal_council_id, "postcode": record.postcode, "address": record.address, "location": location, } class BaseStubCsvStationsKmlDistrictsImporter(BaseCsvStationsKmlDistrictsImporter): council_id = "AAA" def district_record_to_dict(self, record): geojson = record.geom.geojson poly = self.clean_poly(GEOSGeometry(geojson, srid=self.get_srid("districts"))) return { "internal_council_id": record["Name"].value, "name": record["Name"].value, "area": poly, }
bsd-3-clause
lxp/sulong
projects/com.oracle.truffle.llvm.parser.base/src/com/oracle/truffle/llvm/parser/base/model/metadata/MetadataCompositeType.java
5604
/* * Copyright (c) 2016, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.truffle.llvm.parser.base.model.metadata; import com.oracle.truffle.llvm.parser.base.model.blocks.MetadataBlock; import com.oracle.truffle.llvm.parser.base.model.blocks.MetadataBlock.MetadataReference; import com.oracle.truffle.llvm.parser.base.model.metadata.subtypes.MetadataSubtypeName; import com.oracle.truffle.llvm.parser.base.model.metadata.subtypes.MetadataSubytypeSizeAlignOffset; import com.oracle.truffle.llvm.parser.base.model.visitors.MetadataVisitor; public class MetadataCompositeType implements MetadataBaseNode, MetadataSubtypeName, MetadataSubytypeSizeAlignOffset { private MetadataReference context = MetadataBlock.voidRef; private MetadataReference name = MetadataBlock.voidRef; private MetadataReference file = MetadataBlock.voidRef; private long line; private long size; private long align; private long offset; private long flags; private MetadataReference derivedFrom = MetadataBlock.voidRef; private MetadataReference memberDescriptors = MetadataBlock.voidRef; private long runtimeLanguage; @Override public void accept(MetadataVisitor visitor) { visitor.visit(this); } public MetadataReference getContext() { return context; } public void setContext(MetadataReference context) { this.context = context; } @Override public MetadataReference getName() { return name; } @Override public void setName(MetadataReference name) { this.name = name; } public MetadataReference getFile() { return file; } public void setFile(MetadataReference file) { this.file = file; } public long getLine() { return line; } public void setLine(long line) { this.line = line; } @Override public long getSize() { return size; } @Override public void setSize(long size) { this.size = size; } @Override public long getAlign() { return align; } @Override public void setAlign(long align) { this.align = align; } @Override public long getOffset() { return offset; } @Override public void setOffset(long offset) { this.offset = offset; } public long getFlags() { return flags; } public void setFlags(long flags) { this.flags = flags; } public MetadataReference getDerivedFrom() { return derivedFrom; } public void setDerivedFrom(MetadataReference derivedFrom) { this.derivedFrom = derivedFrom; } public MetadataReference getMemberDescriptors() { return memberDescriptors; } public void setMemberDescriptors(MetadataReference memberDescriptors) { this.memberDescriptors = memberDescriptors; } public long getRuntimeLanguage() { return runtimeLanguage; } public void setRuntimeLanguage(long runtimeLanguage) { this.runtimeLanguage = runtimeLanguage; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("MetadataCompositeType [context="); builder.append(context); builder.append(", name="); builder.append(name); builder.append(", file="); builder.append(file); builder.append(", line="); builder.append(line); builder.append(", size="); builder.append(size); builder.append(", align="); builder.append(align); builder.append(", offset="); builder.append(offset); builder.append(", flags="); builder.append(flags); builder.append(", derivedFrom="); builder.append(derivedFrom); builder.append(", memberDescriptors="); builder.append(memberDescriptors); builder.append(", runtimeLanguage="); builder.append(runtimeLanguage); builder.append("]"); return builder.toString(); } }
bsd-3-clause
QuickBlox/javascript-media-recorder
src/qbAudioRecorderWorker.js
3503
importScripts('https://cdn.rawgit.com/zhuker/lamejs/c318d57d/lame.min.js'); var MP3encoder = new lamejs.Mp3Encoder(1, 48000, 256); function QBAudioRecorderWorker() { var self = this; self.bufferChunks = []; self.bufferSize = 0; self.sampleRate = 0; self.mimeType = ''; onmessage = function(event) { self.onMessage(event.data); }; } QBAudioRecorderWorker.prototype = { postMessage: function(data) { postMessage(data); }, onMessage: function(data) { var self = this; switch (data.cmd) { case 'init': self.mimeType = data.mimeType; self.sampleRate = data.sampleRate; self.bufferChunks = []; self.bufferSize = 0; break; case 'record': self.bufferChunks.push(new Float32Array(data.bufferChunk)); self.bufferSize += data.bufferSize; break; case 'finish': self.postMessage(self.getBlobData()); break; } }, encodeWAV: function(samples) { var buffer = new ArrayBuffer(44 + samples.length * 2), view = new DataView(buffer); _writeString(view, 0, 'RIFF'); view.setUint32(4, 32 + samples.length * 2, true); _writeString(view, 8, 'WAVE'); _writeString(view, 12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true); view.setUint32(24, this.sampleRate, true); view.setUint32(28, this.sampleRate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true); _writeString(view, 36, 'data'); view.setUint32(40, samples.length * 2, true); _floatTo16BitPCM(view, 44, samples); function _floatTo16BitPCM(output, offset, input) { for (var i = 0; i < input.length; i++, offset += 2) { var s = Math.max(-1, Math.min(1, input[i])); output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } } function _writeString(view, offset, string) { for (var i = 0; i < string.length; i++) { view.setUint8(offset + i, string.charCodeAt(i)); } } return view; }, encodeMP3: function(buffer) { var data = new Int16Array(buffer), encodedBuffer = MP3encoder.encodeBuffer(data), flushedBuffer = MP3encoder.flush(), mp3Data = []; mp3Data.push(encodedBuffer); mp3Data.push(new Int8Array(flushedBuffer)); return mp3Data; }, getBlobData: function() { var self = this, result = new Float32Array(self.bufferSize), bufferLength = self.bufferChunks.length, offset = 0, buffer, view, data; for (var i = 0; i < bufferLength; i++) { buffer = self.bufferChunks[i]; result.set(buffer, offset); offset += buffer.length; } view = self.encodeWAV(result); switch (self.mimeType) { case 'audio/wav': data = [view]; break; case 'audio/mp3': data = self.encodeMP3(view.buffer); break; default: throw new Error(); } return data; } }; new QBAudioRecorderWorker();
bsd-3-clause
tingelst/pyversor
src/c3d/vsr_cga3D_op.cpp
25932
// Versor Geometric Algebra Library // Copyright (c) 2017 Lars Tingelstad // Copyright (c) 2010 Pablo Colapinto // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // The views and conclusions contained in the software and documentation are // those of the authors and should not be interpreted as representing official // policies, either expressed or implied, of the FreeBSD Project. #include "versor/space/cga3D_op.h" namespace vsr { namespace cga { /*----------------------------------------------------------------------------- * OP *-----------------------------------------------------------------------------*/ Rot Op::AA(const Vec &s) { Rot r = nga::Gen::ratio(Vec::z, s.unit()); return nga::Gen::aa(r); } Rot Op::AA(const Biv &s) { Rot r = nga::Gen::ratio(Vec::z, s.duale().unit()); return nga::Gen::aa(r); } Rot Op::AA(const Dlp &s) { Rot r = nga::Gen::ratio(Vec::z, Vec(s).unit()); return nga::Gen::aa(r); } Rot Op::AA(const Cir &s) { Biv b = Round::dir(s).copy<Biv>(); Rot r = nga::Gen::ratio(Vec::z, Op::dle(b).unit()); return nga::Gen::aa(r); } Vec Op::Pos(const Dlp &s) { return Flat::loc(s, PAO, true); } Pnt Op::Pos(const Cir &s) { return Round::loc(s); } /*----------------------------------------------------------------------------- * GEN *-----------------------------------------------------------------------------*/ Rot Gen::rot(const Biv &b) { return nga::Gen::rot(b); } Rot Gen::rotor(const Biv &b) { return nga::Gen::rot(b); } Bst Gen::bst(const Pair &p) { return nga::Gen::bst(p); } Bst Gen::boost(const Pair &p) { return nga::Gen::bst(p); } Tsd Gen::dil(const Pnt &p, VSR_PRECISION t) { return nga::Gen::dil(p, t); } Tsd Gen::dilator(const Pnt &p, VSR_PRECISION t) { return nga::Gen::dil(p, t); } Rot Gen::ratio(const Vec &v, const Vec &v2) { return nga::Gen::ratio(v, v2); } Biv Gen::log(const Rot &r) { return nga::Gen::log(r); } /*! Generate a Rotor (i.e quaternion) from spherical coordinates @param[in] theta in xz plane from (1,0,0) in range [0,PI] @param[in] phi in rotated xy plane in range [] */ Rot Gen::rot(double theta, double phi) { Rot rt = Gen::rot(Biv::xz * theta / 2.0); Rot rp = Gen::rot(Biv::xy.sp(rt) * phi / 2.0); return rp * rt; } /*! Generate a rotor from euler angles */ Rot Gen::rot(double y, double p, double r) { Rot yaw = Gen::rot(Biv::xz * y / 2.0); Rot pitch = Gen::rot(Biv::yz.spin(yaw) * p / 2.0); Rot tmp = pitch * yaw; Rot roll = Gen::rot(Biv::xy.spin(tmp) * r / 2.0); return roll * tmp; } /*! Generate a Motor from a Dual Line Axis @param Dual Line Generator (the axis of rotation, including pitch and period) */ Mot Gen::mot(const Dll &dll) { Dll b = dll; Biv B(b[0], b[1], b[2]); // Biv B(dll); Mot::value_t w = B.wt(); VSR_PRECISION c = (sqrt(fabs(w))); VSR_PRECISION sc = sin(c); VSR_PRECISION cc = cos(c); if (ERROR(w, .00000001)) { return Mot(1, 0, 0, 0, b[3], b[4], b[5], 0); // translation only! } B = B.unit(); Vec t(b[3], b[4], b[5]); Vec tv; tv = Op::pj(t, B); Vec tw; tw = Op::rj(t, B); tv *= Math::sinc(c); Vec tt = tw * cc + tv; auto ts = B * tw; // Vec_Biv return Mot(cc, B[0] * sc, B[1] * sc, B[2] * sc, tt[0], tt[1], tt[2], ts[3] * sc); } Mot Gen::motor(const Dll &dll) { return mot(dll); } Mot Gen::outer_exponential(const Dll &B) { double n = sqrt(1.0 + B[0] * B[0] + B[1] * B[1] + B[2] * B[2]); double s = B[0] * B[5] - B[1] * B[4] + B[2] * B[3]; Mot m = Mot(1.0, B[0], B[1], B[2], B[3], B[4], B[5], s) / n; return m; } Mot Gen::cayley(const Dll &B) { Mot B_ = Mot(0.0, B[0], B[1], B[2], B[3], B[4], B[5], 0.0); Mot BB = B_ * B_; Mot Rp = Mot(1.0, B[0], B[1], B[2], B[3], B[4], B[5], 0.0); Mot R0 = Mot(1.0 - BB[0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); Mot R4 = Mot(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, BB[7]); Mot Rn = R0 + R4; Mot Rden = R0 * R0; return (Rp * Rp * Rn * !Rden); } /*! Dual Line Generator from a Motor An implementation of J.Lasenby et al "Applications of Conformal Geometric Algebra in Computer Vision and Graphics" @param Motor m (a concatenation of rotation and translation) */ Dll Gen::log(const Mot &m) { Drv cperp, cpara; Dll rq, q, tq; Biv b; q = m; // extract grade 2 part VSR_PRECISION ac = acos(m[0]); // angle of rotor VSR_PRECISION den = Math::sinc(ac); VSR_PRECISION den2 = ac * ac * den; b = ((Ori(1) <= (q * Inf(1))) / den * -1.0); // bivector part - negative necessary . dll? . . tq = (b * q); // Make motor and extract Grade 2 part if (FERROR(den2)) { // Pure translation // printf("%f, %f, %f\n", ac, den, den2 ); // printf("den2 = 0 in motor log\n"); // cperp = b * -1.0; cperp = q; // b * tq * -1.0;// * -1.0; or q //note this used to be cpara... // (but was inaccurate) } else { cperp = (b * Drt(m[7])) / ((den2) * -1.0); // perpendicular (along line of axis) cpara = (b * tq) / ((den2) * -1.0); // parallel (in plane of rotation) } Drv c = cperp + cpara; rq += b; rq += c; return rq; } /*! Dual Line Generator of Motor That Twists Dual Line a to Dual Line b; */ Dll Gen::log(const Dll &a, const Dll &b, VSR_PRECISION t) { Mot m = b / a; VSR_PRECISION n = m.rnorm(); if (n != 0) { m /= n; } return Gen::log(m) * (t / 2.0); } /*! Generate Motor That Twists Dual Line a to Dual Line b; */ Mot Gen::ratio(const Dll &a, const Dll &b, VSR_PRECISION t) { // Mot m = b/a; VSR_PRECISION n = m.rnorm(); if (n!=0) m /= n; else cout << // "zero mot" << endl; return Gen::mot(log(a, b, t)); // Gen::log( m ) * (t/2.0) ); } /*! Generate Motor That Twists Motor a to motor b by amt t; */ Mot Gen::ratio(const Mot &a, const Mot &b, VSR_PRECISION t) { return Gen::mot(Gen::log(b / a) * t); } /*----------------------------------------------------------------------------- * BOOSTS *-----------------------------------------------------------------------------*/ /*! Generate Simple Boost rotor from ratio of two dual spheres @todo investigate need to negate ratio */ Bst Gen::ratio(const DualSphere &a, const DualSphere &b, bool bFlip) { Bst tbst = (b / a).runit(); // if (tbst[0]<0) if (bFlip) { tbst = -tbst; // true unless the one sphere is inside the other } auto ss = 2 * (1 + tbst[0]); auto n = (ss >= 0 ? sqrt(ss) : -sqrt(-ss)); return FERROR(n) ? Bst() : (tbst + 1) / n; } /*! Generate Simple Boost rotor from ratio of two dual spheres */ Pair Gen::log(const DualSphere &a, const DualSphere &b, VSR_PRECISION t, bool bFlip) { Bst tbst = (b / a).runit(); // if (tbst[0]<0) if (bFlip) { tbst = -tbst; // restrict to positive <R> } return Gen::log(tbst) * -t / 2.0; } /*! atanh2 function for logarithm of general rotors*/ Pair Gen::atanh2(const Pair &p, VSR_PRECISION cs, bool bCW, bool bTwoPI) { VSR_PRECISION norm = 1; auto tp = p.wt(); auto sq = sqrt(fabs(tp)); if (tp > 0) { norm = asinh(sq) / sq; } else if (tp < 0) { if (bCW) { norm = -((bTwoPI ? TWOPI : PI) - atan2(sq, cs)) / sq; // alt direction } else { norm = atan2(sq, cs) / sq; } } return p * norm; } /*! theta of rotation @todo eliminate code duplication redundancy with atanh2 * function */ VSR_PRECISION Gen::theta(const Bst &b, bool bCW, bool bTwoPI) { VSR_PRECISION norm = 1; auto p = Pair(b); auto cs = b[0]; auto tp = p.wt(); auto sq = sqrt(fabs(tp)); if (tp > 0) { norm = asinh(sq) / sq; } else if (tp < 0) { if (bCW) { norm = -((bTwoPI ? TWOPI : PI) - atan2(sq, cs)) / sq; // alt direction } else { norm = atan2(sq, cs) / sq; } } return norm; } /*! Log of a simple rotor (uses atanh2, passes in boolean for direction of * interpolation) */ Pair Gen::log(const Bst &b, bool bCW, bool bTwoPI) { return atanh2(Pair(b), b[0], bCW, bTwoPI); } /*! Generate Conformal Transformation from circle a to circle b uses square root method of Dorst et Valkenburg, 2011 */ Con Gen::ratio(const Circle &a, const Circle &b, bool bFlip, float theta) { Con trot = (b / a).runit(); // planar? // float planarity = (Round::carrier(a).dual().unit() ^ // Round::carrier(b).dual().unit()).wt(); if (bFlip && trot[0] < 0) { // fabs(planarity)<=.000009 ) { trot = -trot; // restrict to positive <R> only if coplanar } auto rotone = trot + 1; VSR_PRECISION sca = 1 + trot[0]; VSR_PRECISION sca2 = sca * sca; Sphere sph(trot); auto sph2 = sph.wt(); // orthogonal circles have infinity of roots if (FERROR(sca2 - sph2)) { // printf("infinity of roots . . . \n"); auto rotneg = (-trot) + 1; Vec vec; auto sizeB = nga::Round::size(b, false); // if circle is orthogonal if (sizeB < 1000 && !FERROR(sizeB)) { vec = Vec(Round::location(a) - Round::location(b)).unit(); // or if one is axis of the other } else { vec = Round::vec(a, -theta).unit(); } auto dls = sph.dual(); auto biv = (Pair(vec.copy<Tnv>()).trs(Round::location(a)) ^ dls) .undual(); //.trs(1,0,0); biv = biv.runit(); auto test = (biv * sph - sph * biv).wt(); if (!FERROR((biv <= biv)[0] + 1) || (!FERROR(test))) { printf("HEY NOW NOT COMMUTING\n"); } auto ret = rotone / 2.0 + (biv * (rotneg / 2.0)); return ret; } auto sca3 = sca2 - sph2; auto sqsca3 = sqrt(sca3); // cout << sca2 << " " << sph2 << " " << sca << " " << sqsca3 << endl; // sca = fabs(sca); //<--* added this fabs in auto v1 = (-sph + sca) / (2 * sca3); auto v2 = (sph + (sca + sqsca3)) / sqrt(sca + sqsca3); return rotone * v1 * v2; } /*! Generate Conformal Transformation from Pair a to Pair b uses square root method of Dorst et Valkenburg, 2011 */ Con Gen::ratio(const Pair &a, const Pair &b, bool bFlip, float theta) { return ratio(a.dual(), b.dual(), bFlip, theta); } /*! Bivector Split Takes a general bivector and splits it into commuting pairs will give sinh(B+-) inverse method for ipar below was given by dorst in personal correspondance */ vector<Pair> Gen::split(const Pair &par) { using SqDeriv = decltype(Sphere() + 1); vector<Pair> res; SqDeriv h2 = par * par; auto hh2 = Sphere(h2).wt(); auto ipar = (-Sphere(h2) + h2[0]) / (h2[0] * h2[0] - hh2); // scalar ||f||^2 auto tmp2 = ((h2 * h2) - (h2 * 2 * h2[0]))[0]; auto ff4 = FERROR(tmp2) ? 0 : pow(-tmp2, 1.0 / 4); auto wt = ff4 * ff4; // cout << par << endl; // cout << h2 << endl; // cout << "SPLIT WEIGHT: " << -tmp2 << " " << h2[0] << " " << wt << endl; if (FERROR(wt)) { if (FERROR(h2[0])) { // cout << h2 << endl; // cout << "no real splitting going on" << endl; //<-- i.e. // interpolation of null point pairs res.push_back(par); // res.push_back(Par()); return res; } else { // cout << "(adding random value and retrying)" << endl; static Pair dp(.001, .006, .004, .002, .008, .006, .003, .007, .001, .001); return split(par + dp); } } auto iha = ipar * wt; auto fplus = iha + 1; auto fminus = -iha + 1; Pair pa = par * fplus * .5; Pair pb = par * fminus * .5; res.push_back(pa); res.push_back(pb); return res; } vector<Pair> Gen::split(const Con &rot) { // 1. Get Exterior Derivative Sphere quad(rot); // grade 4 part auto tmp = quad + (-rot[0]); // scalar + quadvector // half the exterior deriv is sinh(B+/-) auto deriv = Pair(tmp * Pair(rot)) * 2; // quad parts are zero here. // find commuting split of that return split(deriv); } /*! Split Log of General Conformal Rotor */ vector<Pair> Gen::log(const Con &rot) { vector<Pair> res; // 0. Some Terms for later on // R^2 auto sqrot = rot * rot; //<R>2 Pair rot2(sqrot); // 1. Get Exterior Derivative Sphere quad(rot); // grade 4 part auto tmp = quad + (-rot[0]); // scalar + quadvector // half the exterior deriv is sinh(B+/-) auto deriv = Pair(tmp * Pair(rot)) * 2; // quad parts are zero here. // find commuting split of that auto v = split(deriv); // get cosh (see p96 of ref) auto sp = v[0].wt(); //(v[0]<=v[0])[0]; auto sm = v[1].wt(); //(v[1]<=v[1])[0]; VSR_PRECISION coshp = FERROR(sm) ? sqrot[0] : -(rot2 <= !v[1])[0]; VSR_PRECISION coshm = FERROR(sp) ? sqrot[0] : -(rot2 <= !v[0])[0]; // 5.27 on p96 of Dorst ref res.push_back(atanh2(v[0], coshp, false) * -.5); res.push_back(atanh2(v[1], coshm, false) * -.5); return res; } /*! Split Log from a ratio of two Circles */ vector<Pair> Gen::log(const Circle &ca, const Circle &cb, bool bFlip, VSR_PRECISION theta) { return log(ratio(ca, cb, bFlip, theta)); } /*! Split Log from a ratio of two Circles */ vector<Pair> Gen::log(const Pair &ca, const Pair &cb, bool bFlip, VSR_PRECISION theta) { return log(ratio(ca, cb, bFlip, theta)); } /*! General Conformal Transformation from a split log*/ Con Gen::con(const vector<Pair> &log, VSR_PRECISION amt) { Con con(1); for (auto &i : log) { con *= Gen::bst(i * -amt); } return con; } /*! General Conformal Transformation from a split log*/ Con Gen::con(const vector<Pair> &log, VSR_PRECISION amtA, VSR_PRECISION amtB) { Con tmp = Gen::bst(log[0] * -amtA); if (log.size() > 1) { tmp *= Gen::bst(log[1] * -amtB); } return tmp; } /*! General Conformal Transformation from two circles */ Con Gen::con(const Circle &ca, const Circle &cb, VSR_PRECISION amt) { return con(log(ca, cb), amt); } /* General Conformal Transformation from two circles and two weights */ Con Gen::con(const Circle &ca, const Circle &cb, VSR_PRECISION amtA, VSR_PRECISION amtB) { return con(log(ca, cb), amtA, amtB); } /*----------------------------------------------------------------------------- * ROTORS *-----------------------------------------------------------------------------*/ /*! * \brief generate a rotor transformation from a euclidean bivector */ Rotor Gen::xf(const Biv &b) { return Gen::rot(b); } /*! * \brief generate a motor transformation from a dual line */ Motor Gen::xf(const DualLine &dll) { return Gen::mot(dll); } /*! * \brief generate a dilation transformation from a flat point */ Dilator Gen::xf(const FlatPoint &flp) { return Gen::dil(Pnt(flp), flp[3]); } /*! * \brief generate a boost transformation from a point pair */ Bst Gen::xf(const Pair &p) { return Gen::bst(p); } /*----------------------------------------------------------------------------- * PAIRS *-----------------------------------------------------------------------------*/ /// Pair on Sphere in v direction Pair Construct::pair(const DualSphere &s, const Vec &v) { return Round::produce(s, v); } /*! * \brief Point Pair at x,y,z with direction vec (default Y) and radius r * (default 1) */ Pair Construct::pair(VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z, Vec vec, VSR_PRECISION r) { return Round::produce(Round::dls(r * -1, x, y, z), vec); // a ^ b ^ c; } /*----------------------------------------------------------------------------- * POINTS *-----------------------------------------------------------------------------*/ /*! * \brief First point of point pair pp */ Point Construct::pointA(const Pair &pp) { return Round::location(Round::split(pp, true)); } /*! * \brief Second point of point pair pp */ Point Construct::pointB(const Pair &pp) { return Round::location(Round::split(pp, false)); } /// Point on Circle at theta t Point Construct::point(const Circle &c, VSR_PRECISION t) { return Round::point(c, t); } /// Point on Sphere in v direction Point Construct::point(const DualSphere &s, const Vec &v) { return pointA(pair(s, v)).null(); } /// Point from x,y,z Point Construct::point(VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z) { return Round::null(x, y, z); } /// Point from vec Point Construct::point(const Vec &v) { return v.null(); } /// Point on line l closest to p Point Construct::point(const Line &line, const Point &p) { return Round::null(Flat::location(line, p, false)); } /// Point on dualline l closest to p Point Construct::point(const DualLine &dll, const Point &p) { return Round::null(Flat::location(dll, p, true)); } /// Point on plane closest to p Point Construct::point(const Plane &plane, const Point &p) { return Round::null(Flat::location(plane, p, false)); } /// Point on dual plane closest to p Point Construct::point(const DualPlane &dlp, const Point &p) { return Round::null(Flat::location(dlp, p, true)); } /*----------------------------------------------------------------------------- * CIRCLES *-----------------------------------------------------------------------------*/ /*! * \brief Circle at origin in plane of bivector B */ Circle Construct::circle(const Biv &B) { return Round::produce(Round::dls(1, 0, 0, 0), B); // a ^ b ^ c; } /*! * \brief Circle at point p with radius r, facing direction biv */ Circle Construct::circle(const Point &p, VSR_PRECISION r, const Biv &biv) { return Round::produce(Round::dls(p, r * -1), biv); } /// Circle at origin with normal v and radius r (default r=1.0) Circle Construct::circle(const Vec &v, VSR_PRECISION r) { return Round::produce(Round::dls(r * -1, 0, 0, 0), Op::dle(v)); // a ^ b ^ c; } /// Circle at x,y,z facing in biv direction Circle Construct::circle(VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z, Biv biv, VSR_PRECISION r) { return Round::produce(Round::dls(r * -1, x, y, z), biv); // a ^ b ^ c; } /*----------------------------------------------------------------------------- * HYPERBOLIC AND SPHERICAL LINES *-----------------------------------------------------------------------------*/ /// Hyperbolic line through two points Circle Construct::hline(const Point &a, const Point &b) { return a ^ b ^ EP; } /// Spherical line through two points Circle Construct::sline(const Point &a, const Point &b) { return a ^ b ^ EM; } /*----------------------------------------------------------------------------- * SPHERES *-----------------------------------------------------------------------------*/ /// Sphere at x,y,z with radius r (default r=1.0) DualSphere Construct::sphere(VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z, VSR_PRECISION r) { return Round::dls(r, x, y, z); } /// Sphere at point p with radius r (default r=1.0) DualSphere Construct::sphere(const Point &p, VSR_PRECISION r) { return Round::dls(p, r); } /*----------------------------------------------------------------------------- * PLANES *-----------------------------------------------------------------------------*/ /// Dual plane with normal and distance from center DualPlane Construct::plane(VSR_PRECISION a, VSR_PRECISION b, VSR_PRECISION c, VSR_PRECISION d) { return Dlp(a, b, c, d); } /// Dual plane from vec and distance from center DualPlane Construct::plane(const Vec &v, VSR_PRECISION d) { return v + Inf(d); } /// Direct plane through three points Plane Construct::plane(const Pnt &a, const Pnt &b, const Pnt &c) { return a ^ b ^ c ^ Inf(1); } /*----------------------------------------------------------------------------- * LINES *-----------------------------------------------------------------------------*/ /*! * \brief DualLine axis of circle c */ DualLine Construct::axis(const Cir &c) { return (Inf(-1) <= c).runit(); } /// Line from two Vecs Line Construct::line(const Vec &a, const Vec &b) { return point(a[0], a[1], a[2]) ^ Vec(b[0], b[1], b[2]) ^ Inf(1); } /// Direct line through origin Line Construct::line(VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z) { return Ori(1) ^ Vec(x, y, z) ^ Inf(1); } /// Direct line through origin Line Construct::dualLine(VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z) { return line(x, y, z).dual(); } /// Direct line through two points Line Construct::line(const Point &a, const Point &b) { return a ^ b ^ Inf(1); } /// Direct line through point a in direction b Line Construct::line(const Point &a, const Vec &b) { return a ^ b ^ Inf(1); } /// Squared Distance between a line and a point VSR_PRECISION Construct::distance(const Lin &lin, const Pnt &pnt) { return (pnt <= lin.dual())[0] * -2.0; } /* Line line(VSR_PRECISION x, VSR_PRECISION y, VSR_PRECISION z){ */ /* return point(a[0], a[1], a[2]) ^ Vec(b[0], b[1], b[2]) ^ Inf(1); */ /* } */ #pragma mark COINCIDENCE_FUNCTIONS /// circle intersection of dual spheres Circle Construct::meet(const Dls &s, const Dls &d) { return (s ^ d).dual(); } /// circle intersection of dual sphere and direct plane Circle Construct::meet(const Dls &s, const Dlp &d) { return (s ^ d).dual(); } /// circle intersection of dual spehre and direct plane Circle Construct::meet(const Dls &s, const Pln &d) { return (s ^ d.dual()).dual(); } // circle intersection of direct sphere and dual plane Circle Construct::meet(const Sphere &s, const DualPlane &d) { return (s.dual() ^ d).dual(); } // circle intersection of direct sphere and direct plane Circle Construct::meet(const Sphere &s, const Plane &d) { return (s.dual() ^ d.dual()).dual(); } // normalized and nulled point intersection of line and dual plane Point Construct::meet(const Line &lin, const DualPlane &dlp) { Flp flp = ((lin).dual() ^ dlp).dual(); return (flp / flp[3]).null(); } // normalized and nulled point intersection of dualline and dual plane Point Construct::meet(const Dll &dll, const DualPlane &dlp) { auto flp = (dll ^ dlp).dual(); return flp.null(); } // Point intersection of two lines Point Construct::meet(const Line &la, const Line &lb) { Line r = la.reflect(lb); Line r2 = (la - r.unit()).unit(); Point pori = Flat::loc(r2, Ori(1), false); Point tp = pori.re(lb); return (((tp / tp[3]) + pori) / 2.0).null(); } /* //test for origin */ /* auto t = Ori(1) ^ la; Sca(t.wt()).vprint(); */ /* (t.dual() ^ lb.dual() ).dual().vprint(); */ /* if (t.wt() != 0 ) { */ /* return ( t.dual() ^ lb.dual() ).dual(); */ /* } else { */ /* auto t2 = (Ori(1) ^ lb ); */ /* if ( t2.wt() != 0 ) return ( la.dual() ^ t2.dual() ).dual(); */ /* else return Flp(); */ /* } */ //} // point pair intersection of circle and Dual plane Par Construct::meet(const Cir &cir, const Dlp &dlp) { return ((cir).dual() ^ dlp).dual(); } // point pair intersection of circle and Dual sphere Par Construct::meet(const Cir &cir, const Dls &s) { return ((cir).dual() ^ s).dual(); } #pragma mark HIT_TESTS /*! * \brief hit tests between point and pair (treats pair as an "edge") */ bool Construct::hit(const Point &pnt, const Pair &par) { // if inside surround < 0 if ((pnt <= Round::sur(par))[0] < 0) { if ((pnt ^ par ^ Inf(1)).wt() == 0.0) { return true; } } return false; } /*! * \brief hit tests between point and circle (treats circle as "disc") */ bool Construct::hit(const Point &p, const Circle &cir) { if ((p <= Round::sur(cir))[0] > 0) { if (fabs((p ^ Round::car(cir)).wt()) < .00001) { return true; } } return false; } double Construct::squaredDistance(const Point &a, const Point &b) { return Round::sqd(a, b); } // #pragma mark HYPERBOLIC_FUNCTIONS /*----------------------------------------------------------------------------- * hyperbolic functions (see alan cortzen's document on this) *-----------------------------------------------------------------------------*/ /*! * \brief hyperbolic normalization of a conformal point */ Point Construct::hnorm(const Pnt &p) { return -(p / (EP <= p)); } /*! * \brief hyperbolic distance between two conformal points */ double Construct::hdist(const Pnt &pa, const Pnt &pb) { return acosh(1 - (hnorm(pa) <= hnorm(pb))[0]); } /*! * \brief hyperbolic translation transformation generator between two * conformal points */ Pair Construct::hgen(const Pnt &pa, const Pnt &pb, double amt) { double dist = hdist(pa, pb); //<-- h distance auto hline = pa ^ pb ^ EP; //<-- h line (circle) auto par_versor = (EP <= hline).runit(); //<-- h trans generator (pair) // par_versor /= par_versor.rnorm(); //<-- normalized ... return par_versor * dist * amt * .5; //<-- and ready to be applied } /*! * \brief hyperbolic spin transformation from pa to pb by amt (0,1) */ Point Construct::hspin(const Pnt &pa, const Pnt &pb, double amt) { return Round::loc(pa.boost(hgen(pa, pb, amt))); // versor * dist * amt * .5) ); } } // namespace cga } // namespace vsr
bsd-3-clause
VampireMe/admin-9939-com
librarys/controllers/wapjb/WapController.php
962
<?php namespace librarys\controllers\wapjb; use librarys\controllers\BaseController; /** * Site controller */ class WapController extends BaseController { public function init(){ $this->fillSuffix(); parent::init(); $this->initVariables(); } public function initVariables(){ $this->setLayout(); } private function fillSuffix(){ header('Cache-Control:max-age=3600'); $uristr = $_SERVER['REQUEST_URI']; $str_params =''; if ($pos = strpos($uristr, '?')) { $str_params=substr($uristr, $pos); $uristr = substr($uristr, 0, $pos); } if(($last_char = substr($uristr, -1) )!='/' && (stripos($uristr,'.shtml')===false)){ $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$uristr.'/'; $redirect_url.= $str_params; header("Location:$redirect_url", true, 301); exit; } } }
bsd-3-clause
stevschmid/nsearch
libnsearch/test/Database/GlobalSearchTest.cpp
5356
#include <catch.hpp> #include <nsearch/Alphabet/DNA.h> #include <nsearch/Database.h> #include <nsearch/Database/GlobalSearch.h> #include <nsearch/FASTA/Reader.h> #include <sstream> #include <string> #include <vector> const char DatabaseContents[] = R"( >RF00807;mir-314;AFFE01007792.1/82767-82854 42026:Drosophila bipectinata UCGUAACUUGUGUGGCUUCGAAUGUACCUAGUUGAGGAAAAAUCAGUUUG GAUUUUGUUACCUCUGGUAUUCGAGCCAAUAAGUUCGG >RF00807;mir-314;AAFS01000446.1/64778-64866 46245:Drosophila pseudoobscura pseudoobscura UCGUAACUUGUGUGGCUUCGAAUGUACCUAGUUGAGGAAAACUCCGAAAU GGAUUUUGUUACCUCUGGUAUUCGAGCCAAUAAGUUCGG >RF00807;mir-314;AANI01017486.1/342740-342830 7244:Drosophila virilis UCGUAACUUGUGUGGCUUGAAUGUACCUGGUUGAGGAACGAAUUCAACGU UUGGAUUUUGUUGCCUUUGGUAUUCGAGCCAAUAAGUUCGG >RF00807;mir-314;AAPU01011627.1/156896-156990 7230:Drosophila mojavensis UCGUAACUUGUGUGGCUUCGAAUGUACCUCGUCGAGCGAAAAGCGAAUUC AUUGUUGGAUUUUGUUGCUCUUGGUAUUCGAGCCAAUAAGUUCGG >RF00752;mir-14;AAWU01029067.1/5309-5242 7176:Culex quinquefasciatus (southern house mosquito) UGUGGGAGCGAGAUUAAGGCUUGCUGGUUUCACGUUCGAGUAAAGUCAGU CUUUUUCUCUCUCCUAUU >RF00752;mir-14;AAGE02012112.1/774-706 7159:Aedes aegypti (yellow fever mosquito) UGUGGGAGCGAGAUUAAGGCUUGCUGGUCAUUUAUUACACUCGAAGUCAG UCUUUUUCUCUCUCCUAUU >RF00752;mir-14;AANI01011011.1/11101-11163 7244:Drosophila virilis UGUGGGAGCGAGACGGGGACUCACUGUGCUUUUUAUAUAGUCAGUCUUUU UCUCUCUCCUAUA >RF00715;mir-383;AAMC01036319.1/13960-13888 8364:Xenopus (Silurana) tropicalis (western clawed frog) CUCCUCAGAUCAGAAGGUGAUUGUGGCUUUUAGUAGAUAUUAAGCAGCCA CAGCACUGCCUGGUCAGAAAGAG >RF00715;mir-383;AAQR03137803.1/1757-1829 30611:Otolemur garnettii (small-eared galago) CUCCUCAGAUCAGAAGGUGAUUGUGGCUUUGGGUGCAUGGUUAUAAGCCA CAGCACUGCCUGGUCAGAAAGAG >RF00715;mir-383;AFEY01400405.1/5982-5910 9305:Sarcophilus harrisii (Tasmanian devil) CUCCUCAGAUCAGAAGGUGAUUGUGGCUUUGGGCAGACAUGGAACAGCCA CAUCACUGGCUGGUCAGAAAGAG >RF01157;sn1185;DQ789405.1/1-66 6238:Caenorhabditis briggsae AUCGGUGAUGUGAUAUCCAGUUCUGCUACUGAAGCGUUGUGAAGAUUAAC UUUCCCCGUCUGAGAU >RF01157;sn1185;AEHI01092347.1/1008-1073 860376:Caenorhabditis angaria ACUGAUGAUGUUAACUCCAGUUCUGCUACUGAAUGAAUGUGACGAUAUUC UUUCCCCGACUGAGGU >RF01157;sn1185;ABLE03029241.1/4849-4913 281687:Caenorhabditis japonica AUUGAUGAUGUUCAUCCAGUUCUGCUACUGAAUCAGUGUGAAGAUAUUCU UUCCCCGACUGAGAU >RF01885;HSR-omega_1;AFPP01029324.1/15839-15914 1041015:Drosophila rhopaloa ACCACCUAACCAAGCAAUAUGUAUUUCUUUCUCUAAACUUUAUAGUUGGG CGUUGAAAGUUGAUAUCGAUCCGUGA >RF01885;HSR-omega_1;AFFH01007186.1/256640-256716 30033:Drosophila kikkawai AUCACUUAACCAGCAAUAUGUAUUUCUUUCUCUAAACUUUAUAGUUGGGC GUUGAAAGUUGAUACGCGAACGUGAAA >RF01885;HSR-omega_1;AAPU01011178.1/205842-205767 7230:Drosophila mojavensis ACACGUUAACCAAGCAUUAUGUAUUUCUUUCUCUAAACUUUAUAGUUGGG CGUUGAAAGUUGAUACGCGAUCGAAC )"; TEST_CASE( "Global Search" ) { Database< DNA > db( 8 ); SearchParams< DNA > sp; sp.maxAccepts = 1; sp.maxRejects = 8; sp.minIdentity = 0.75f; std::istringstream dbFile( DatabaseContents ); FASTA::Reader< DNA> dbReader( dbFile ); SequenceList< DNA > sequences; while( !dbReader.EndOfFile() ) { Sequence< DNA > seq; dbReader >> seq; sequences.push_back( std::move( seq ) ); } db.Initialize( sequences ); Sequence< DNA > query( "RF00807;mir-314;AAPT01020574.1/773332-773257 7222:Drosophila grimshawi", "UCGUAACUUGUGUGGCUUCGAAUGUACCUGGCUAAGGAAAGUUGGAUUUCCUAGGUAUUCGAGCCAAUAAGUUC" "GG" ); SECTION( "Default" ) { GlobalSearch< DNA > gs( db, sp ); auto hits = gs.Query( query ); REQUIRE( hits.size() == 1 ); REQUIRE( hits[ 0 ].target.identifier == "RF00807;mir-314;AFFE01007792.1/82767-82854 42026:Drosophila bipectinata" ); } SECTION( "Min Identity" ) { sp.minIdentity = 0.9f; GlobalSearch< DNA > gs( db, sp ); auto hits = gs.Query( query ); REQUIRE( hits.size() == 0 ); } SECTION( "Max Accepts" ) { sp.minIdentity = 0.6f; sp.maxAccepts = 2; GlobalSearch< DNA > gs( db, sp ); auto hits = gs.Query( query ); REQUIRE( hits.size() == 2 ); std::vector< std::string > ids; for( auto &hit : hits ) { ids.push_back( hit.target.identifier ); } REQUIRE( std::find( ids.begin(), ids.end(), "RF00807;mir-314;AAPU01011627.1/156896-156990 7230:Drosophila mojavensis" ) != ids.end() ); REQUIRE( std::find( ids.begin(), ids.end(), "RF00807;mir-314;AFFE01007792.1/82767-82854 42026:Drosophila bipectinata" ) != ids.end() ); } SECTION( "Strand support" ) { // our read goes in the "other" direction query = query.Reverse().Complement(); SECTION( "Looking on plus strand (default)" ) { // no match, default is plus GlobalSearch< DNA > gs( db, sp ); auto hits = gs.Query( query ); REQUIRE( hits.size() == 0 ); } SECTION( "Looking on minus strand" ) { // match, we are looking on the minus strand now sp.strand = DNA::Strand::Minus; GlobalSearch< DNA > gs( db, sp ); auto hits = gs.Query( query ); REQUIRE( hits.size() == 1 ); REQUIRE( hits[ 0 ].strand == DNA::Strand::Minus ); } SECTION( "Looking on both strands" ) { sp.strand = DNA::Strand::Both; GlobalSearch< DNA > gs( db, sp ); auto hits = gs.Query( query ); REQUIRE( hits.size() == 1 ); REQUIRE( hits[ 0 ].strand == DNA::Strand::Minus ); } } }
bsd-3-clause
ric2b/Vivaldi-browser
chromium/media/capture/video/video_frame_receiver_on_task_runner.cc
2728
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/capture/video/video_frame_receiver_on_task_runner.h" #include <utility> #include "base/bind.h" #include "base/single_thread_task_runner.h" namespace media { VideoFrameReceiverOnTaskRunner::VideoFrameReceiverOnTaskRunner( const base::WeakPtr<VideoFrameReceiver>& receiver, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : receiver_(receiver), task_runner_(std::move(task_runner)) {} VideoFrameReceiverOnTaskRunner::~VideoFrameReceiverOnTaskRunner() = default; void VideoFrameReceiverOnTaskRunner::OnNewBuffer( int buffer_id, media::mojom::VideoBufferHandlePtr buffer_handle) { task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnNewBuffer, receiver_, buffer_id, std::move(buffer_handle))); } void VideoFrameReceiverOnTaskRunner::OnFrameReadyInBuffer( ReadyFrameInBuffer frame, std::vector<ReadyFrameInBuffer> scaled_frames) { task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnFrameReadyInBuffer, receiver_, std::move(frame), std::move(scaled_frames))); } void VideoFrameReceiverOnTaskRunner::OnBufferRetired(int buffer_id) { task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnBufferRetired, receiver_, buffer_id)); } void VideoFrameReceiverOnTaskRunner::OnError(VideoCaptureError error) { task_runner_->PostTask(FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnError, receiver_, error)); } void VideoFrameReceiverOnTaskRunner::OnFrameDropped( VideoCaptureFrameDropReason reason) { task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnFrameDropped, receiver_, reason)); } void VideoFrameReceiverOnTaskRunner::OnLog(const std::string& message) { task_runner_->PostTask(FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnLog, receiver_, message)); } void VideoFrameReceiverOnTaskRunner::OnStarted() { task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnStarted, receiver_)); } void VideoFrameReceiverOnTaskRunner::OnStartedUsingGpuDecode() { task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnStartedUsingGpuDecode, receiver_)); } void VideoFrameReceiverOnTaskRunner::OnStopped() { task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameReceiver::OnStopped, receiver_)); } } // namespace media
bsd-3-clause
SergeySlonimsky/zebra_truck
controllers/SiteController.php
1189
<?php namespace app\controllers; use app\models\Order; use app\modules\dashboard\models\User; use Yii; use yii\web\Controller; class SiteController extends Controller { public function actionIndex() { $order = new Order(); if ($order->load(Yii::$app->request->post())) { if ($order->save()) { Yii::$app->session->setFlash('success', 'Your order successfully send. Our manager will contact you soon'); $order = new Order(); } } return $this->render('index', compact('order')); } public function actionAbout() { $admin = new User(); $admin->username = 'admin'; $admin->setPassword('123456'); $admin->status = 20; $admin->generateAuthKey(); $admin->email = 'admin@mail.com'; $admin->save(); return $this->render('about'); } public function actionContact() { return $this->render('contact'); } public function actionLogin() { return $this->redirect(['/dashboard/default/login']); } public function actionError() { return $this->render('error'); } }
bsd-3-clause
ric2b/Vivaldi-browser
chromium/chrome/browser/ui/webui/settings/chromeos/search/per_session_settings_user_action_tracker.cc
4811
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/settings/chromeos/search/per_session_settings_user_action_tracker.h" #include "base/metrics/histogram_functions.h" namespace chromeos { namespace settings { namespace { // The maximum amount of time that the settings window can be blurred to be // considered short enough for the "first change" metric. constexpr base::TimeDelta kShortBlurTimeLimit = base::TimeDelta::FromMinutes(1); // The minimum amount of time between a setting change and a subsequent setting // change. If two changes occur les than this amount of time from each other, // they are ignored by metrics. See https://crbug.com/1073714 for details. constexpr base::TimeDelta kMinSubsequentChange = base::TimeDelta::FromMilliseconds(200); // Min/max values for the duration metrics. Note that these values are tied to // the metrics defined below; if these ever change, the metric names must also // be updated. constexpr base::TimeDelta kMinDurationMetric = base::TimeDelta::FromMilliseconds(100); constexpr base::TimeDelta kMaxDurationMetric = base::TimeDelta::FromMinutes(10); void LogDurationMetric(const char* metric_name, base::TimeDelta duration) { base::UmaHistogramCustomTimes(metric_name, duration, kMinDurationMetric, kMaxDurationMetric, /*buckets=*/50); } } // namespace PerSessionSettingsUserActionTracker::PerSessionSettingsUserActionTracker() : metric_start_time_(base::TimeTicks::Now()) {} PerSessionSettingsUserActionTracker::~PerSessionSettingsUserActionTracker() = default; void PerSessionSettingsUserActionTracker::RecordPageFocus() { if (last_blur_timestamp_.is_null()) return; // Log the duration of being blurred. const base::TimeDelta blurred_duration = base::TimeTicks::Now() - last_blur_timestamp_; LogDurationMetric("ChromeOS.Settings.BlurredWindowDuration", blurred_duration); // If the window was blurred for more than |kShortBlurTimeLimit|, // the user was away from the window for long enough that we consider the // user coming back to the window a new session for the purpose of metrics. if (blurred_duration >= kShortBlurTimeLimit) { ResetMetricsCountersAndTimestamp(); last_record_setting_changed_timestamp_ = base::TimeTicks(); } } void PerSessionSettingsUserActionTracker::RecordPageBlur() { last_blur_timestamp_ = base::TimeTicks::Now(); } void PerSessionSettingsUserActionTracker::RecordClick() { ++num_clicks_since_start_time_; } void PerSessionSettingsUserActionTracker::RecordNavigation() { ++num_navigations_since_start_time_; } void PerSessionSettingsUserActionTracker::RecordSearch() { ++num_searches_since_start_time_; } void PerSessionSettingsUserActionTracker::RecordSettingChange() { base::TimeTicks now = base::TimeTicks::Now(); if (!last_record_setting_changed_timestamp_.is_null()) { // If it has been less than |kMinSubsequentChange| since the last recorded // setting change, this change is discarded. See https://crbug.com/1073714 // for details. if (now - last_record_setting_changed_timestamp_ < kMinSubsequentChange) return; base::UmaHistogramCounts1000( "ChromeOS.Settings.NumClicksUntilChange.SubsequentChange", num_clicks_since_start_time_); base::UmaHistogramCounts1000( "ChromeOS.Settings.NumNavigationsUntilChange.SubsequentChange", num_navigations_since_start_time_); base::UmaHistogramCounts1000( "ChromeOS.Settings.NumSearchesUntilChange.SubsequentChange", num_searches_since_start_time_); LogDurationMetric("ChromeOS.Settings.TimeUntilChange.SubsequentChange", now - metric_start_time_); } else { base::UmaHistogramCounts1000( "ChromeOS.Settings.NumClicksUntilChange.FirstChange", num_clicks_since_start_time_); base::UmaHistogramCounts1000( "ChromeOS.Settings.NumNavigationsUntilChange.FirstChange", num_navigations_since_start_time_); base::UmaHistogramCounts1000( "ChromeOS.Settings.NumSearchesUntilChange.FirstChange", num_searches_since_start_time_); LogDurationMetric("ChromeOS.Settings.TimeUntilChange.FirstChange", now - metric_start_time_); } ResetMetricsCountersAndTimestamp(); last_record_setting_changed_timestamp_ = now; } void PerSessionSettingsUserActionTracker::ResetMetricsCountersAndTimestamp() { metric_start_time_ = base::TimeTicks::Now(); num_clicks_since_start_time_ = 0u; num_navigations_since_start_time_ = 0u; num_searches_since_start_time_ = 0u; } } // namespace settings } // namespace chromeos
bsd-3-clause
rbjarnason/active-citizen
exporters/dataset_tools.js
1898
var removeDiacritics = require('diacritics').remove; var shuffleArray = function (array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }; var clean = function (string) { string = string.replace(/(\r\n|\n|\r)/gm," "); string = string.replace(',',' '); string = string.replace('\n',' '); string = string.replace(/\'/g,' '); string = string.replace(/\,/g,' '); string = string.replace(/\(/g,' '); string = string.replace(/\=/g,' '); string = string.replace(/\)/g,' '); string = string.replace(/\-/g,' '); string = string.replace(/\./g,' '); string = string.replace(/['"]+/g, ''); string = string.replace(/<a\b[^>]*>(.*?)<\/a>/i," "); string = removeDiacritics(string); string = string.replace(/[^A-Za-z0-9(),!?\'\`]/, ' '); string = string.replace(/[^\x00-\x7F]/g, " "); string = string.replace(/\s+/g,' ').trim(); return string; }; var replaceBetterReykjavikCategoryId = function (id) { if ([1,2,19,24,18,16,20,23,17,21,13,25,22,14].indexOf(id) > -1) { return 2; } else { switch(id) { case 4: return 1; break; case 3: return 3; break; case 15: return 4; break; case 11: return 5; break; case 8: return 6; break; case 9: return 7; break; case 10: return 8; break; case 12: return 9; break; case 5: return 10; break; case 26: return 11; break; case 6: return 12; break; case 7: return 13; break; } } }; module.exports = { replaceBetterReykjavikCategoryId: replaceBetterReykjavikCategoryId, clean: clean, shuffleArray: shuffleArray };
bsd-3-clause
CartoDB/camshaft
lib/filter/grouped-rank.js
1017
'use strict'; var dot = require('dot'); dot.templateSettings.strip = false; var Range = require('./range'); var groupRankQueryTemplate = dot.template([ 'SELECT *,', ' rank() OVER (', ' PARTITION BY {{=it._groupColumn}}', ' ORDER BY {{=it._orderColumn}} {{=it._orderDirection}}', ' ) AS rank', 'FROM ({{=it._query}}) _cdb_filter_grouped_rank' ].join('\n')); function GroupedRank (column, filterParams) { this.column = column.name; this.rank = filterParams.rank; this.group = filterParams.group; this.rangeFilter = new Range({ name: 'rank' }, { min: filterParams.min, max: filterParams.max }); } module.exports = GroupedRank; GroupedRank.prototype.sql = function (rawSql) { var groupRankQuery = groupRankQueryTemplate({ _query: rawSql, _orderColumn: this.column, _groupColumn: this.group, _orderDirection: (this.rank === 'bottom' ? 'ASC' : 'DESC') }); return this.rangeFilter.sql(groupRankQuery); };
bsd-3-clause
ShareStuffHere/Adventure-Town
Town/Building.java
46
package town; public interface Building { }
bsd-3-clause
markfinal/BuildAMation
tests/ProceduralHeaderTest1/bam/Scripts/ProceduralHeaderTest1.cs
2841
#region License // Copyright (c) 2010-2019, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace ProceduralHeaderTest1 { sealed class TestApp : C.ConsoleApplication { protected override void Init() { base.Init(); var source = this.CreateCSourceCollection("$(packagedir)/source/*.c"); var genHeader = Bam.Core.Graph.Instance.FindReferencedModule<GenHeader>(); source.DependsOn(genHeader); source.UsePublicPatches(genHeader); } } class GenHeader : C.ProceduralHeaderFile { protected override Bam.Core.TokenizedString OutputPath { get { return this.CreateTokenizedString("$(packagebuilddir)/$(moduleoutputdir)/genheader.h"); } } protected override string Contents { get { var contents = new System.Text.StringBuilder(); contents.AppendLine("#define GENERATED_HEADER"); contents.AppendLine("char *function()"); contents.AppendLine("{"); contents.AppendLine("\treturn \"Hello world\";"); contents.AppendLine("}"); return contents.ToString(); } } } }
bsd-3-clause
votinginfoproject/Metis
public/assets/js/app/controllers/feedElectoralDistrictController.js
2866
'use strict'; /* * Feed Electoral District Controller * */ function FeedElectoralDistrictCtrl($scope, $rootScope, $feedDataPaths, $feedsService, $routeParams, $appProperties, $location, $filter, ngTableParams) { // get the vipfeed param from the route var feedid = $scope.vipfeed = $routeParams.vipfeed; if ($routeParams['locality']) { $scope.localityid = $routeParams.locality; } if ($routeParams['precinct']) { $scope.precinctid = $routeParams.precinct; } if ($routeParams['contest']) { var rootPath = '/db/v3/feeds/' + feedid + '/contests/' + $routeParams.contest + '/electoral-district'; $feedDataPaths.getResponse({ path: '/db/v3/feeds/' + feedid + '/contests/' + $routeParams['contest'], scope: $rootScope, key: 'feedContest', errorMessage: 'Cound not retrieve Contests.'}, function(result) { $rootScope.feedContest = result[0]; }); } if ($routeParams['electoraldistrict']) { var rootPath = '/db/v3/feeds/' + feedid + '/electoral-districts/' + $routeParams.electoraldistrict; $feedDataPaths.getResponse({ path: rootPath + '/contest', scope: $rootScope, key: 'feedContest', errorMessage: 'Cound not retrieve Contests.'}, function(result) { $rootScope.feedContest = result[0]; }); } $feedDataPaths.getResponse({ path: rootPath, scope: $rootScope, key: 'feedElectoralDistrict', errorMessage: 'Cound not retrieve Electoral District Data.'}, function(result) { $rootScope.feedElectoralDistrict = result[0]; }); $feedDataPaths.getResponse({ path: rootPath + '/precincts', scope: $rootScope, key: 'feedPrecincts', errorMessage: 'Cound not retrieve Precinct Data.'}, function(result) { $scope.precinctsTable = $rootScope.createTableParams(ngTableParams, $filter, result, $appProperties.highPagination, { id: 'asc' }); }); $feedDataPaths.getResponse({ path: rootPath + '/precinct-splits', scope: $rootScope, key: 'feedPrecinctSplits', errorMessage: 'Cound not retrieve Precinct Split Data.'}, function(result) { $scope.precinctSplitsTable = $rootScope.createTableParams(ngTableParams, $filter, result, $appProperties.highPagination, { id: 'asc' }); }); // initialize page header variables $rootScope.setPageHeader("Electoral District", $rootScope.getBreadCrumbs(), "feeds", "", null); }
bsd-3-clause
ZoltanTheHun/SkyHussars
src/main/java/skyhussars/engine/plane/PlaneGeometry.java
5239
/* * Copyright (c) 2016, ZoltanTheHun * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package skyhussars.engine.plane; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import skyhussars.engine.plane.instruments.AnalogueAirspeedIndicator; public class PlaneGeometry { private final static Logger logger = LoggerFactory.getLogger(PlaneGeometry.class); private final Node root; private final Node cockpitNode; private final Node outside; private final Node soundNode; private Optional<Node> airspeedIndicatorNode; private final AnalogueAirspeedIndicator airspeedIndicator; public static enum GeometryMode { COCKPIT_MODE, MODEL_MODE } public PlaneGeometry(AnalogueAirspeedIndicator airspeedIndicator) { root = new Node(); cockpitNode = new Node(); // rootNode.attachChild(cockpitNode); outside = new Node(); soundNode = new Node(); root.attachChild(cockpitNode); root.attachChild(outside); root.attachChild(soundNode); this.airspeedIndicator = airspeedIndicator; } public PlaneGeometry attachSpatialToCockpitNode(Spatial cockpit) { if (cockpit instanceof Geometry) { Geometry geom = (Geometry) cockpit; logger.info("Geom is:" + geom.getName()); } if (cockpit instanceof Node) { Node geom = (Node) cockpit; logger.info("Node is:" + geom.getName()); if(geom.getChildren() != null) { Optional<Spatial> spd = geom.getChildren().stream().filter(s -> "spd".equals(s.getName())).findFirst(); airspeedIndicatorNode = spd.map(s -> { List<Spatial> a = ((Node) s).getChildren(); Optional<Spatial> b = a.stream().filter(t -> "indicator".equals(t.getName())).findFirst(); return b; }).orElse(Optional.empty()).map(i -> (Node) i); } } if (cockpit instanceof Geometry) { Geometry geom = (Geometry) cockpit; System.out.println(geom.getName()); } cockpitNode.attachChild(cockpit); return this; } public void update(){ airspeedIndicatorNode.map(n -> { n.setLocalRotation(airspeedIndicator.rotation()); return n; }); } public PlaneGeometry attachSpatialToRootNode(Spatial spatial) { soundNode.attachChild(spatial); return this; } public PlaneGeometry attachSpatialToModelNode(Spatial model) { outside.attachChild(model); return this; } public synchronized void switchTo(GeometryMode geometryMode) { switch (geometryMode) { case COCKPIT_MODE: outside.setCullHint(Node.CullHint.Always); cockpitNode.setCullHint(Node.CullHint.Inherit); break; case MODEL_MODE: cockpitNode.setCullHint(Node.CullHint.Always); outside.setCullHint(Node.CullHint.Inherit); break; } } public Node root() {return root;} public Node outside() {return outside;} public Quaternion rotation(){return root.getLocalRotation();} public PlaneGeometry rotation(Quaternion rotation){root.setLocalRotation(rotation); return this;} public PlaneGeometry translation(Vector3f translation){root.setLocalTranslation(translation); return this;} public Vector3f translation(){return root.getLocalTranslation();} public Vector3f forwardNormal(){return root.getLocalRotation().mult(Vector3f.UNIT_Z).normalize();} public Vector3f upNormal(){return root.getLocalRotation().mult(Vector3f.UNIT_Y).normalize();} }
bsd-3-clause
0atman/flask-admin
flask_admin/model/filters.py
3836
from flask.ext.admin.babel import lazy_gettext class BaseFilter(object): """ Base filter class. """ def __init__(self, name, options=None, data_type=None): """ Constructor. :param name: Displayed name :param options: List of fixed options. If provided, will use drop down instead of textbox. :param data_type: Client-side widget type to use. """ self.name = name self.options = options self.data_type = data_type def get_options(self, view): """ Return list of predefined options. Override to customize behavior. :param view: Associated administrative view class. """ if self.options: return [(v, unicode(n)) for v, n in self.options] return None def validate(self, value): """ Validate value. If value is valid, returns `True` and `False` otherwise. :param value: Value to validate """ return True def clean(self, value): """ Parse value into python format. :param value: Value to parse """ return value def apply(self, query): """ Apply search criteria to the query and return new query. :param query: Query """ raise NotImplemented() def operation(self): """ Return readable operation name. For example: u'equals' """ raise NotImplemented() def __unicode__(self): return self.name # Customized filters class BaseBooleanFilter(BaseFilter): """ Base boolean filter, uses fixed list of options. """ def __init__(self, name, options=None, data_type=None): super(BaseBooleanFilter, self).__init__(name, (('1', lazy_gettext('Yes')), ('0', lazy_gettext('No'))), data_type) def validate(self, value): return value == '0' or value == '1' class BaseDateFilter(BaseFilter): """ Base Date filter. Uses client-side date picker control. """ def __init__(self, name, options=None): super(BaseDateFilter, self).__init__(name, options, data_type='datepicker') def validate(self, value): # TODO: Validation return True class BaseDateTimeFilter(BaseFilter): """ Base DateTime filter. Uses client-side date picker control. """ def __init__(self, name, options=None): super(BaseDateTimeFilter, self).__init__(name, options, data_type='datetimepicker') def validate(self, value): # TODO: Validation return True def convert(*args): """ Decorator for field to filter conversion routine. See :mod:`flask.ext.admin.contrib.sqlamodel.filters` for usage example. """ def _inner(func): func._converter_for = args return func return _inner class BaseFilterConverter(object): """ Base filter converter. Derive from this class to implement custom field to filter conversion logic. """ def __init__(self): self.converters = dict() for p in dir(self): attr = getattr(self, p) if hasattr(attr, '_converter_for'): for p in attr._converter_for: self.converters[p] = attr
bsd-3-clause
logvinoleg89/auxyn.dev
console/migrations/m150701_115912_fix_report_table.php
1748
<?php use yii\db\Schema; use yii\db\Migration; class m150701_115912_fix_report_table extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->dropColumn('{{%report}}', 'reason'); $this->createTable('{{%reason}}', [ 'id' => Schema::TYPE_PK, 'text' => Schema::TYPE_STRING . ' NOT NULL', 'type' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 1', 'createdAt' => Schema::TYPE_INTEGER . ' NOT NULL', 'updatedAt' => Schema::TYPE_INTEGER . ' NOT NULL', ], $tableOptions); $this->createTable('{{%reportReason}}', [ 'id' => Schema::TYPE_PK, 'idReason' => Schema::TYPE_INTEGER . ' NOT NULL', 'idReport' => Schema::TYPE_INTEGER . ' NOT NULL', 'createdAt' => Schema::TYPE_INTEGER . ' NOT NULL', 'updatedAt' => Schema::TYPE_INTEGER . ' NOT NULL', ], $tableOptions); $this->addForeignKey('reportReasonReportKey', '{{%reportReason}}', 'idReport', '{{%report}}', 'id', 'CASCADE', 'CASCADE'); $this->addForeignKey('reportReasonReasonKey', '{{%reportReason}}', 'idReason', '{{%reason}}', 'id', 'CASCADE', 'CASCADE'); } public function down() { //Not adding dropped columns back since there is no code that uses them in git yet. $this->dropTable('{{%reportReason}}'); $this->dropTable('{{%reason}}'); } }
bsd-3-clause
versionone/VersionOne.Integration.TFS.Core
VersionOne.Integration.Tfs.Core/VersionOne.Integration.Tfs.Core.DataLayer/VersionOneQuery.cs
2917
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using VersionOne.SDK.APIClient; namespace VersionOne.Integration.Tfs.Core.DataLayer { public class VersionOneQuery { public readonly VersionOneSettings Settings; public readonly VersionOneAPIConnector processor; public VersionOneQuery(VersionOneSettings settings) { Settings = settings; ProxyProvider proxyProvider = ((settings.ProxySettings != null) && settings.ProxySettings.ProxyIsEnabled) ? new ProxyProvider(settings.ProxySettings.Uri, settings.ProxySettings.Username, settings.ProxySettings.Password, settings.ProxySettings.Domain) : null; processor = new VersionOneAPIConnector(settings.Path, null, proxyProvider).WithVersionOneUsernameAndPassword(settings.Username, settings.Password).WithWindowsIntegratedAuthentication(); } public void SetUpstreamUserAgent(string userAgent) { processor.SetUpstreamUserAgent(userAgent); } public List<List<WorkitemDto>> GetActiveWorkitems() { string strAllItems = string.Empty; Stream streamAllItems = processor.HttpPost("/query.v1", System.Text.Encoding.UTF8.GetBytes(getActiveWorkitemQuery()), "application/json"); using (StreamReader reader = new StreamReader(streamAllItems, Encoding.UTF8)) { strAllItems = reader.ReadToEnd(); } return JsonConvert.DeserializeObject<List<List<WorkitemDto>>>(strAllItems); } private string getActiveWorkitemQuery() { return @" from: PrimaryWorkitem select: - Name - Number - from: Owners select: - Username - AssetType - from: Children select: - Name - Number - from: Owners select: - Username - AssetType filter: - AssetState='Active' - AssetType='Task'|AssetType='Test' filter: - Timebox.State.Code='ACTV' - AssetState='Active' "; } public class WorkitemDto { public string Number { get; set; } public string Name { get; set; } public string AssetType { get; set; } public List<WorkitemDto> Children { get; set; } public List<OwnerDto> Owners { get; set; } } public class OwnerDto { public string Username { get; set; } } } }
bsd-3-clause
palfrey/twfy
www/includes/easyparliament/templates/html/hansard_column.php
3400
<?php // For displaying the main Hansard content listings (by date). // Remember, we are currently within the DEBATELIST or WRANSLISTS class, // in the render() function. // The array $data will be packed full of luverly stuff about hansard objects. // See the bottom of hansard_gid for information about its structure and contents... global $PAGE, $DATA, $this_page, $hansardmajors; twfy_debug("TEMPLATE", "hansard_column.php"); $PAGE->page_start(); $PAGE->stripe_start(); print_r($data); if (isset ($data)) { $prevlevel = ''; print "\t\t\t\t<ul id=\"hansard-day\" class=\"hansard-day\">\n"; // Cycle through each row... for ($i=0; $i<count($data); $i++) { $row = $data[$i]; // Start a top-level item, eg a section. if ($row['htype'] == '10') { if ($prevlevel == 'sub') { print "\t\t\t\t\t</ul>\n\t\t\t\t</li>\n"; } elseif ($prevlevel == 'top') { print "</li>\n"; } print "\t\t\t\t<li>"; // Start a sub-level item, eg a subsection. } else { if ($prevlevel == '') { print "\t\t\t\t<li>\n"; } elseif ($prevlevel == 'top') { print "\n\t\t\t\t\t<ul>\n"; } print "\t\t\t\t\t<li>"; } // Are we going to make this (sub)section a link // and does it contain printable speeches? if ($row['htype'] == '10' && isset($row['excerpt']) && strstr($row['excerpt'], "was asked&#8212;")) { // We fake it here. We hope this section only has a single line like // "The Secretary of State was asked-" and we don't want to make it a link. $has_content = false; } elseif (isset($row['contentcount']) && $row['contentcount'] > 0) { $has_content = true; } else { $has_content = false; } if ($has_content) { print '<a href="' . $row['listurl'] . '"><strong>' . $row['body'] . '</strong></a> '; // For the "x speeches, x comments" text. $moreinfo = array(); if ($hansardmajors[$row['major']]['type'] != 'other') { // All wrans have 2 speeches, so no need for this. // All WMS have 1 speech $plural = $row['contentcount'] == 1 ? 'speech' : 'speeches'; $moreinfo[] = $row['contentcount'] . " $plural"; } if ($row['totalcomments'] > 0) { $plural = $row['totalcomments'] == 1 ? 'annotation' : 'annotations'; $moreinfo[] = $row['totalcomments'] . " $plural"; } if (count($moreinfo) > 0) { print "<small>(" . implode (', ', $moreinfo) . ") </small>"; } } else { // Nothing in this item, so no link. print '<strong>' . $row['body'] . '</strong>'; } if (isset($row['excerpt'])) { print "<br>\n\t\t\t\t\t<span class=\"excerpt-debates\">" . trim_characters($row['excerpt'], 0, 200) . "</span>"; } // End a top-level item. if ($row['htype'] == '10') { $prevlevel = 'top'; // End a sub-level item. } else { print "</li>\n"; $prevlevel = 'sub'; } } // End cycling through rows. if ($prevlevel == 'sub') { // Finish final sub-level list. print "\t\t\t\t\t</ul>\n\t\t\t\t\t</li>\n"; } print "\n\t\t\t\t</ul> <!-- end hansard-day -->\n"; } // End display of rows. else { ?> <p>No data to display.</p> <?php } $sidebar = $hansardmajors[$this->major]['sidebar']; $PAGE->stripe_end(array( array ( 'type' => 'nextprev' ), array ( 'type' => 'include', 'content' => 'calendar_'.$sidebar ), array ( 'type' => 'include', 'content' => $sidebar ) )); ?>
bsd-3-clause
sunlightlabs/django-feedinator
feedinator/models.py
3029
import datetime from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from pytz import common_timezones FEED_TYPE_CHOICES = ( (u'rss', u'RSS'), (u'rss-0.90', u'RSS 0.90'), (u'rss-0.91', u'RSS 0.91'), (u'rss-1.0', u'RSS 1.0'), (u'rss-2.0', u'RSS 2.0 by Dave Winer'), (u'rss-2.0.10', u'RSS 2.0 by RSS Advisory Board'), (u'atom', u'Atom'), (u'atom-0.3', u'Atom 0.3'), (u'atom-1.0', u'Atom 1.0'), ) TIMEZONE_CHOICES = [(tz, tz) for tz in common_timezones] class Feed(models.Model): url = models.URLField() codename = models.CharField(max_length=128, blank=True) type = models.CharField(max_length=16, choices=FEED_TYPE_CHOICES, blank=True, null=True) title = models.CharField(max_length=225) link = models.URLField(blank=True) timezone = models.CharField(max_length=32, choices=TIMEZONE_CHOICES, default='UTC') description = models.TextField(blank=True) ttl = models.IntegerField(default=60) date_added = models.DateTimeField(auto_now_add=True) last_fetched = models.DateTimeField(blank=True, null=True) next_fetch = models.DateTimeField() def __unicode__(self): return self.title def save(self, *args, **kwargs): if not self.last_fetched: self.last_fetched = datetime.datetime.now() self.next_fetch = self.last_fetched else: self.next_fetch = self.last_fetched + datetime.timedelta(0, 0, 0, 0, self.ttl) super(Feed, self).save(*args, **kwargs) class Subscription(models.Model): feed = models.ForeignKey(Feed, related_name='subscriptions') content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() subscriber = generic.GenericForeignKey() def __unicode__(self): return '%s to %s' % (self.subscriber, self.feed) class FeedEntryManager(models.Manager): pass class FeedEntry(models.Model): objects = FeedEntryManager() uid = models.CharField(max_length=255) feed = models.ForeignKey(Feed, related_name="entries") title = models.CharField(max_length=255) link = models.URLField(blank=True) summary = models.TextField(blank=True) content = models.TextField(blank=True) author_name = models.CharField(max_length=255, blank=True) author_email = models.EmailField(blank=True, null=True) author_uri = models.URLField(blank=True, null=True) date_published = models.DateTimeField(blank=True, null=True) date_updated = models.DateTimeField(blank=True, null=True) last_fetched = models.DateTimeField() class Meta: ordering = ['-date_published'] def __unicode__(self): return u"%s: %s" % (self.feed.title, self.title) class Tag(models.Model): name = models.CharField(max_length=128) feed_entry = models.ForeignKey(FeedEntry, related_name="tags") class Meta: ordering = ['name'] def __unicode__(self): return self.name
bsd-3-clause
sigma-z/Jentin
test/Jentin/Mvc/Response/RedirectResponseTest.php
1007
<?php /* * This file is part of the Jentin framework. * (c) Steffen Zeidler <sigma_z@sigma-scripts.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Test\Jentin\Mvc\Response; use Jentin\Mvc\Response\RedirectResponse; use PHPUnit\Framework\TestCase; /** * RedirectResponseTest * @author Steffen Zeidler <sigma_z@sigma-scripts.de> */ class RedirectResponseTest extends TestCase { /** * @expectedException \InvalidArgumentException */ public function testEmptyRedirectUrlException() { $response = new RedirectResponse(); $response->sendResponse(); } public function testSetRedirectUrl() { $url = 'http://google.de/'; $response = new RedirectResponse(); $response->setRedirectUrl($url); $this->assertEquals($url, $response->getHeader('Location')); $this->assertEquals(301, $response->getStatusCode()); } }
bsd-3-clause
rproepp/spykeviewer
spykeviewer/ui/ipython_connection.py
3664
import sys import logging ipython_available = False try: # Ipython 0.12, 0.13 import IPython from IPython.zmq.ipkernel import IPKernelApp from IPython.frontend.qt.kernelmanager import QtKernelManager from IPython.frontend.qt.console.rich_ipython_widget \ import RichIPythonWidget from IPython.lib.kernel import find_connection_file from PyQt4.QtCore import QTimer import atexit class LocalKernelApp(IPKernelApp): def initialize(self, argv=None): if argv is None: argv = [] super(LocalKernelApp, self).initialize(argv) self.kernel.eventloop = self.loop_qt4_nonblocking self.kernel.start() self.start() def loop_qt4_nonblocking(self, kernel): """ Non-blocking version of the ipython qt4 kernel loop """ kernel.timer = QTimer() kernel.timer.timeout.connect(kernel.do_one_iteration) kernel.timer.start(1000 * kernel._poll_interval) def push(self, d): for k, v in d.iteritems(): self.kernel.shell.user_ns[k] = v class IPythonConnection(): def __init__(self): self._stdout = sys.stdout self._stderr = sys.stderr self._dishook = sys.displayhook sys.stderr = sys.__stderr__ # Prevent message on kernel creation self.kernel_app = LocalKernelApp.instance() self.kernel_app.initialize() sys.stdout = self._stdout sys.stderr = self._stderr sys.displayhook = self._dishook def get_widget(self, droplist_completion=True): if IPython.__version__ < '0.13': completion = droplist_completion else: completion = 'droplist' if droplist_completion else 'plain' widget = RichIPythonWidget(gui_completion=completion) cf = find_connection_file(self.kernel_app.connection_file) km = QtKernelManager(connection_file=cf, config=widget.config) km.load_connection_file() km.start_channels() widget.kernel_manager = km atexit.register(km.cleanup_connection_file) sys.stdout = self._stdout sys.stderr = self._stderr sys.displayhook = self._dishook return widget def push(self, d): self.kernel_app.push(d) ipython_available = True except ImportError: try: # Ipython >= 1.0 from IPython.qt.inprocess import QtInProcessKernelManager from IPython.qt.console.rich_ipython_widget import RichIPythonWidget class IPythonConnection(): def __init__(self): self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() # Suppress debug messages self.kernel.log.setLevel(logging.WARNING) def get_widget(self, droplist_completion=True): completion = 'droplist' if droplist_completion else 'plain' widget = RichIPythonWidget(gui_completion=completion) widget.kernel_manager = self.kernel_manager widget.kernel_client = self.kernel_client return widget def push(self, d): self.kernel.shell.push(d) ipython_available = True except ImportError: pass
bsd-3-clause
mizalewski/yii2-multitenancy-sample
console/migrations/m150315_202652_create_content.php
665
<?php use yii\db\Schema; use yii\db\Migration; class m150315_202652_create_content extends Migration { const CONTENT_TABLE_NAME = '{{%content}}'; const TENANT_TABLE_NAME = '{{%tenant}}'; public function safeUp() { $this->createTable(self::CONTENT_TABLE_NAME, [ 'id' => 'pk', 'tenant_id' => Schema::TYPE_INTEGER.' NOT NULL', 'text' => Schema::TYPE_TEXT.' NOT NULL', ]); $this->addForeignKey('FK_content_tenant', self::CONTENT_TABLE_NAME, 'tenant_id', self::TENANT_TABLE_NAME, 'id'); } public function safeDown() { $this->dropTable(self::CONTENT_TABLE_NAME); } }
bsd-3-clause
nwjs/chromium.src
chrome/browser/safe_browsing/threat_details_unittest.cc
77630
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include <algorithm> #include "base/bind.h" #include "base/macros.h" #include "base/pickle.h" #include "base/run_loop.h" #include "base/test/metrics/histogram_tester.h" #include "base/time/time.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/chrome_safe_browsing_blocking_page_factory.h" #include "chrome/browser/safe_browsing/chrome_ui_manager_delegate.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/history/core/browser/history_backend.h" #include "components/history/core/browser/history_service.h" #include "components/safe_browsing/content/browser/threat_details.h" #include "components/safe_browsing/content/browser/threat_details_history.h" #include "components/safe_browsing/content/browser/ui_manager.h" #include "components/safe_browsing/content/common/safe_browsing.mojom.h" #include "components/safe_browsing/core/browser/referrer_chain_provider.h" #include "components/safe_browsing/core/common/proto/csd.pb.h" #include "components/security_interstitials/content/unsafe_resource_util.h" #include "components/security_interstitials/core/unsafe_resource.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/navigation_simulator.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/web_contents_tester.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/http/http_util.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gmock/include/gmock/gmock.h" using content::BrowserThread; using content::WebContents; using testing::_; using testing::DoAll; using testing::Eq; using testing::Return; using testing::SetArgPointee; using testing::UnorderedPointwise; namespace safe_browsing { namespace { // Mixture of HTTP and HTTPS. No special treatment for HTTPS. static const char* kOriginalLandingURL = "http://www.originallandingpage.com/with/path"; static const char* kDOMChildURL = "https://www.domchild.com/with/path"; static const char* kDOMChildUrl2 = "https://www.domchild2.com/path"; static const char* kDOMParentURL = "https://www.domparent.com/with/path"; static const char* kFirstRedirectURL = "http://redirectone.com/with/path"; static const char* kSecondRedirectURL = "https://redirecttwo.com/with/path"; static const char* kReferrerURL = "http://www.referrer.com/with/path"; static const char* kDataURL = "data:text/html;charset=utf-8;base64,PCFET0"; static const char* kBlankURL = "about:blank"; static const char* kThreatURL = "http://www.threat.com/with/path"; static const char* kThreatURLHttps = "https://www.threat.com/with/path"; static const char* kThreatHeaders = "HTTP/1.1 200 OK\n" "Content-Type: image/jpeg\n" "Some-Other-Header: foo\n"; // Persisted for http, stripped for https static const char* kThreatData = "exploit();"; static const char* kLandingURL = "http://www.landingpage.com/with/path"; static const char* kLandingHeaders = "HTTP/1.1 200 OK\n" "Content-Type: text/html\n" "Content-Length: 1024\n" "Set-Cookie: tastycookie\n"; // This header is stripped. static const char* kLandingData = "<iframe src='http://www.threat.com/with/path'>"; using content::BrowserThread; using content::WebContents; // Lets us control synchronization of the done callback for ThreatDetails. // Also exposes the constructor. class ThreatDetailsWrap : public ThreatDetails { public: ThreatDetailsWrap( SafeBrowsingUIManager* ui_manager, WebContents* web_contents, const security_interstitials::UnsafeResource& unsafe_resource, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, history::HistoryService* history_service, ReferrerChainProvider* referrer_chain_provider) : ThreatDetails(ui_manager, web_contents, unsafe_resource, url_loader_factory, history_service, referrer_chain_provider, /*trim_to_ad_tags=*/false, base::BindOnce(&ThreatDetailsWrap::ThreatDetailsDone, base::Unretained(this))), run_loop_(nullptr), done_callback_count_(0) {} ThreatDetailsWrap( SafeBrowsingUIManager* ui_manager, WebContents* web_contents, const security_interstitials::UnsafeResource& unsafe_resource, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, history::HistoryService* history_service, ReferrerChainProvider* referrer_chain_provider, bool trim_to_ad_tags) : ThreatDetails(ui_manager, web_contents, unsafe_resource, url_loader_factory, history_service, referrer_chain_provider, trim_to_ad_tags, base::BindOnce(&ThreatDetailsWrap::ThreatDetailsDone, base::Unretained(this))), run_loop_(nullptr), done_callback_count_(0) {} ~ThreatDetailsWrap() override {} void ThreatDetailsDone(content::WebContents* web_contents) { ++done_callback_count_; run_loop_->Quit(); run_loop_ = nullptr; } // Used to synchronize ThreatDetailsDone() with WaitForThreatDetailsDone(). // RunLoop::RunUntilIdle() is not sufficient because the MessageLoop task // queue completely drains at some point between the send and the wait. void SetRunLoopToQuit(base::RunLoop* run_loop) { DCHECK(run_loop_ == nullptr); run_loop_ = run_loop; } size_t done_callback_count() { return done_callback_count_; } void StartCollection() { ThreatDetails::StartCollection(); } private: base::RunLoop* run_loop_; size_t done_callback_count_; }; class MockSafeBrowsingUIManager : public SafeBrowsingUIManager { public: // The safe browsing UI manager does not need a service for this test. MockSafeBrowsingUIManager() : SafeBrowsingUIManager( std::make_unique<ChromeSafeBrowsingUIManagerDelegate>(), std::make_unique<ChromeSafeBrowsingBlockingPageFactory>(), GURL(chrome::kChromeUINewTabURL)), report_sent_(false) {} MockSafeBrowsingUIManager(const MockSafeBrowsingUIManager&) = delete; MockSafeBrowsingUIManager& operator=(const MockSafeBrowsingUIManager&) = delete; // When the serialized report is sent, this is called. void SendSerializedThreatDetails(content::BrowserContext* browser_context, const std::string& serialized) override { report_sent_ = true; serialized_ = serialized; } const std::string& GetSerialized() { return serialized_; } bool ReportWasSent() { return report_sent_; } private: ~MockSafeBrowsingUIManager() override {} std::string serialized_; bool report_sent_; }; class MockReferrerChainProvider : public ReferrerChainProvider { public: virtual ~MockReferrerChainProvider() {} MOCK_METHOD3(IdentifyReferrerChainByWebContents, AttributionResult(content::WebContents* web_contents, int user_gesture_count_limit, ReferrerChain* out_referrer_chain)); MOCK_METHOD4(IdentifyReferrerChainByEventURL, AttributionResult(const GURL& event_url, SessionID event_tab_id, int user_gesture_count_limit, ReferrerChain* out_referrer_chain)); MOCK_METHOD3(IdentifyReferrerChainByPendingEventURL, AttributionResult(const GURL& event_url, int user_gesture_count_limit, ReferrerChain* out_referrer_chain)); }; } // namespace class ThreatDetailsTest : public ChromeRenderViewHostTestHarness { public: typedef SafeBrowsingUIManager::UnsafeResource UnsafeResource; ThreatDetailsTest() : referrer_chain_provider_(new MockReferrerChainProvider()), ui_manager_(new MockSafeBrowsingUIManager()) {} void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); test_shared_loader_factory_ = base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_); } std::string WaitForThreatDetailsDone(ThreatDetailsWrap* report, bool did_proceed, int num_visit) { report->FinishCollection(did_proceed, num_visit); // Wait for the callback (ThreatDetailsDone). base::RunLoop run_loop; report->SetRunLoopToQuit(&run_loop); run_loop.Run(); // Make sure the done callback was run exactly once. EXPECT_EQ(1u, report->done_callback_count()); return ui_manager_->GetSerialized(); } history::HistoryService* history_service() { return HistoryServiceFactory::GetForProfile( profile(), ServiceAccessType::EXPLICIT_ACCESS); } bool ReportWasSent() { return ui_manager_->ReportWasSent(); } protected: TestingProfile::TestingFactories GetTestingFactories() const override { return {{HistoryServiceFactory::GetInstance(), HistoryServiceFactory::GetDefaultFactory()}}; } void InitResource(SBThreatType threat_type, ThreatSource threat_source, bool is_subresource, const GURL& url, UnsafeResource* resource) { const content::GlobalRenderFrameHostId primary_main_frame_id = web_contents()->GetMainFrame()->GetGlobalId(); resource->url = url; resource->is_subresource = is_subresource; resource->threat_type = threat_type; resource->threat_source = threat_source; resource->render_process_id = primary_main_frame_id.child_id; resource->render_frame_id = primary_main_frame_id.frame_routing_id; } void VerifyResults(const ClientSafeBrowsingReportRequest& report_pb, const ClientSafeBrowsingReportRequest& expected_pb) { EXPECT_EQ(expected_pb.type(), report_pb.type()); EXPECT_EQ(expected_pb.url(), report_pb.url()); EXPECT_EQ(expected_pb.page_url(), report_pb.page_url()); EXPECT_EQ(expected_pb.referrer_url(), report_pb.referrer_url()); EXPECT_EQ(expected_pb.did_proceed(), report_pb.did_proceed()); EXPECT_EQ(expected_pb.has_repeat_visit(), report_pb.has_repeat_visit()); if (expected_pb.has_repeat_visit() && report_pb.has_repeat_visit()) { EXPECT_EQ(expected_pb.repeat_visit(), report_pb.repeat_visit()); } ASSERT_EQ(expected_pb.resources_size(), report_pb.resources_size()); // Put the actual resources in a map, then iterate over the expected // resources, making sure each exists and is equal. std::map<int, const ClientSafeBrowsingReportRequest::Resource*> actual_resource_map; for (const ClientSafeBrowsingReportRequest::Resource& resource : report_pb.resources()) { actual_resource_map[resource.id()] = &resource; } // Make sure no resources disappeared when moving them to a map (IDs should // be unique). ASSERT_EQ(expected_pb.resources_size(), static_cast<int>(actual_resource_map.size())); for (const ClientSafeBrowsingReportRequest::Resource& expected_resource : expected_pb.resources()) { ASSERT_GT(actual_resource_map.count(expected_resource.id()), 0u); VerifyResource(*actual_resource_map[expected_resource.id()], expected_resource); } ASSERT_EQ(expected_pb.dom_size(), report_pb.dom_size()); // Put the actual elements in a map, then iterate over the expected // elements, making sure each exists and is equal. std::map<int, const HTMLElement*> actual_dom_map; for (const HTMLElement& element : report_pb.dom()) { actual_dom_map[element.id()] = &element; } // Make sure no elements disappeared when moving them to a map (IDs should // be unique). ASSERT_EQ(expected_pb.dom_size(), static_cast<int>(actual_dom_map.size())); for (const HTMLElement& expected_element : expected_pb.dom()) { ASSERT_GT(actual_dom_map.count(expected_element.id()), 0u); VerifyElement(*actual_dom_map[expected_element.id()], expected_element); } EXPECT_TRUE(report_pb.client_properties().has_url_api_type()); EXPECT_EQ(expected_pb.client_properties().url_api_type(), report_pb.client_properties().url_api_type()); EXPECT_EQ(expected_pb.complete(), report_pb.complete()); EXPECT_EQ(expected_pb.referrer_chain_size(), report_pb.referrer_chain_size()); // TODO: check each elem url } void VerifyResource( const ClientSafeBrowsingReportRequest::Resource& resource, const ClientSafeBrowsingReportRequest::Resource& expected) { EXPECT_EQ(expected.id(), resource.id()); EXPECT_EQ(expected.url(), resource.url()); EXPECT_EQ(expected.parent_id(), resource.parent_id()); ASSERT_EQ(expected.child_ids_size(), resource.child_ids_size()); for (int i = 0; i < expected.child_ids_size(); i++) { EXPECT_EQ(expected.child_ids(i), resource.child_ids(i)); } // Verify HTTP Responses if (expected.has_response()) { ASSERT_TRUE(resource.has_response()); EXPECT_EQ(expected.response().firstline().code(), resource.response().firstline().code()); ASSERT_EQ(expected.response().headers_size(), resource.response().headers_size()); for (int i = 0; i < expected.response().headers_size(); ++i) { EXPECT_EQ(expected.response().headers(i).name(), resource.response().headers(i).name()); EXPECT_EQ(expected.response().headers(i).value(), resource.response().headers(i).value()); } EXPECT_EQ(expected.response().body(), resource.response().body()); EXPECT_EQ(expected.response().bodylength(), resource.response().bodylength()); EXPECT_EQ(expected.response().bodydigest(), resource.response().bodydigest()); } // Verify IP:port pair EXPECT_EQ(expected.response().remote_ip(), resource.response().remote_ip()); } void VerifyElement(const HTMLElement& element, const HTMLElement& expected) { EXPECT_EQ(expected.id(), element.id()); EXPECT_EQ(expected.tag(), element.tag()); EXPECT_EQ(expected.resource_id(), element.resource_id()); EXPECT_THAT(element.child_ids(), UnorderedPointwise(Eq(), expected.child_ids())); ASSERT_EQ(expected.attribute_size(), element.attribute_size()); std::map<std::string, std::string> actual_attributes_map; for (const HTMLElement::Attribute& attribute : element.attribute()) { actual_attributes_map[attribute.name()] = attribute.value(); } ASSERT_EQ(expected.attribute_size(), static_cast<int>(actual_attributes_map.size())); for (const HTMLElement::Attribute& expected_attribute : expected.attribute()) { ASSERT_GT(actual_attributes_map.count(expected_attribute.name()), 0u); EXPECT_EQ(expected_attribute.value(), actual_attributes_map[expected_attribute.name()]); } } // Adds a page to history. // The redirects is the redirect url chain leading to the url. void AddPageToHistory(const GURL& url, history::RedirectList* redirects) { // The last item of the redirect chain has to be the final url when adding // to history backend. redirects->push_back(url); history_service()->AddPage(url, base::Time::Now(), reinterpret_cast<history::ContextID>(1), 0, GURL(), *redirects, ui::PAGE_TRANSITION_TYPED, history::SOURCE_BROWSED, false, false); } void WriteCacheEntry(const std::string& url, const std::string& headers, const std::string& content) { auto head = network::mojom::URLResponseHead::New(); head->headers = base::MakeRefCounted<net::HttpResponseHeaders>( net::HttpUtil::AssembleRawHeaders(headers)); head->remote_endpoint = net::IPEndPoint(net::IPAddress(1, 2, 3, 4), 80); head->mime_type = "text/html"; network::URLLoaderCompletionStatus status; status.decoded_body_length = content.size(); test_url_loader_factory_.AddResponse(GURL(url), std::move(head), content, status); } void SimulateFillCache(const std::string& url) { WriteCacheEntry(url, kThreatHeaders, kThreatData); WriteCacheEntry(kLandingURL, kLandingHeaders, kLandingData); } std::unique_ptr<MockReferrerChainProvider> referrer_chain_provider_; scoped_refptr<MockSafeBrowsingUIManager> ui_manager_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; }; // Tests creating a simple threat report of a malware URL. TEST_F(ThreatDetailsTest, ThreatSubResource) { auto navigation = content::NavigationSimulator::CreateBrowserInitiated( GURL(kLandingURL), web_contents()); navigation->SetReferrer(blink::mojom::Referrer::New( GURL(kReferrerURL), network::mojom::ReferrerPolicy::kDefault)); navigation->Commit(); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_MALWARE, ThreatSource::CLIENT_SIDE_DETECTION, true /* is_subresource */, GURL(kThreatURL), &resource); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, 1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_MALWARE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); // The referrer is stripped to its origin because it's a cross-origin URL. expected.set_referrer_url( GURL(kReferrerURL).DeprecatedGetOriginAsURL().spec()); expected.set_did_proceed(true); expected.set_repeat_visit(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_url(GURL(kReferrerURL).DeprecatedGetOriginAsURL().spec()); VerifyResults(actual, expected); } // Tests creating a simple threat report of a suspicious site that contains // the referrer chain. TEST_F(ThreatDetailsTest, SuspiciousSiteWithReferrerChain) { auto navigation = content::NavigationSimulator::CreateBrowserInitiated( GURL(kLandingURL), web_contents()); navigation->SetReferrer(blink::mojom::Referrer::New( GURL(kReferrerURL), network::mojom::ReferrerPolicy::kDefault)); navigation->Commit(); UnsafeResource resource; InitResource(SB_THREAT_TYPE_SUSPICIOUS_SITE, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); ReferrerChain returned_referrer_chain; returned_referrer_chain.Add()->set_url(kReferrerURL); returned_referrer_chain.Add()->set_url(kSecondRedirectURL); EXPECT_CALL(*referrer_chain_provider_, IdentifyReferrerChainByWebContents(web_contents(), _, _)) .WillOnce(DoAll(SetArgPointee<2>(returned_referrer_chain), Return(ReferrerChainProvider::SUCCESS))); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, 1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_SUSPICIOUS); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); // The referrer is stripped to its origin because it's a cross-origin URL. expected.set_referrer_url( GURL(kReferrerURL).DeprecatedGetOriginAsURL().spec()); expected.set_did_proceed(true); expected.set_repeat_visit(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_url(GURL(kReferrerURL).DeprecatedGetOriginAsURL().spec()); // Make sure the referrer chain returned by the provider is copied into the // resulting proto. expected.mutable_referrer_chain()->CopyFrom(returned_referrer_chain); VerifyResults(actual, expected); } // Tests creating a simple threat report of a phishing page where the // subresource has a different original_url. TEST_F(ThreatDetailsTest, ThreatSubResourceWithOriginalUrl) { content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_PHISHING, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); resource.original_url = GURL(kOriginalLandingURL); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); std::string serialized = WaitForThreatDetailsDone( report.get(), false /* did_proceed*/, 1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_PHISHING); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(false); expected.set_repeat_visit(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kOriginalLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_url(kThreatURL); // The Resource for kThreatURL should have the Resource for // kOriginalLandingURL (with id 1) as parent. pb_resource->set_parent_id(1); VerifyResults(actual, expected); } // Tests creating a threat report of a UwS page with data from the renderer. TEST_F(ThreatDetailsTest, ThreatDOMDetails) { content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_UNWANTED, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); // Send a message from the DOM, with 2 nodes, a parent and a child. std::vector<mojom::ThreatDOMDetailsNodePtr> params; mojom::ThreatDOMDetailsNodePtr child_node = mojom::ThreatDOMDetailsNode::New(); child_node->url = GURL(kDOMChildURL); child_node->tag_name = "iframe"; child_node->parent = GURL(kDOMParentURL); child_node->attributes.push_back( mojom::AttributeNameValue::New("src", kDOMChildURL)); params.push_back(std::move(child_node)); mojom::ThreatDOMDetailsNodePtr parent_node = mojom::ThreatDOMDetailsNode::New(); parent_node->url = GURL(kDOMParentURL); parent_node->children.push_back(GURL(kDOMChildURL)); params.push_back(std::move(parent_node)); report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(params)); std::string serialized = WaitForThreatDetailsDone( report.get(), false /* did_proceed*/, 0 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_UNWANTED); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(false); expected.set_repeat_visit(false); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_url(kDOMChildURL); pb_resource->set_parent_id(3); pb_resource = expected.add_resources(); pb_resource->set_id(3); pb_resource->set_url(kDOMParentURL); pb_resource->add_child_ids(2); expected.set_complete(false); // Since the cache was missing. HTMLElement* pb_element = expected.add_dom(); pb_element->set_id(0); pb_element->set_tag("IFRAME"); pb_element->set_resource_id(2); pb_element->add_attribute()->set_name("src"); pb_element->mutable_attribute(0)->set_value(kDOMChildURL); VerifyResults(actual, expected); } // Tests creating a threat report when receiving data from multiple renderers. // We use three layers in this test: // kDOMParentURL // \- <div id=outer> // \- <iframe src=kDOMChildURL foo=bar> // \- <div id=inner bar=baz/> - div and script are at the same level. // \- <script src=kDOMChildURL2> TEST_F(ThreatDetailsTest, ThreatDOMDetails_MultipleFrames) { // Create a child renderer inside the main frame to house the inner iframe. // Perform the navigation first in order to manipulate the frame tree. content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); content::RenderFrameHost* child_rfh = content::RenderFrameHostTester::For(main_rfh())->AppendChild("subframe"); // Define two sets of DOM nodes - one for an outer page containing an iframe, // and then another for the inner page containing the contents of that iframe. std::vector<mojom::ThreatDOMDetailsNodePtr> outer_params; mojom::ThreatDOMDetailsNodePtr outer_child_div = mojom::ThreatDOMDetailsNode::New(); outer_child_div->node_id = 1; outer_child_div->child_node_ids.push_back(2); outer_child_div->tag_name = "div"; outer_child_div->parent = GURL(kDOMParentURL); outer_child_div->attributes.push_back( mojom::AttributeNameValue::New("id", "outer")); outer_params.push_back(std::move(outer_child_div)); mojom::ThreatDOMDetailsNodePtr outer_child_iframe = mojom::ThreatDOMDetailsNode::New(); outer_child_iframe->node_id = 2; outer_child_iframe->parent_node_id = 1; outer_child_iframe->url = GURL(kDOMChildURL); outer_child_iframe->tag_name = "iframe"; outer_child_iframe->parent = GURL(kDOMParentURL); outer_child_iframe->attributes.push_back( mojom::AttributeNameValue::New("src", kDOMChildURL)); outer_child_iframe->attributes.push_back( mojom::AttributeNameValue::New("foo", "bar")); outer_child_iframe->child_frame_routing_id = child_rfh->GetRoutingID(); outer_params.push_back(std::move(outer_child_iframe)); mojom::ThreatDOMDetailsNodePtr outer_summary_node = mojom::ThreatDOMDetailsNode::New(); outer_summary_node->url = GURL(kDOMParentURL); outer_summary_node->children.push_back(GURL(kDOMChildURL)); outer_params.push_back(std::move(outer_summary_node)); // Now define some more nodes for the body of the iframe. std::vector<mojom::ThreatDOMDetailsNodePtr> inner_params; mojom::ThreatDOMDetailsNodePtr inner_child_div = mojom::ThreatDOMDetailsNode::New(); inner_child_div->node_id = 1; inner_child_div->tag_name = "div"; inner_child_div->parent = GURL(kDOMChildURL); inner_child_div->attributes.push_back( mojom::AttributeNameValue::New("id", "inner")); inner_child_div->attributes.push_back( mojom::AttributeNameValue::New("bar", "baz")); inner_params.push_back(std::move(inner_child_div)); mojom::ThreatDOMDetailsNodePtr inner_child_script = mojom::ThreatDOMDetailsNode::New(); inner_child_script->node_id = 2; inner_child_script->url = GURL(kDOMChildUrl2); inner_child_script->tag_name = "script"; inner_child_script->parent = GURL(kDOMChildURL); inner_child_script->attributes.push_back( mojom::AttributeNameValue::New("src", kDOMChildUrl2)); inner_params.push_back(std::move(inner_child_script)); mojom::ThreatDOMDetailsNodePtr inner_summary_node = mojom::ThreatDOMDetailsNode::New(); inner_summary_node->url = GURL(kDOMChildURL); inner_summary_node->children.push_back(GURL(kDOMChildUrl2)); inner_params.push_back(std::move(inner_summary_node)); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_UNWANTED); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(false); expected.set_repeat_visit(false); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); ClientSafeBrowsingReportRequest::Resource* res_dom_child = expected.add_resources(); res_dom_child->set_id(2); res_dom_child->set_url(kDOMChildURL); res_dom_child->set_parent_id(3); res_dom_child->add_child_ids(4); ClientSafeBrowsingReportRequest::Resource* res_dom_parent = expected.add_resources(); res_dom_parent->set_id(3); res_dom_parent->set_url(kDOMParentURL); res_dom_parent->add_child_ids(2); ClientSafeBrowsingReportRequest::Resource* res_dom_child2 = expected.add_resources(); res_dom_child2->set_id(4); res_dom_child2->set_url(kDOMChildUrl2); res_dom_child2->set_parent_id(2); expected.set_complete(false); // Since the cache was missing. HTMLElement* elem_dom_outer_div = expected.add_dom(); elem_dom_outer_div->set_id(0); elem_dom_outer_div->set_tag("DIV"); elem_dom_outer_div->add_attribute()->set_name("id"); elem_dom_outer_div->mutable_attribute(0)->set_value("outer"); elem_dom_outer_div->add_child_ids(1); HTMLElement* elem_dom_outer_iframe = expected.add_dom(); elem_dom_outer_iframe->set_id(1); elem_dom_outer_iframe->set_tag("IFRAME"); elem_dom_outer_iframe->set_resource_id(res_dom_child->id()); elem_dom_outer_iframe->add_attribute()->set_name("src"); elem_dom_outer_iframe->mutable_attribute(0)->set_value(kDOMChildURL); elem_dom_outer_iframe->add_attribute()->set_name("foo"); elem_dom_outer_iframe->mutable_attribute(1)->set_value("bar"); elem_dom_outer_iframe->add_child_ids(2); elem_dom_outer_iframe->add_child_ids(3); HTMLElement* elem_dom_inner_div = expected.add_dom(); elem_dom_inner_div->set_id(2); elem_dom_inner_div->set_tag("DIV"); elem_dom_inner_div->add_attribute()->set_name("id"); elem_dom_inner_div->mutable_attribute(0)->set_value("inner"); elem_dom_inner_div->add_attribute()->set_name("bar"); elem_dom_inner_div->mutable_attribute(1)->set_value("baz"); HTMLElement* elem_dom_inner_script = expected.add_dom(); elem_dom_inner_script->set_id(3); elem_dom_inner_script->set_tag("SCRIPT"); elem_dom_inner_script->set_resource_id(res_dom_child2->id()); elem_dom_inner_script->add_attribute()->set_name("src"); elem_dom_inner_script->mutable_attribute(0)->set_value(kDOMChildUrl2); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_UNWANTED, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); // Send both sets of nodes, from different render frames. { auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); std::vector<mojom::ThreatDOMDetailsNodePtr> outer_params_copy; for (auto& node : outer_params) { outer_params_copy.push_back(node.Clone()); } std::vector<mojom::ThreatDOMDetailsNodePtr> inner_params_copy; for (auto& node : inner_params) { inner_params_copy.push_back(node.Clone()); } // Send both sets of nodes from different render frames. report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(outer_params_copy)); report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), child_rfh, std::move(inner_params_copy)); std::string serialized = WaitForThreatDetailsDone( report.get(), false /* did_proceed*/, 0 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); VerifyResults(actual, expected); } // Try again but with the messages coming in a different order. The IDs change // slightly, but everything else remains the same. { // Adjust the expected IDs: the inner params come first, so InnerScript // and InnerDiv appear before DomParent res_dom_child2->set_id(2); res_dom_child2->set_parent_id(3); res_dom_child->set_id(3); res_dom_child->set_parent_id(4); res_dom_child->clear_child_ids(); res_dom_child->add_child_ids(2); res_dom_parent->set_id(4); res_dom_parent->clear_child_ids(); res_dom_parent->add_child_ids(3); // Also adjust the elements - they change order since InnerDiv and // InnerScript come in first. elem_dom_inner_div->set_id(0); elem_dom_inner_script->set_id(1); elem_dom_inner_script->set_resource_id(res_dom_child2->id()); elem_dom_outer_div->set_id(2); elem_dom_outer_div->clear_child_ids(); elem_dom_outer_div->add_child_ids(3); elem_dom_outer_iframe->set_id(3); elem_dom_outer_iframe->set_resource_id(res_dom_child->id()); elem_dom_outer_iframe->clear_child_ids(); elem_dom_outer_iframe->add_child_ids(0); elem_dom_outer_iframe->add_child_ids(1); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); // Send both sets of nodes from different render frames. report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), child_rfh, std::move(inner_params)); report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(outer_params)); std::string serialized = WaitForThreatDetailsDone( report.get(), false /* did_proceed*/, 0 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); VerifyResults(actual, expected); } } // Tests an ambiguous DOM, meaning that an inner render frame can not be mapped // to an iframe element in the parent frame, which is a failure to lookup the // frames in the frame tree and should not happen. // We use three layers in this test: // kDOMParentURL // \- <frame src=kDataURL> // \- <script src=kDOMChildURL2> TEST_F(ThreatDetailsTest, ThreatDOMDetails_AmbiguousDOM) { // Create a child renderer inside the main frame to house the inner iframe. // Perform the navigation first in order to manipulate the frame tree. content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); content::RenderFrameHost* child_rfh = content::RenderFrameHostTester::For(main_rfh())->AppendChild("subframe"); // Define two sets of DOM nodes - one for an outer page containing a frame, // and then another for the inner page containing the contents of that frame. std::vector<mojom::ThreatDOMDetailsNodePtr> outer_params; mojom::ThreatDOMDetailsNodePtr outer_child_node = mojom::ThreatDOMDetailsNode::New(); outer_child_node->url = GURL(kDataURL); outer_child_node->tag_name = "frame"; outer_child_node->parent = GURL(kDOMParentURL); outer_child_node->attributes.push_back( mojom::AttributeNameValue::New("src", kDataURL)); outer_params.push_back(std::move(outer_child_node)); mojom::ThreatDOMDetailsNodePtr outer_summary_node = mojom::ThreatDOMDetailsNode::New(); outer_summary_node->url = GURL(kDOMParentURL); outer_summary_node->children.push_back(GURL(kDataURL)); // Set |child_frame_routing_id| for this node to something non-sensical so // that the child frame lookup fails. outer_summary_node->child_frame_routing_id = -100; outer_params.push_back(std::move(outer_summary_node)); // Now define some more nodes for the body of the frame. The URL of this // inner frame is "about:blank". std::vector<mojom::ThreatDOMDetailsNodePtr> inner_params; mojom::ThreatDOMDetailsNodePtr inner_child_node = mojom::ThreatDOMDetailsNode::New(); inner_child_node->url = GURL(kDOMChildUrl2); inner_child_node->tag_name = "script"; inner_child_node->parent = GURL(kBlankURL); inner_child_node->attributes.push_back( mojom::AttributeNameValue::New("src", kDOMChildUrl2)); inner_params.push_back(std::move(inner_child_node)); mojom::ThreatDOMDetailsNodePtr inner_summary_node = mojom::ThreatDOMDetailsNode::New(); inner_summary_node->url = GURL(kBlankURL); inner_summary_node->children.push_back(GURL(kDOMChildUrl2)); inner_params.push_back(std::move(inner_summary_node)); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_UNWANTED); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(false); expected.set_repeat_visit(false); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_url(kDOMParentURL); pb_resource->add_child_ids(3); // TODO(lpz): The data URL is added, despite being unreportable, because it // is a child of the top-level page. Consider if this should happen. pb_resource = expected.add_resources(); pb_resource->set_id(3); pb_resource->set_url(kDataURL); // This child can't be mapped to its containing iframe so its parent is unset. pb_resource = expected.add_resources(); pb_resource->set_id(4); pb_resource->set_url(kDOMChildUrl2); expected.set_complete(false); // Since the cache was missing. // This Element represents the Frame with the data URL. It has no resource or // children since it couldn't be mapped to anything. It does still contain the // src attribute with the data URL set. HTMLElement* pb_element = expected.add_dom(); pb_element->set_id(0); pb_element->set_tag("FRAME"); pb_element->add_attribute()->set_name("src"); pb_element->mutable_attribute(0)->set_value(kDataURL); pb_element = expected.add_dom(); pb_element->set_id(1); pb_element->set_tag("SCRIPT"); pb_element->set_resource_id(4); pb_element->add_attribute()->set_name("src"); pb_element->mutable_attribute(0)->set_value(kDOMChildUrl2); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_UNWANTED, ThreatSource::CLIENT_SIDE_DETECTION, true /* is_subresource */, GURL(kThreatURL), &resource); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); base::HistogramTester histograms; // Send both sets of nodes from different render frames. report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(outer_params)); report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), child_rfh, std::move(inner_params)); std::string serialized = WaitForThreatDetailsDone( report.get(), false /* did_proceed*/, 0 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); VerifyResults(actual, expected); } // Tests creating a threat report when receiving data from multiple renderers // that gets trimmed to just the ad and its contents. // This test uses the following structure. // kDOMParentURL // \- <div id=outer> # Trimmed // \- <script id=shared-resource src=kFirstRedirectURL> # Trimmed // \- <script id=outer-sibling src=kReferrerURL> # Reported (parent of ad ID) // \- <script id=sibling src=kFirstRedirectURL> # Reported (sibling of ad ID) // \- <div data-google-query-id=ad-tag> # Reported (ad ID) // \- <iframe src=kDOMChildURL foo=bar> # Reported (child of ad ID) // \- <div id=inner bar=baz/> # Reported (child of ad ID) // \- <script src=kDOMChildURL2> # Reported (child of ad ID) // // *Note: the best way to match the inputs and expectations in the body of the // test with the structure above, is to use URLs for resources, and the ID // attributes for DOM elements. TEST_F(ThreatDetailsTest, ThreatDOMDetails_TrimToAdTags) { // Create a child renderer inside the main frame to house the inner iframe. // Perform the navigation first in order to manipulate the frame tree. content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); content::RenderFrameHost* child_rfh = content::RenderFrameHostTester::For(main_rfh())->AppendChild("subframe"); // Define two sets of DOM nodes - one for an outer page containing an iframe, // and then another for the inner page containing the contents of that iframe. std::vector<mojom::ThreatDOMDetailsNodePtr> outer_params; mojom::ThreatDOMDetailsNodePtr outer_div = mojom::ThreatDOMDetailsNode::New(); outer_div->node_id = 1; outer_div->tag_name = "div"; outer_div->parent = GURL(kDOMParentURL); outer_div->attributes.push_back( mojom::AttributeNameValue::New("id", "outer")); outer_params.push_back(std::move(outer_div)); mojom::ThreatDOMDetailsNodePtr shared_resource_script = mojom::ThreatDOMDetailsNode::New(); shared_resource_script->node_id = 2; shared_resource_script->tag_name = "script"; shared_resource_script->url = GURL(kFirstRedirectURL); shared_resource_script->parent = GURL(kDOMParentURL); shared_resource_script->attributes.push_back( mojom::AttributeNameValue::New("id", "shared-resource")); outer_params.push_back(std::move(shared_resource_script)); mojom::ThreatDOMDetailsNodePtr outer_sibling_script = mojom::ThreatDOMDetailsNode::New(); outer_sibling_script->node_id = 3; outer_sibling_script->url = GURL(kReferrerURL); outer_sibling_script->child_node_ids.push_back(4); outer_sibling_script->child_node_ids.push_back(5); outer_sibling_script->tag_name = "script"; outer_sibling_script->parent = GURL(kDOMParentURL); outer_sibling_script->attributes.push_back( mojom::AttributeNameValue::New("src", kReferrerURL)); outer_sibling_script->attributes.push_back( mojom::AttributeNameValue::New("id", "outer-sibling")); outer_params.push_back(std::move(outer_sibling_script)); mojom::ThreatDOMDetailsNodePtr sibling_script = mojom::ThreatDOMDetailsNode::New(); sibling_script->node_id = 4; sibling_script->url = GURL(kFirstRedirectURL); sibling_script->tag_name = "script"; sibling_script->parent = GURL(kDOMParentURL); sibling_script->parent_node_id = 3; sibling_script->attributes.push_back( mojom::AttributeNameValue::New("src", kFirstRedirectURL)); sibling_script->attributes.push_back( mojom::AttributeNameValue::New("id", "sibling")); outer_params.push_back(std::move(sibling_script)); mojom::ThreatDOMDetailsNodePtr outer_ad_tag_div = mojom::ThreatDOMDetailsNode::New(); outer_ad_tag_div->node_id = 5; outer_ad_tag_div->parent_node_id = 3; outer_ad_tag_div->child_node_ids.push_back(6); outer_ad_tag_div->tag_name = "div"; outer_ad_tag_div->parent = GURL(kDOMParentURL); outer_ad_tag_div->attributes.push_back( mojom::AttributeNameValue::New("data-google-query-id", "ad-tag")); outer_params.push_back(std::move(outer_ad_tag_div)); mojom::ThreatDOMDetailsNodePtr outer_child_iframe = mojom::ThreatDOMDetailsNode::New(); outer_child_iframe->node_id = 6; outer_child_iframe->parent_node_id = 5; outer_child_iframe->url = GURL(kDOMChildURL); outer_child_iframe->tag_name = "iframe"; outer_child_iframe->parent = GURL(kDOMParentURL); outer_child_iframe->attributes.push_back( mojom::AttributeNameValue::New("src", kDOMChildURL)); outer_child_iframe->attributes.push_back( mojom::AttributeNameValue::New("foo", "bar")); outer_child_iframe->child_frame_routing_id = child_rfh->GetRoutingID(); outer_params.push_back(std::move(outer_child_iframe)); mojom::ThreatDOMDetailsNodePtr outer_summary_node = mojom::ThreatDOMDetailsNode::New(); outer_summary_node->url = GURL(kDOMParentURL); outer_summary_node->children.push_back(GURL(kDOMChildURL)); outer_summary_node->children.push_back(GURL(kReferrerURL)); outer_summary_node->children.push_back(GURL(kFirstRedirectURL)); outer_params.push_back(std::move(outer_summary_node)); // Now define some more nodes for the body of the iframe. std::vector<mojom::ThreatDOMDetailsNodePtr> inner_params; mojom::ThreatDOMDetailsNodePtr inner_child_div = mojom::ThreatDOMDetailsNode::New(); inner_child_div->node_id = 1; inner_child_div->tag_name = "div"; inner_child_div->parent = GURL(kDOMChildURL); inner_child_div->attributes.push_back( mojom::AttributeNameValue::New("id", "inner")); inner_child_div->attributes.push_back( mojom::AttributeNameValue::New("bar", "baz")); inner_params.push_back(std::move(inner_child_div)); mojom::ThreatDOMDetailsNodePtr inner_child_script = mojom::ThreatDOMDetailsNode::New(); inner_child_script->node_id = 2; inner_child_script->url = GURL(kDOMChildUrl2); inner_child_script->tag_name = "script"; inner_child_script->parent = GURL(kDOMChildURL); inner_child_script->attributes.push_back( mojom::AttributeNameValue::New("src", kDOMChildUrl2)); inner_params.push_back(std::move(inner_child_script)); mojom::ThreatDOMDetailsNodePtr inner_summary_node = mojom::ThreatDOMDetailsNode::New(); inner_summary_node->url = GURL(kDOMChildURL); inner_summary_node->children.push_back(GURL(kDOMChildUrl2)); inner_params.push_back(std::move(inner_summary_node)); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_UNWANTED); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(false); expected.set_repeat_visit(false); expected.set_complete(false); // Since the cache was missing. ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); ClientSafeBrowsingReportRequest::Resource* res_dom_child2 = expected.add_resources(); res_dom_child2->set_id(2); res_dom_child2->set_url(kDOMChildUrl2); res_dom_child2->set_parent_id(3); res_dom_child2->set_tag_name("script"); ClientSafeBrowsingReportRequest::Resource* res_dom_child = expected.add_resources(); res_dom_child->set_id(3); res_dom_child->set_url(kDOMChildURL); res_dom_child->set_parent_id(5); res_dom_child->add_child_ids(2); res_dom_child->set_tag_name("iframe"); ClientSafeBrowsingReportRequest::Resource* res_ad_parent = expected.add_resources(); res_ad_parent->set_id(6); res_ad_parent->set_url(kReferrerURL); res_ad_parent->set_parent_id(5); res_ad_parent->set_tag_name("script"); ClientSafeBrowsingReportRequest::Resource* res_sibling = expected.add_resources(); res_sibling->set_id(4); res_sibling->set_url(kFirstRedirectURL); res_sibling->set_parent_id(5); res_sibling->set_tag_name("script"); ClientSafeBrowsingReportRequest::Resource* res_dom_parent = expected.add_resources(); res_dom_parent->set_id(5); res_dom_parent->set_url(kDOMParentURL); res_dom_parent->add_child_ids(3); res_dom_parent->add_child_ids(6); res_dom_parent->add_child_ids(4); HTMLElement* elem_dom_parent_script = expected.add_dom(); elem_dom_parent_script->set_id(4); elem_dom_parent_script->set_tag("SCRIPT"); elem_dom_parent_script->set_resource_id(res_ad_parent->id()); elem_dom_parent_script->add_attribute()->set_name("src"); elem_dom_parent_script->mutable_attribute(0)->set_value(kReferrerURL); elem_dom_parent_script->add_attribute()->set_name("id"); elem_dom_parent_script->mutable_attribute(1)->set_value("outer-sibling"); elem_dom_parent_script->add_child_ids(5); elem_dom_parent_script->add_child_ids(6); HTMLElement* elem_dom_sibling_script = expected.add_dom(); elem_dom_sibling_script->set_id(5); elem_dom_sibling_script->set_tag("SCRIPT"); elem_dom_sibling_script->set_resource_id(res_sibling->id()); elem_dom_sibling_script->add_attribute()->set_name("src"); elem_dom_sibling_script->mutable_attribute(0)->set_value(kFirstRedirectURL); elem_dom_sibling_script->add_attribute()->set_name("id"); elem_dom_sibling_script->mutable_attribute(1)->set_value("sibling"); HTMLElement* elem_dom_ad_tag_div = expected.add_dom(); elem_dom_ad_tag_div->set_id(6); elem_dom_ad_tag_div->set_tag("DIV"); elem_dom_ad_tag_div->add_attribute()->set_name("data-google-query-id"); elem_dom_ad_tag_div->mutable_attribute(0)->set_value("ad-tag"); elem_dom_ad_tag_div->add_child_ids(7); HTMLElement* elem_dom_outer_iframe = expected.add_dom(); elem_dom_outer_iframe->set_id(7); elem_dom_outer_iframe->set_tag("IFRAME"); elem_dom_outer_iframe->set_resource_id(res_dom_child->id()); elem_dom_outer_iframe->add_attribute()->set_name("src"); elem_dom_outer_iframe->mutable_attribute(0)->set_value(kDOMChildURL); elem_dom_outer_iframe->add_attribute()->set_name("foo"); elem_dom_outer_iframe->mutable_attribute(1)->set_value("bar"); elem_dom_outer_iframe->add_child_ids(0); elem_dom_outer_iframe->add_child_ids(1); HTMLElement* elem_dom_inner_div = expected.add_dom(); elem_dom_inner_div->set_id(0); elem_dom_inner_div->set_tag("DIV"); elem_dom_inner_div->add_attribute()->set_name("id"); elem_dom_inner_div->mutable_attribute(0)->set_value("inner"); elem_dom_inner_div->add_attribute()->set_name("bar"); elem_dom_inner_div->mutable_attribute(1)->set_value("baz"); HTMLElement* elem_dom_inner_script = expected.add_dom(); elem_dom_inner_script->set_id(1); elem_dom_inner_script->set_tag("SCRIPT"); elem_dom_inner_script->set_resource_id(res_dom_child2->id()); elem_dom_inner_script->add_attribute()->set_name("src"); elem_dom_inner_script->mutable_attribute(0)->set_value(kDOMChildUrl2); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_UNWANTED, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); // Send both sets of nodes, from different render frames. auto trimmed_report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get(), /*trim_to_ad_tags=*/true); trimmed_report->StartCollection(); // Send both sets of nodes from different render frames. trimmed_report->OnReceivedThreatDOMDetails( mojo::Remote<mojom::ThreatReporter>(), child_rfh, std::move(inner_params)); trimmed_report->OnReceivedThreatDOMDetails( mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(outer_params)); std::string serialized = WaitForThreatDetailsDone( trimmed_report.get(), false /* did_proceed*/, 0 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); VerifyResults(actual, expected); } // Tests that an empty report does not get sent. Empty reports can result from // trying to trim a report to ad tags when no ad tags are present. // This test uses the following structure. // kDOMParentURL // \- <frame src=kDataURL> // \- <script src=kDOMChildURL2> TEST_F(ThreatDetailsTest, ThreatDOMDetails_EmptyReportNotSent) { // Create a child renderer inside the main frame to house the inner iframe. // Perform the navigation first in order to manipulate the frame tree. content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); content::RenderFrameHost* child_rfh = content::RenderFrameHostTester::For(main_rfh())->AppendChild("subframe"); // Define two sets of DOM nodes - one for an outer page containing a frame, // and then another for the inner page containing the contents of that frame. std::vector<mojom::ThreatDOMDetailsNodePtr> outer_params; mojom::ThreatDOMDetailsNodePtr outer_child_node = mojom::ThreatDOMDetailsNode::New(); outer_child_node->url = GURL(kDataURL); outer_child_node->tag_name = "frame"; outer_child_node->parent = GURL(kDOMParentURL); outer_child_node->attributes.push_back( mojom::AttributeNameValue::New("src", kDataURL)); outer_params.push_back(std::move(outer_child_node)); mojom::ThreatDOMDetailsNodePtr outer_summary_node = mojom::ThreatDOMDetailsNode::New(); outer_summary_node->url = GURL(kDOMParentURL); outer_summary_node->children.push_back(GURL(kDataURL)); // Set |child_frame_routing_id| for this node to something non-sensical so // that the child frame lookup fails. outer_summary_node->child_frame_routing_id = -100; outer_params.push_back(std::move(outer_summary_node)); // Now define some more nodes for the body of the frame. The URL of this // inner frame is "about:blank". std::vector<mojom::ThreatDOMDetailsNodePtr> inner_params; mojom::ThreatDOMDetailsNodePtr inner_child_node = mojom::ThreatDOMDetailsNode::New(); inner_child_node->url = GURL(kDOMChildUrl2); inner_child_node->tag_name = "script"; inner_child_node->parent = GURL(kBlankURL); inner_child_node->attributes.push_back( mojom::AttributeNameValue::New("src", kDOMChildUrl2)); inner_params.push_back(std::move(inner_child_node)); mojom::ThreatDOMDetailsNodePtr inner_summary_node = mojom::ThreatDOMDetailsNode::New(); inner_summary_node->url = GURL(kBlankURL); inner_summary_node->children.push_back(GURL(kDOMChildUrl2)); inner_params.push_back(std::move(inner_summary_node)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_UNWANTED, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); // Send both sets of nodes, from different render frames. auto trimmed_report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get(), /*trim_to_ad_tags=*/true); trimmed_report->StartCollection(); // Send both sets of nodes from different render frames. trimmed_report->OnReceivedThreatDOMDetails( mojo::Remote<mojom::ThreatReporter>(), child_rfh, std::move(inner_params)); trimmed_report->OnReceivedThreatDOMDetails( mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(outer_params)); std::string serialized = WaitForThreatDetailsDone( trimmed_report.get(), false /* did_proceed*/, 0 /* num_visit */); EXPECT_FALSE(ReportWasSent()); } // Tests creating a threat report of a malware page where there are redirect // urls to an unsafe resource url. TEST_F(ThreatDetailsTest, ThreatWithRedirectUrl) { content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_MALWARE, ThreatSource::REMOTE, true /* is_subresource */, GURL(kThreatURL), &resource); resource.original_url = GURL(kOriginalLandingURL); // add some redirect urls resource.redirect_urls.push_back(GURL(kFirstRedirectURL)); resource.redirect_urls.push_back(GURL(kSecondRedirectURL)); resource.redirect_urls.push_back(GURL(kThreatURL)); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, 0 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_MALWARE); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::ANDROID_SAFETYNET); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(true); expected.set_repeat_visit(false); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kOriginalLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_url(kThreatURL); pb_resource->set_parent_id(4); pb_resource = expected.add_resources(); pb_resource->set_id(3); pb_resource->set_url(kFirstRedirectURL); pb_resource->set_parent_id(1); pb_resource = expected.add_resources(); pb_resource->set_id(4); pb_resource->set_url(kSecondRedirectURL); pb_resource->set_parent_id(3); VerifyResults(actual, expected); } // Test collecting threat details for a blocked main frame load. TEST_F(ThreatDetailsTest, ThreatOnMainPageLoadBlocked) { const char* kUnrelatedReferrerURL = "http://www.unrelatedreferrer.com/some/path"; const char* kUnrelatedURL = "http://www.unrelated.com/some/path"; // Load and commit an unrelated URL. The ThreatDetails should not use this // navigation entry. auto navigation = content::NavigationSimulator::CreateBrowserInitiated( GURL(kUnrelatedURL), web_contents()); navigation->SetReferrer(blink::mojom::Referrer::New( GURL(kUnrelatedReferrerURL), network::mojom::ReferrerPolicy::kDefault)); navigation->Commit(); // Start a pending load with a referrer. controller().LoadURL( GURL(kLandingURL), content::Referrer(GURL(kReferrerURL), network::mojom::ReferrerPolicy::kDefault), ui::PAGE_TRANSITION_TYPED, std::string()); // Create UnsafeResource for the pending main page load. UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_MALWARE, ThreatSource::UNKNOWN, false /* is_subresource */, GURL(kLandingURL), &resource); // Start ThreatDetails collection. auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); // Simulate clicking don't proceed. controller().DiscardNonCommittedEntries(); // Finish ThreatDetails collection. std::string serialized = WaitForThreatDetailsDone( report.get(), false /* did_proceed*/, 1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_MALWARE); expected.set_url(kLandingURL); expected.set_page_url(kLandingURL); // Note that the referrer policy is not actually enacted here, since that's // done in Blink. expected.set_referrer_url(kReferrerURL); expected.set_did_proceed(false); expected.set_repeat_visit(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kReferrerURL); VerifyResults(actual, expected); } // Tests that a pending load does not interfere with collecting threat details // for the committed page. TEST_F(ThreatDetailsTest, ThreatWithPendingLoad) { const char* kPendingReferrerURL = "http://www.pendingreferrer.com/some/path"; const char* kPendingURL = "http://www.pending.com/some/path"; // Load and commit the landing URL with a referrer. auto navigation = content::NavigationSimulator::CreateBrowserInitiated( GURL(kLandingURL), web_contents()); navigation->SetReferrer(blink::mojom::Referrer::New( GURL(kReferrerURL), network::mojom::ReferrerPolicy::kDefault)); navigation->Commit(); // Create UnsafeResource for fake sub-resource of landing page. UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_MALWARE, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); // Start a pending load before creating ThreatDetails. controller().LoadURL( GURL(kPendingURL), content::Referrer(GURL(kPendingReferrerURL), network::mojom::ReferrerPolicy::kDefault), ui::PAGE_TRANSITION_TYPED, std::string()); // Do ThreatDetails collection. auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, 1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_MALWARE); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); // The referrer is stripped to its origin because it's a cross-origin URL. expected.set_referrer_url( GURL(kReferrerURL).DeprecatedGetOriginAsURL().spec()); expected.set_did_proceed(true); expected.set_repeat_visit(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_url(GURL(kReferrerURL).DeprecatedGetOriginAsURL().spec()); VerifyResults(actual, expected); } TEST_F(ThreatDetailsTest, ThreatOnFreshTab) { // A fresh WebContents should not have any NavigationEntries yet. (See // https://crbug.com/524208.) EXPECT_EQ(nullptr, controller().GetLastCommittedEntry()); EXPECT_EQ(nullptr, controller().GetPendingEntry()); // Initiate the connection to a (pretend) renderer process. NavigateAndCommit(GURL("about:blank")); // Simulate a subresource malware hit (this could happen if the WebContents // was created with window.open, and had content injected into it). UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_MALWARE, ThreatSource::CLIENT_SIDE_DETECTION, true /* is_subresource */, GURL(kThreatURL), &resource); // Do ThreatDetails collection. auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, 1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_MALWARE); expected.set_url(kThreatURL); expected.set_did_proceed(true); expected.set_repeat_visit(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kThreatURL); VerifyResults(actual, expected); } // Tests the interaction with the HTTP cache. TEST_F(ThreatDetailsTest, HTTPCache) { content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_CLIENT_SIDE_PHISHING, ThreatSource::CLIENT_SIDE_DETECTION, true /* is_subresource */, GURL(kThreatURL), &resource); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, test_shared_loader_factory_, history_service(), referrer_chain_provider_.get()); report->StartCollection(); SimulateFillCache(kThreatURL); // The cache collection starts after the IPC from the DOM is fired. std::vector<mojom::ThreatDOMDetailsNodePtr> params; report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(params)); // Let the cache callbacks complete. base::RunLoop().RunUntilIdle(); DVLOG(1) << "Getting serialized report"; std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, -1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_CLIENT_SIDE_PHISHING); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); ClientSafeBrowsingReportRequest::HTTPResponse* pb_response = pb_resource->mutable_response(); pb_response->mutable_firstline()->set_code(200); ClientSafeBrowsingReportRequest::HTTPHeader* pb_header = pb_response->add_headers(); pb_header->set_name("Content-Type"); pb_header->set_value("text/html"); pb_header = pb_response->add_headers(); pb_header->set_name("Content-Length"); pb_header->set_value("1024"); pb_response->set_body(kLandingData); std::string landing_data(kLandingData); pb_response->set_bodylength(landing_data.size()); pb_response->set_bodydigest(base::MD5String(landing_data)); pb_response->set_remote_ip("1.2.3.4:80"); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); pb_response = pb_resource->mutable_response(); pb_response->mutable_firstline()->set_code(200); pb_header = pb_response->add_headers(); pb_header->set_name("Content-Type"); pb_header->set_value("image/jpeg"); pb_header = pb_response->add_headers(); pb_header->set_name("Some-Other-Header"); pb_header->set_value("foo"); pb_response->set_body(kThreatData); std::string threat_data(kThreatData); pb_response->set_bodylength(threat_data.size()); pb_response->set_bodydigest(base::MD5String(threat_data)); pb_response->set_remote_ip("1.2.3.4:80"); expected.set_complete(true); VerifyResults(actual, expected); } // Test that only some fields of the HTTPS resource (eg: allowlisted headers) // are reported. TEST_F(ThreatDetailsTest, HttpsResourceSanitization) { content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_CLIENT_SIDE_PHISHING, ThreatSource::CLIENT_SIDE_DETECTION, true /* is_subresource */, GURL(kThreatURLHttps), &resource); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, test_shared_loader_factory_, history_service(), referrer_chain_provider_.get()); report->StartCollection(); SimulateFillCache(kThreatURLHttps); // The cache collection starts after the IPC from the DOM is fired. std::vector<mojom::ThreatDOMDetailsNodePtr> params; report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(params)); // Let the cache callbacks complete. base::RunLoop().RunUntilIdle(); DVLOG(1) << "Getting serialized report"; std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, -1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_CLIENT_SIDE_PHISHING); expected.set_url(kThreatURLHttps); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); ClientSafeBrowsingReportRequest::HTTPResponse* pb_response = pb_resource->mutable_response(); pb_response->mutable_firstline()->set_code(200); ClientSafeBrowsingReportRequest::HTTPHeader* pb_header = pb_response->add_headers(); pb_header->set_name("Content-Type"); pb_header->set_value("text/html"); pb_header = pb_response->add_headers(); pb_header->set_name("Content-Length"); pb_header->set_value("1024"); pb_response->set_body(kLandingData); std::string landing_data(kLandingData); pb_response->set_bodylength(landing_data.size()); pb_response->set_bodydigest(base::MD5String(landing_data)); pb_response->set_remote_ip("1.2.3.4:80"); // The threat URL is HTTP so the request and response are cleared (except for // allowlisted headers and certain safe fields). Namely the firstline and body // are missing. pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURLHttps); pb_response = pb_resource->mutable_response(); pb_header = pb_response->add_headers(); pb_header->set_name("Content-Type"); pb_header->set_value("image/jpeg"); std::string threat_data(kThreatData); pb_response->set_bodylength(threat_data.size()); pb_response->set_bodydigest(base::MD5String(threat_data)); pb_response->set_remote_ip("1.2.3.4:80"); expected.set_complete(true); VerifyResults(actual, expected); } // Tests the interaction with the HTTP cache (where the cache is empty). TEST_F(ThreatDetailsTest, HTTPCacheNoEntries) { content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_CLIENT_SIDE_MALWARE, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, test_shared_loader_factory_, history_service(), referrer_chain_provider_.get()); report->StartCollection(); // Simulate no cache entry found. test_url_loader_factory_.AddResponse( GURL(kThreatURL), network::mojom::URLResponseHead::New(), std::string(), network::URLLoaderCompletionStatus(net::ERR_CACHE_MISS)); test_url_loader_factory_.AddResponse( GURL(kLandingURL), network::mojom::URLResponseHead::New(), std::string(), network::URLLoaderCompletionStatus(net::ERR_CACHE_MISS)); // The cache collection starts after the IPC from the DOM is fired. std::vector<mojom::ThreatDOMDetailsNodePtr> params; report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(params)); // Let the cache callbacks complete. base::RunLoop().RunUntilIdle(); DVLOG(1) << "Getting serialized report"; std::string serialized = WaitForThreatDetailsDone( report.get(), false /* did_proceed*/, -1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_CLIENT_SIDE_MALWARE); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(false); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_url(kThreatURL); expected.set_complete(true); VerifyResults(actual, expected); } // Test getting redirects from history service. TEST_F(ThreatDetailsTest, HistoryServiceUrls) { // Add content to history service. // There are two redirect urls before reacing malware url: // kFirstRedirectURL -> kSecondRedirectURL -> kThreatURL GURL baseurl(kThreatURL); history::RedirectList redirects; redirects.push_back(GURL(kFirstRedirectURL)); redirects.push_back(GURL(kSecondRedirectURL)); AddPageToHistory(baseurl, &redirects); // Wait for history service operation finished. profile()->BlockUntilHistoryProcessesPendingRequests(); content::WebContentsTester::For(web_contents()) ->NavigateAndCommit(GURL(kLandingURL)); UnsafeResource resource; InitResource(SB_THREAT_TYPE_URL_MALWARE, ThreatSource::LOCAL_PVER4, true /* is_subresource */, GURL(kThreatURL), &resource); auto report = std::make_unique<ThreatDetailsWrap>( ui_manager_.get(), web_contents(), resource, nullptr, history_service(), referrer_chain_provider_.get()); report->StartCollection(); // The redirects collection starts after the IPC from the DOM is fired. std::vector<mojom::ThreatDOMDetailsNodePtr> params; report->OnReceivedThreatDOMDetails(mojo::Remote<mojom::ThreatReporter>(), main_rfh(), std::move(params)); // Let the redirects callbacks complete. base::RunLoop().RunUntilIdle(); std::string serialized = WaitForThreatDetailsDone( report.get(), true /* did_proceed*/, 1 /* num_visit */); ClientSafeBrowsingReportRequest actual; actual.ParseFromString(serialized); ClientSafeBrowsingReportRequest expected; expected.set_type(ClientSafeBrowsingReportRequest::URL_MALWARE); expected.mutable_client_properties()->set_url_api_type( ClientSafeBrowsingReportRequest::PVER4_NATIVE); expected.set_url(kThreatURL); expected.set_page_url(kLandingURL); expected.set_referrer_url(""); expected.set_did_proceed(true); expected.set_repeat_visit(true); ClientSafeBrowsingReportRequest::Resource* pb_resource = expected.add_resources(); pb_resource->set_id(0); pb_resource->set_url(kLandingURL); pb_resource = expected.add_resources(); pb_resource->set_id(1); pb_resource->set_parent_id(2); pb_resource->set_url(kThreatURL); pb_resource = expected.add_resources(); pb_resource->set_id(2); pb_resource->set_parent_id(3); pb_resource->set_url(kSecondRedirectURL); pb_resource = expected.add_resources(); pb_resource->set_id(3); pb_resource->set_url(kFirstRedirectURL); VerifyResults(actual, expected); } } // namespace safe_browsing
bsd-3-clause
giacomov/3ML
threeML/io/serialization.py
754
from future import standard_library standard_library.install_aliases() from threeML.classicMLE.joint_likelihood import JointLikelihood from threeML.bayesian.bayesian_analysis import BayesianAnalysis __all__ = [] # copyreg is called copy_reg in python2 try: import copyreg # py3 except ImportError: import copyreg as copyreg # py2 # Serialization for JointLikelihood object def pickle_joint_likelihood(jl): return JointLikelihood, (jl.likelihood_model, jl.data_list) copyreg.pickle(JointLikelihood, pickle_joint_likelihood) # Serialization for BayesianAnalysis object def pickle_bayesian_analysis(bs): return BayesianAnalysis, (bs.likelihood_model, bs.data_list) copyreg.pickle(BayesianAnalysis, pickle_bayesian_analysis)
bsd-3-clause
alexseyka1/efir.city
vendor/composer/autoload_real.php
2333
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit53f0f37c0cd56dd1cdf5343164ffba14 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit53f0f37c0cd56dd1cdf5343164ffba14', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit53f0f37c0cd56dd1cdf5343164ffba14', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION'); if ($useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit53f0f37c0cd56dd1cdf5343164ffba14::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); if ($useStaticLoader) { $includeFiles = Composer\Autoload\ComposerStaticInit53f0f37c0cd56dd1cdf5343164ffba14::$files; } else { $includeFiles = require __DIR__ . '/autoload_files.php'; } foreach ($includeFiles as $fileIdentifier => $file) { composerRequire53f0f37c0cd56dd1cdf5343164ffba14($fileIdentifier, $file); } return $loader; } } function composerRequire53f0f37c0cd56dd1cdf5343164ffba14($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { require $file; $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; } }
bsd-3-clause
liangwang/m5
src/arch/arm/linux/linux.hh
6295
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007-2008 The Florida State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_LINUX_LINUX_HH__ #define __ARCH_ARM_LINUX_LINUX_HH__ #include "kern/linux/linux.hh" class ArmLinux : public Linux { public: /// This table maps the target open() flags to the corresponding /// host open() flags. static OpenFlagTransTable openFlagTable[]; /// Number of entries in openFlagTable[]. static const int NUM_OPEN_FLAGS; //@{ /// open(2) flag values. static const int TGT_O_RDONLY = 00000000; //!< O_RDONLY static const int TGT_O_WRONLY = 00000001; //!< O_WRONLY static const int TGT_O_RDWR = 00000002; //!< O_RDWR static const int TGT_O_CREAT = 00000100; //!< O_CREAT static const int TGT_O_EXCL = 00000200; //!< O_EXCL static const int TGT_O_NOCTTY = 00000400; //!< O_NOCTTY static const int TGT_O_TRUNC = 00001000; //!< O_TRUNC static const int TGT_O_APPEND = 00002000; //!< O_APPEND static const int TGT_O_NONBLOCK = 00004000; //!< O_NONBLOCK static const int TGT_O_SYNC = 00010000; //!< O_SYNC static const int TGT_FASYNC = 00020000; //!< FASYNC static const int TGT_O_DIRECTORY = 00040000; //!< O_DIRECTORY static const int TGT_O_NOFOLLOW = 00100000; //!< O_NOFOLLOW static const int TGT_O_DIRECT = 00200000; //!< O_DIRECT static const int TGT_O_LARGEFILE = 00400000; //!< O_LARGEFILE static const int TGT_O_NOATIME = 01000000; //!< O_NOATIME //@} /// For mmap(). static const unsigned TGT_MAP_ANONYMOUS = 0x20; //@{ /// For getrusage(). static const int TGT_RUSAGE_SELF = 0; static const int TGT_RUSAGE_CHILDREN = -1; static const int TGT_RUSAGE_BOTH = -2; //@} //@{ /// ioctl() command codes. static const unsigned TIOCGETP_ = 0x5401; static const unsigned TIOCSETP_ = 0x80067409; static const unsigned TIOCSETN_ = 0x8006740a; static const unsigned TIOCSETC_ = 0x80067411; static const unsigned TIOCGETC_ = 0x40067412; static const unsigned FIONREAD_ = 0x4004667f; static const unsigned TIOCISATTY_ = 0x2000745e; static const unsigned TIOCGETS_ = 0x402c7413; static const unsigned TIOCGETA_ = 0x40127417; static const unsigned TCSETAW_ = 0x5407; // 2.6.15 kernel //@} /// For table(). static const int TBL_SYSINFO = 12; /// Resource enumeration for getrlimit(). enum rlimit_resources { TGT_RLIMIT_CPU = 0, TGT_RLIMIT_FSIZE = 1, TGT_RLIMIT_DATA = 2, TGT_RLIMIT_STACK = 3, TGT_RLIMIT_CORE = 4, TGT_RLIMIT_RSS = 5, TGT_RLIMIT_NPROC = 6, TGT_RLIMIT_NOFILE = 7, TGT_RLIMIT_MEMLOCK = 8, TGT_RLIMIT_AS = 9, TGT_RLIMIT_LOCKS = 10 }; typedef struct { uint32_t st_dev; uint32_t st_ino; uint16_t st_mode; uint16_t st_nlink; uint16_t st_uid; uint16_t st_gid; uint32_t st_rdev; uint32_t st_size; uint32_t st_blksize; uint32_t st_blocks; uint32_t st_atimeX; uint32_t st_atime_nsec; uint32_t st_mtimeX; uint32_t st_mtime_nsec; uint32_t st_ctimeX; uint32_t st_ctime_nsec; } tgt_stat; typedef struct { uint64_t st_dev; uint8_t __pad0[4]; uint32_t __st_ino; uint32_t st_mode; uint32_t st_nlink; uint32_t st_uid; uint32_t st_gid; uint64_t st_rdev; uint8_t __pad3[4]; int64_t __attribute__ ((aligned (8))) st_size; uint32_t st_blksize; uint64_t __attribute__ ((aligned (8))) st_blocks; uint32_t st_atimeX; uint32_t st_atime_nsec; uint32_t st_mtimeX; uint32_t st_mtime_nsec; uint32_t st_ctimeX; uint32_t st_ctime_nsec; uint64_t st_ino; } tgt_stat64; typedef struct { int32_t uptime; /* Seconds since boot */ uint32_t loads[3]; /* 1, 5, and 15 minute load averages */ uint32_t totalram; /* Total usable main memory size */ uint32_t freeram; /* Available memory size */ uint32_t sharedram; /* Amount of shared memory */ uint32_t bufferram; /* Memory used by buffers */ uint32_t totalswap; /* Total swap space size */ uint32_t freeswap; /* swap space still available */ uint16_t procs; /* Number of current processes */ uint32_t totalhigh; /* Total high memory size */ uint32_t freehigh; /* Available high memory size */ uint32_t mem_unit; /* Memory unit size in bytes */ } tgt_sysinfo; }; #endif
bsd-3-clause
adem-team/advanced
lukisongroup/master/models/KategoricusSearch.php
2209
<?php namespace lukisongroup\master\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use lukisongroup\master\models\Kategoricus; /** * KategoricusSearch represents the model behind the search form about `lukisongroup\esm\models\Kategoricus`. */ class KategoricusSearch extends Kategoricus { /** * @inheritdoc */ public function rules() { return [ [['CUST_KTG', 'CUST_KTG_PARENT', 'STATUS'], 'integer'], [['CUST_KTG_NM','CUST_KTG_PARENT','CUST_KTG', 'CREATED_BY', 'CREATED_AT', 'UPDATED_BY', 'UPDATED_AT'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } // public function cust() // { // } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function searchparent($params) { $query = Kategoricus::find() ->where('CUST_KTG_PARENT <> 0') ->orderBy('CUST_KTG_PARENT'); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 20, ], ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'CUST_KTG_NM' => $this->CUST_KTG_NM, 'CUST_KTG_PARENT' => $this->CUST_KTG_PARENT // 'CREATED_AT' => $this->CREATED_AT, // 'UPDATED_AT' => $this->UPDATED_AT, // 'STATUS' => $this->STATUS, ]); $query->andFilterWhere(['like', 'CUST_KTG_NM', $this->CUST_KTG_NM]) ->andFilterWhere(['like', 'CUST_KTG', $this->CUST_KTG]) ->andFilterWhere(['like', 'CUST_KTG_PARENT', $this->CUST_KTG_PARENT]); return $dataProvider; } }
bsd-3-clause
m-ishchenko/portal
tests/unit/fixtures/data/employeespositions.php
480
<?php return[ [ 'id' => '1', 'employee_id' => '1', 'position_id' => '10', ], [ 'id' => '2', 'employee_id' => '2', 'position_id' => '9', ], [ 'id' => '3', 'employee_id' => '3', 'position_id' => '9', ], [ 'id' => '4', 'employee_id' => '4', 'position_id' => '11', ] ];
bsd-3-clause
socam/qmlmessages
src/windowmanager.cpp
5730
/* Copyright (C) 2012 John Brooks <john.brooks@dereferenced.net> * * You may use this file under the terms of the BSD license as follows: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Nemo Mobile nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "windowmanager.h" #include "dbusadaptor.h" #include <QApplication> #include <QDeclarativeEngine> #include <QDeclarativeContext> #include <QDeclarativeItem> #include <QGraphicsView> #include <QGraphicsObject> #include <QDBusConnection> #include <QDBusInterface> static WindowManager *wmInstance = 0; WindowManager *WindowManager::instance() { if (!wmInstance) wmInstance = new WindowManager(qApp); return wmInstance; } WindowManager::WindowManager(QObject *parent) : QObject(parent), mEngine(0) { createScene(); new DBusAdaptor(this); QDBusConnection::sessionBus().registerService("org.nemomobile.qmlmessages"); if (!QDBusConnection::sessionBus().registerObject("/", this)) { qWarning() << "Cannot register DBus object!"; } } WindowManager::~WindowManager() { delete mWindow; delete mEngine; delete mScene; } void WindowManager::createScene() { if (mEngine) return; mEngine = new QDeclarativeEngine; mEngine->rootContext()->setContextProperty("windowManager", QVariant::fromValue<QObject*>(this)); mScene = new QGraphicsScene; // From QDeclarativeView mScene->setItemIndexMethod(QGraphicsScene::NoIndex); mScene->setStickyFocus(true); QDeclarativeComponent component(mEngine, QUrl("qrc:qml/main.qml")); if (!component.isReady()) { qWarning() << component.errors(); } mRootObject = static_cast<QGraphicsObject*>(component.create()); mScene->addItem(mRootObject); } void WindowManager::ensureWindow() { if (mWindow) return; createScene(); //QWeakPointer<QGraphicsView> mWindow; mWindow = new QGraphicsView; QGraphicsView *w = mWindow; // mWindow is a QWeakPointer, so it'll be cleared on delete w->setAttribute(Qt::WA_DeleteOnClose); w->setWindowTitle(tr("Messages")); w->setAttribute(Qt::WA_OpaquePaintEvent); w->setAttribute(Qt::WA_NoSystemBackground); w->viewport()->setAttribute(Qt::WA_OpaquePaintEvent); w->viewport()->setAttribute(Qt::WA_NoSystemBackground); // From QDeclarativeView w->setFrameStyle(0); w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); w->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); w->setOptimizationFlags(QGraphicsView::DontSavePainterState); w->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); w->viewport()->setFocusPolicy(Qt::NoFocus); w->setFocusPolicy(Qt::StrongFocus); w->setScene(mScene); QDeclarativeItem *i = qobject_cast<QDeclarativeItem*>(mRootObject); w->resize(i->width(), i->height()); w->setSceneRect(QRectF(0, 0, i->width(), i->height())); } void WindowManager::showGroupsWindow() { ensureWindow(); Q_ASSERT(mRootObject); bool ok = mRootObject->metaObject()->invokeMethod(mRootObject, "showGroupsList"); if (!ok) qWarning() << Q_FUNC_INFO << "showGroupsList call failed"; mWindow->showFullScreen(); mWindow->activateWindow(); mWindow->raise(); } void WindowManager::showConversation(const QString &localUid, const QString &remoteUid, unsigned type) { Q_UNUSED(type); ensureWindow(); Q_ASSERT(mRootObject); bool ok = mRootObject->metaObject()->invokeMethod(mRootObject, "showConversation", Q_ARG(QVariant, localUid), Q_ARG(QVariant, remoteUid)); if (!ok) qWarning() << Q_FUNC_INFO << "showConversation call failed"; mWindow->showFullScreen(); mWindow->activateWindow(); mWindow->raise(); } void WindowManager::emitToForeground() { emit toForeground(); } void WindowManager::notifyHistoryPageAccess() { QDBusConnection connection = QDBusConnection::sessionBus(); if (connection.isConnected()) { //Send notification to desktop's notification manager QDBusInterface* indicatorIface = new QDBusInterface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", connection); indicatorIface->call(QDBus::NoBlock, "clearCalls"); } }
bsd-3-clause
fresskarma/tinyos-1.x
tools/java/org/python/modules/sre/MatchObject.java
5391
/* * Copyright 2000 Finn Bock * * This program contains material copyrighted by: * Copyright (c) 1997-2000 by Secret Labs AB. All rights reserved. * * This version of the SRE library can be redistributed under CNRI's * Python 1.6 license. For any other use, please contact Secret Labs * AB (info@pythonware.com). * * Portions of this engine have been developed in cooperation with * CNRI. Hewlett-Packard provided funding for 1.6 integration and * other compatibility work. */ package org.python.modules.sre; import org.python.core.*; public class MatchObject extends PyObject { public String string; /* link to the target string */ public PyObject regs; /* cached list of matching spans */ PatternObject pattern; /* link to the regex (pattern) object */ int pos, endpos; /* current target slice */ int lastindex; /* last index marker seen by the engine (-1 if none) */ int groups; /* number of groups (start/end marks) */ int[] mark; public PyObject group(PyObject[] args) { switch (args.length) { case 0: return getslice(Py.Zero, Py.None); case 1: return getslice(args[0], Py.None); default: PyObject[] result = new PyObject[args.length]; for (int i = 0; i < args.length; i++) result[i] = getslice(args[i], Py.None); return new PyTuple(result); } } public PyObject groups(PyObject[] args, String[] kws) { ArgParser ap = new ArgParser("groups", args, kws, "default"); PyObject def = ap.getPyObject(0, Py.None); PyObject[] result = new PyObject[groups-1]; for (int i = 1; i < groups; i++) { result[i-1] = getslice_by_index(i, def); } return new PyTuple(result); } public PyObject groupdict(PyObject[] args, String[] kws) { ArgParser ap = new ArgParser("groupdict", args, kws, "default"); PyObject def = ap.getPyObject(0, Py.None); PyObject result = new PyDictionary(); if (pattern.groupindex == null) return result; PyObject keys = pattern.groupindex.invoke("keys"); PyObject key; for (int i = 0; (key = keys.__finditem__(i)) != null; i++) { PyObject item = getslice(key, def); result.__setitem__(key, item); } return result; } public PyObject start() { return start(Py.Zero); } public PyObject start(PyObject index_) { int index = getindex(index_); if (index < 0 || index >= groups) throw Py.IndexError("no such group"); return Py.newInteger(mark[index*2]); } public PyObject end() { return end(Py.Zero); } public PyObject end(PyObject index_) { int index = getindex(index_); if (index < 0 || index >= groups) throw Py.IndexError("no such group"); return Py.newInteger(mark[index*2+1]); } public PyTuple span() { return span(Py.Zero); } public PyTuple span(PyObject index_) { int index = getindex(index_); if (index < 0 || index >= groups) throw Py.IndexError("no such group"); int start = mark[index*2]; int end = mark[index*2+1]; return _pair(start, end); } public PyObject regs() { PyObject[] regs = new PyObject[groups]; for (int index = 0; index < groups; index++) { regs[index] = _pair(mark[index*2], mark[index*2+1]); } return new PyTuple(regs); } PyTuple _pair(int i1, int i2) { return new PyTuple(new PyObject[] { Py.newInteger(i1), Py.newInteger(i2) }); } private PyObject getslice(PyObject index, PyObject def) { return getslice_by_index(getindex(index), def); } private int getindex(PyObject index) { if (index instanceof PyInteger) return ((PyInteger) index).getValue(); int i = -1; if (pattern.groupindex != null) { index = pattern.groupindex.__finditem__(index); if (index != null) if (index instanceof PyInteger) return ((PyInteger) index).getValue(); } return i; } private PyObject getslice_by_index(int index, PyObject def) { if (index < 0 || index >= groups) throw Py.IndexError("no such group"); index *= 2; int start = mark[index]; int end = mark[index+1]; //System.out.println("group:" + index + " " + start + " " + // end + " l:" + string.length()); if (string == null || start < 0) return def; return new PyString(string.substring(start, end)); } public PyObject __findattr__(String key) { //System.out.println("__findattr__:" + key); if (key == "flags") return Py.newInteger(pattern.flags); if (key == "groupindex") return pattern.groupindex; if (key == "re") return pattern; if (key == "pos") return Py.newInteger(pos); if (key == "endpos") return Py.newInteger(endpos); if (key == "lastindex") return lastindex == -1 ? Py.None : Py.newInteger(lastindex); return super.__findattr__(key); } }
bsd-3-clause
brics/brics_3d
examples/wm_hdf5.cpp
3950
/****************************************************************************** * BRICS_3D - 3D Perception and Modeling Library * Copyright (c) 2017, KU Leuven * * Author: Sebastian Blumenthal * * * This software is published under a dual-license: GNU Lesser General Public * License LGPL 2.1 and Modified BSD license. The dual-license implies that * users of this code may choose which terms they prefer. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License LGPL and the BSD license for * more details. * ******************************************************************************/ /* * This example illustrates how o read a HDF5 append only log file. * */ /* BRICS_3D includes */ #include <brics_3d/core/Logger.h> #include <brics_3d/core/HomogeneousMatrix44.h> #include <brics_3d/worldModel/WorldModel.h> #include <brics_3d/worldModel/sceneGraph/UuidGenerator.h> #include <brics_3d/worldModel/sceneGraph/DotVisualizer.h> #include <brics_3d/worldModel/sceneGraph/HDF5UpdateSerializer.h> #include <brics_3d/worldModel/sceneGraph/HDF5UpdateDeserializer.h> #include <brics_3d/worldModel/sceneGraph/OSGVisualizer.h> using namespace brics_3d; using brics_3d::Logger; int main(int argc, char **argv) { LOG(INFO) << " HDF5 log file parser example."; if ((argc != 2) && (argc != 3)) { printf("Usage: %s input_file\n", *argv); return 1; } const char *fileName = argv[1]; /* Create a world model handle */ Logger::setMinLoglevel(Logger::LOGERROR); brics_3d::rsg::Id rootId; // Explicitly set the root Id (optional) /* * The rootId is the one and only information from the model we * to obtain at creation time. */ rootId = brics_3d::rsg::HDF5UpdateDeserializer::getRootIdFromAppendOnlyLogFile(fileName); LOG(INFO) << "Root id = " << rootId.toString(); brics_3d::WorldModel* wm = new brics_3d::WorldModel(new brics_3d::rsg::UuidGenerator(rootId)); /* Attach debug visualization */ brics_3d::rsg::DotVisualizer* graphVizualizer = new brics_3d::rsg::DotVisualizer(&wm->scene); // NOTE: the constructor // needs the world model handle. brics_3d::rsg::VisualizationConfiguration dotConfiguration; // Again, _optional_ configuration file. dotConfiguration.visualizeAttributes = true; // Vizualize attributes of a node iff true. dotConfiguration.visualizeIds = true; // Vizualize Ids of a node iff true. dotConfiguration.abbreviateIds = false; // Vizualize only the lower 2 bytes of anId iff true. graphVizualizer->setConfig(dotConfiguration); graphVizualizer->setKeepHistory(true); // Do not overwrite the produced files. Default is false. graphVizualizer->setFileName("hdf5_append_only_graph"); wm->scene.attachUpdateObserver(graphVizualizer); // Enable graph visualization #ifdef BRICS_OSG_ENABLE brics_3d::rsg::OSGVisualizer* geometryVizualizer = new brics_3d::rsg::OSGVisualizer(); // Create the visualizer. brics_3d::rsg::VisualizationConfiguration osgConfiguration; // _Optional_ configuration file. osgConfiguration.visualizeAttributes = true; // Vizualize attributes of a node iff true. osgConfiguration.visualizeIds = true; // Vizualize Ids of a node iff true. osgConfiguration.abbreviateIds = true; // Vizualize only the lower 2 bytes of an Id iff true. geometryVizualizer->setConfig(osgConfiguration); wm->scene.attachUpdateObserver(geometryVizualizer); // Enable 3D visualization wm->scene.advertiseRootNode(); #endif /* Do the actual HDF5 log file parsing. */ brics_3d::rsg::HDF5UpdateDeserializer deserializer(wm); deserializer.loadFromAppendOnlyLogFile(fileName); #ifdef BRICS_OSG_ENABLE /* Wait until user closes the GUI */ while(!geometryVizualizer->done()) { //nothing here } #endif return 0; } /* EOF */
bsd-3-clause
buptUnixGuys/jerasure-jni
jni/JJerasure.cpp
13978
#include <stdlib.h> #include "JJerasure.h" #include "jerasure.h" #include "javautility.h" #include "reed_sol.h" #define talloc(type, num) (type *) malloc(sizeof(type)*(num)) /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_matrix_to_bitmatrix * Signature: (III[I)[I */ JNIEXPORT jintArray JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1matrix_1to_1bitmatrix (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jmatrix) { bool outOfMemory = false; jintArray result = NULL; jint* matrix = env->GetIntArrayElements(jmatrix, NULL); if(matrix != NULL) { int* resultMatrix = jerasure_matrix_to_bitmatrix(k, m, w, (int*)matrix); if(resultMatrix != NULL) { result = env->NewIntArray(k*m*w*w); if(result != NULL) { env->SetIntArrayRegion(result, 0, k*m*w*w, (jint*)resultMatrix); } else { outOfMemory = true; } } else { outOfMemory = true; } free(resultMatrix); } else { outOfMemory = true; } if(outOfMemory) { throwOutOfMemoryError(env, "Could not allocate memory."); } env->ReleaseIntArrayElements(jmatrix, matrix, NULL); return result; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_do_parity * Signature: (I[Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;I)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1do_1parity (JNIEnv *env, jclass clazz, jint k, jobjectArray jdata_ptrs, jobject jparity_ptr, jint size) { char **data = convertFromBufferArray(env, jdata_ptrs); char *coding = (char*)env->GetDirectBufferAddress(jparity_ptr); jerasure_do_parity(k, data, coding, size); delete[] data; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_matrix_encode * Signature: (III[I[Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;I)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1matrix_1encode (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jmatrix, jobjectArray jdata_ptrs, jobjectArray jcoding_ptrs, jint size) { jint* matrix = env->GetIntArrayElements(jmatrix, NULL); if(matrix == NULL){ throwOutOfMemoryError(env, ""); } char **data = convertFromBufferArray(env, jdata_ptrs); char **coding = convertFromBufferArray(env, jcoding_ptrs); jerasure_matrix_encode(k, m ,w, (int*)matrix, data, coding, size); env->ReleaseIntArrayElements(jmatrix, matrix, NULL); delete[] data; delete[] coding; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_bitmatrix_encode * Signature: (III[I[Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;II)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1bitmatrix_1encode (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jbitmatrix, jobjectArray jdata_ptrs, jobjectArray jcoding_ptrs, jint size, jint packetsize) { jint* bitmatrix = env->GetIntArrayElements(jbitmatrix, NULL); if(bitmatrix == NULL){ throwOutOfMemoryError(env, ""); } char **data = convertFromBufferArray(env, jdata_ptrs); char **coding = convertFromBufferArray(env, jcoding_ptrs); jerasure_bitmatrix_encode(k,m,w, (int*)bitmatrix, data, coding, size, packetsize); env->ReleaseIntArrayElements(jbitmatrix, bitmatrix, NULL); delete[] data; delete[] coding; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_matrix_decode * Signature: (III[IZ[I[Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;I)Z */ JNIEXPORT jboolean JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1matrix_1decode (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jmatrix, jboolean row_k_ones, jintArray jerasures, jobjectArray jdata_ptrs, jobjectArray jcoding_ptrs, jint size) { int result = -1; jint *erasures = NULL, *matrix = NULL; erasures = env->GetIntArrayElements(jerasures, NULL); matrix = env->GetIntArrayElements(jmatrix, NULL); char **data = convertFromBufferArray(env, jdata_ptrs); char **coding = convertFromBufferArray(env, jcoding_ptrs); if(erasures != NULL && matrix != NULL){ result = jerasure_matrix_decode(k, m, w, (int*)matrix, (row_k_ones == JNI_TRUE ? 1 : 0), (int*)erasures, data, coding, size); } else { throwOutOfMemoryError(env, ""); } env->ReleaseIntArrayElements(jmatrix, matrix, NULL); env->ReleaseIntArrayElements(jerasures, erasures, NULL); delete[] data; delete[] coding; if(result == 0) return JNI_TRUE; return JNI_FALSE; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_bitmatrix_decode * Signature: (III[IZ[I[Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;II)Z */ JNIEXPORT jboolean JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1bitmatrix_1decode (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jbitmatrix, jboolean row_k_ones, jintArray jerasures, jobjectArray jdata_ptrs, jobjectArray jcoding_ptrs, jint size, jint packetsize) { int result = -1; jint *bitmatrix = NULL, *erasures = NULL; bitmatrix = env->GetIntArrayElements(jbitmatrix, NULL); erasures = env->GetIntArrayElements(jerasures, NULL); char **data = convertFromBufferArray(env, jdata_ptrs); char **coding = convertFromBufferArray(env, jcoding_ptrs); if(bitmatrix != NULL && erasures != NULL) { result = jerasure_bitmatrix_decode(k,m,w, (int*)bitmatrix, (row_k_ones == JNI_TRUE ? 1 : 0), (int*)erasures, data, coding, size, packetsize); } else { throwOutOfMemoryError(env, ""); } env->ReleaseIntArrayElements(jbitmatrix, bitmatrix, NULL); env->ReleaseIntArrayElements(jerasures, erasures, NULL); delete[] data; delete[] coding; if(result == 0) return JNI_TRUE; return JNI_FALSE; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_make_decoding_matrix * Signature: (III[I[Z[I[I)Z */ JNIEXPORT jboolean JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1make_1decoding_1matrix (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jmatrix, jbooleanArray jerased, jintArray jdecoding_matrix, jintArray jdm_ids) { int result = -1; int *erased = talloc(int, k+m); jboolean* erasedj = env->GetBooleanArrayElements(jerased, NULL); jint* matrix = env->GetIntArrayElements(jmatrix, NULL); jint* decoding_matrix = env->GetIntArrayElements(jdecoding_matrix, NULL); jint* dm_ids = env->GetIntArrayElements(jdm_ids, NULL); if(matrix != NULL && erased != NULL && erasedj != NULL && matrix != NULL && decoding_matrix != NULL && dm_ids != NULL) { for(int i = 0; i < (k+m); ++i) { if(erasedj[i] == JNI_TRUE) { erased[i] = 1; } else { erased[i] = 0; } } result = jerasure_make_decoding_matrix(k, m, w, (int*)matrix, erased, (int*)decoding_matrix, (int*)dm_ids); } else { throwOutOfMemoryError(env, ""); } env->ReleaseBooleanArrayElements(jerased, erasedj, NULL); env->ReleaseIntArrayElements(jmatrix, matrix, NULL); env->ReleaseIntArrayElements(jdecoding_matrix, decoding_matrix, NULL); env->ReleaseIntArrayElements(jdm_ids, dm_ids, NULL); free(erased); if(result == 0) return JNI_TRUE; return JNI_FALSE; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_make_decoding_bitmatrix * Signature: (III[I[Z[I[I)Z */ JNIEXPORT jboolean JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1make_1decoding_1bitmatrix (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jintArray jmatrix, jbooleanArray jerased, jintArray jdecoding_matrix, jintArray jdm_ids) { int result = -1; int* erased = talloc(int, k+m); jboolean* erasedj = env->GetBooleanArrayElements(jerased, NULL); jint* dm_ids = env->GetIntArrayElements(jdm_ids, NULL); jint* decoding_matrix = env->GetIntArrayElements(jdecoding_matrix, NULL); jint* matrix = env->GetIntArrayElements(jmatrix, NULL); if(erasedj != NULL && erased != NULL && dm_ids != NULL && decoding_matrix != NULL && matrix != NULL) { for(int i = 0; i < k+m; ++i) { if(erasedj[i] == JNI_TRUE) { erased[i] = 1; } else { erased[i] = 0; } } result = jerasure_make_decoding_bitmatrix(k, m, w, (int*)matrix, erased, (int*)decoding_matrix, (int*)dm_ids); } else { throwOutOfMemoryError(env, ""); } free(erased); env->ReleaseBooleanArrayElements(jerased, erasedj, NULL); env->ReleaseIntArrayElements(jdm_ids, dm_ids, NULL); env->ReleaseIntArrayElements(jdecoding_matrix, decoding_matrix, NULL); env->ReleaseIntArrayElements(jmatrix, matrix, NULL); if(result == 0) return JNI_TRUE; return JNI_FALSE; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_erasures_to_erased * Signature: (II[I)[Z */ JNIEXPORT jbooleanArray JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1erasures_1to_1erased (JNIEnv *env, jclass clazz, jint k, jint m, jintArray jerasures) { bool outOfMemory = false; jbooleanArray result; jint* erasures = env->GetIntArrayElements(jerasures, NULL); if(erasures != NULL) { int *erased = jerasure_erasures_to_erased(k,m,(int*)erasures); if(erased != NULL) { result = env->NewBooleanArray(k+m); if(result != NULL) { jboolean* resultValues = env->GetBooleanArrayElements(result, NULL); for(int i = 0; i < k+m; ++i) { resultValues[i] = (erased[i] == 1 ? JNI_TRUE : JNI_FALSE); } env->ReleaseBooleanArrayElements(result, resultValues, NULL); } else { outOfMemory = true; } } else { outOfMemory = true; } free(erased); } else { outOfMemory = true; } if(outOfMemory) { throwOutOfMemoryError(env, ""); } env->ReleaseIntArrayElements(jerasures, erasures, NULL); return result; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_matrix_dotprod * Signature: (II[I[II[[B[[BI)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1matrix_1dotprod (JNIEnv *env, jclass clazz, jint, jint, jintArray, jintArray, jint, jobjectArray, jobjectArray, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_bitmatrix_dotprod * Signature: (II[I[II[[B[[BII)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1bitmatrix_1dotprod (JNIEnv *env, jclass clazz, jint, jint, jintArray, jintArray, jint, jobjectArray, jobjectArray, jint, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_invert_matrix * Signature: ([I[III)I */ JNIEXPORT jint JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1invert_1matrix (JNIEnv *env, jclass clazz, jintArray, jintArray, jint, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_invert_bitmatrix * Signature: ([I[II)I */ JNIEXPORT jint JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1invert_1bitmatrix (JNIEnv *env, jclass clazz, jintArray, jintArray, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_invertible_matrix * Signature: ([III)I */ JNIEXPORT jint JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1invertible_1matrix (JNIEnv *env, jclass clazz, jintArray, jint, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_invertible_bitmatrix * Signature: ([II)I */ JNIEXPORT jint JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1invertible_1bitmatrix (JNIEnv *env, jclass clazz, jintArray, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_print_matrix * Signature: ([IIII)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1print_1matrix (JNIEnv *env, jclass clazz, jintArray, jint, jint, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_print_bitmatrix * Signature: ([IIII)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1print_1bitmatrix (JNIEnv *env, jclass clazz, jintArray, jint, jint, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_matrix_multiply * Signature: ([I[IIIIII)[I */ JNIEXPORT jintArray JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1matrix_1multiply (JNIEnv *env, jclass clazz, jintArray, jintArray, jint, jint, jint, jint, jint); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: jerasure_get_stats * Signature: ([D)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_jerasure_1get_1stats (JNIEnv *env, jclass clazz, jdoubleArray); /* * Class: cn_ctyun_ec_jni_Jerasure * Method: my_jerasure_matrix_encode * Signature: (IIIJ[Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;I)V */ JNIEXPORT void JNICALL Java_cn_ctyun_ec_jni_Jerasure_my_1jerasure_1matrix_1encode (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jlong jmatrixId, jobjectArray jdata_ptrs, jobjectArray jcoding_ptrs, jint size) { int* matrix = (int*) jmatrixId; char **data = convertFromBufferArray(env, jdata_ptrs); char **coding = convertFromBufferArray(env, jcoding_ptrs); jerasure_matrix_encode(k, m ,w, (int*)matrix, data, coding, size); delete[] data; delete[] coding; } /* * Class: cn_ctyun_ec_jni_Jerasure * Method: my_jerasure_matrix_decode * Signature: (IIIJZ[I[Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;I)Z */ JNIEXPORT jboolean JNICALL Java_cn_ctyun_ec_jni_Jerasure_my_1jerasure_1matrix_1decode (JNIEnv *env, jclass clazz, jint k, jint m, jint w, jlong jmatrixId, jboolean row_k_ones, jintArray jerasures, jobjectArray jdata_ptrs, jobjectArray jcoding_ptrs, jint size) { int result = -1; jint *erasures = NULL; erasures = env->GetIntArrayElements(jerasures, NULL); int *matrix = (int*) jmatrixId; char **data = convertFromBufferArray(env, jdata_ptrs); char **coding = convertFromBufferArray(env, jcoding_ptrs); if(erasures != NULL && matrix != NULL){ result = jerasure_matrix_decode(k, m, w, (int*)matrix, (row_k_ones == JNI_TRUE ? 1 : 0), (int*)erasures, data, coding, size); } else { throwOutOfMemoryError(env, ""); } env->ReleaseIntArrayElements(jerasures, erasures, NULL); delete[] data; delete[] coding; if(result == 0) return JNI_TRUE; return JNI_FALSE; }
bsd-3-clause
mrobam/Library
backend/views/issuing/edit.php
541
<?php use yii\bootstrap\ActiveForm; use yii\helpers\ArrayHelper; ?> <h2>Выдача книги</h2> <?php $form= ActiveForm::begin();?> <?=$form->field($issuing, 'book_id')->listBox(ArrayHelper::map($books,'id','name','author'))?> <?=$form->field($issuing, 'reader_id')->listBox(ArrayHelper::map($readers,'id','firstname', 'lastname'))?> <?=$form->field($issuing, 'expiration_date')?> <?=$form->field($issuing, 'issue_date')?> <button class="btn btn-primary" type="submit"> Сохранить</button> <?php ActiveForm::end();?>
bsd-3-clause
linkorb/ZendFramework-1.10.8-minimal-patched
library/Zend/Gdata/Media/Extension/MediaCategory.php
4528
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Media * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: MediaCategory.php,v 1.1 2010-10-25 15:20:28 h.wang Exp $ */ /** * @see Zend_Gdata_App_Extension */ require_once 'Zend/Gdata/App/Extension.php'; /** * Represents the media:category element * * @category Zend * @package Zend_Gdata * @subpackage Media * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Media_Extension_MediaCategory extends Zend_Gdata_Extension { protected $_rootElement = 'category'; protected $_rootNamespace = 'media'; /** * @var string */ protected $_scheme = null; protected $_label = null; /** * Creates an individual MediaCategory object. * * @param string $text Indication of the type and content of the media * @param string $scheme URI that identifies the categorization scheme * @param string $label Human-readable label to be displayed in applications */ public function __construct($text = null, $scheme = null, $label = null) { $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces); parent::__construct(); $this->_text = $text; $this->_scheme = $scheme; $this->_label = $label; } /** * Retrieves a DOMElement which corresponds to this element and all * child properties. This is used to build an entry back into a DOM * and eventually XML text for sending to the server upon updates, or * for application storage/persistence. * * @param DOMDocument $doc The DOMDocument used to construct DOMElements * @return DOMElement The DOMElement representing this element and all * child properties. */ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_scheme !== null) { $element->setAttribute('scheme', $this->_scheme); } if ($this->_label !== null) { $element->setAttribute('label', $this->_label); } return $element; } /** * Given a DOMNode representing an attribute, tries to map the data into * instance members. If no mapping is defined, the name and value are * stored in an array. * * @param DOMNode $attribute The DOMNode attribute needed to be handled */ protected function takeAttributeFromDOM($attribute) { switch ($attribute->localName) { case 'scheme': $this->_scheme = $attribute->nodeValue; break; case 'label': $this->_label = $attribute->nodeValue; break; default: parent::takeAttributeFromDOM($attribute); } } /** * Returns the URI that identifies the categorization scheme * Optional. * * @return string URI that identifies the categorization scheme */ public function getScheme() { return $this->_scheme; } /** * @param string $value URI that identifies the categorization scheme * @return Zend_Gdata_Media_Extension_MediaCategory Provides a fluent interface */ public function setScheme($value) { $this->_scheme = $value; return $this; } /** * @return string Human-readable label to be displayed in applications */ public function getLabel() { return $this->_label; } /** * @param string $value Human-readable label to be displayed in applications * @return Zend_Gdata_Media_Extension_MediaCategory Provides a fluent interface */ public function setLabel($value) { $this->_label = $value; return $this; } }
bsd-3-clause
abdmaster/zf3-multitenant-app
core/Helpers/config/module.config.php
751
<?php namespace Helpers; use Zend\I18n\View\Helper\Translate; return [ 'controller_plugins' => [ 'factories' => [ 'setTitle' => Controller\Plugin\Factory\SetTitleFactory::class, ], ], 'view_helpers' => [ 'invokables' => [ 'translate' => Translate::class, ], 'factories' => [ 'currentRoute' => View\Factory\CurrentRouteFactory::class, 'currentRouteParams' => View\Factory\CurrentRouteParamsFactory::class, 'siteName' => View\Factory\SiteNameFactory::class, 'formElementPartial' => View\Factory\FormElementPartialFactory::class, 'formBuilder' => View\Factory\FormBuilderFactory::class, ], ], ];
bsd-3-clause
percolate/percolate-java-sdk
api/src/main/java/com/percolate/sdk/api/request/previewformat/PreviewFormatRequest.java
1122
package com.percolate.sdk.api.request.previewformat; import com.percolate.sdk.api.PercolateApi; import com.percolate.sdk.api.utils.RetrofitApiFactory; import com.percolate.sdk.dto.PreviewFormats; import com.percolate.sdk.dto.SinglePreviewFormat; import org.jetbrains.annotations.NotNull; import retrofit2.Call; /** * Preview Format request proxy. */ public class PreviewFormatRequest { private PreviewFormatService service; public PreviewFormatRequest(@NotNull PercolateApi context) { this.service = new RetrofitApiFactory(context).getService(PreviewFormatService.class); } /** * Query preview format endpoint. * * @param uid preview format uid. * @return {@link Call} object. */ public Call<SinglePreviewFormat> get(@NotNull final String uid) { return service.get(uid); } /** * Query preview format endpoint. * * @param params API params. * @return {@link Call} object. */ public Call<PreviewFormats> list(@NotNull final PreviewFormatListParams params) { return service.list(params.getParams()); } }
bsd-3-clause
Rusk85/CavemanToolBySapiensworks
src/CavemanTools.MVC/IpTracking.cs
2457
using System; using System.Web; using System.Web.Security; namespace CavemanTools.Mvc { //todo review ip tracking /// <summary> /// Class for tracking ip changing /// </summary> public class IpTracking { private string _cookieName="_it"; public string CookieName { get { return _cookieName; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException(); _cookieName = value; } } public IpTracking(HttpContextBase context) { if (context == null) throw new ArgumentNullException("context"); if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) { IP = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } else { IP = context.Request.UserHostAddress; } FrontIp = context.Request.UserHostAddress; //check if we have cookie var ck = context.Request.Cookies[CookieName]; if (ck == null) { ck = IssueCookie(); IsChanged = true; context.Response.AppendCookie(ck); } else { OldIp = GetCookieIp(ck); if (OldIp != IP) { IsChanged = true; ck = IssueCookie(); context.Response.SetCookie(ck); } } } /// <summary> /// Gets user ip, ignoring proxies /// </summary> public string FrontIp { get; private set; } string GetCookieIp(HttpCookie ck) { if (string.IsNullOrEmpty(ck.Value)) return null; try { var ft = FormsAuthentication.Decrypt(ck.Value); if (ft == null) return null; return ft.UserData; } catch (Exception) { return null; } } public void ClearCookie(HttpResponseBase resp) { if (resp == null) throw new ArgumentNullException("resp"); resp.SetCookie(new HttpCookie(CookieName, null) { Expires = new DateTime(2010,1,1) }); } HttpCookie IssueCookie() { var ft = new FormsAuthenticationTicket(2, CookieName, DateTime.UtcNow, DateTime.UtcNow.AddDays(1), false, IP); var data = FormsAuthentication.Encrypt(ft); var ck = new HttpCookie(CookieName, data); ck.Expires = DateTime.UtcNow.AddDays(1); return ck; } /// <summary> /// Gets current ip, takes proxies into consideration /// </summary> public string IP { get; private set; } public string OldIp { get; private set; } public bool IsChanged { get; private set; } } }
bsd-3-clause
crysthianophp/dsl-tutorial
vendor/los/loslog/tests/LosLogTests/Log/ErrorLoggerTest.php
360
<?php namespace LosLogTests\Log; use LosLog\Log\ErrorLogger; class ErrorLoggerTest extends \PHPUnit_Framework_TestCase { public function testErrorLog() { ErrorLogger::registerHandlers(); $arq = file('testeErro.txt'); $log = file_get_contents('data/logs/error.log'); $this->assertContains('testeErro', $log); } }
bsd-3-clause
leesab/irods
iRODS/lib/core/src/getUtil.cpp
18685
/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ #ifndef windows_platform #include <sys/time.h> #endif #include "rodsPath.hpp" #include "rodsErrorTable.hpp" #include "rodsLog.hpp" #include "lsUtil.hpp" #include "getUtil.hpp" #include "miscUtil.hpp" #include "rcPortalOpr.hpp" int setSessionTicket( rcComm_t *myConn, char *ticket ) { ticketAdminInp_t ticketAdminInp; int status; ticketAdminInp.arg1 = "session"; ticketAdminInp.arg2 = ticket; ticketAdminInp.arg3 = ""; ticketAdminInp.arg4 = ""; ticketAdminInp.arg5 = ""; ticketAdminInp.arg6 = ""; status = rcTicketAdmin( myConn, &ticketAdminInp ); if ( status != 0 ) { printf( "set ticket error %d \n", status ); } return( status ); } int getUtil( rcComm_t **myConn, rodsEnv *myRodsEnv, rodsArguments_t *myRodsArgs, rodsPathInp_t *rodsPathInp ) { int i = 0; int status = 0; int savedStatus = 0; rodsPath_t *targPath = 0; dataObjInp_t dataObjOprInp; rodsRestart_t rodsRestart; rcComm_t *conn = *myConn; if ( rodsPathInp == NULL ) { return ( USER__NULL_INPUT_ERR ); } if ( myRodsArgs->ticket == True ) { if ( myRodsArgs->ticketString == NULL ) { rodsLog( LOG_ERROR, "initCondForPut: NULL ticketString error" ); return ( USER__NULL_INPUT_ERR ); } else { setSessionTicket( conn, myRodsArgs->ticketString ); } } initCondForGet( conn, myRodsEnv, myRodsArgs, &dataObjOprInp, &rodsRestart ); if ( rodsPathInp->resolved == False ) { status = resolveRodsTarget( conn, myRodsEnv, rodsPathInp, 1 ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "getUtil: resolveRodsTarget" ); return ( status ); } rodsPathInp->resolved = True; } /* initialize the progress struct */ if ( gGuiProgressCB != NULL ) { bzero( &conn->operProgress, sizeof( conn->operProgress ) ); for ( i = 0; i < rodsPathInp->numSrc; i++ ) { targPath = &rodsPathInp->targPath[i]; if ( targPath->objType == LOCAL_FILE_T ) { conn->operProgress.totalNumFiles++; if ( rodsPathInp->srcPath[i].size > 0 ) { conn->operProgress.totalFileSize += rodsPathInp->srcPath[i].size; } } else { getCollSizeForProgStat( conn, rodsPathInp->srcPath[i].outPath, &conn->operProgress ); } } } if ( conn->fileRestart.flags == FILE_RESTART_ON ) { fileRestartInfo_t *info; status = readLfRestartFile( conn->fileRestart.infoFile, &info ); if ( status >= 0 ) { status = lfRestartGetWithInfo( conn, info ); if ( status >= 0 ) { /* save info so we know what got restarted and what not to * delete in setStateForResume */ rstrcpy( conn->fileRestart.info.objPath, info->objPath, MAX_NAME_LEN ); rstrcpy( conn->fileRestart.info.fileName, info->fileName, MAX_NAME_LEN ); conn->fileRestart.info.status = FILE_RESTARTED; printf( "%s was restarted successfully\n", conn->fileRestart.info.objPath ); unlink( conn->fileRestart.infoFile ); } if ( info != NULL ) { free( info ); } } } for ( i = 0; i < rodsPathInp->numSrc; i++ ) { targPath = &rodsPathInp->targPath[i]; if ( rodsPathInp->srcPath[i].rodsObjStat != NULL && rodsPathInp->srcPath[i].rodsObjStat->specColl != NULL ) { dataObjOprInp.specColl = rodsPathInp->srcPath[i].rodsObjStat->specColl; } else { dataObjOprInp.specColl = NULL; } if ( targPath->objType == LOCAL_FILE_T ) { rmKeyVal( &dataObjOprInp.condInput, TRANSLATED_PATH_KW ); status = getDataObjUtil( conn, rodsPathInp->srcPath[i].outPath, targPath->outPath, rodsPathInp->srcPath[i].size, rodsPathInp->srcPath[i].objMode, myRodsEnv, myRodsArgs, &dataObjOprInp ); } else if ( targPath->objType == LOCAL_DIR_T ) { setStateForRestart( conn, &rodsRestart, targPath, myRodsArgs ); addKeyVal( &dataObjOprInp.condInput, TRANSLATED_PATH_KW, "" ); status = getCollUtil( myConn, rodsPathInp->srcPath[i].outPath, targPath->outPath, myRodsEnv, myRodsArgs, &dataObjOprInp, &rodsRestart ); } else { /* should not be here */ rodsLog( LOG_ERROR, "getUtil: invalid get dest objType %d for %s", targPath->objType, targPath->outPath ); return ( USER_INPUT_PATH_ERR ); } /* XXXX may need to return a global status */ if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "getUtil: get error for %s", targPath->outPath ); savedStatus = status; break; } } if ( rodsRestart.fd > 0 ) { close( rodsRestart.fd ); } if ( savedStatus < 0 ) { status = savedStatus; } else if ( status == CAT_NO_ROWS_FOUND ) { status = 0; } if ( status < 0 && myRodsArgs->retries == True ) { int reconnFlag; /* this is recursive. Only do it the first time */ myRodsArgs->retries = False; if ( myRodsArgs->reconnect == True ) { reconnFlag = RECONN_TIMEOUT; } else { reconnFlag = NO_RECONN; } while ( myRodsArgs->retriesValue > 0 ) { rErrMsg_t errMsg; bzero( &errMsg, sizeof( errMsg ) ); status = rcReconnect( myConn, myRodsEnv->rodsHost, myRodsEnv, reconnFlag ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "getUtil: rcReconnect error for %s", targPath->outPath ); return status; } status = getUtil( myConn, myRodsEnv, myRodsArgs, rodsPathInp ); if ( status >= 0 ) { printf( "Retry get successful\n" ); break; } else { rodsLogError( LOG_ERROR, status, "getUtil: retry getUtil error" ); } myRodsArgs->retriesValue--; } } return status; } int getDataObjUtil( rcComm_t *conn, char *srcPath, char *targPath, rodsLong_t srcSize, uint dataMode, rodsEnv *myRodsEnv, rodsArguments_t *rodsArgs, dataObjInp_t *dataObjOprInp ) { int status; struct timeval startTime, endTime; if ( srcPath == NULL || targPath == NULL ) { rodsLog( LOG_ERROR, "getDataObjUtil: NULL srcPath or targPath input" ); return ( USER__NULL_INPUT_ERR ); } if ( conn->fileRestart.info.status == FILE_RESTARTED && strcmp( conn->fileRestart.info.objPath, srcPath ) == 0 ) { /* it was restarted */ conn->fileRestart.info.status = FILE_NOT_RESTART; return 0; } if ( rodsArgs->verbose == True ) { ( void ) gettimeofday( &startTime, ( struct timezone * )0 ); } if ( gGuiProgressCB != NULL ) { rstrcpy( conn->operProgress.curFileName, srcPath, MAX_NAME_LEN ); conn->operProgress.curFileSize = srcSize; conn->operProgress.curFileSizeDone = 0; conn->operProgress.flag = 0; gGuiProgressCB( &conn->operProgress ); } rstrcpy( dataObjOprInp->objPath, srcPath, MAX_NAME_LEN ); /* rcDataObjGet verifies dataSize if given */ if ( rodsArgs->replNum == True || rodsArgs->resource == True ) { /* don't verify because it may be an old copy and hence the size * could be wrong */ dataObjOprInp->dataSize = 0; } else { dataObjOprInp->dataSize = srcSize; } status = rcDataObjGet( conn, dataObjOprInp, targPath ); if ( status >= 0 ) { /* old objState use numCopies in place of dataMode. * Just a sanity check */ myChmod( targPath, dataMode ); if ( rodsArgs->verbose == True ) { ( void ) gettimeofday( &endTime, ( struct timezone * )0 ); printTiming( conn, dataObjOprInp->objPath, srcSize, targPath, &startTime, &endTime ); } if ( gGuiProgressCB != NULL ) { conn->operProgress.totalNumFilesDone++; conn->operProgress.totalFileSizeDone += srcSize; } } return ( status ); } int initCondForGet( rcComm_t *conn, rodsEnv *myRodsEnv, rodsArguments_t *rodsArgs, dataObjInp_t *dataObjOprInp, rodsRestart_t *rodsRestart ) { char *tmpStr; if ( dataObjOprInp == NULL ) { rodsLog( LOG_ERROR, "initCondForGet: NULL dataObjOprInp input" ); return ( USER__NULL_INPUT_ERR ); } memset( dataObjOprInp, 0, sizeof( dataObjInp_t ) ); if ( rodsArgs == NULL ) { return ( 0 ); } dataObjOprInp->oprType = GET_OPR; if ( rodsArgs->force == True ) { addKeyVal( &dataObjOprInp->condInput, FORCE_FLAG_KW, "" ); } if ( rodsArgs->verifyChecksum == True ) { addKeyVal( &dataObjOprInp->condInput, VERIFY_CHKSUM_KW, "" ); } #ifdef windows_platform dataObjOprInp->numThreads = NO_THREADING; #else if ( rodsArgs->number == True ) { if ( rodsArgs->numberValue == 0 ) { dataObjOprInp->numThreads = NO_THREADING; } else { dataObjOprInp->numThreads = rodsArgs->numberValue; } } #endif if ( rodsArgs->replNum == True ) { addKeyVal( &dataObjOprInp->condInput, REPL_NUM_KW, rodsArgs->replNumValue ); } if ( rodsArgs->resource == True ) { if ( rodsArgs->resourceString == NULL ) { rodsLog( LOG_ERROR, "initCondForPut: NULL resourceString error" ); return ( USER__NULL_INPUT_ERR ); } else { addKeyVal( &dataObjOprInp->condInput, RESC_NAME_KW, rodsArgs->resourceString ); } } if ( rodsArgs->ticket == True ) { if ( rodsArgs->ticketString == NULL ) { rodsLog( LOG_ERROR, "initCondForPut: NULL ticketString error" ); return ( USER__NULL_INPUT_ERR ); } else { addKeyVal( &dataObjOprInp->condInput, TICKET_KW, rodsArgs->ticketString ); } } if ( rodsArgs->rbudp == True ) { /* use -Q for rbudp transfer */ addKeyVal( &dataObjOprInp->condInput, RBUDP_TRANSFER_KW, "" ); } if ( rodsArgs->veryVerbose == True ) { addKeyVal( &dataObjOprInp->condInput, VERY_VERBOSE_KW, "" ); } if ( ( tmpStr = getenv( RBUDP_SEND_RATE_KW ) ) != NULL ) { addKeyVal( &dataObjOprInp->condInput, RBUDP_SEND_RATE_KW, tmpStr ); } if ( ( tmpStr = getenv( RBUDP_PACK_SIZE_KW ) ) != NULL ) { addKeyVal( &dataObjOprInp->condInput, RBUDP_PACK_SIZE_KW, tmpStr ); } if ( rodsArgs->purgeCache == True ) { // JMC - backport 4537 addKeyVal( &dataObjOprInp->condInput, PURGE_CACHE_KW, "" ); } memset( rodsRestart, 0, sizeof( rodsRestart_t ) ); if ( rodsArgs->restart == True ) { int status; status = openRestartFile( rodsArgs->restartFileString, rodsRestart, rodsArgs ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "initCondForPut: openRestartFile of %s errno", rodsArgs->restartFileString ); return ( status ); } } if ( rodsArgs->retries == True && rodsArgs->restart == False && rodsArgs->lfrestart == False ) { rodsLog( LOG_ERROR, "initCondForGet: --retries must be used with -X option" ); return USER_INPUT_OPTION_ERR; } if ( rodsArgs->lfrestart == True ) { if ( rodsArgs->rbudp == True ) { rodsLog( LOG_NOTICE, "initCondForPut: --lfrestart cannot be used with -Q option" ); } else { conn->fileRestart.flags = FILE_RESTART_ON; rstrcpy( conn->fileRestart.infoFile, rodsArgs->lfrestartFileString, MAX_NAME_LEN ); } } // =-=-=-=-=-=-=- // JMC - backport 4604 if ( rodsArgs->rlock == True ) { addKeyVal( &dataObjOprInp->condInput, LOCK_TYPE_KW, READ_LOCK_TYPE ); } // =-=-=-=-=-=-=- // =-=-=-=-=-=-=- // JMC - backport 4612 if ( rodsArgs->wlock == True ) { rodsLog( LOG_ERROR, "initCondForPut: --wlock not supported, changing it to --rlock" ); addKeyVal( &dataObjOprInp->condInput, LOCK_TYPE_KW, READ_LOCK_TYPE ); } // =-=-=-=-=-=-=- dataObjOprInp->openFlags = O_RDONLY; return ( 0 ); } int getCollUtil( rcComm_t **myConn, char *srcColl, char *targDir, rodsEnv *myRodsEnv, rodsArguments_t *rodsArgs, dataObjInp_t *dataObjOprInp, rodsRestart_t *rodsRestart ) { int status = 0; int savedStatus = 0; char srcChildPath[MAX_NAME_LEN], targChildPath[MAX_NAME_LEN]; char parPath[MAX_NAME_LEN], childPath[MAX_NAME_LEN]; collHandle_t collHandle; collEnt_t collEnt; dataObjInp_t childDataObjInp; rcComm_t *conn; if ( srcColl == NULL || targDir == NULL ) { rodsLog( LOG_ERROR, "getCollUtil: NULL srcColl or targDir input" ); return ( USER__NULL_INPUT_ERR ); } if ( rodsArgs->recursive != True ) { rodsLog( LOG_ERROR, "getCollUtil: -r option must be used for getting %s collection", targDir ); return ( USER_INPUT_OPTION_ERR ); } if ( rodsArgs->redirectConn == True ) { int reconnFlag; if ( rodsArgs->reconnect == True ) { reconnFlag = RECONN_TIMEOUT; } else { reconnFlag = NO_RECONN; } /* reconnect to the resource server */ rstrcpy( dataObjOprInp->objPath, srcColl, MAX_NAME_LEN ); redirectConnToRescSvr( myConn, dataObjOprInp, myRodsEnv, reconnFlag ); rodsArgs->redirectConn = 0; /* only do it once */ } conn = *myConn; printCollOrDir( targDir, LOCAL_DIR_T, rodsArgs, dataObjOprInp->specColl ); status = rclOpenCollection( conn, srcColl, 0, &collHandle ); if ( status < 0 ) { rodsLog( LOG_ERROR, "getCollUtil: rclOpenCollection of %s error. status = %d", srcColl, status ); return status; } while ( ( status = rclReadCollection( conn, &collHandle, &collEnt ) ) >= 0 ) { if ( collEnt.objType == DATA_OBJ_T ) { rodsLong_t mySize; mySize = collEnt.dataSize; /* have to save it. May be freed */ snprintf( targChildPath, MAX_NAME_LEN, "%s/%s", targDir, collEnt.dataName ); snprintf( srcChildPath, MAX_NAME_LEN, "%s/%s", collEnt.collName, collEnt.dataName ); status = chkStateForResume( conn, rodsRestart, targChildPath, rodsArgs, LOCAL_FILE_T, &dataObjOprInp->condInput, 1 ); if ( status < 0 ) { /* restart failed */ break; } else if ( status == 0 ) { continue; } status = getDataObjUtil( conn, srcChildPath, targChildPath, mySize, collEnt.dataMode, myRodsEnv, rodsArgs, dataObjOprInp ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "getCollUtil: getDataObjUtil failed for %s. status = %d", srcChildPath, status ); savedStatus = status; if ( rodsRestart->fd > 0 ) { break; } } else { status = procAndWrriteRestartFile( rodsRestart, targChildPath ); } } else if ( collEnt.objType == COLL_OBJ_T ) { if ( ( status = splitPathByKey( collEnt.collName, parPath, childPath, '/' ) ) < 0 ) { rodsLogError( LOG_ERROR, status, "getCollUtil:: splitPathByKey for %s error, status = %d", collEnt.collName, status ); return ( status ); } snprintf( targChildPath, MAX_NAME_LEN, "%s/%s", targDir, childPath ); mkdirR( targDir, targChildPath, 0750 ); /* the child is a spec coll. need to drill down */ childDataObjInp = *dataObjOprInp; if ( collEnt.specColl.collClass != NO_SPEC_COLL ) { childDataObjInp.specColl = &collEnt.specColl; } else { childDataObjInp.specColl = NULL; } status = getCollUtil( myConn, collEnt.collName, targChildPath, myRodsEnv, rodsArgs, &childDataObjInp, rodsRestart ); if ( status < 0 && status != CAT_NO_ROWS_FOUND ) { rodsLogError( LOG_ERROR, status, "getCollUtil: getCollUtil failed for %s. status = %d", collEnt.collName, status ); savedStatus = status; if ( rodsRestart->fd > 0 ) { break; } } } } rclCloseCollection( &collHandle ); if ( savedStatus < 0 ) { return ( savedStatus ); } else if ( status == CAT_NO_ROWS_FOUND || status == SYS_SPEC_COLL_OBJ_NOT_EXIST ) { return ( 0 ); } else { return ( status ); } }
bsd-3-clause
justin-hayes/motech
modules/tasks/tasks/src/main/java/org/motechproject/tasks/validation/TaskValidator.java
18815
package org.motechproject.tasks.validation; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.motechproject.tasks.domain.ActionEvent; import org.motechproject.tasks.domain.ActionParameter; import org.motechproject.tasks.domain.Channel; import org.motechproject.tasks.domain.DataSource; import org.motechproject.tasks.domain.Filter; import org.motechproject.tasks.domain.FilterSet; import org.motechproject.tasks.domain.KeyInformation; import org.motechproject.tasks.domain.Lookup; import org.motechproject.tasks.domain.ManipulationTarget; import org.motechproject.tasks.domain.ManipulationType; import org.motechproject.tasks.domain.OperatorType; import org.motechproject.tasks.domain.ParameterType; import org.motechproject.tasks.domain.Task; import org.motechproject.tasks.domain.TaskActionInformation; import org.motechproject.tasks.domain.TaskConfig; import org.motechproject.tasks.domain.TaskDataProvider; import org.motechproject.tasks.domain.TaskError; import org.motechproject.tasks.domain.TaskTriggerInformation; import org.motechproject.tasks.domain.TriggerEvent; import org.motechproject.tasks.service.TriggerEventService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.commons.collections.CollectionUtils.isEmpty; import static org.motechproject.tasks.domain.KeyInformation.parse; /** * Utility class for validating tasks. */ @Component public class TaskValidator extends GeneralValidator { public static final String TASK = "task"; private static final String MODULE_VERSION = "moduleVersion"; private TriggerEventService triggerEventService; /** * Validates the given task by checking if all necessary data is set. Returns the set of TaskError containing * information about missing fields. * * @param task the task to be validated, not null * @return the set of encountered errors */ public Set<TaskError> validate(Task task) { Set<TaskError> errors = new HashSet<>(); checkBlankValue(errors, TASK, "name", task.getName()); errors.addAll(validateRetryOnFailureValues(task.getNumberOfRetries(), task.getRetryIntervalInMilliseconds())); errors.addAll(validateTrigger(task.getTrigger())); checkEmpty(errors, TASK, "actions", task.getActions()); for (int i = 0; i < task.getActions().size(); ++i) { errors.addAll(validateAction(i, task.getActions().get(i))); } errors.addAll(validateTaskConfig(task.getTaskConfig())); return errors; } /** * Validates the trigger of the given task by checking if it is specified in the given channel. * * @param task the task for which the trigger should be validated, not null * @return the set of encountered errors */ public Set<TaskError> validateTrigger(Task task) { Set<TaskError> errors = new HashSet<>(); TaskTriggerInformation triggerInformation = task.getTrigger(); boolean exists = triggerEventService.triggerExists(triggerInformation); if (!exists) { errors.add(new TaskError( "task.validation.error.triggerNotExist", triggerInformation.getDisplayName() )); } return errors; } /** * Checks if the channel contains the given actions. * * @param actionInformation the information about action, not null * @param channel the channel to be checked, not null * @return the set of encountered errors */ public Set<TaskError> validateAction(TaskActionInformation actionInformation, Channel channel) { Set<TaskError> errors = new HashSet<>(); boolean exists = channel.containsAction(actionInformation); if (!exists) { errors.add(new TaskError( "task.validation.error.actionNotExist", actionInformation.getDisplayName(), channel.getDisplayName() )); } return errors; } /** * Validates if the given provider contains the given data source and trigger event. * * @param provider the provider to be checked, not null * @param dataSource the data source to be validated, not null * @param trigger the trigger to be validated, not null * @param availableProviders the map of the IDs and the providers, not null * @return the set of encountered errors */ public Set<TaskError> validateProvider(TaskDataProvider provider, DataSource dataSource, TriggerEvent trigger, Map<Long, TaskDataProvider> availableProviders) { Set<TaskError> errors = new HashSet<>(); Map<String, String> fields = new HashMap<>(); Map<String, ParameterType> fieldsTypes = new HashMap<>(); if (!provider.containsProviderObject(dataSource.getType())) { errors.add(new TaskError( "task.validation.error.providerObjectNotExist", dataSource.getType(), provider.getName() )); } else { for (Lookup lookup : dataSource.getLookup()) { if (!provider.containsProviderObjectLookup(dataSource.getType(), dataSource.getName())) { errors.add(new TaskError( "task.validation.error.providerObjectLookupNotExist", lookup.getField(), dataSource.getType(), provider.getName() )); } fields.put(lookup.getField(), lookup.getValue()); fieldsTypes.put(lookup.getField(), ParameterType.UNKNOWN); } errors.addAll(validateFieldsParameter(fields, fieldsTypes, trigger, availableProviders)); } return errors; } /** * Validates whether fields of the the action are properly set. * * @param action the information about action, not null * @param actionEvent the action event, not null * @param trigger the trigger of the task the action belongs to, not null * @param providers the map of IDs and providers, not null * @return the set of encountered errors */ public Set<TaskError> validateActionFields(TaskActionInformation action, ActionEvent actionEvent, TriggerEvent trigger, Map<Long, TaskDataProvider> providers) { Map<String, String> fields = action.getValues(); Map<String, ParameterType> fieldsTypes = new HashMap<>(); for (ActionParameter param : actionEvent.getActionParameters()) { fieldsTypes.put(param.getKey(), param.getType()); } return validateFieldsParameter(fields, fieldsTypes, trigger, providers); } private Set<TaskError> validateFieldsParameter(Map<String, String> fields, Map<String, ParameterType> fieldsTypes, TriggerEvent trigger, Map<Long, TaskDataProvider> providers) { Set<TaskError> errors = new HashSet<>(); for (Map.Entry<String, String> entry : fields.entrySet()) { if (entry.getValue() != null) { for (KeyInformation key : KeyInformation.parseAll(entry.getValue())) { errors.addAll(validateKeyInformation(key, fieldsTypes.get(entry.getKey()), trigger, providers)); } } } return errors; } private Set<TaskError> validateDateFormat(Map<String, String> actionInputFields) { Set<TaskError> errors = new HashSet<>(); for (Map.Entry<String, String> entry : actionInputFields.entrySet()) { String entryValue = entry.getValue(); if (entryValue.contains("dateTime")) { Pattern pattern = Pattern.compile("\\{\\{(.*?)\\?dateTime\\((.*?)\\)\\}\\}"); Matcher matcher = pattern.matcher(entryValue); while (matcher.find()) { try { DateTime now = DateTime.now(); DateTimeFormat.forPattern(matcher.group(2)).print(now); } catch (IllegalArgumentException e) { String[] objectFields = matcher.group(1).split("\\."); errors.add(new TaskError( "task.validation.error.dateFormat", String.format( "%s.%s", objectFields[objectFields.length - 2], objectFields[objectFields.length - 1] ), entry.getKey() )); } } } } return errors; } private Set<TaskError> validateAction(int idx, TaskActionInformation action) { Set<TaskError> errors = new HashSet<>(); checkNullValue(errors, TASK, String.format("actions[%d]", idx), action); if (isEmpty(errors)) { String objectName = String.format("%s.actions[%d]", TASK, idx); checkBlankValue(errors, objectName, "channelName", action.getChannelName()); checkBlankValue(errors, objectName, "moduleName", action.getModuleName()); checkBlankValue(errors, objectName, MODULE_VERSION, action.getModuleVersion()); checkVersion(errors, objectName, MODULE_VERSION, action.getModuleVersion()); if (!action.hasSubject() && !action.hasService()) { errors.add(new TaskError("task.validation.error.taskAction")); } checkNullValue(errors, objectName, "values", action.getValues()); for (Map.Entry<String, String> entry : action.getValues().entrySet()) { checkBlankValue( errors, String.format("%s.values", objectName), entry.getKey(), entry.getValue() ); } errors.addAll(validateDateFormat(action.getValues())); } return errors; } private Set<TaskError> validateTrigger(TaskTriggerInformation trigger) { Set<TaskError> errors = new HashSet<>(); checkNullValue(errors, TASK, "action", trigger); if (isEmpty(errors)) { String objectName = TASK + ".trigger"; checkBlankValue(errors, objectName, "channelName", trigger.getChannelName()); checkBlankValue(errors, objectName, "moduleName", trigger.getModuleName()); checkBlankValue(errors, objectName, MODULE_VERSION, trigger.getModuleVersion()); checkBlankValue(errors, objectName, "subject", trigger.getSubject()); checkVersion(errors, objectName, MODULE_VERSION, trigger.getModuleVersion()); } return errors; } private Set<TaskError> validateFilter(Integer setOrder, int index, Filter filter, TaskConfig config) { Set<TaskError> errors = new HashSet<>(); String field = String.format("taskConfig.filterSet[%d].filters[%d]", setOrder, index); KeyInformation key = parse(filter.getKey()); DataSource dataSource = config.getDataSource( key.getDataProviderId(), key.getObjectId(), key.getObjectType() ); checkNullValue(errors, TASK, field, filter); if (isEmpty(errors)) { String objectName = "task." + field; if (key.fromAdditionalData() && dataSource == null) { errors.add(new TaskError( "task.validation.error.DataSourceNotExist", key.getObjectType() )); } checkBlankValue(errors, objectName, "key", filter.getKey()); checkBlankValue(errors, objectName, "displayName", filter.getDisplayName()); checkBlankValue(errors, objectName, "operator", filter.getOperator()); checkNullValue(errors, objectName, "type", filter.getType()); if (OperatorType.needExpression(filter.getOperator())) { checkBlankValue(errors, objectName, "expression", filter.getExpression()); } } return errors; } private Set<TaskError> validateKeyInformation(KeyInformation key, ParameterType fieldType, TriggerEvent trigger, Map<Long, TaskDataProvider> providers) { Set<TaskError> errors = new HashSet<>(); if (key.fromTrigger() && trigger.containsParameter(key.getKey()) && key.hasManipulations()) { for (String manipulation : key.getManipulations()) { errors.addAll(validateManipulations(manipulation, key, ParameterType.fromString(trigger.getKeyType(key.getKey())), fieldType )); } } else if (key.fromAdditionalData() && providers.containsKey(key.getDataProviderId()) && providers.get(key.getDataProviderId()).containsProviderObjectField(key.getObjectType(), key.getKey()) && key.hasManipulations()) { for (String manipulations : key.getManipulations()) { errors.addAll(validateManipulations(manipulations, key, ParameterType.fromString(providers.get(key.getDataProviderId()).getKeyType(key.getKey())), fieldType )); } } return errors; } private Set<TaskError> validateManipulations(String manipulation, KeyInformation key, ParameterType parameterType, ParameterType fieldType) { Set<TaskError> errors = new HashSet<>(); TaskError error; String at = key.getKey() + "?" + manipulation; if (parameterType == ParameterType.UNICODE || parameterType == ParameterType.TEXTAREA || parameterType == ParameterType.UNKNOWN) { error = validateStringManipulation(manipulation, at); if (error != null) { errors.add(error); } } else if (parameterType == ParameterType.DATE) { error = validateDateManipulation(manipulation, fieldType, at); if (error != null) { errors.add(error); } } else { errors.add(new TaskError( "task.validation.error.wrongAnotherManipulation", manipulation, at )); } return errors; } private TaskError validateStringManipulation(String manipulation, String foundAt) { TaskError error = null; ManipulationType type = ManipulationType.fromString(manipulation.replaceAll("\\((.*?)\\)", "")); if (type.getTarget() != ManipulationTarget.STRING) { if (type.getTarget() == ManipulationTarget.ALL) { error = new TaskError( "task.validation.error.wrongAnotherManipulation", manipulation, foundAt ); } else { error = new TaskError( "task.validation.error.wrongStringManipulation", manipulation, foundAt ); } } return error; } private TaskError validateDateManipulation(String manipulation, ParameterType fieldType, String foundAt) { TaskError error = null; ManipulationType type = ManipulationType.fromString(manipulation.replaceAll("\\((.*?)\\)", "")); if (type.getTarget() != ManipulationTarget.DATE) { if (type.getTarget() == ManipulationTarget.ALL) { error = new TaskError( "task.validation.error.wrongAnotherManipulation", manipulation, foundAt ); } else { error = new TaskError( "task.validation.error.wrongDateManipulation", manipulation, foundAt ); } } else if (fieldType.equals(ParameterType.DATE) && !type.allowResultType(ManipulationTarget.DATE)) { error = new TaskError( "task.validation.error.wrongDateManipulationTarget", manipulation, foundAt ); } return error; } private Set<TaskError> validateDataSource(DataSource dataSource) { Set<TaskError> errors = new HashSet<>(); String field = "taskConfig.dataSource[" + dataSource.getOrder() + "]"; for (Lookup lookup : dataSource.getLookup()) { if (isEmpty(errors)) { String objectName = "task." + field; checkNullValue(errors, objectName, "objectId", dataSource.getObjectId()); checkNullValue(errors, objectName, "providerId", dataSource.getProviderId()); checkBlankValue(errors, objectName, "type", dataSource.getType()); checkBlankValue(errors, objectName, "lookup.field", lookup.getField()); checkBlankValue(errors, objectName, "lookup.value", lookup.getValue()); } } return errors; } private Set<TaskError> validateTaskConfig(TaskConfig config) { Set<TaskError> errors = new HashSet<>(); for (FilterSet filterSet : config.getFilters()) { List<Filter> filters = filterSet.getFilters(); for (int i = 0; i < filters.size(); ++i) { errors.addAll(validateFilter(filterSet.getOrder(), i, filters.get(i), config)); } } for (DataSource dataSource : config.getDataSources()) { errors.addAll(validateDataSource(dataSource)); } return errors; } private static Set<TaskError> validateRetryOnFailureValues(int numberOfRetries, int retryIntervalInMilliseconds) { Set<TaskError> errors = new HashSet<>(); if (numberOfRetries < 0 || retryIntervalInMilliseconds < 0) { TaskError error = new TaskError("task.validation.error.invalidRetryOnFailureValues"); errors.add(error); } return errors; } @Autowired public void setTriggerEventService(TriggerEventService triggerEventService) { this.triggerEventService = triggerEventService; } }
bsd-3-clause
leonardosantos/dhclientlist
dhclientlist/drivers/tp_link/generic.py
684
# coding: utf-8 import requests import re import json def get(address, username, password): GROUP_LENGTH = 4 page = requests.get("http://%s/userRpm/AssignedIpAddrListRpm.htm" % address, auth=(username, password)) list_str = re.search("(var DHCPDynList = new Array\(([^\)]*)\))", page.content.replace("\n", "")).groups()[1] list_arr = json.loads('[%s]' % list_str) list_arr = list_arr[0:(len(list_arr) // GROUP_LENGTH) * GROUP_LENGTH] groups = [{'name': list_arr[i], 'mac': list_arr[i+1], 'ip': list_arr[i+2], 'lease': list_arr[i+3]} for i in range(len(list_arr))[0::GROUP_LENGTH]] return groups
bsd-3-clause
rnyberg/pyfibot
pyfibot/modules/module_openweather_fi.py
2678
# -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals import logging from datetime import datetime, timedelta from math import ceil log = logging.getLogger('openweather') default_location = 'Helsinki' threshold = 120 def init(bot): global default_location global threshold config = bot.config.get('module_openweather', {}) default_location = config.get('default_location', 'Helsinki') threshold = int(config.get('threshold', 120)) # threshold to show measuring time in minutes log.info('Using %s as default location' % default_location) def command_saa(bot, user, channel, args): global default_location global threshold if args: location = args.decode('utf-8') else: location = default_location url = 'http://openweathermap.org/data/2.5/weather?q=%s&units=metric' r = bot.get_url(url % location) if 'cod' not in r.json() or int(r.json()['cod']) != 200: return bot.say(channel, 'Error: API error.') data = r.json() if 'name' not in data: return bot.say(channel, 'Error: Location not found.') if 'main' not in data: return bot.say(channel, 'Error: Unknown error.') location = '%s, %s' % (data['name'], data['sys']['country']) main = data['main'] old_data = False if 'dt' in data: measured = datetime.utcfromtimestamp(data['dt']) if datetime.utcnow() - timedelta(minutes=threshold) > measured: old_data = True if old_data: text = '%s (%s UTC): ' % (location, measured.strftime('%Y-%m-%d %H:%M')) else: text = '%s: ' % location if 'temp' not in main: return bot.say(channel, 'Error: Data not found.') temperature = main['temp'] # temperature converted from kelvin to celcius text += u'Lämpötila: %.1f°C' % temperature if 'wind' in data and 'speed' in data['wind']: wind = data['wind']['speed'] # Wind speed in mps (m/s) feels_like = 13.12 + 0.6215 * temperature - 11.37 * (wind * 3.6) ** 0.16 + 0.3965 * temperature * (wind * 3.6) ** 0.16 text += ', tuntuu kuin: %.1f°C' % feels_like text += ', tuuli: %.1f m/s' % wind if 'humidity' in main: humidity = main['humidity'] # Humidity in % text += ', ilmankosteus: %d%%' % humidity if 'pressure' in main: pressure = main['pressure'] # Atmospheric pressure in hPa text += ', ilmanpaine: %d hPa' % pressure if 'clouds' in data and 'all' in data['clouds']: cloudiness = data['clouds']['all'] # Cloudiness in % text += ', pilvisyys: %d%%' % cloudiness return bot.say(channel, text)
bsd-3-clause
joycode/LibNVim
LibNVim/Editions/EditionAppendToLineEnd.cs
458
using System; using System.Collections.Generic; using System.Text; namespace LibNVim.Editions { class EditionAppendToLineEnd : AbstractVimEditionInsertText { public EditionAppendToLineEnd(Interfaces.IVimHost host, int repeat) : base(host, repeat) { } protected override void OnBeforeInsert(Interfaces.IVimHost host) { host.MoveToEndOfLine(); } } }
bsd-3-clause
NextToBe/X-works
frontend/models/Course.php
2979
<?php /** * Course * * 作者: Tony * 创建时间: 2016-11-06 * 修改记录: * */ namespace frontend\models; use yii\base\Exception; use yii\db\ActiveRecord; use Yii; class Course extends ActiveRecord { const EVENT_SET_COURSE = 'set_course'; public function init() { $this->on(self::EVENT_SET_COURSE, [$this, 'init_grades_and_absences']); } /** * @return array */ public function rules() { return [ ['name', 'required', 'message' => '请输入课程名称'], ['description', 'required', 'message' => '请输入课程描述'] ]; } /** * @return array */ public function scenarios() { return [ 'create' => ['name', 'description'] ]; } /** * @return string */ public static function tableName() { return 'courses'; } /** * @param string $name * * @return object */ public static function findByName(string $name) { return self::findOne(['name' => $name]); } /** * @return objects */ public function checkTasks() { return $this->hasMany(Task::className(), ['course' => $this->name]); } /** * @return boolean */ public function create() { try { $this->date = date('d-M-Y'); $this->teacher_id = Yii::$app->user->identity->id; $this->save(); return true; } catch (Exception $e) { var_dump($e->getMessage()); return false; } } /** * 回调函数:初始化每个学生的成绩 * * @return void */ public function init_grades_and_absences() { $students = Student::find()->all(); foreach($students as $student) { $grade = new Grade(); $grade->setScenario('create'); //初始化成绩, 平时分数和缺席次数 $grade->student_id = $student->id; $grade->grade = 0; $grade->absences = 0; $grade->course = $this->name; $grade->scores = 0; $grade->save(); } // 初始化点名配置 Config::setConfig($this->name . '_call_freq', 8); Config::setConfig($this->name . '_call_score', 5); } /** * 根据教师或者助教的ID获取课程 * * @param int $user_id 用户id * @return course_name */ public static function getCourse($user_id) { $user = User::findOne(['id' => $user_id]); if ($user->type == Teacher::TYPE_TEACHER) { $course = self::findOne(['teacher_id' => $user_id]); } else { $assist = Assistant::findOne(['id' => $user_id]); $course = self::findOne(['teacher_id' => $assist->teacher_id]); } if ($course) { return $course->name; } else { return ''; } } }
bsd-3-clause
muratymt/yiicms
components/core/cronjob/CronJob.php
498
<?php /** * Created by PhpStorm. * User: admin * Date: 28.01.2016 * Time: 8:44 */ namespace yiicms\components\core\cronjob; use yii\base\Object; abstract class CronJob extends Object { /** * @var string описание задания */ public $description = ''; /** * функция входа в выполнение работы * @return bool true если задание выполнено успешно */ abstract public function run(); }
bsd-3-clause
CIT-VSB-TUO/ResBill
resbill/src/main/java/cz/vsb/resbill/model/BaseVersionedEntity.java
1065
package cz.vsb.resbill.model; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.Version; /** * A common ancestor of entities with automatically generated primary key that * are ready for optimistic locking. * * @author HAL191 * */ @MappedSuperclass public abstract class BaseVersionedEntity extends BaseGeneratedIdEntity implements VersionedEntity { private static final long serialVersionUID = 4891678972378019341L; @Version @Column(name = "lock_version", nullable = false) private int lockVersion; @Override public int getLockVersion() { return lockVersion; } @Override public void setLockVersion(int lockVersion) { this.lockVersion = lockVersion; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("BaseVersionedEntity ["); builder.append(super.toString()); builder.append(", lockVersion="); builder.append(lockVersion); builder.append("]"); return builder.toString(); } }
bsd-3-clause
MonsantoCo/chinese-restaurant-process
src/test/scala/com/monsanto/stats/tables/clustering/VecMapSpec.scala
2027
package com.monsanto.stats.tables.clustering import com.monsanto.stats.tables.UnitSpec import org.scalatest._ import enablers.Collecting import scala.collection.GenTraversable import prop.GeneratorDrivenPropertyChecks import org.scalactic.Equality import org.scalactic.anyvals.{ PosZInt, PosZDouble } import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.Gen._ import scala.collection.mutable import com.monsanto.stats.tables._ class VecMapSpec extends UnitSpec { val allTopicVectorResults: Vector[TopicVectorInput] = MnMGen.getData() val p5 = ModelParams(5, 1, 1) val crp = new CRP(p5, allTopicVectorResults) "A VecMap" should { "offer a toMap method that returns a Map equal to the Map passed to its factory method" in { crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9)).toMap shouldEqual Map(1 -> 1, 2 -> 4, 3 -> 9) } "be equal to another VecMap created with an equal Map" in { crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9)) shouldEqual crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9)) } "offer a size method that returns the size of the initializing Map" in { crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9, 5 -> 25)).size shouldEqual 4 crp.VecMap(Map.empty).size shouldEqual 0 crp.VecMap(Map(10 -> 9)).size shouldEqual 1 } "offer a + method that combines sums (does Matrix addition on this one-row matrix)" in { val vecMap = crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9, 5 -> 25)) vecMap + crp.VecMap(Map.empty) shouldEqual vecMap crp.VecMap(Map.empty) + vecMap shouldEqual vecMap vecMap + vecMap shouldEqual crp.VecMap(Map(1 -> 2, 2 -> 8, 3 -> 18, 5 -> 50)) crp.VecMap(Map.empty) + crp.VecMap(Map.empty) shouldEqual crp.VecMap(Map.empty) vecMap + crp.VecMap(Map(77 -> 77, 88 -> 88, 99 -> 99)) shouldEqual crp.VecMap(Map(1 -> 1, 2 -> 4, 3 -> 9, 5 -> 25, 77 -> 77, 88 -> 88, 99 -> 99)) vecMap + crp.VecMap(Map(77 -> 77, 88 -> 88, 99 -> 99)) shouldEqual crp.VecMap(Map(2 -> 4, 3 -> 9, 5 -> 25, 77 -> 77, 88 -> 88, 99 -> 99, 1 -> 1)) } } }
bsd-3-clause
MvegaR/proyecto
frontend/views/edificio/update.php
568
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model frontend\models\Edificio */ $this->title = 'Modificar Edificio: ' . ' ' . $model->ID_EDIFICIO; $this->params['breadcrumbs'][] = ['label' => 'Edificios', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->ID_EDIFICIO, 'url' => ['view', 'id' => $model->ID_EDIFICIO]]; $this->params['breadcrumbs'][] = 'Update'; ?> <div class="edificio-update"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
bsd-3-clause
mcassola/ServerKinect
ServerKinect/Shape/GrahamScan.cs
2478
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.Shape { internal class GrahamScan { private IList<Point> points; public GrahamScan(IList<Point> points) { this.points = points; } public ConvexHull FindHull() { if (this.points.Count <= 3) { return new ConvexHull(this.points); } var pointsSortedByAngle = this.SortPointsByAngle(); int index = 1; while (index + 1 < pointsSortedByAngle.Count) { var value = PointAngleComparer2D.Compare(pointsSortedByAngle[index - 1], pointsSortedByAngle[index + 1], pointsSortedByAngle[index]); if (value < 0) { index++; } else //Also removes points that are on a line when value == 0 { pointsSortedByAngle.RemoveAt(index); if (index > 1) { index--; } } } pointsSortedByAngle.Add(pointsSortedByAngle.First()); return new ConvexHull(pointsSortedByAngle); } private Point FindMinimalOrdinatePoint() { var minPoint = this.points[0]; for (int index = 1; index < this.points.Count; index++) { minPoint = ReturnMinPoint(minPoint, this.points[index]); } return minPoint; } private Point ReturnMinPoint(Point p1, Point p2) { if (p1.Y < p2.Y) { return p1; } else if (p1.Y == p2.Y) { if (p1.X < p2.X) { return p1; } } return p2; } private IList<Point> SortPointsByAngle() { var p0 = this.FindMinimalOrdinatePoint(); var comparer = new PointAngleComparer2D(p0); var sortedPoints = new List<Point>(this.points); sortedPoints.Remove(p0); sortedPoints.Insert(0, p0); sortedPoints.Sort(1, sortedPoints.Count - 1, comparer); return sortedPoints; } } }
bsd-3-clause
NCIP/annotation-and-image-markup
ATB_1.0_src/src/main/java/edu/stanford/isis/atb/ui/view/widget/tree/renderer/template/ImagingObservationCharacteristicRenderer.java
2598
/* * 2010 – 2012 Copyright Northwestern University and Stanford University * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. */ package edu.stanford.isis.atb.ui.view.widget.tree.renderer.template; import static org.apache.commons.lang3.StringUtils.trimToEmpty; import javax.swing.Icon; import edu.stanford.isis.atb.domain.template.ImagingObservationCharacteristic; import edu.stanford.isis.atb.ui.Const; import edu.stanford.isis.atb.ui.view.resources.TreeImageBundle; import edu.stanford.isis.atb.ui.view.widget.tree.renderer.AbstractElementRenderer; import edu.stanford.isis.atb.ui.view.widget.tree.renderer.RenderInfo; /** * @author Vitaliy Semeshko */ public class ImagingObservationCharacteristicRenderer extends AbstractElementRenderer<ImagingObservationCharacteristic> { public ImagingObservationCharacteristicRenderer() { super(TreeImageBundle.getInstance().getImagingObservationCharIcon()); } @Override public RenderInfo collectRenderInfo(final ImagingObservationCharacteristic el) { return new RenderInfo() { @Override public String getText() { return "<html>Imaging Observation Characteristic: " + trimToEmpty(el.getLabel()) + "</html>"; } @Override public String getToolTipText() { return "<html>" + "<img src=\"" + ImagingObservationCharacteristicRenderer.this.getIconLocation() + "\"></img>" + "<b>&nbsp;" + "Imaging Observation Characteristic" + "</b><br><br>" + "<b>Label: </b> " + trimToEmpty(el.getLabel()) + "<br>" + "<b>Item Number: </b> " + trimToEmpty(String.valueOf(el.getItemNumber())) + "<br>" + "<b>Authors: </b> " + trimToEmpty(el.getAuthors()) + "<br>" + "<b>Explanatory Text: </b> " + shortText(el.getExplanatoryText()) + "<br>" + "<b>Min Cardinality: </b> " + trimToEmpty(String.valueOf(el.getMinCardinality())) + "<br>" + "<b>Max Cardinality: </b> " + getCardinalityText(el.getMaxCardinality()) + "<br>" + "<b>Should Display: </b> " + trimToEmpty(String.valueOf(el.isShouldDisplay())) + "<br>" + "<b>Annotator Confidence: </b> " + String.valueOf(el.isAnnotatorConfidence()) + "<br>" + "<b>Group Label: </b> " + trimToEmpty(el.getGroupLabel()) + "<br>" + "</html>"; } @Override public Icon getIcon() { return ImagingObservationCharacteristicRenderer.this.getIcon(); } private String getCardinalityText(long value) { return value >= Long.MAX_VALUE ? Const.TXT_INFINITY : String.valueOf(value); } }; } }
bsd-3-clause
adini121/atlassian
atlassian-visual-comparison/src/main/java/com/atlassian/selenium/visualcomparison/utils/ReportRenderer.java
1111
package com.atlassian.selenium.visualcomparison.utils; import com.atlassian.annotations.Internal; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import java.io.StringWriter; import java.util.Properties; @Internal public class ReportRenderer { private static boolean initialised = false; public static VelocityContext createContext() throws Exception { if (!initialised) { Properties p = new Properties(); p.setProperty("resource.loader", "class"); p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(p); initialised = true; } return new VelocityContext(); } public static String render(VelocityContext context, String templateName) throws Exception { Template template = Velocity.getTemplate(templateName); StringWriter sw = new StringWriter(); template.merge(context, sw); return sw.toString(); } }
bsd-3-clause
BaiduFE/Tangram-component
src/baidu/ui/Menubar/Menubar$fx.js
1252
/* * Tangram * Copyright 2009 Baidu Inc. All rights reserved. */ ///import baidu.ui.Menubar; ///import baidu.fx.expand; ///import baidu.fx.collapse; ///import baidu.dom.g; /** * 为Menubar增加动画效果 * @name baidu.ui.Menubar.Menubar$fx * @addon baidu.ui.Menubar */ baidu.ui.Menubar.extend({ enableFx:true, showFx : baidu.fx.expand, showFxOptions : {duration:200}, hideFx : baidu.fx.collapse, hideFxOptions : {duration:500,restoreAfterFinish:true} }); baidu.ui.Menubar.register(function(me){ if(me.enableFx){ var fxHandle = null; me.addEventListener('onopen', function(){ !baidu.ui.Menubar.showing && 'function' == typeof me.showFx && me.showFx(baidu.g(me.getId()),me.showFxOptions); }); me.addEventListener('onbeforeclose',function(e){ me.dispatchEvent("onclose"); fxHandle = me.hideFx(baidu.g(me.getId()),me.hideFxOptions); fxHandle.addEventListener('onafterfinish',function(){ me._close(); }); e.returnValue = false; }); me.addEventListener('ondispose', function(){ fxHandle && fxHandle.end(); }); } });
bsd-3-clause
manuelpichler/pdepend
src/main/php/PDepend/Source/AST/ASTArtifactList.php
6365
<?php /** * This file is part of PDepend. * * PHP Version 5 * * Copyright (c) 2008-2013, Manuel Pichler <mapi@pdepend.org>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Manuel Pichler nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @copyright 2008-2013 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ namespace PDepend\Source\AST; use PDepend\Source\AST\ASTArtifactList\CollectionArtifactFilter; /** * Iterator for code nodes. * * @copyright 2008-2013 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ class ASTArtifactList implements \ArrayAccess, \Iterator, \Countable { /** * The type of this class. */ const CLAZZ = __CLASS__; /** * List of {@link \PDepend\Source\AST\ASTArtifact} objects in * this iterator. * * @var \PDepend\Source\AST\ASTArtifact[] */ private $artifacts = array(); /** * Total number of available nodes. * * @var integer */ private $count = 0; /** * Current internal offset. * * @var integer */ private $offset = 0; /** * Constructs a new node iterator from the given {@link \PDepend\Source\AST\ASTArtifact} * node array. * * @param \PDepend\Source\AST\ASTArtifact[] $artifacts */ public function __construct(array $artifacts) { $filter = CollectionArtifactFilter::getInstance(); $nodeKeys = array(); foreach ($artifacts as $artifact) { $uuid = $artifact->getUuid(); if (isset($nodeKeys[$uuid])) { continue; } if ($filter->accept($artifact)) { $nodeKeys[$uuid] = $uuid; $this->artifacts[] = $artifact; ++$this->count; } } } /** * Returns the number of {@link \PDepend\Source\AST\ASTArtifact} * objects in this iterator. * * @return integer */ public function count() { return count($this->artifacts); } /** * Returns the current node or <b>false</b> * * @return \PDepend\Source\AST\ASTArtifact */ public function current() { if ($this->offset >= $this->count) { return false; } return $this->artifacts[$this->offset]; } /** * Returns the name of the current {@link \PDepend\Source\AST\ASTArtifact}. * * @return string */ public function key() { return $this->artifacts[$this->offset]->getName(); } /** * Moves the internal pointer to the next {@link \PDepend\Source\AST\ASTArtifact}. * * @return void */ public function next() { ++$this->offset; } /** * Rewinds the internal pointer. * * @return void */ public function rewind() { $this->offset = 0; } /** * Returns <b>true</b> while there is a next {@link \PDepend\Source\AST\ASTArtifact}. * * @return boolean */ public function valid() { return ($this->offset < $this->count); } /** * Whether a offset exists * * @param mixed $offset An offset to check for. * * @return boolean Returns true on success or false on failure. The return * value will be casted to boolean if non-boolean was returned. * @since 1.0.0 * @link http://php.net/manual/en/arrayaccess.offsetexists.php */ public function offsetExists($offset) { return isset($this->artifacts[$offset]); } /** * Offset to retrieve * * @param mixed $offset * @return \PDepend\Source\AST\ASTArtifact Can return all value types. * @throws \OutOfBoundsException * @since 1.0.0 * @link http://php.net/manual/en/arrayaccess.offsetget.php */ public function offsetGet($offset) { if (isset($this->artifacts[$offset])) { return $this->artifacts[$offset]; } throw new \OutOfBoundsException("The offset {$offset} does not exist."); } /** * Offset to set * * @param mixed $offset * @param mixed $value * @return void * @throws \BadMethodCallException * @since 1.0.0 * @link http://php.net/manual/en/arrayaccess.offsetset.php */ public function offsetSet($offset, $value) { throw new \BadMethodCallException('Not supported operation.'); } /** * Offset to unset * * @param mixed $offset * @return void * @throws \BadMethodCallException * @since 1.0.0 * @link http://php.net/manual/en/arrayaccess.offsetunset.php */ public function offsetUnset($offset) { throw new \BadMethodCallException('Not supported operation.'); } }
bsd-3-clause
ludoo/wpkit
attic/wpfrontman/extra/domain_based/urls_3.py
3597
'''WP Frontman urlrules for blog '3', generated on 2011-04-08T16:57:45.453238''' from django.conf.urls.defaults import * urlpatterns = patterns('wp_frontman.views', url('^$', 'index', name='wpf_index'), url('^page/(?P<page>[0-9]+)/$', 'index', name='wpf_index'), # url('^page(?P<page>[0-9]+)/$', 'index'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[^/]+)/$', 'post', name='wpf_post'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[^/]+)/page/(?P<page>[0-9]+)/$', 'post', name='wpf_post'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[^/]+)/trackback/$', 'trackback', name='wpf_trackback'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$', 'archives', name='wpf_archives'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/page/(?P<page>[0-9]+)/$', 'archives', name='wpf_archives'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/page(?P<page>[0-9]+)/$', 'archives'), url('^(?P<year>[0-9]{4})/$', 'archives', name='wpf_archives'), url('^(?P<year>[0-9]{4})/page/?(?P<page>[0-9]+)/$', 'archives', name='wpf_archives'), url('^author/(?P<slug>[^/]+)/$', 'author', name='wpf_author'), url('^author/(?P<slug>[^/]+)/page/?(?P<page>[0-9]+)/$', 'author', name='wpf_author'), url('^category/(?P<slug>[^/]+)/$', 'category', name='wpf_category'), url('^category/(?P<slug>[^/]+)/page/?(?P<page>[0-9]+)/$', 'category', name='wpf_category'), url('^search/$', 'search', name='wpf_search'), url('^search/(?P<q>.+)/$', 'search', name='wpf_search'), url('^search/(?P<q>.+)/page/?(?P<page>[0-9]+)/$', 'search', name='wpf_search'), url('^tag/(?P<slug>[^/]+)/$', 'tag', name='wpf_tag'), url('^tag/(?P<slug>[^/]+)/page/?(?P<page>[0-9]+)/$', 'tag', name='wpf_tag'), url('^feed/$', 'feed', name='wpf_feed'), url('^(?:feed/)?(?:feed|rdf|rss|rss2|atom)/$', 'feed'), url('^wp-(?:atom|feed|rdf|rss|rss2)\.php$', 'feed'), url('^comments/feed/$', 'feed_comments', name='wpf_feed_comments'), url('^comments/(?:feed/)?(?P<feed_type>feed|rdf|rss|rss2|atom)/$', 'feed_comments'), url('^wp-commentsrss2.php$', 'feed_comments'), url('^author/(?P<nicename>[^/]+)/feed/$', 'feed_author', name='wpf_feed_author'), url('^author/(?P<nicename>[^/]+)(?:/feed)?/(?P<feed_type>feed|rdf|rss|rss2|atom)/$', 'feed_author'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[^/]+)/feed/$', 'feed_post', name='wpf_feed_post'), url('^(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/(?P<day>[0-9]{1,2})/(?P<slug>[^/]+)/(?:feed/)?(?P<feed_type>feed|rdf|rss|rss2|atom)/$', 'feed_post'), # change the following according to your needs, url('^users/registration/$', 'user_registration', 'wpf_user_registration'), url('^users/activation/$', 'user_activation', 'wpf_user_activation'), url('^users/login/$', 'user_login', 'wpf_user_login'), # dummy rules to have reverse url mapping work when using wp for users stuff, #url('^wp-signup.php$', 'user_registration', 'wpf_user_registration'), #url('^wp-activate.php$', 'user_activation', 'wpf_user_activation'), #url('^wp-login.php$', 'user_login', 'wpf_user_login'), #url('^category/(?P<slug>[^/]+)(?:/feed)?/(?P<feed_type>feed|rdf|rss|rss2|atom)/$', 'feed_category', name='wpf_feed_category'), #url('^search/(?P<q>.+)(?:/feed)?/(?P<feed_type>feed|rdf|rss|rss2|atom)/$', 'feed_search', name='wpf_feed_search'), #url('^tag/(?P<slug>[^/]+)(?:/feed)?/(?P<feed_type>feed|rdf|rss|rss2|atom)/$', 'feed_tag', name='wpf_feed_tag') )
bsd-3-clause
stefanberndtsson/nmdb3
app/models/goof.rb
56
class Goof < ActiveRecord::Base belongs_to :movie end
bsd-3-clause
maxhutch/magma
testing/testing_cgemv_batched.cpp
8621
/* -- MAGMA (version 2.1.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date August 2016 @generated from testing/testing_zgemv_batched.cpp, normal z -> c, Tue Aug 30 09:39:16 2016 @author Mark Gates @author Azzam Haidar @author Tingxing Dong */ // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // includes, project #include "flops.h" #include "magma_v2.h" #include "magma_lapack.h" #include "testings.h" #if defined(_OPENMP) #include <omp.h> #include "../control/magma_threadsetting.h" // internal header #endif /* //////////////////////////////////////////////////////////////////////////// -- Testing cgemm_batched */ int main( int argc, char** argv) { TESTING_CHECK( magma_init() ); magma_print_environment(); real_Double_t gflops, magma_perf, magma_time, cpu_perf, cpu_time; float magma_error, work[1]; magma_int_t M, N, Xm, Ym, lda, ldda; magma_int_t sizeA, sizeX, sizeY; magma_int_t incx = 1; magma_int_t incy = 1; magma_int_t ione = 1; magma_int_t ISEED[4] = {0,0,0,1}; int status = 0; magma_int_t batchCount; magmaFloatComplex *h_A, *h_X, *h_Y, *h_Ymagma; magmaFloatComplex *d_A, *d_X, *d_Y; magmaFloatComplex c_neg_one = MAGMA_C_NEG_ONE; magmaFloatComplex alpha = MAGMA_C_MAKE( 0.29, -0.86 ); magmaFloatComplex beta = MAGMA_C_MAKE( -0.48, 0.38 ); magmaFloatComplex **A_array = NULL; magmaFloatComplex **X_array = NULL; magmaFloatComplex **Y_array = NULL; magma_opts opts( MagmaOptsBatched ); opts.parse_opts( argc, argv ); batchCount = opts.batchcount; opts.lapack |= opts.check; float tol = opts.tolerance * lapackf77_slamch("E"); printf("%% trans = %s\n", lapack_trans_const(opts.transA) ); printf("%% BatchCount M N MAGMA Gflop/s (ms) CPU Gflop/s (ms) MAGMA error\n"); printf("%%============================================================================\n"); for( int itest = 0; itest < opts.ntest; ++itest ) { for( int iter = 0; iter < opts.niter; ++iter ) { M = opts.msize[itest]; N = opts.nsize[itest]; lda = M; ldda = magma_roundup( M, opts.align ); // multiple of 32 by default gflops = FLOPS_CGEMV( M, N ) / 1e9 * batchCount; if ( opts.transA == MagmaNoTrans ) { Xm = N; Ym = M; } else { Xm = M; Ym = N; } sizeA = lda*N*batchCount; sizeX = incx*Xm*batchCount; sizeY = incy*Ym*batchCount; TESTING_CHECK( magma_cmalloc_cpu( &h_A, sizeA )); TESTING_CHECK( magma_cmalloc_cpu( &h_X, sizeX )); TESTING_CHECK( magma_cmalloc_cpu( &h_Y, sizeY )); TESTING_CHECK( magma_cmalloc_cpu( &h_Ymagma, sizeY )); TESTING_CHECK( magma_cmalloc( &d_A, ldda*N*batchCount )); TESTING_CHECK( magma_cmalloc( &d_X, sizeX )); TESTING_CHECK( magma_cmalloc( &d_Y, sizeY )); TESTING_CHECK( magma_malloc( (void**) &A_array, batchCount * sizeof(magmaFloatComplex*) )); TESTING_CHECK( magma_malloc( (void**) &X_array, batchCount * sizeof(magmaFloatComplex*) )); TESTING_CHECK( magma_malloc( (void**) &Y_array, batchCount * sizeof(magmaFloatComplex*) )); /* Initialize the matrices */ lapackf77_clarnv( &ione, ISEED, &sizeA, h_A ); lapackf77_clarnv( &ione, ISEED, &sizeX, h_X ); lapackf77_clarnv( &ione, ISEED, &sizeY, h_Y ); /* ===================================================================== Performs operation using MAGMABLAS =================================================================== */ magma_csetmatrix( M, N*batchCount, h_A, lda, d_A, ldda, opts.queue ); magma_csetvector( Xm*batchCount, h_X, incx, d_X, incx, opts.queue ); magma_csetvector( Ym*batchCount, h_Y, incy, d_Y, incy, opts.queue ); magma_cset_pointer( A_array, d_A, ldda, 0, 0, ldda*N, batchCount, opts.queue ); magma_cset_pointer( X_array, d_X, 1, 0, 0, incx*Xm, batchCount, opts.queue ); magma_cset_pointer( Y_array, d_Y, 1, 0, 0, incy*Ym, batchCount, opts.queue ); magma_time = magma_sync_wtime( opts.queue ); magmablas_cgemv_batched(opts.transA, M, N, alpha, A_array, ldda, X_array, incx, beta, Y_array, incy, batchCount, opts.queue); magma_time = magma_sync_wtime( opts.queue ) - magma_time; magma_perf = gflops / magma_time; magma_cgetvector( Ym*batchCount, d_Y, incy, h_Ymagma, incy, opts.queue ); /* ===================================================================== Performs operation using CPU BLAS =================================================================== */ if ( opts.lapack ) { cpu_time = magma_wtime(); #if !defined (BATCHED_DISABLE_PARCPU) && defined(_OPENMP) magma_int_t nthreads = magma_get_lapack_numthreads(); magma_set_lapack_numthreads(1); magma_set_omp_numthreads(nthreads); #pragma omp parallel for schedule(dynamic) #endif for (int i=0; i < batchCount; i++) { blasf77_cgemv( lapack_trans_const(opts.transA), &M, &N, &alpha, h_A + i*lda*N, &lda, h_X + i*Xm, &incx, &beta, h_Y + i*Ym, &incy ); } #if !defined (BATCHED_DISABLE_PARCPU) && defined(_OPENMP) magma_set_lapack_numthreads(nthreads); #endif cpu_time = magma_wtime() - cpu_time; cpu_perf = gflops / cpu_time; } /* ===================================================================== Check the result =================================================================== */ if ( opts.lapack ) { // compute relative error for magma, relative to lapack, // |C_magma - C_lapack| / |C_lapack| magma_error = 0; for (int s=0; s < batchCount; s++) { float Anorm = lapackf77_clange( "F", &M, &N, h_A + s * lda * N, &lda, work ); float Xnorm = lapackf77_clange( "F", &Xm, &ione, h_X + s * Xm, &Xm, work ); blasf77_caxpy( &Ym, &c_neg_one, h_Y + s * Ym, &incy, h_Ymagma + s * Ym, &incy ); float err = lapackf77_clange( "F", &Ym, &ione, h_Ymagma + s * Ym, &Ym, work ) / (Anorm * Xnorm); if ( isnan(err) || isinf(err) ) { magma_error = err; break; } magma_error = max( err, magma_error ); } bool okay = (magma_error < tol); status += ! okay; printf("%10lld %5lld %5lld %7.2f (%7.2f) %7.2f (%7.2f) %8.2e %s\n", (long long) batchCount, (long long) M, (long long) N, magma_perf, 1000.*magma_time, cpu_perf, 1000.*cpu_time, magma_error, (okay ? "ok" : "failed")); } else { printf("%10lld %5lld %5lld %7.2f (%7.2f) --- ( --- ) ---\n", (long long) batchCount, (long long) M, (long long) N, magma_perf, 1000.*magma_time); } magma_free_cpu( h_A ); magma_free_cpu( h_X ); magma_free_cpu( h_Y ); magma_free_cpu( h_Ymagma ); magma_free( d_A ); magma_free( d_X ); magma_free( d_Y ); magma_free( A_array ); magma_free( X_array ); magma_free( Y_array ); fflush( stdout); } if ( opts.niter > 1 ) { printf( "\n" ); } } opts.cleanup(); TESTING_CHECK( magma_finalize() ); return status; }
bsd-3-clause
ms2300/multiplayer-elo
elo_classes.py
1033
# Copyright (c) 2016 by Matt Sewall. # All rights reserved. class Competitor: def __init__(self, name, school, place, elo): self.name = name self.school = school self.place = place self.elo = elo def __eq__(self, other): return self.name == other.name and \ self.school == other.school def __hash__(self): return hash((self.name, self.school)) # Used as a class for example.py, and is not relevant to the core algorithm class Athlete: def __init__(self, name, school): self.name = name self.school = school def __eq__(self, other): return self.name == other.name and \ self.school == other.school def __hash__(self): return hash((self.name, self.school)) def __repr__(self): return self.name class Meet: competitors = [] def addCompetitor(self, name, place, elo, school): player = Competitor(name, school, place, elo) self.competitors.append(player)
bsd-3-clause
fjcorona/zfpruebasoap2
module/Soapserver/config/module.config.php
2189
<?php return array( 'view_manager' => array( 'template_path_stack' => array( 'indexcontroller' => __DIR__ . '/../view', ), 'strategies' => array( 'ViewJsonStrategy' ) ), 'controllers' => array( 'invokables' => array( 'indexcontroller' => 'Soapserver\Controller\IndexController', ), ), 'router' => array( 'routes' => array( 'indexcontroller' => array( 'type' => 'Literal', 'priority' => 1000, 'options' => array( 'route' => '/soapserver', 'defaults' => array( 'controller' => 'indexcontroller', 'action' => 'index', ), ), 'may_terminate' => true, 'child_routes' => array( 'soap' => array( 'type' => 'Literal', 'options' => array( 'route' => '/soap', 'defaults' => array( 'controller' => 'indexcontroller', 'action' => 'soap', ), ), ), 'cliente' => array( 'type' => 'Literal', 'options' => array( 'route' => '/cliente', 'defaults' => array( 'controller' => 'indexcontroller', 'action' => 'cliente', ), ), ), ), ), ), ), );
bsd-3-clause
NCIP/ctms-commons
grid/ccts-grid-services/cagrid14-services/RegistrationConsumerGridService-caGrid1.4/src/gov/nih/nci/ccts/grid/service/RegistrationConsumerImplBase.java
2147
/* * Copyright Northwestern University and SemanticBits, LLC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/ctms-commons/LICENSE.txt for details. */ package gov.nih.nci.ccts.grid.service; import gov.nih.nci.ccts.grid.service.globus.resource.RegistrationConsumerResource; import gov.nih.nci.ccts.grid.service.RegistrationConsumerConfiguration; import java.rmi.RemoteException; import javax.naming.InitialContext; import javax.xml.namespace.QName; import org.apache.axis.MessageContext; import org.globus.wsrf.Constants; import org.globus.wsrf.ResourceContext; import org.globus.wsrf.ResourceContextException; import org.globus.wsrf.ResourceException; import org.globus.wsrf.ResourceHome; import org.globus.wsrf.ResourceProperty; import org.globus.wsrf.ResourcePropertySet; /** * DO NOT EDIT: This class is autogenerated! * * Provides some simple accessors for the Impl. * * @created by Introduce Toolkit version 1.4 * */ public abstract class RegistrationConsumerImplBase { public RegistrationConsumerImplBase() throws RemoteException { } public RegistrationConsumerConfiguration getConfiguration() throws Exception { return RegistrationConsumerConfiguration.getConfiguration(); } public gov.nih.nci.ccts.grid.service.globus.resource.RegistrationConsumerResourceHome getResourceHome() throws Exception { ResourceHome resource = getResourceHome("home"); return (gov.nih.nci.ccts.grid.service.globus.resource.RegistrationConsumerResourceHome)resource; } protected ResourceHome getResourceHome(String resourceKey) throws Exception { MessageContext ctx = MessageContext.getCurrentContext(); ResourceHome resourceHome = null; String servicePath = ctx.getTargetService(); String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/" + resourceKey; try { javax.naming.Context initialContext = new InitialContext(); resourceHome = (ResourceHome) initialContext.lookup(jndiName); } catch (Exception e) { throw new Exception("Unable to instantiate resource home. : " + resourceKey, e); } return resourceHome; } }
bsd-3-clause
cdvcz/datex2
datex2-api/src/main/java/cz/cdv/datex2/internal/ClientSubscriptionImpl.java
3448
package cz.cdv.datex2.internal; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.jws.WebService; import org.springframework.beans.factory.annotation.Autowired; import cz.cdv.datex2.wsdl.clientsubscribe.ClientSubscribeInterface; import eu.datex2.schema._2._2_0.D2LogicalModel; import eu.datex2.schema._2._2_0.Exchange; import eu.datex2.schema._2._2_0.OperatingModeEnum; import eu.datex2.schema._2._2_0.Subscription; import eu.datex2.schema._2._2_0.Target; import eu.datex2.schema._2._2_0.UpdateMethodEnum; @WebService(endpointInterface = "cz.cdv.datex2.wsdl.clientsubscribe.ClientSubscribeInterface", targetNamespace = "http://cdv.cz/datex2/wsdl/clientSubscribe", name = "clientSubscribeInterface", serviceName = "clientSubscribeService", portName = "clientSubscribeSoapEndPoint") public class ClientSubscriptionImpl implements ClientSubscribeInterface { @Autowired private Subscriptions subscriptions; private String supplierPath; public ClientSubscriptionImpl(String supplierPath, String subscriptionPath) { this.supplierPath = supplierPath; } @Override public String subscribe(D2LogicalModel body) { if (body == null || body.getExchange() == null || body.getExchange().getSubscription() == null) return null; Exchange exchange = body.getExchange(); String subscriptionReference = exchange.getSubscriptionReference(); Subscription subscription = exchange.getSubscription(); if (subscription == null) return null; OperatingModeEnum mode = subscription.getOperatingMode(); if (Boolean.TRUE.equals(subscription.isDeleteSubscription())) { if (subscriptionReference != null) { subscriptions.delete(supplierPath, subscriptionReference); } return null; } UpdateMethodEnum updateMethod = subscription.getUpdateMethod(); List<PushTarget> pushTargets = getPushTargets(subscription.getTarget()); Float periodSeconds = subscription.getDeliveryInterval(); Calendar startTime = subscription.getSubscriptionStartTime(); Calendar stopTime = subscription.getSubscriptionStopTime(); if (mode == OperatingModeEnum.OPERATING_MODE_2 && periodSeconds != null) { // push periodic if (periodSeconds <= 0) return null; if (subscriptionReference == null) { String reference = subscriptions.addPeriodic(supplierPath, startTime, stopTime, periodSeconds, updateMethod, pushTargets); return reference; } else { String reference = subscriptions.updatePeriodic(supplierPath, subscriptionReference, startTime, stopTime, periodSeconds, updateMethod, pushTargets); return reference; } } else if (mode == OperatingModeEnum.OPERATING_MODE_1) { // push on occurrence if (subscriptionReference == null) { String reference = subscriptions.add(supplierPath, updateMethod, startTime, stopTime, pushTargets); return reference; } else { String reference = subscriptions.update(supplierPath, subscriptionReference, updateMethod, startTime, stopTime, pushTargets); return reference; } } else { return subscriptionReference; } } private List<PushTarget> getPushTargets(List<Target> targets) { List<PushTarget> pushTargets = new ArrayList<>(); if (targets == null || targets.size() == 0) return pushTargets; for (Target t : targets) { if (t == null) continue; pushTargets.add(PushTarget.create(t)); } return pushTargets; } }
bsd-3-clause
NanaYngvarrdottir/Software-Testing
OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs
10983
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using OpenMetaverse; using Aurora.Framework; namespace OpenSim.Region.Framework.Scenes.Serialization { /// <summary> /// Static methods to serialize and deserialize scene objects to and from XML /// </summary> public class SceneXmlLoader { public static void LoadPrimsFromXml(IScene scene, string fileName, bool newIDS, Vector3 loadOffset) { XmlDocument doc = new XmlDocument(); if (fileName.StartsWith("http:") || File.Exists(fileName)) { XmlTextReader reader = new XmlTextReader(fileName) {WhitespaceHandling = WhitespaceHandling.None}; doc.Load(reader); reader.Close(); XmlNode rootNode = doc.FirstChild; foreach (XmlNode aPrimNode in rootNode.ChildNodes) { SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml, scene); if (group == null) return; group.IsDeleted = false; group.m_isLoaded = true; foreach (SceneObjectPart part in group.ChildrenList) { part.IsLoading = false; } scene.SceneGraph.AddPrimToScene(group); } } else { throw new Exception("Could not open file " + fileName + " for reading"); } } public static void SavePrimsToXml(IScene scene, string fileName) { FileStream file = new FileStream(fileName, FileMode.Create); StreamWriter stream = new StreamWriter(file); int primCount = 0; stream.WriteLine("<scene>\n"); ISceneEntity[] entityList = scene.Entities.GetEntities (); foreach (ISceneEntity ent in entityList) { if (ent is SceneObjectGroup) { stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent)); primCount++; } } stream.WriteLine("</scene>\n"); stream.Close(); file.Close(); } public static string SaveGroupToXml2(SceneObjectGroup grp) { return SceneObjectSerializer.ToXml2Format(grp); } public static SceneObjectGroup DeserializeGroupFromXml2 (string xmlString, IScene scene) { XmlDocument doc = new XmlDocument (); XmlTextReader reader = new XmlTextReader(new StringReader(xmlString)) {WhitespaceHandling = WhitespaceHandling.None}; doc.Load (reader); reader.Close (); XmlNode rootNode = doc.FirstChild; return SceneObjectSerializer.FromXml2Format (rootNode.OuterXml, scene); } public static SceneObjectGroup DeserializeGroupFromXml2 (byte[] xml, IScene scene) { XmlDocument doc = new XmlDocument (); MemoryStream stream = new MemoryStream (xml); XmlTextReader reader = new XmlTextReader(stream) {WhitespaceHandling = WhitespaceHandling.None}; doc.Load (reader); reader.Close (); stream.Close (); XmlNode rootNode = doc.FirstChild; return SceneObjectSerializer.FromXml2Format (rootNode.OuterXml, scene); } /// <summary> /// Load prims from the xml2 format. This method will close the reader /// </summary> /// <param name="scene"></param> /// <param name="reader"></param> /// <param name="startScripts"></param> public static void LoadPrimsFromXml2(IScene scene, XmlTextReader reader, bool startScripts) { XmlDocument doc = new XmlDocument(); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); reader.Close(); XmlNode rootNode = doc.FirstChild; #if (!ISWIN) List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); foreach(XmlNode aPrimNode in rootNode.ChildNodes) { SceneObjectGroup grp = CreatePrimFromXml2(scene, aPrimNode.OuterXml); if(grp != null) sceneObjects.Add(grp); } #else ICollection<SceneObjectGroup> sceneObjects = rootNode.ChildNodes.Cast<XmlNode>().Select(aPrimNode => CreatePrimFromXml2(scene, aPrimNode.OuterXml)). Where(obj => obj != null).ToList(); #endif foreach (SceneObjectGroup sceneObject in sceneObjects) { if (scene.SceneGraph.AddPrimToScene(sceneObject)) { sceneObject.ScheduleGroupUpdate (PrimUpdateFlags.ForcedFullUpdate); if (startScripts) { sceneObject.CreateScriptInstances(0, false, StateSource.RegionStart, UUID.Zero, false); } } } } /// <summary> /// Create a prim from the xml2 representation. /// </summary> /// <param name="scene"></param> /// <param name="xmlData"></param> /// <returns>The scene object created. null if the scene object already existed</returns> protected static SceneObjectGroup CreatePrimFromXml2(IScene scene, string xmlData) { SceneObjectGroup obj = DeserializeGroupFromXml2(xmlData, scene); return obj; } public static void SavePrimsToXml2(IScene scene, string fileName) { ISceneEntity[] entityList = scene.Entities.GetEntities (); SavePrimListToXml2(entityList, fileName); } public static void SavePrimsToXml2(IScene scene, TextWriter stream, Vector3 min, Vector3 max) { ISceneEntity[] entityList = scene.Entities.GetEntities (); SavePrimListToXml2(entityList, stream, min, max); } public static void SaveNamedPrimsToXml2(IScene scene, string primName, string fileName) { //MainConsole.Instance.InfoFormat( // "[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}", // primName, scene.RegionInfo.RegionName, fileName); ISceneEntity[] entityList = scene.Entities.GetEntities (); #if (!ISWIN) List<ISceneEntity> primList = new List<ISceneEntity>(); foreach (ISceneEntity ent in entityList) { if (ent is SceneObjectGroup) { if (ent.Name == primName) { primList.Add(ent); } } } SavePrimListToXml2(primList.ToArray(), fileName); #else SavePrimListToXml2(entityList.OfType<SceneObjectGroup>().Where(ent => ent.Name == primName).Cast<ISceneEntity>().ToArray(), fileName); #endif } public static void SavePrimListToXml2 (ISceneEntity[] entityList, string fileName) { FileStream file = new FileStream(fileName, FileMode.Create); try { StreamWriter stream = new StreamWriter(file); try { SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero); } finally { stream.Close(); } } finally { file.Close(); } } public static void SavePrimListToXml2 (ISceneEntity[] entityList, TextWriter stream, Vector3 min, Vector3 max) { int primCount = 0; stream.WriteLine("<scene>\n"); foreach (ISceneEntity ent in entityList) { if (ent is SceneObjectGroup) { SceneObjectGroup g = (SceneObjectGroup)ent; if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero)) { Vector3 pos = g.RootPart.GetWorldPosition(); if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z) continue; if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z) continue; } stream.WriteLine(SceneObjectSerializer.ToXml2Format(g)); //SceneObjectSerializer.SOGToXml2(writer, (SceneObjectGroup)ent); //stream.WriteLine(); primCount++; } } stream.WriteLine("</scene>\n"); stream.Flush(); } } }
bsd-3-clause
chromium2014/src
content/browser/indexed_db/indexed_db_factory_unittest.cc
18574
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/indexed_db_factory.h" #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_simple_task_runner.h" #include "content/browser/indexed_db/indexed_db_connection.h" #include "content/browser/indexed_db/indexed_db_context_impl.h" #include "content/browser/indexed_db/mock_indexed_db_callbacks.h" #include "content/browser/indexed_db/mock_indexed_db_database_callbacks.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebIDBDatabaseException.h" #include "third_party/WebKit/public/platform/WebIDBTypes.h" #include "url/gurl.h" #include "webkit/common/database/database_identifier.h" using base::ASCIIToUTF16; namespace content { namespace { class MockIDBFactory : public IndexedDBFactory { public: explicit MockIDBFactory(IndexedDBContextImpl* context) : IndexedDBFactory(context) {} scoped_refptr<IndexedDBBackingStore> TestOpenBackingStore( const GURL& origin, const base::FilePath& data_directory) { blink::WebIDBDataLoss data_loss = blink::WebIDBDataLossNone; std::string data_loss_message; bool disk_full; leveldb::Status s; scoped_refptr<IndexedDBBackingStore> backing_store = OpenBackingStore(origin, data_directory, NULL /* request_context */, &data_loss, &data_loss_message, &disk_full, &s); EXPECT_EQ(blink::WebIDBDataLossNone, data_loss); return backing_store; } void TestCloseBackingStore(IndexedDBBackingStore* backing_store) { CloseBackingStore(backing_store->origin_url()); } void TestReleaseBackingStore(IndexedDBBackingStore* backing_store, bool immediate) { ReleaseBackingStore(backing_store->origin_url(), immediate); } private: virtual ~MockIDBFactory() {} DISALLOW_COPY_AND_ASSIGN(MockIDBFactory); }; } // namespace class IndexedDBFactoryTest : public testing::Test { public: IndexedDBFactoryTest() { task_runner_ = new base::TestSimpleTaskRunner(); context_ = new IndexedDBContextImpl(base::FilePath(), NULL /* special_storage_policy */, NULL /* quota_manager_proxy */, task_runner_.get()); idb_factory_ = new MockIDBFactory(context_.get()); } protected: // For timers to post events. base::MessageLoop loop_; MockIDBFactory* factory() const { return idb_factory_.get(); } void clear_factory() { idb_factory_ = NULL; } IndexedDBContextImpl* context() const { return context_.get(); } private: scoped_refptr<base::TestSimpleTaskRunner> task_runner_; scoped_refptr<IndexedDBContextImpl> context_; scoped_refptr<MockIDBFactory> idb_factory_; DISALLOW_COPY_AND_ASSIGN(IndexedDBFactoryTest); }; TEST_F(IndexedDBFactoryTest, BackingStoreLifetime) { GURL origin1("http://localhost:81"); GURL origin2("http://localhost:82"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); scoped_refptr<IndexedDBBackingStore> disk_store1 = factory()->TestOpenBackingStore(origin1, temp_directory.path()); scoped_refptr<IndexedDBBackingStore> disk_store2 = factory()->TestOpenBackingStore(origin1, temp_directory.path()); EXPECT_EQ(disk_store1.get(), disk_store2.get()); scoped_refptr<IndexedDBBackingStore> disk_store3 = factory()->TestOpenBackingStore(origin2, temp_directory.path()); factory()->TestCloseBackingStore(disk_store1); factory()->TestCloseBackingStore(disk_store3); EXPECT_FALSE(disk_store1->HasOneRef()); EXPECT_FALSE(disk_store2->HasOneRef()); EXPECT_TRUE(disk_store3->HasOneRef()); disk_store2 = NULL; EXPECT_TRUE(disk_store1->HasOneRef()); } TEST_F(IndexedDBFactoryTest, BackingStoreLazyClose) { GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); scoped_refptr<IndexedDBBackingStore> store = factory()->TestOpenBackingStore(origin, temp_directory.path()); // Give up the local refptr so that the factory has the only // outstanding reference. IndexedDBBackingStore* store_ptr = store.get(); store = NULL; EXPECT_FALSE(store_ptr->close_timer()->IsRunning()); factory()->TestReleaseBackingStore(store_ptr, false); EXPECT_TRUE(store_ptr->close_timer()->IsRunning()); factory()->TestOpenBackingStore(origin, temp_directory.path()); EXPECT_FALSE(store_ptr->close_timer()->IsRunning()); factory()->TestReleaseBackingStore(store_ptr, false); EXPECT_TRUE(store_ptr->close_timer()->IsRunning()); // Take back a ref ptr and ensure that the actual close // stops a running timer. store = store_ptr; factory()->TestCloseBackingStore(store_ptr); EXPECT_FALSE(store_ptr->close_timer()->IsRunning()); } TEST_F(IndexedDBFactoryTest, MemoryBackingStoreLifetime) { GURL origin1("http://localhost:81"); GURL origin2("http://localhost:82"); scoped_refptr<IndexedDBBackingStore> mem_store1 = factory()->TestOpenBackingStore(origin1, base::FilePath()); scoped_refptr<IndexedDBBackingStore> mem_store2 = factory()->TestOpenBackingStore(origin1, base::FilePath()); EXPECT_EQ(mem_store1.get(), mem_store2.get()); scoped_refptr<IndexedDBBackingStore> mem_store3 = factory()->TestOpenBackingStore(origin2, base::FilePath()); factory()->TestCloseBackingStore(mem_store1); factory()->TestCloseBackingStore(mem_store3); EXPECT_FALSE(mem_store1->HasOneRef()); EXPECT_FALSE(mem_store2->HasOneRef()); EXPECT_FALSE(mem_store3->HasOneRef()); clear_factory(); EXPECT_FALSE(mem_store1->HasOneRef()); // mem_store1 and 2 EXPECT_FALSE(mem_store2->HasOneRef()); // mem_store1 and 2 EXPECT_TRUE(mem_store3->HasOneRef()); mem_store2 = NULL; EXPECT_TRUE(mem_store1->HasOneRef()); } TEST_F(IndexedDBFactoryTest, RejectLongOrigins) { base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); const base::FilePath base_path = temp_directory.path(); int limit = base::GetMaximumPathComponentLength(base_path); EXPECT_GT(limit, 0); std::string origin(limit + 1, 'x'); GURL too_long_origin("http://" + origin + ":81/"); scoped_refptr<IndexedDBBackingStore> diskStore1 = factory()->TestOpenBackingStore(too_long_origin, base_path); EXPECT_FALSE(diskStore1); GURL ok_origin("http://someorigin.com:82/"); scoped_refptr<IndexedDBBackingStore> diskStore2 = factory()->TestOpenBackingStore(ok_origin, base_path); EXPECT_TRUE(diskStore2); } class DiskFullFactory : public IndexedDBFactory { public: explicit DiskFullFactory(IndexedDBContextImpl* context) : IndexedDBFactory(context) {} private: virtual ~DiskFullFactory() {} virtual scoped_refptr<IndexedDBBackingStore> OpenBackingStore( const GURL& origin_url, const base::FilePath& data_directory, net::URLRequestContext* request_context, blink::WebIDBDataLoss* data_loss, std::string* data_loss_message, bool* disk_full, leveldb::Status* s) OVERRIDE { *disk_full = true; *s = leveldb::Status::IOError("Disk is full"); return scoped_refptr<IndexedDBBackingStore>(); } DISALLOW_COPY_AND_ASSIGN(DiskFullFactory); }; class LookingForQuotaErrorMockCallbacks : public IndexedDBCallbacks { public: LookingForQuotaErrorMockCallbacks() : IndexedDBCallbacks(NULL, 0, 0), error_called_(false) {} virtual void OnError(const IndexedDBDatabaseError& error) OVERRIDE { error_called_ = true; EXPECT_EQ(blink::WebIDBDatabaseExceptionQuotaError, error.code()); } bool error_called() const { return error_called_; } private: virtual ~LookingForQuotaErrorMockCallbacks() {} bool error_called_; DISALLOW_COPY_AND_ASSIGN(LookingForQuotaErrorMockCallbacks); }; TEST_F(IndexedDBFactoryTest, QuotaErrorOnDiskFull) { const GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); scoped_refptr<DiskFullFactory> factory = new DiskFullFactory(context()); scoped_refptr<LookingForQuotaErrorMockCallbacks> callbacks = new LookingForQuotaErrorMockCallbacks; scoped_refptr<IndexedDBDatabaseCallbacks> dummy_database_callbacks = new IndexedDBDatabaseCallbacks(NULL, 0, 0); const base::string16 name(ASCIIToUTF16("name")); IndexedDBPendingConnection connection(callbacks, dummy_database_callbacks, 0, /* child_process_id */ 2, /* transaction_id */ 1 /* version */); factory->Open(name, connection, NULL /* request_context */, origin, temp_directory.path()); EXPECT_TRUE(callbacks->error_called()); } TEST_F(IndexedDBFactoryTest, BackingStoreReleasedOnForcedClose) { GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); scoped_refptr<MockIndexedDBCallbacks> callbacks(new MockIndexedDBCallbacks()); scoped_refptr<MockIndexedDBDatabaseCallbacks> db_callbacks( new MockIndexedDBDatabaseCallbacks()); const int64 transaction_id = 1; IndexedDBPendingConnection connection( callbacks, db_callbacks, 0, /* child_process_id */ transaction_id, IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION); factory()->Open(ASCIIToUTF16("db"), connection, NULL /* request_context */, origin, temp_directory.path()); EXPECT_TRUE(callbacks->connection()); EXPECT_TRUE(factory()->IsBackingStoreOpen(origin)); EXPECT_FALSE(factory()->IsBackingStorePendingClose(origin)); callbacks->connection()->ForceClose(); EXPECT_FALSE(factory()->IsBackingStoreOpen(origin)); EXPECT_FALSE(factory()->IsBackingStorePendingClose(origin)); } TEST_F(IndexedDBFactoryTest, BackingStoreReleaseDelayedOnClose) { GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); scoped_refptr<MockIndexedDBCallbacks> callbacks(new MockIndexedDBCallbacks()); scoped_refptr<MockIndexedDBDatabaseCallbacks> db_callbacks( new MockIndexedDBDatabaseCallbacks()); const int64 transaction_id = 1; IndexedDBPendingConnection connection( callbacks, db_callbacks, 0, /* child_process_id */ transaction_id, IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION); factory()->Open(ASCIIToUTF16("db"), connection, NULL /* request_context */, origin, temp_directory.path()); EXPECT_TRUE(callbacks->connection()); IndexedDBBackingStore* store = callbacks->connection()->database()->backing_store(); EXPECT_FALSE(store->HasOneRef()); // Factory and database. EXPECT_TRUE(factory()->IsBackingStoreOpen(origin)); callbacks->connection()->Close(); EXPECT_TRUE(store->HasOneRef()); // Factory. EXPECT_TRUE(factory()->IsBackingStoreOpen(origin)); EXPECT_TRUE(factory()->IsBackingStorePendingClose(origin)); EXPECT_TRUE(store->close_timer()->IsRunning()); // Take a ref so it won't be destroyed out from under the test. scoped_refptr<IndexedDBBackingStore> store_ref = store; // Now simulate shutdown, which should stop the timer. factory()->ContextDestroyed(); EXPECT_TRUE(store->HasOneRef()); // Local. EXPECT_FALSE(store->close_timer()->IsRunning()); EXPECT_FALSE(factory()->IsBackingStoreOpen(origin)); EXPECT_FALSE(factory()->IsBackingStorePendingClose(origin)); } TEST_F(IndexedDBFactoryTest, DeleteDatabaseClosesBackingStore) { GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); EXPECT_FALSE(factory()->IsBackingStoreOpen(origin)); const bool expect_connection = false; scoped_refptr<MockIndexedDBCallbacks> callbacks( new MockIndexedDBCallbacks(expect_connection)); factory()->DeleteDatabase(ASCIIToUTF16("db"), NULL /* request_context */, callbacks, origin, temp_directory.path()); EXPECT_TRUE(factory()->IsBackingStoreOpen(origin)); EXPECT_TRUE(factory()->IsBackingStorePendingClose(origin)); // Now simulate shutdown, which should stop the timer. factory()->ContextDestroyed(); EXPECT_FALSE(factory()->IsBackingStoreOpen(origin)); EXPECT_FALSE(factory()->IsBackingStorePendingClose(origin)); } TEST_F(IndexedDBFactoryTest, GetDatabaseNamesClosesBackingStore) { GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); EXPECT_FALSE(factory()->IsBackingStoreOpen(origin)); const bool expect_connection = false; scoped_refptr<MockIndexedDBCallbacks> callbacks( new MockIndexedDBCallbacks(expect_connection)); factory()->GetDatabaseNames( callbacks, origin, temp_directory.path(), NULL /* request_context */); EXPECT_TRUE(factory()->IsBackingStoreOpen(origin)); EXPECT_TRUE(factory()->IsBackingStorePendingClose(origin)); // Now simulate shutdown, which should stop the timer. factory()->ContextDestroyed(); EXPECT_FALSE(factory()->IsBackingStoreOpen(origin)); EXPECT_FALSE(factory()->IsBackingStorePendingClose(origin)); } TEST_F(IndexedDBFactoryTest, ForceCloseReleasesBackingStore) { GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); scoped_refptr<MockIndexedDBCallbacks> callbacks(new MockIndexedDBCallbacks()); scoped_refptr<MockIndexedDBDatabaseCallbacks> db_callbacks( new MockIndexedDBDatabaseCallbacks()); const int64 transaction_id = 1; IndexedDBPendingConnection connection( callbacks, db_callbacks, 0, /* child_process_id */ transaction_id, IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION); factory()->Open(ASCIIToUTF16("db"), connection, NULL /* request_context */, origin, temp_directory.path()); EXPECT_TRUE(callbacks->connection()); EXPECT_TRUE(factory()->IsBackingStoreOpen(origin)); EXPECT_FALSE(factory()->IsBackingStorePendingClose(origin)); callbacks->connection()->Close(); EXPECT_TRUE(factory()->IsBackingStoreOpen(origin)); EXPECT_TRUE(factory()->IsBackingStorePendingClose(origin)); factory()->ForceClose(origin); EXPECT_FALSE(factory()->IsBackingStoreOpen(origin)); EXPECT_FALSE(factory()->IsBackingStorePendingClose(origin)); // Ensure it is safe if the store is not open. factory()->ForceClose(origin); } class UpgradeNeededCallbacks : public MockIndexedDBCallbacks { public: UpgradeNeededCallbacks() {} virtual void OnSuccess(scoped_ptr<IndexedDBConnection> connection, const IndexedDBDatabaseMetadata& metadata) OVERRIDE { EXPECT_TRUE(connection_.get()); EXPECT_FALSE(connection.get()); } virtual void OnUpgradeNeeded( int64 old_version, scoped_ptr<IndexedDBConnection> connection, const content::IndexedDBDatabaseMetadata& metadata) OVERRIDE { connection_ = connection.Pass(); } protected: virtual ~UpgradeNeededCallbacks() {} private: DISALLOW_COPY_AND_ASSIGN(UpgradeNeededCallbacks); }; class ErrorCallbacks : public MockIndexedDBCallbacks { public: ErrorCallbacks() : MockIndexedDBCallbacks(false), saw_error_(false) {} virtual void OnError(const IndexedDBDatabaseError& error) OVERRIDE { saw_error_= true; } bool saw_error() const { return saw_error_; } private: virtual ~ErrorCallbacks() {} bool saw_error_; DISALLOW_COPY_AND_ASSIGN(ErrorCallbacks); }; TEST_F(IndexedDBFactoryTest, DatabaseFailedOpen) { GURL origin("http://localhost:81"); base::ScopedTempDir temp_directory; ASSERT_TRUE(temp_directory.CreateUniqueTempDir()); const base::string16 db_name(ASCIIToUTF16("db")); const int64 db_version = 2; const int64 transaction_id = 1; scoped_refptr<IndexedDBDatabaseCallbacks> db_callbacks( new MockIndexedDBDatabaseCallbacks()); // Open at version 2, then close. { scoped_refptr<MockIndexedDBCallbacks> callbacks( new UpgradeNeededCallbacks()); IndexedDBPendingConnection connection(callbacks, db_callbacks, 0, /* child_process_id */ transaction_id, db_version); factory()->Open(db_name, connection, NULL /* request_context */, origin, temp_directory.path()); EXPECT_TRUE(factory()->IsDatabaseOpen(origin, db_name)); // Pump the message loop so the upgrade transaction can run. base::MessageLoop::current()->RunUntilIdle(); EXPECT_TRUE(callbacks->connection()); callbacks->connection()->database()->Commit(transaction_id); callbacks->connection()->Close(); EXPECT_FALSE(factory()->IsDatabaseOpen(origin, db_name)); } // Open at version < 2, which will fail; ensure factory doesn't retain // the database object. { scoped_refptr<ErrorCallbacks> callbacks(new ErrorCallbacks()); IndexedDBPendingConnection connection(callbacks, db_callbacks, 0, /* child_process_id */ transaction_id, db_version - 1); factory()->Open(db_name, connection, NULL /* request_context */, origin, temp_directory.path()); EXPECT_TRUE(callbacks->saw_error()); EXPECT_FALSE(factory()->IsDatabaseOpen(origin, db_name)); } // Terminate all pending-close timers. factory()->ForceClose(origin); } } // namespace content
bsd-3-clause
krishauser/KrisLibrary
utils/ParamList.cpp
3198
#include "ParamList.h" #include "stringutils.h" #include "ioutils.h" #include <sstream> #include <errors.h> using namespace std; ParamList::ParamList() {} ParamList::ParamList(const PrimitiveValue& a1) :args(1) { args[0] = a1; } ParamList::ParamList(const PrimitiveValue& a1,const PrimitiveValue& a2) :args(2) { args[0] = a1; args[1] = a2; } ParamList::ParamList(const PrimitiveValue& a1,const PrimitiveValue& a2,const PrimitiveValue& a3) :args(3) { args[0] = a1; args[1] = a2; args[2] = a3; } ParamList::ParamList(const PrimitiveValue& a1,const PrimitiveValue& a2,const PrimitiveValue& a3,const PrimitiveValue& a4) :args(3) { args[0] = a1; args[1] = a2; args[2] = a3; args[3] = a4; } ParamList::ParamList(const vector<PrimitiveValue>& _args) :args(_args) {} ParamList::ParamList(const map<string,PrimitiveValue>& _args) { for(map<string,PrimitiveValue>::const_iterator i=_args.begin();i!=_args.end();i++) { names[i->first] = args.size(); args.push_back(i->second); } } string ParamList::write() const { stringstream temp; map<int,string> nameMap; for(map<string,int>::const_iterator i=names.begin();i!=names.end();i++) nameMap[i->second] = i->first; for(size_t i=0;i<args.size();i++) { if(nameMap.count(i) != 0) { temp<<nameMap[i]<<"="; } temp<<args[i]; if(i+1 != args.size()) temp<<", "; } return temp.str(); } bool ParamList::parse(const string& str) { vector<string> argText; size_t index=0; while(index != string::npos) { size_t index2 = str.find_first_of(',',index); if(index2 == string::npos) { argText.push_back(str.substr(index)); index = string::npos; } else { argText.push_back(str.substr(index,index2-index)); index = index2+1; } } names.clear(); args.resize(argText.size()); for(size_t i=0;i<argText.size();i++) { //strip whitespace argText[i] = Strip(argText[i]); if(argText[i].empty()) { return false; } if(argText[i][0] == '\"' && argText[i][argText[i].length()-1] == '\"') { //quoted string args[i] = TranslateEscapes(argText[i].substr(1,argText[i].length()-2)); } else if(argText[i].find('=') != string::npos) { //an assignment size_t index=argText[i].find('='); string name=Strip(argText[i].substr(0,index-1)); string arg=Strip(argText[i].substr(index+1)); if(name.empty()) return false; if(arg.empty()) return false; if(names.count(name) != 0) return false; //duplicate named argument names[name] = i; stringstream ss(arg); ss>>args[i]; if(!ss) return false; } else { stringstream ss(argText[i]); ss>>args[i]; if(!ss) return false; } } return true; } PrimitiveValue& ParamList::operator [] (const string& name) { map<string,int>::iterator i = names.find(name); if(i == names.end()) { names[name] = args.size(); args.resize(args.size()+1); return args.back(); } return args[i->second]; } const PrimitiveValue& ParamList::operator [] (const string& name) const { map<string,int>::const_iterator i = names.find(name); Assert(i != names.end()); return args[i->second]; }
bsd-3-clause
youtube/cobalt
net/third_party/quiche/src/spdy/core/spdy_prefixed_buffer_reader_test.cc
4374
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/spdy/core/spdy_prefixed_buffer_reader.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "net/third_party/quiche/src/spdy/platform/api/spdy_string.h" #include "net/third_party/quiche/src/spdy/platform/api/spdy_string_piece.h" namespace spdy { namespace test { using testing::ElementsAreArray; class SpdyPrefixedBufferReaderTest : public ::testing::Test { protected: SpdyPrefixedBufferReader Build(const SpdyString& prefix, const SpdyString& suffix) { prefix_ = prefix; suffix_ = suffix; return SpdyPrefixedBufferReader(prefix_.data(), prefix_.length(), suffix_.data(), suffix_.length()); } SpdyString prefix_, suffix_; }; TEST_F(SpdyPrefixedBufferReaderTest, ReadRawFromPrefix) { SpdyPrefixedBufferReader reader = Build("foobar", ""); EXPECT_EQ(6u, reader.Available()); char buffer[] = "123456"; EXPECT_FALSE(reader.ReadN(10, buffer)); // Not enough buffer. EXPECT_TRUE(reader.ReadN(6, buffer)); EXPECT_THAT(buffer, ElementsAreArray("foobar")); EXPECT_EQ(0u, reader.Available()); } TEST_F(SpdyPrefixedBufferReaderTest, ReadPieceFromPrefix) { SpdyPrefixedBufferReader reader = Build("foobar", ""); EXPECT_EQ(6u, reader.Available()); SpdyPinnableBufferPiece piece; EXPECT_FALSE(reader.ReadN(10, &piece)); // Not enough buffer. EXPECT_TRUE(reader.ReadN(6, &piece)); EXPECT_FALSE(piece.IsPinned()); EXPECT_EQ(SpdyStringPiece("foobar"), SpdyStringPiece(piece)); EXPECT_EQ(0u, reader.Available()); } TEST_F(SpdyPrefixedBufferReaderTest, ReadRawFromSuffix) { SpdyPrefixedBufferReader reader = Build("", "foobar"); EXPECT_EQ(6u, reader.Available()); char buffer[] = "123456"; EXPECT_FALSE(reader.ReadN(10, buffer)); // Not enough buffer. EXPECT_TRUE(reader.ReadN(6, buffer)); EXPECT_THAT(buffer, ElementsAreArray("foobar")); EXPECT_EQ(0u, reader.Available()); } TEST_F(SpdyPrefixedBufferReaderTest, ReadPieceFromSuffix) { SpdyPrefixedBufferReader reader = Build("", "foobar"); EXPECT_EQ(6u, reader.Available()); SpdyPinnableBufferPiece piece; EXPECT_FALSE(reader.ReadN(10, &piece)); // Not enough buffer. EXPECT_TRUE(reader.ReadN(6, &piece)); EXPECT_FALSE(piece.IsPinned()); EXPECT_EQ(SpdyStringPiece("foobar"), SpdyStringPiece(piece)); EXPECT_EQ(0u, reader.Available()); } TEST_F(SpdyPrefixedBufferReaderTest, ReadRawSpanning) { SpdyPrefixedBufferReader reader = Build("foob", "ar"); EXPECT_EQ(6u, reader.Available()); char buffer[] = "123456"; EXPECT_FALSE(reader.ReadN(10, buffer)); // Not enough buffer. EXPECT_TRUE(reader.ReadN(6, buffer)); EXPECT_THAT(buffer, ElementsAreArray("foobar")); EXPECT_EQ(0u, reader.Available()); } TEST_F(SpdyPrefixedBufferReaderTest, ReadPieceSpanning) { SpdyPrefixedBufferReader reader = Build("foob", "ar"); EXPECT_EQ(6u, reader.Available()); SpdyPinnableBufferPiece piece; EXPECT_FALSE(reader.ReadN(10, &piece)); // Not enough buffer. EXPECT_TRUE(reader.ReadN(6, &piece)); EXPECT_TRUE(piece.IsPinned()); EXPECT_EQ(SpdyStringPiece("foobar"), SpdyStringPiece(piece)); EXPECT_EQ(0u, reader.Available()); } TEST_F(SpdyPrefixedBufferReaderTest, ReadMixed) { SpdyPrefixedBufferReader reader = Build("abcdef", "hijkl"); EXPECT_EQ(11u, reader.Available()); char buffer[] = "1234"; SpdyPinnableBufferPiece piece; EXPECT_TRUE(reader.ReadN(3, buffer)); EXPECT_THAT(buffer, ElementsAreArray("abc4")); EXPECT_EQ(8u, reader.Available()); EXPECT_TRUE(reader.ReadN(2, buffer)); EXPECT_THAT(buffer, ElementsAreArray("dec4")); EXPECT_EQ(6u, reader.Available()); EXPECT_TRUE(reader.ReadN(3, &piece)); EXPECT_EQ(SpdyStringPiece("fhi"), SpdyStringPiece(piece)); EXPECT_TRUE(piece.IsPinned()); EXPECT_EQ(3u, reader.Available()); EXPECT_TRUE(reader.ReadN(2, &piece)); EXPECT_EQ(SpdyStringPiece("jk"), SpdyStringPiece(piece)); EXPECT_FALSE(piece.IsPinned()); EXPECT_EQ(1u, reader.Available()); EXPECT_TRUE(reader.ReadN(1, buffer)); EXPECT_THAT(buffer, ElementsAreArray("lec4")); EXPECT_EQ(0u, reader.Available()); } } // namespace test } // namespace spdy
bsd-3-clause
cymapgt/SpreadsheetProcessor
src/SpreadsheetProcessor/PHPExcelWrapper/PHPExcelBorderStyle.php
1047
<?php namespace cymapgt\core\application\spreadsheet\SpreadsheetProcessor\PHPExcelWrapper; // These are taken directly from PHPExcel/Style/Border.php // They are duplicated becuase the point of this wrapper is to not have // to include a whole bunch of other files in whatver script your using class PHPExcelBorderStyle { const BORDER_NONE = 'none'; const BORDER_DASHDOT = 'dashDot'; const BORDER_DASHDOTDOT = 'dashDotDot'; const BORDER_DASHED = 'dashed'; const BORDER_DOTTED = 'dotted'; const BORDER_DOUBLE = 'double'; const BORDER_HAIR = 'hair'; const BORDER_MEDIUM = 'medium'; const BORDER_MEDIUMDASHDOT = 'mediumDashDot'; const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot'; const BORDER_MEDIUMDASHED = 'mediumDashed'; const BORDER_SLANTDASHDOT = 'slantDashDot'; const BORDER_THICK = 'thick'; const BORDER_THIN = 'thin'; }
bsd-3-clause
gulopine/steel
steel/fields/strings.py
3829
from steel.fields import Field from steel.fields.numbers import Integer from steel.common import args from steel.common.fields import FullyDecoded class String(Field): size = args.Override(default=None) encoding = args.Argument(resolve_field=True) padding = args.Argument(default=b'\x00') terminator = args.Argument(default=b'\x00') def read(self, file): if self.size is not None: return file.read(self.size) else: # TODO: There's gotta be a better way, but it works for now value = b'' while True: data = file.read(1) if data: value += data if data == self.terminator: break else: break return value def decode(self, value): return value.rstrip(self.terminator).rstrip(self.padding).decode(self.encoding) def encode(self, value): value = value.encode(self.encoding) if self.size is not None: value = value.ljust(self.size, self.padding) else: value += self.terminator return value def validate(self, obj, value): value = value.encode(self.encoding) if self.size is not None: if len(value) > self.size: raise ValueError("String %r is longer than %r bytes." % (value, self.size)) class LengthIndexedString(String): def read(self, file): size_bytes, size = Integer(size=self.size).read_value(file) value_bytes = file.read(size) return size_bytes + value_bytes def decode(self, value): # Skip the length portion of the byte string before decoding return value[self.size:].decode(self.encoding) def encode(self, value): value_bytes = value.encode(self.encoding) size_bytes = Integer(size=self.size).encode(len(value_bytes)) return size_bytes + value_bytes class FixedString(String): size = args.Override(default=None) encoding = args.Override(default='ascii') padding = args.Override(default=b'') terminator = args.Override(default=b'') def __init__(self, value, *args, **kwargs): super(FixedString, self).__init__(*args, **kwargs) if isinstance(value, bytes): # If raw bytes are supplied, encoding is not used self.encoded_value = value self.decoded_value = value self.encoding = None elif isinstance(value, str): self.decoded_value = value self.encoded_value = super(FixedString, self).encode(value) self.size = len(self.encoded_value) self.default = self.encoded_value def read(self, file): value = file.read(self.size) # Make sure to validate the string, even if it's not explicitly accessed. # This will prevent invalid files from being read beyond the fixed string. if value != self.encoded_value: raise ValueError('Expected %r, got %r.' % (self.encoded_value, value)) raise FullyDecoded(self.encoded_value, self.decoded_value) def decode(self, value): if value != self.encoded_value: raise ValueError('Expected %r, got %r.' % (self.encoded_value, value)) return self.decoded_value def encode(self, value): if value != self.decoded_value: raise ValueError('Expected %r, got %r.' % (self.decoded_value, value)) return self.encoded_value class Bytes(Field): def encode(self, value): # Nothing to do here return value def decode(self, value): # Nothing to do here return value
bsd-3-clause
thailvn/dev
module/Web/src/Web/Lib/GooglePlus.php
2131
<?php namespace Web\Lib; use Application\Lib\Log; use Web\Module as WebModule; /** * GooglePlus * * @package Lib * @created 2015-09-05 * @version 1.0 * @author thailh * @copyright YouGO INC */ class GooglePlus { protected static $service; // for application module public static function instance($accessToken) { static::$service or static::_init($accessToken); return static::$service; } public static function _init($accessToken) { $scopes = implode(' ' , [ \Google_Service_Oauth2::PLUS_LOGIN, \Google_Service_Plus::PLUS_ME ]); $client = new \Google_Client(); $client->setClientId(WebModule::getConfig('google_app_id2')); $client->setClientSecret(WebModule::getConfig('google_app_secret2')); $client->setRedirectUri(WebModule::getConfig('google_app_redirect_uri2')); $client->addScope($scopes); $client->setAccessToken($accessToken); static::$service = new \Google_Service_Plus($client); } public static function post($data, $accessToken, &$errorMessage = '') { try { $momentBody = new \Google_Service_Plus_Moment(); $momentBody->setType("http://schemas.google.com/AddActivity"); $itemScope = new \Google_Service_Plus_ItemScope(); $itemScope->setType("http://schemas.google.com/AddActivity"); $itemScope->setName($data['name']); $itemScope->setUrl($data['url']); $itemScope->setDescription('Test'); $momentBody->setTarget($itemScope); $momentResult = static::instance($accessToken)->moments->insert('me', 'vault', $momentBody); return $momentResult; // if ($postId = $post->getId()) { // return $postId; // } } catch (\Exception $e) { $errorMessage = $e->getMessage(); echo $errorMessage; Log::warning($errorMessage); } return false; } }
bsd-3-clause
ManolisCh/experiment_2
laser_noise/src/laser_noise_node.cpp
4917
#include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <std_msgs/Bool.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_real.hpp> #include <boost/random/variate_generator.hpp> #include <geometry_msgs/PoseWithCovarianceStamped.h> class LaserNoise { public: LaserNoise() { ros::NodeHandle private_nh("laser_noise"); // Initialise the noise period and the rectacular area of noise bounded by the rectacle of which the 4 points are the corners. private_nh.param("noise_period", noise_period_, 30.0); private_nh.param("x_max", x_max_, 532.61); private_nh.param("x_min", x_min_, 531.10); private_nh.param("y_max", y_max_, 48.41); private_nh.param("y_min", y_min_, 41.24); //randomGen_.seed(time(NULL)); // seed the generator laser_sub_ = n_.subscribe<sensor_msgs::LaserScan>("scan", 20, &LaserNoise::laserReadCallBAck, this); pose_sub_ = n_.subscribe<geometry_msgs::PoseWithCovarianceStamped>("amcl_pose", 20, &LaserNoise::poseCallback, this); reset_node_sub_ = n_.subscribe<std_msgs::Bool>("/noise_reset", 20, &LaserNoise::resetCallBack, this); scan_pub_ = n_.advertise<sensor_msgs::LaserScan>("scan_with_noise", 20); noise_active_pub_ = n_.advertise<std_msgs::Bool>("noise_active", 20); timerNoise_ = n_.createTimer(ros::Duration(noise_period_) , &LaserNoise::timerNoiseCallback, this, false, false); areaTriger_ = 0, timerTriger_ =0, timerActivated_= 0; } private: // boost::mt19937 randomGen_; ros::NodeHandle n_; ros::Subscriber laser_sub_ , pose_sub_ , reset_node_sub_; ros::Publisher scan_pub_ , noise_active_pub_; sensor_msgs::LaserScan addedNoiseScan_; ros::Timer timerNoise_ ; void laserReadCallBAck(const sensor_msgs::LaserScan::ConstPtr& msg); double GaussianKernel(double mu,double sigma), uniformNoise_; void poseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg); void timerNoiseCallback(const ros::TimerEvent&); void resetCallBack(const std_msgs::Bool::ConstPtr& msg); bool areaTriger_ , timerTriger_, timerActivated_; double noise_period_, x_max_, x_min_, y_max_, y_min_ ; }; void LaserNoise::resetCallBack(const std_msgs::Bool::ConstPtr& msg) { if (msg->data == true) { timerTriger_ = 0; timerNoise_.stop(); // needed to make sure the timer is not running in background } } void LaserNoise::laserReadCallBAck(const sensor_msgs::LaserScan::ConstPtr& msg) { double sigma; double oldRange; std_msgs::Bool noise; addedNoiseScan_ = *msg ; // Guassian noise added if (areaTriger_ == 1 && timerTriger_ == 0) { for (int i=0; i < addedNoiseScan_.ranges.size() ; i++) { sigma = addedNoiseScan_.ranges[i] * 0.2; // Proportional standard deviation oldRange = addedNoiseScan_.ranges[i] ; addedNoiseScan_.ranges[i] = addedNoiseScan_.ranges[i] + GaussianKernel(0,sigma); if (addedNoiseScan_.ranges[i] > addedNoiseScan_.range_max) { addedNoiseScan_.ranges[i] = addedNoiseScan_.range_max;} else if (addedNoiseScan_.ranges[i] < addedNoiseScan_.range_min) { addedNoiseScan_.ranges[i] = oldRange;} } noise.data = true; noise_active_pub_.publish(noise); } addedNoiseScan_.header.stamp = ros::Time::now(); scan_pub_.publish(addedNoiseScan_); } void LaserNoise::poseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) { if ( (msg->pose.pose.position.x < x_max_) && (msg->pose.pose.position.x > x_min_) && (msg->pose.pose.position.y < y_max_) && (msg->pose.pose.position.y > y_min_) ) { areaTriger_ =1; timerNoise_.start(); } else { areaTriger_ = 0; std_msgs::Bool noise; noise.data = false; noise_active_pub_.publish(noise); //timerTriger_ = 0; } } void LaserNoise::timerNoiseCallback(const ros::TimerEvent&) { timerTriger_ = 1; timerNoise_.stop(); ROS_INFO("TIMER ACTIVATED"); } // Utility for adding noise double LaserNoise::GaussianKernel(double mu,double sigma) { // using Box-Muller transform to generate two independent standard normally disbributed normal variables double U = (double)rand()/(double)RAND_MAX; // normalized uniform random variable double V = (double)rand()/(double)RAND_MAX; // normalized uniform random variable double X = sqrt(-2.0 * ::log(U)) * cos( 2.0*M_PI * V); //double Y = sqrt(-2.0 * ::log(U)) * sin( 2.0*M_PI * V); // the other indep. normal variable // we'll just use X // scale to our mu and sigma X = sigma * X + mu; return X; } int main(int argc, char** argv) { ros::init(argc, argv, "laser_noise"); LaserNoise lasernoise; ros::spin(); }
bsd-3-clause
endlessm/chromium-browser
third_party/blink/renderer/platform/exported/web_blob_info.cc
4077
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/public/platform/web_blob_info.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "third_party/blink/public/mojom/blob/blob.mojom-blink.h" #include "third_party/blink/renderer/platform/blob/blob_data.h" namespace blink { WebBlobInfo::WebBlobInfo(const WebString& uuid, const WebString& type, uint64_t size, mojo::ScopedMessagePipeHandle handle) : WebBlobInfo( BlobDataHandle::Create(uuid, type, size, mojo::PendingRemote<mojom::blink::Blob>( std::move(handle), mojom::blink::Blob::Version_))) {} WebBlobInfo::WebBlobInfo(const WebString& uuid, const WebString& file_name, const WebString& type, const base::Optional<base::Time>& last_modified, uint64_t size, mojo::ScopedMessagePipeHandle handle) : WebBlobInfo( BlobDataHandle::Create(uuid, type, size, mojo::PendingRemote<mojom::blink::Blob>( std::move(handle), mojom::blink::Blob::Version_)), file_name, last_modified) {} // static WebBlobInfo WebBlobInfo::BlobForTesting(const WebString& uuid, const WebString& type, uint64_t size) { return WebBlobInfo(uuid, type, size, mojo::MessagePipe().handle0); } // static WebBlobInfo WebBlobInfo::FileForTesting(const WebString& uuid, const WebString& file_name, const WebString& type) { return WebBlobInfo(uuid, file_name, type, base::nullopt, std::numeric_limits<uint64_t>::max(), mojo::MessagePipe().handle0); } WebBlobInfo::~WebBlobInfo() { blob_handle_.Reset(); } WebBlobInfo::WebBlobInfo(const WebBlobInfo& other) { *this = other; } WebBlobInfo& WebBlobInfo::operator=(const WebBlobInfo& other) = default; mojo::ScopedMessagePipeHandle WebBlobInfo::CloneBlobHandle() const { if (!blob_handle_) return mojo::ScopedMessagePipeHandle(); return blob_handle_->CloneBlobRemote().PassPipe(); } WebBlobInfo::WebBlobInfo(scoped_refptr<BlobDataHandle> handle) : WebBlobInfo(handle, handle->GetType(), handle->size()) {} WebBlobInfo::WebBlobInfo(scoped_refptr<BlobDataHandle> handle, const WebString& file_name, const base::Optional<base::Time>& last_modified) : WebBlobInfo(handle, file_name, handle->GetType(), last_modified, handle->size()) {} WebBlobInfo::WebBlobInfo(scoped_refptr<BlobDataHandle> handle, const WebString& type, uint64_t size) : is_file_(false), uuid_(handle->Uuid()), type_(type), size_(size), blob_handle_(std::move(handle)) {} WebBlobInfo::WebBlobInfo(scoped_refptr<BlobDataHandle> handle, const WebString& file_name, const WebString& type, const base::Optional<base::Time>& last_modified, uint64_t size) : is_file_(true), uuid_(handle->Uuid()), type_(type), size_(size), blob_handle_(std::move(handle)), file_name_(file_name), last_modified_(last_modified) {} scoped_refptr<BlobDataHandle> WebBlobInfo::GetBlobHandle() const { return blob_handle_.Get(); } } // namespace blink
bsd-3-clause
aaly/MPF
System/driveList.hpp
302
/****************************************************** * copyright 2011, 2012, 2013 AbdAllah Aly Saad , aaly90[@]gmail.com * Part of Mesk Page Framework (MPF) ******************************************************/ #ifndef DRIVELIST_H #define DRIVELIST_H #include <QComboBox> #endif // DRIVELIST_H
bsd-3-clause
jjgoings/McMurchie-Davidson
tests/test003.py
506
import numpy as np from numpy.testing import assert_allclose from mmd.molecule import Molecule methane = """ 0 1 C 0.000000 0.000000 0.000000 H 0.626425042 -0.626425042 -0.626425042 H 0.626425042 0.626425042 0.626425042 H -0.626425042 0.626425042 -0.626425042 H -0.626425042 -0.626425042 0.626425042 """ def test_methane_sto3g(): mol = Molecule(geometry=methane,basis='sto-3g') mol.RHF() assert_allclose(mol.energy.real,-39.726850324347,atol=1e-12)
bsd-3-clause
innaDa/RcmUser
src/Event/EventProvider.php
1450
<?php namespace RcmUser\Event; use Zend\EventManager\EventManager; use Zend\EventManager\EventManagerAwareInterface; use Zend\EventManager\EventManagerInterface; /** * Class EventProvider * * EventProvider * * PHP version 5 * * @category Reliv * @package RcmUser\Event * @author James Jervis <jjervis@relivinc.com> * @copyright 2014 Reliv International * @license License.txt New BSD License * @version Release: <package_version> * @link https://github.com/reliv */ abstract class EventProvider implements EventManagerAwareInterface { /** * @var EventManagerInterface $events */ protected $events; /** * setEventManager - Set the event manager instance used by this context * * @param EventManagerInterface $events events * * @return $this */ public function setEventManager(EventManagerInterface $events) { $identifiers = [ __CLASS__, get_called_class() ]; $events->setIdentifiers($identifiers); $this->events = $events; return $this; } /** * getEventManager - Loads an EventManager instance if none registered. * * @return EventManagerInterface */ public function getEventManager() { if (!$this->events instanceof EventManagerInterface) { $this->setEventManager(new EventManager()); } return $this->events; } }
bsd-3-clause
spekkionu/zfapp
tests/unit/src/system/models/Model_AdminTest.php
1553
<?php /** * Test class for Model_Admin. * Generated by PHPUnit on 2012-06-02 at 19:28:26. */ class Model_AdminTest extends Test_DbTestCase { /** * tests Model_Admin::getAdministratorList */ public function testGetAdministratorList() { $mgr = new Model_Admin(); $results = $mgr->getAdministratorList(); $this->assertInstanceOf('Zend_Paginator', $results); $this->assertEquals(1, $results->getTotalItemCount()); } /** * tests Model_Admin::addAdministrator */ public function testAddAdministrator() { $mgr = new Model_Admin(); $data = array( 'username' => 'newusername', 'password' => 'password', 'firstname' => 'Firstname', 'lastname' => 'Lastname', 'email' => 'newadmin@address.com', 'active' => '1', ); $id = $mgr->addAdministrator($data); $this->assertGreaterThan(0, $id); } /** * tests Model_Admin::updateAdministrator */ public function testUpdateAdministrator() { $id = 2; $mgr = new Model_Admin(); $data = array( 'username' => 'newusername', 'firstname' => 'newFirstname', 'lastname' => 'newLastname', 'email' => 'admin@address.com', 'active' => '1', ); $updated = $mgr->updateAdministrator($id, $data); $this->assertEquals(1, $updated); } /** * tests Model_Admin::deleteAdministrator */ public function testDeleteAdministrator() { $id = 2; $mgr = new Model_Admin(); $deleted = $mgr->deleteAdministrator($id); $this->assertEquals(1, $deleted); } }
bsd-3-clause
Artld/study-in-sg
homework_rails/config/initializers/secret_token.rb
504
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. HomeworkRails::Application.config.secret_token = '928fdd6eb6960db4050388db39c1e348bbf36f981dfa5b743c06147d138de6a2980385bf83c78ac0fd67070139de9b74fd976b5bf8c53b24c3313630da880d04'
bsd-3-clause
fpytloun/mezzanine-references
mezzanine_references/admin.py
371
from django.contrib import admin from mezzanine.pages.admin import PageAdmin from mezzanine.core.admin import TabularDynamicInlineAdmin from .models import References, Reference class ReferenceInline(TabularDynamicInlineAdmin): model = Reference class ReferencesAdmin(PageAdmin): inlines = (ReferenceInline,) admin.site.register(References, ReferencesAdmin)
bsd-3-clause
tovmeod/anaf
anaf/core/dashboard/views.py
9613
""" Core module Dashboard views """ from anaf.core.rendering import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from anaf.core.decorators import mylogin_required, handle_response_format from anaf.core.models import Object, Widget from forms import WidgetForm from anaf.core.conf import settings from jinja2 import Markup import json import re import copy def _preprocess_widget(widget, name): "Populates widget with missing fields" module_name = widget['module_name'] import_name = module_name + ".views" module_views = __import__(import_name, fromlist=[str(module_name)]) if hasattr(module_views, name): if 'title' not in widget: widget['title'] = getattr(module_views, name).__doc__ widget = copy.deepcopy(widget) if 'view' not in widget: widget['view'] = getattr(module_views, name) return widget def _get_all_widgets(request): "Retrieve widgets from all available modules" user = request.user.profile perspective = user.get_perspective() modules = perspective.get_modules() widgets = {} # For each Module in the Perspective get widgets for module in modules: try: import_name = module.name + ".widgets" module_widget_lib = __import__( import_name, fromlist=[str(module.name)]) module_widgets = module_widget_lib.get_widgets(request) # Preprocess widget, ensure it has all required fields for name in module_widgets: if 'module_name' not in module_widgets[name]: module_widgets[name]['module_name'] = module.name if 'module_title' not in module_widgets[name]: module_widgets[name]['module_title'] = module.title module_widgets[name] = _preprocess_widget( module_widgets[name], name) widgets.update(module_widgets) except ImportError: pass except AttributeError: pass return widgets def _get_widget(request, module, widget_name): "Gets a widget by name" import_name = module.name + ".widgets" module_widget_lib = __import__(import_name, fromlist=[str(module.name)]) module_widgets = module_widget_lib.get_widgets(request) widget = {} # Preprocess widget, ensure it has all required fields for name in module_widgets: if name == widget_name: widget = module_widgets[name] if 'module_name' not in widget: widget['module_name'] = module.name if 'module_title' not in widget: widget['module_title'] = module.title widget = _preprocess_widget(widget, widget_name) break return widget def _create_widget_object(request, module_name, widget_name): "Create a Widget object if one is available for the current user Perspective" user = request.user.profile perspective = user.get_perspective() modules = perspective.get_modules() obj = None current_module = modules.filter(name=module_name) widget = None if current_module: current_module = current_module[0] widget = _get_widget(request, current_module, widget_name) if widget: obj = Widget(user=user, perspective=perspective) obj.module_name = widget['module_name'] obj.widget_name = widget_name obj.save() # except Exception: # pass return obj def _get_widget_content(content, response_format='html'): "Extracts widget content from rendred HTML" widget_content = "" regexp = r"<!-- widget_content -->(?P<widget_content>.*?)<!-- /widget_content -->" if response_format == 'ajax': try: ajax_content = json.loads(content) widget_content = ajax_content['response'][ 'content']['module_content'] except: blocks = re.finditer(regexp, content, re.DOTALL) for block in blocks: widget_content = block.group('widget_content').strip() else: blocks = re.finditer(regexp, content, re.DOTALL) for block in blocks: widget_content = block.group('widget_content').strip() return Markup(widget_content) @handle_response_format @mylogin_required def index(request, response_format='html'): "Homepage" trash = Object.filter_by_request(request, manager=Object.objects.filter(trash=True), mode='r', filter_trash=False).count() user = request.user.profile perspective = user.get_perspective() widget_objects = Widget.objects.filter(user=user, perspective=perspective) clean_widgets = [] for widget_object in widget_objects: try: module = perspective.get_modules().filter( name=widget_object.module_name)[0] widget = _get_widget(request, module, widget_object.widget_name) if 'view' in widget: try: content = unicode( widget['view'](request, response_format=response_format).content, 'utf_8') widget_content = _get_widget_content( content, response_format=response_format) except Exception, e: widget_content = "" if settings.DEBUG: widget_content = str(e) widget['content'] = widget_content if widget: widget_object.widget = widget clean_widgets.append(widget_object) except IndexError: widget_object.delete() return render_to_response('core/dashboard/index', {'trash': trash, 'widgets': clean_widgets}, context_instance=RequestContext(request), response_format=response_format) @handle_response_format @mylogin_required def dashboard_widget_add(request, module_name=None, widget_name=None, response_format='html'): "Add a Widget to the Dashboard" trash = Object.filter_by_request(request, manager=Object.objects.filter(trash=True), mode='r', filter_trash=False).count() if module_name and widget_name: widget = _create_widget_object(request, module_name, widget_name) if widget: return HttpResponseRedirect(reverse('core_dashboard_index')) widgets = _get_all_widgets(request) return render_to_response('core/dashboard/widget_add', {'trash': trash, 'widgets': widgets}, context_instance=RequestContext(request), response_format=response_format) @handle_response_format @mylogin_required def dashboard_widget_edit(request, widget_id, response_format='html'): "Edit an existing Widget on the Dashboard" user = request.user.profile widget_object = get_object_or_404(Widget, pk=widget_id) if widget_object.user == user: perspective = user.get_perspective() module = perspective.get_modules().filter( name=widget_object.module_name)[0] widget = _get_widget(request, module, widget_object.widget_name) widget_object.widget = widget if 'view' in widget: try: content = unicode( widget['view'](request, response_format=response_format).content, 'utf_8') widget_content = _get_widget_content( content, response_format=response_format) except Exception: widget_content = "" widget['content'] = widget_content if request.POST: form = WidgetForm(user, request.POST, instance=widget_object) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('core_dashboard_index')) else: form = WidgetForm(user, instance=widget_object) return render_to_response('core/dashboard/widget_edit', {'widget': widget_object, 'form': form}, context_instance=RequestContext(request), response_format=response_format) return HttpResponseRedirect(reverse('home')) @handle_response_format @mylogin_required def dashboard_widget_delete(request, widget_id, response_format='html'): "Delete an existing Widget from the Dashboard" widget = get_object_or_404(Widget, pk=widget_id) if widget.user == request.user.profile: widget.delete() return HttpResponseRedirect(reverse('core_dashboard_index')) @handle_response_format @mylogin_required def dashboard_widget_arrange(request, panel='left', response_format='html'): "Arrange widgets with AJAX request" user = request.user.profile if panel == 'left' or not panel: shift = -100 else: shift = 100 if request.GET and 'id_widget[]' in request.GET: widget_ids = request.GET.getlist('id_widget[]') widgets = Widget.objects.filter(user=user, pk__in=widget_ids) for widget in widgets: if unicode(widget.id) in widget_ids: widget.weight = shift + widget_ids.index(unicode(widget.id)) widget.save() return HttpResponseRedirect(reverse('core_dashboard_index'))
bsd-3-clause
aperala/elsi
config/environments/production.rb
3408
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false config.action_mailer.default_url_options = { :host => "https://guarded-island-8032.herokuapp.com/" } # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
bsd-3-clause
Achuth17/scikit-bio
skbio/sequence/tests/test_sequence.py
102057
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function from six.moves import zip_longest import copy import re from types import GeneratorType from collections import Counter, defaultdict, Hashable from unittest import TestCase, main import numpy as np import numpy.testing as npt import pandas as pd from skbio import Sequence from skbio.util import assert_data_frame_almost_equal from skbio.sequence._sequence import (_single_index_to_slice, _is_single_index, _as_slice_if_single_index) class SequenceSubclass(Sequence): """Used for testing purposes.""" pass class TestSequence(TestCase): def setUp(self): self.sequence_kinds = frozenset([ str, Sequence, lambda s: np.fromstring(s, dtype='|S1'), lambda s: np.fromstring(s, dtype=np.uint8)]) def empty_generator(): raise StopIteration() yield self.getitem_empty_indices = [ [], (), {}, empty_generator(), # ndarray of implicit float dtype np.array([]), np.array([], dtype=int)] def test_init_default_parameters(self): seq = Sequence('.ABC123xyz-') npt.assert_equal(seq.values, np.array('.ABC123xyz-', dtype='c')) self.assertEqual('.ABC123xyz-', str(seq)) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(11))) def test_init_nondefault_parameters(self): seq = Sequence('.ABC123xyz-', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(11)}) npt.assert_equal(seq.values, np.array('.ABC123xyz-', dtype='c')) self.assertEqual('.ABC123xyz-', str(seq)) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'id': 'foo', 'description': 'bar baz'}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'quality': range(11)}, index=np.arange(11))) def test_init_handles_missing_metadata_efficiently(self): seq = Sequence('ACGT') # metadata attributes should be None and not initialized to a "missing" # representation self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) # initializing from an existing Sequence object should handle metadata # attributes efficiently on both objects new_seq = Sequence(seq) self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(new_seq._metadata) self.assertIsNone(new_seq._positional_metadata) self.assertFalse(seq.has_metadata()) self.assertFalse(seq.has_positional_metadata()) self.assertFalse(new_seq.has_metadata()) self.assertFalse(new_seq.has_positional_metadata()) def test_init_empty_sequence(self): # Test constructing an empty sequence using each supported input type. for s in (b'', # bytes u'', # unicode np.array('', dtype='c'), # char vector np.fromstring('', dtype=np.uint8), # byte vec Sequence('')): # another Sequence object seq = Sequence(s) self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') self.assertEqual(seq.values.shape, (0, )) npt.assert_equal(seq.values, np.array('', dtype='c')) self.assertEqual(str(seq), '') self.assertEqual(len(seq), 0) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(0))) def test_init_single_character_sequence(self): for s in (b'A', u'A', np.array('A', dtype='c'), np.fromstring('A', dtype=np.uint8), Sequence('A')): seq = Sequence(s) self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') self.assertEqual(seq.values.shape, (1,)) npt.assert_equal(seq.values, np.array('A', dtype='c')) self.assertEqual(str(seq), 'A') self.assertEqual(len(seq), 1) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(1))) def test_init_multiple_character_sequence(self): for s in (b'.ABC\t123 xyz-', u'.ABC\t123 xyz-', np.array('.ABC\t123 xyz-', dtype='c'), np.fromstring('.ABC\t123 xyz-', dtype=np.uint8), Sequence('.ABC\t123 xyz-')): seq = Sequence(s) self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') self.assertEqual(seq.values.shape, (14,)) npt.assert_equal(seq.values, np.array('.ABC\t123 xyz-', dtype='c')) self.assertEqual(str(seq), '.ABC\t123 xyz-') self.assertEqual(len(seq), 14) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(14))) def test_init_from_sequence_object(self): # We're testing this in its simplest form in other tests. This test # exercises more complicated cases of building a sequence from another # sequence. # just the sequence, no other metadata seq = Sequence('ACGT') self.assertEqual(Sequence(seq), seq) # sequence with metadata should have everything propagated seq = Sequence('ACGT', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(4)}) self.assertEqual(Sequence(seq), seq) # should be able to override metadata self.assertEqual( Sequence(seq, metadata={'id': 'abc', 'description': '123'}, positional_metadata={'quality': [42] * 4}), Sequence('ACGT', metadata={'id': 'abc', 'description': '123'}, positional_metadata={'quality': [42] * 4})) # subclasses work too seq = SequenceSubclass('ACGT', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(4)}) self.assertEqual( Sequence(seq), Sequence('ACGT', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(4)})) def test_init_from_contiguous_sequence_bytes_view(self): bytes = np.array([65, 42, 66, 42, 65], dtype=np.uint8) view = bytes[:3] seq = Sequence(view) # sequence should be what we'd expect self.assertEqual(seq, Sequence('A*B')) # we shouldn't own the memory because no copy should have been made self.assertFalse(seq._owns_bytes) # can't mutate view because it isn't writeable anymore with self.assertRaises(ValueError): view[1] = 100 # sequence shouldn't have changed self.assertEqual(seq, Sequence('A*B')) # mutate bytes (*not* the view) bytes[0] = 99 # Sequence changed because we are only able to make the view read-only, # not its source (bytes). This is somewhat inconsistent behavior that # is (to the best of our knowledge) outside our control. self.assertEqual(seq, Sequence('c*B')) def test_init_from_noncontiguous_sequence_bytes_view(self): bytes = np.array([65, 42, 66, 42, 65], dtype=np.uint8) view = bytes[::2] seq = Sequence(view) # sequence should be what we'd expect self.assertEqual(seq, Sequence('ABA')) # we should own the memory because a copy should have been made self.assertTrue(seq._owns_bytes) # mutate bytes and its view bytes[0] = 99 view[1] = 100 # sequence shouldn't have changed self.assertEqual(seq, Sequence('ABA')) def test_init_no_copy_of_sequence(self): bytes = np.array([65, 66, 65], dtype=np.uint8) seq = Sequence(bytes) # should share the same memory self.assertIs(seq._bytes, bytes) # shouldn't be able to mutate the Sequence object's internals by # mutating the shared memory with self.assertRaises(ValueError): bytes[1] = 42 def test_init_empty_metadata(self): for empty in None, {}: seq = Sequence('', metadata=empty) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) def test_init_empty_metadata_key(self): seq = Sequence('', metadata={'': ''}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'': ''}) def test_init_empty_metadata_item(self): seq = Sequence('', metadata={'foo': ''}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': ''}) def test_init_single_character_metadata_item(self): seq = Sequence('', metadata={'foo': 'z'}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': 'z'}) def test_init_multiple_character_metadata_item(self): seq = Sequence('', metadata={'foo': '\nabc\tdef G123'}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': '\nabc\tdef G123'}) def test_init_metadata_multiple_keys(self): seq = Sequence('', metadata={'foo': 'abc', 42: {'nested': 'metadata'}}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': 'abc', 42: {'nested': 'metadata'}}) def test_init_empty_positional_metadata(self): # empty seq with missing/empty positional metadata for empty in None, {}, pd.DataFrame(): seq = Sequence('', positional_metadata=empty) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(0))) # non-empty seq with missing positional metadata seq = Sequence('xyz', positional_metadata=None) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) def test_init_empty_positional_metadata_item(self): for item in ([], (), np.array([])): seq = Sequence('', positional_metadata={'foo': item}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': item}, index=np.arange(0))) def test_init_single_positional_metadata_item(self): for item in ([2], (2, ), np.array([2])): seq = Sequence('G', positional_metadata={'foo': item}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': item}, index=np.arange(1))) def test_init_multiple_positional_metadata_item(self): for item in ([0, 42, 42, 1, 0, 8, 100, 0, 0], (0, 42, 42, 1, 0, 8, 100, 0, 0), np.array([0, 42, 42, 1, 0, 8, 100, 0, 0])): seq = Sequence('G' * 9, positional_metadata={'foo': item}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': item}, index=np.arange(9))) def test_init_positional_metadata_multiple_columns(self): seq = Sequence('^' * 5, positional_metadata={'foo': np.arange(5), 'bar': np.arange(5)[::-1]}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': np.arange(5), 'bar': np.arange(5)[::-1]}, index=np.arange(5))) def test_init_positional_metadata_with_custom_index(self): df = pd.DataFrame({'foo': np.arange(5), 'bar': np.arange(5)[::-1]}, index=['a', 'b', 'c', 'd', 'e']) seq = Sequence('^' * 5, positional_metadata=df) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': np.arange(5), 'bar': np.arange(5)[::-1]}, index=np.arange(5))) def test_init_invalid_sequence(self): # invalid dtype (numpy.ndarray input) with self.assertRaises(TypeError): # int64 Sequence(np.array([1, 2, 3])) with self.assertRaises(TypeError): # |S21 Sequence(np.array([1, "23", 3])) with self.assertRaises(TypeError): # object Sequence(np.array([1, {}, ()])) # invalid input type (non-numpy.ndarray input) with self.assertRaisesRegexp(TypeError, 'tuple'): Sequence(('a', 'b', 'c')) with self.assertRaisesRegexp(TypeError, 'list'): Sequence(['a', 'b', 'c']) with self.assertRaisesRegexp(TypeError, 'set'): Sequence({'a', 'b', 'c'}) with self.assertRaisesRegexp(TypeError, 'dict'): Sequence({'a': 42, 'b': 43, 'c': 44}) with self.assertRaisesRegexp(TypeError, 'int'): Sequence(42) with self.assertRaisesRegexp(TypeError, 'float'): Sequence(4.2) with self.assertRaisesRegexp(TypeError, 'int64'): Sequence(np.int_(50)) with self.assertRaisesRegexp(TypeError, 'float64'): Sequence(np.float_(50)) with self.assertRaisesRegexp(TypeError, 'Foo'): class Foo(object): pass Sequence(Foo()) # out of ASCII range with self.assertRaises(UnicodeEncodeError): Sequence(u'abc\u1F30') def test_init_invalid_metadata(self): for md in (0, 'a', ('f', 'o', 'o'), np.array([]), pd.DataFrame()): with self.assertRaisesRegexp(TypeError, 'metadata must be a dict'): Sequence('abc', metadata=md) def test_init_invalid_positional_metadata(self): # not consumable by Pandas with self.assertRaisesRegexp(TypeError, 'Positional metadata invalid. Must be ' 'consumable by pd.DataFrame. ' 'Original pandas error message: '): Sequence('ACGT', positional_metadata=2) # 0 elements with self.assertRaisesRegexp(ValueError, '\(0\).*\(4\)'): Sequence('ACGT', positional_metadata=[]) # not enough elements with self.assertRaisesRegexp(ValueError, '\(3\).*\(4\)'): Sequence('ACGT', positional_metadata=[2, 3, 4]) # too many elements with self.assertRaisesRegexp(ValueError, '\(5\).*\(4\)'): Sequence('ACGT', positional_metadata=[2, 3, 4, 5, 6]) # Series not enough rows with self.assertRaisesRegexp(ValueError, '\(3\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.Series(range(3))) # Series too many rows with self.assertRaisesRegexp(ValueError, '\(5\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.Series(range(5))) # DataFrame not enough rows with self.assertRaisesRegexp(ValueError, '\(3\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.DataFrame({'quality': range(3)})) # DataFrame too many rows with self.assertRaisesRegexp(ValueError, '\(5\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.DataFrame({'quality': range(5)})) def test_values_property(self): # Property tests are only concerned with testing the interface # provided by the property: that it can be accessed, can't be # reassigned or mutated in place, and that the correct type is # returned. More extensive testing of border cases (e.g., different # sequence lengths or input types, odd characters, etc.) are performed # in Sequence.__init__ tests. seq = Sequence('ACGT') # should get back a numpy.ndarray of '|S1' dtype self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') npt.assert_equal(seq.values, np.array('ACGT', dtype='c')) # test that we can't mutate the property with self.assertRaises(ValueError): seq.values[1] = 'A' # test that we can't set the property with self.assertRaises(AttributeError): seq.values = np.array("GGGG", dtype='c') def test_metadata_property_getter(self): md = {'foo': 'bar'} seq = Sequence('', metadata=md) self.assertIsInstance(seq.metadata, dict) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) # update existing key seq.metadata['foo'] = 'baz' self.assertEqual(seq.metadata, {'foo': 'baz'}) # add new key seq.metadata['foo2'] = 'bar2' self.assertEqual(seq.metadata, {'foo': 'baz', 'foo2': 'bar2'}) def test_metadata_property_getter_missing(self): seq = Sequence('ACGT') self.assertIsNone(seq._metadata) self.assertEqual(seq.metadata, {}) self.assertIsNotNone(seq._metadata) def test_metadata_property_setter(self): md = {'foo': 'bar'} seq = Sequence('', metadata=md) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) new_md = {'bar': 'baz', 42: 42} seq.metadata = new_md self.assertEqual(seq.metadata, new_md) self.assertIsNot(seq.metadata, new_md) seq.metadata = {} self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_metadata()) def test_metadata_property_setter_invalid_type(self): seq = Sequence('abc', metadata={123: 456}) for md in (None, 0, 'a', ('f', 'o', 'o'), np.array([]), pd.DataFrame()): with self.assertRaisesRegexp(TypeError, 'metadata must be a dict'): seq.metadata = md # object should still be usable and its original metadata shouldn't # have changed self.assertEqual(seq.metadata, {123: 456}) def test_metadata_property_deleter(self): md = {'foo': 'bar'} seq = Sequence('CAT', metadata=md) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) del seq.metadata self.assertIsNone(seq._metadata) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) # test deleting again del seq.metadata self.assertIsNone(seq._metadata) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) # test deleting missing metadata immediately after instantiation seq = Sequence('ACGT') self.assertIsNone(seq._metadata) del seq.metadata self.assertIsNone(seq._metadata) def test_metadata_property_shallow_copy(self): md = {'key1': 'val1', 'key2': 'val2', 'key3': [1, 2]} seq = Sequence('CAT', metadata=md) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) # updates to keys seq.metadata['key1'] = 'new val' self.assertEqual(seq.metadata, {'key1': 'new val', 'key2': 'val2', 'key3': [1, 2]}) # original metadata untouched self.assertEqual(md, {'key1': 'val1', 'key2': 'val2', 'key3': [1, 2]}) # updates to mutable value (by reference) seq.metadata['key3'].append(3) self.assertEqual( seq.metadata, {'key1': 'new val', 'key2': 'val2', 'key3': [1, 2, 3]}) # original metadata changed because we didn't deep copy self.assertEqual( md, {'key1': 'val1', 'key2': 'val2', 'key3': [1, 2, 3]}) def test_positional_metadata_property_getter(self): md = pd.DataFrame({'foo': [22, 22, 0]}) seq = Sequence('ACA', positional_metadata=md) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]})) self.assertIsNot(seq.positional_metadata, md) # update existing column seq.positional_metadata['foo'] = [42, 42, 43] assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [42, 42, 43]})) # add new column seq.positional_metadata['foo2'] = [True, False, True] assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [42, 42, 43], 'foo2': [True, False, True]})) def test_positional_metadata_property_getter_missing(self): seq = Sequence('ACGT') self.assertIsNone(seq._positional_metadata) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame(index=np.arange(4))) self.assertIsNotNone(seq._positional_metadata) def test_positional_metadata_property_setter(self): md = pd.DataFrame({'foo': [22, 22, 0]}) seq = Sequence('ACA', positional_metadata=md) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]})) self.assertIsNot(seq.positional_metadata, md) new_md = pd.DataFrame({'bar': np.arange(3)}, index=['a', 'b', 'c']) seq.positional_metadata = new_md assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'bar': np.arange(3)}, index=np.arange(3))) self.assertIsNot(seq.positional_metadata, new_md) seq.positional_metadata = pd.DataFrame(index=np.arange(3)) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) self.assertFalse(seq.has_positional_metadata()) def test_positional_metadata_property_setter_invalid_type(self): # More extensive tests for invalid input are on Sequence.__init__ tests seq = Sequence('abc', positional_metadata={'foo': [1, 2, 42]}) # not consumable by Pandas with self.assertRaisesRegexp(TypeError, 'Positional metadata invalid. Must be ' 'consumable by pd.DataFrame. ' 'Original pandas error message: '): seq.positional_metadata = 2 # object should still be usable and its original metadata shouldn't # have changed assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [1, 2, 42]})) # wrong length with self.assertRaisesRegexp(ValueError, '\(2\).*\(3\)'): seq.positional_metadata = {'foo': [1, 2]} assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [1, 2, 42]})) # None isn't valid when using setter (differs from constructor) with self.assertRaisesRegexp(ValueError, '\(0\).*\(3\)'): seq.positional_metadata = None assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [1, 2, 42]})) def test_positional_metadata_property_deleter(self): md = pd.DataFrame({'foo': [22, 22, 0]}) seq = Sequence('ACA', positional_metadata=md) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]})) self.assertIsNot(seq.positional_metadata, md) del seq.positional_metadata self.assertIsNone(seq._positional_metadata) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) # test deleting again del seq.positional_metadata self.assertIsNone(seq._positional_metadata) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) # test deleting missing positional metadata immediately after # instantiation seq = Sequence('ACGT') self.assertIsNone(seq._positional_metadata) del seq.positional_metadata self.assertIsNone(seq._positional_metadata) def test_positional_metadata_property_shallow_copy(self): # define metadata as a DataFrame because this has the potential to have # its underlying data shared md = pd.DataFrame({'foo': [22, 22, 0]}, index=['a', 'b', 'c']) seq = Sequence('ACA', positional_metadata=md) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]}, index=np.arange(3))) self.assertIsNot(seq.positional_metadata, md) # original metadata untouched orig_md = pd.DataFrame({'foo': [22, 22, 0]}, index=['a', 'b', 'c']) assert_data_frame_almost_equal(md, orig_md) # change values of column (using same dtype) seq.positional_metadata['foo'] = [42, 42, 42] assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [42, 42, 42]}, index=np.arange(3))) # original metadata untouched assert_data_frame_almost_equal(md, orig_md) # change single value of underlying data seq.positional_metadata.values[0][0] = 10 assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [10, 42, 42]}, index=np.arange(3))) # original metadata untouched assert_data_frame_almost_equal(md, orig_md) # create column of object dtype -- these aren't deep copied md = pd.DataFrame({'obj': [[], [], []]}, index=['a', 'b', 'c']) seq = Sequence('ACA', positional_metadata=md) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'obj': [[], [], []]}, index=np.arange(3))) # mutate list seq.positional_metadata['obj'][0].append(42) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'obj': [[42], [], []]}, index=np.arange(3))) # original metadata changed because we didn't do a full deep copy assert_data_frame_almost_equal( md, pd.DataFrame({'obj': [[42], [], []]}, index=['a', 'b', 'c'])) def test_positional_metadata_property_set_column_series(self): seq_text = 'ACGTACGT' l = len(seq_text) seq = Sequence(seq_text, positional_metadata={'foo': range(l)}) seq.positional_metadata['bar'] = pd.Series(range(l-3)) # pandas.Series will be padded with NaN if too short npt.assert_equal(seq.positional_metadata['bar'], np.array(list(range(l-3)) + [np.NaN]*3)) seq.positional_metadata['baz'] = pd.Series(range(l+3)) # pandas.Series will be truncated if too long npt.assert_equal(seq.positional_metadata['baz'], np.array(range(l))) def test_positional_metadata_property_set_column_array(self): seq_text = 'ACGTACGT' l = len(seq_text) seq = Sequence(seq_text, positional_metadata={'foo': range(l)}) # array-like objects will fail if wrong size for array_like in (np.array(range(l-1)), range(l-1), np.array(range(l+1)), range(l+1)): with self.assertRaisesRegexp(ValueError, "Length of values does not match " "length of index"): seq.positional_metadata['bar'] = array_like def test_eq_and_ne(self): seq_a = Sequence("A") seq_b = Sequence("B") self.assertTrue(seq_a == seq_a) self.assertTrue(Sequence("a") == Sequence("a")) self.assertTrue(Sequence("a", metadata={'id': 'b'}) == Sequence("a", metadata={'id': 'b'})) self.assertTrue(Sequence("a", metadata={'id': 'b', 'description': 'c'}) == Sequence("a", metadata={'id': 'b', 'description': 'c'})) self.assertTrue(Sequence("a", metadata={'id': 'b', 'description': 'c'}, positional_metadata={'quality': [1]}) == Sequence("a", metadata={'id': 'b', 'description': 'c'}, positional_metadata={'quality': [1]})) self.assertTrue(seq_a != seq_b) self.assertTrue(SequenceSubclass("a") != Sequence("a")) self.assertTrue(Sequence("a") != Sequence("b")) self.assertTrue(Sequence("a") != Sequence("a", metadata={'id': 'b'})) self.assertTrue(Sequence("a", metadata={'id': 'c'}) != Sequence("a", metadata={'id': 'c', 'description': 't'})) self.assertTrue(Sequence("a", positional_metadata={'quality': [1]}) != Sequence("a")) self.assertTrue(Sequence("a", positional_metadata={'quality': [1]}) != Sequence("a", positional_metadata={'quality': [2]})) self.assertTrue(Sequence("c", positional_metadata={'quality': [3]}) != Sequence("b", positional_metadata={'quality': [3]})) self.assertTrue(Sequence("a", metadata={'id': 'b'}) != Sequence("c", metadata={'id': 'b'})) def test_eq_sequences_without_metadata_compare_equal(self): self.assertTrue(Sequence('') == Sequence('')) self.assertTrue(Sequence('z') == Sequence('z')) self.assertTrue( Sequence('ACGT') == Sequence('ACGT')) def test_eq_sequences_with_metadata_compare_equal(self): seq1 = Sequence('ACGT', metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'qual': [1, 2, 3, 4]}) seq2 = Sequence('ACGT', metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'qual': [1, 2, 3, 4]}) self.assertTrue(seq1 == seq2) # order shouldn't matter self.assertTrue(seq2 == seq1) def test_eq_sequences_from_different_sources_compare_equal(self): # sequences that have the same data but are constructed from different # types of data should compare equal seq1 = Sequence('ACGT', metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'quality': (1, 2, 3, 4)}) seq2 = Sequence(np.array([65, 67, 71, 84], dtype=np.uint8), metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'quality': np.array([1, 2, 3, 4])}) self.assertTrue(seq1 == seq2) def test_eq_type_mismatch(self): seq1 = Sequence('ACGT') seq2 = SequenceSubclass('ACGT') self.assertFalse(seq1 == seq2) def test_eq_metadata_mismatch(self): # both provided seq1 = Sequence('ACGT', metadata={'id': 'foo'}) seq2 = Sequence('ACGT', metadata={'id': 'bar'}) self.assertFalse(seq1 == seq2) # one provided seq1 = Sequence('ACGT', metadata={'id': 'foo'}) seq2 = Sequence('ACGT') self.assertFalse(seq1 == seq2) def test_eq_positional_metadata_mismatch(self): # both provided seq1 = Sequence('ACGT', positional_metadata={'quality': [1, 2, 3, 4]}) seq2 = Sequence('ACGT', positional_metadata={'quality': [1, 2, 3, 5]}) self.assertFalse(seq1 == seq2) # one provided seq1 = Sequence('ACGT', positional_metadata={'quality': [1, 2, 3, 4]}) seq2 = Sequence('ACGT') self.assertFalse(seq1 == seq2) def test_eq_sequence_mismatch(self): seq1 = Sequence('ACGT') seq2 = Sequence('TGCA') self.assertFalse(seq1 == seq2) def test_eq_handles_missing_metadata_efficiently(self): seq1 = Sequence('ACGT') seq2 = Sequence('ACGT') self.assertTrue(seq1 == seq2) # metadata attributes should be None and not initialized to a "missing" # representation self.assertIsNone(seq1._metadata) self.assertIsNone(seq1._positional_metadata) self.assertIsNone(seq2._metadata) self.assertIsNone(seq2._positional_metadata) def test_getitem_gives_new_sequence(self): seq = Sequence("Sequence string !1@2#3?.,") self.assertFalse(seq is seq[:]) def test_getitem_with_int_has_positional_metadata(self): s = "Sequence string !1@2#3?.," length = len(s) seq = Sequence(s, metadata={'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("S", {'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': np.array([0])}) self.assertEqual(seq[0], eseq) eseq = Sequence(",", metadata={'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': np.array([len(seq) - 1])}) self.assertEqual(seq[len(seq) - 1], eseq) eseq = Sequence("t", metadata={'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': [10]}) self.assertEqual(seq[10], eseq) def test_single_index_to_slice(self): a = [1, 2, 3, 4] self.assertEqual(slice(0, 1), _single_index_to_slice(0)) self.assertEqual([1], a[_single_index_to_slice(0)]) self.assertEqual(slice(-1, None), _single_index_to_slice(-1)) self.assertEqual([4], a[_single_index_to_slice(-1)]) def test_is_single_index(self): self.assertTrue(_is_single_index(0)) self.assertFalse(_is_single_index(True)) self.assertFalse(_is_single_index(bool())) self.assertFalse(_is_single_index('a')) def test_as_slice_if_single_index(self): self.assertEqual(slice(0, 1), _as_slice_if_single_index(0)) slice_obj = slice(2, 3) self.assertIs(slice_obj, _as_slice_if_single_index(slice_obj)) def test_slice_positional_metadata(self): seq = Sequence('ABCDEFGHIJ', positional_metadata={'foo': np.arange(10), 'bar': np.arange(100, 110)}) self.assertTrue(pd.DataFrame({'foo': [0], 'bar': [100]}).equals( seq._slice_positional_metadata(0))) self.assertTrue(pd.DataFrame({'foo': [0], 'bar': [100]}).equals( seq._slice_positional_metadata(slice(0, 1)))) self.assertTrue(pd.DataFrame({'foo': [0, 1], 'bar': [100, 101]}).equals( seq._slice_positional_metadata(slice(0, 2)))) self.assertTrue(pd.DataFrame( {'foo': [9], 'bar': [109]}, index=[9]).equals( seq._slice_positional_metadata(9))) def test_getitem_with_int_no_positional_metadata(self): seq = Sequence("Sequence string !1@2#3?.,", metadata={'id': 'id2', 'description': 'no_qual'}) eseq = Sequence("t", metadata={'id': 'id2', 'description': 'no_qual'}) self.assertEqual(seq[10], eseq) def test_getitem_with_slice_has_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("012", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.arange(3)}) self.assertEquals(seq[0:3], eseq) self.assertEquals(seq[:3], eseq) self.assertEquals(seq[:3:1], eseq) eseq = Sequence("def", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [13, 14, 15]}) self.assertEquals(seq[-3:], eseq) self.assertEquals(seq[-3::1], eseq) eseq = Sequence("02468ace", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [0, 2, 4, 6, 8, 10, 12, 14]}) self.assertEquals(seq[0:length:2], eseq) self.assertEquals(seq[::2], eseq) eseq = Sequence(s[::-1], metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.arange(length)[::-1]}) self.assertEquals(seq[length::-1], eseq) self.assertEquals(seq[::-1], eseq) eseq = Sequence('fdb97531', metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [15, 13, 11, 9, 7, 5, 3, 1]}) self.assertEquals(seq[length::-2], eseq) self.assertEquals(seq[::-2], eseq) self.assertEquals(seq[0:500:], seq) eseq = Sequence('', metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.array([], dtype=np.int64)}) self.assertEquals(seq[length:0], eseq) self.assertEquals(seq[-length:0], eseq) self.assertEquals(seq[1:0], eseq) eseq = Sequence("0", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [0]}) self.assertEquals(seq[0:1], eseq) self.assertEquals(seq[0:1:1], eseq) self.assertEquals(seq[-length::-1], eseq) def test_getitem_with_slice_no_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id4', 'description': 'no_qual4'}) eseq = Sequence("02468ace", metadata={'id': 'id4', 'description': 'no_qual4'}) self.assertEquals(seq[0:length:2], eseq) self.assertEquals(seq[::2], eseq) def test_getitem_with_tuple_of_mixed_with_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id5', 'description': 'dsc5'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("00000", metadata={'id': 'id5', 'description': 'dsc5'}, positional_metadata={'quality': [0, 0, 0, 0, 0]}) self.assertEquals(seq[0, 0, 0, 0, 0], eseq) self.assertEquals(seq[0, 0:1, 0, 0, 0], eseq) self.assertEquals(seq[0, 0:1, 0, -length::-1, 0, 1:0], eseq) self.assertEquals(seq[0:1, 0:1, 0:1, 0:1, 0:1], eseq) self.assertEquals(seq[0:1, 0, 0, 0, 0], eseq) eseq = Sequence("0123fed9", metadata={'id': 'id5', 'description': 'dsc5'}, positional_metadata={'quality': [0, 1, 2, 3, 15, 14, 13, 9]}) self.assertEquals(seq[0, 1, 2, 3, 15, 14, 13, 9], eseq) self.assertEquals(seq[0, 1, 2, 3, :-4:-1, 9], eseq) self.assertEquals(seq[0:4, :-4:-1, 9, 1:0], eseq) self.assertEquals(seq[0:4, :-4:-1, 9:10], eseq) def test_getitem_with_tuple_of_mixed_no_positional_metadata(self): seq = Sequence("0123456789abcdef", metadata={'id': 'id6', 'description': 'no_qual6'}) eseq = Sequence("0123fed9", metadata={'id': 'id6', 'description': 'no_qual6'}) self.assertEquals(seq[0, 1, 2, 3, 15, 14, 13, 9], eseq) self.assertEquals(seq[0, 1, 2, 3, :-4:-1, 9], eseq) self.assertEquals(seq[0:4, :-4:-1, 9], eseq) self.assertEquals(seq[0:4, :-4:-1, 9:10], eseq) def test_getitem_with_iterable_of_mixed_has_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id7', 'description': 'dsc7'}, positional_metadata={'quality': np.arange(length)}) def generator(): yield slice(0, 4) yield slice(200, 400) yield -1 yield slice(-2, -4, -1) yield 9 eseq = Sequence("0123fed9", metadata={'id': 'id7', 'description': 'dsc7'}, positional_metadata={'quality': [0, 1, 2, 3, 15, 14, 13, 9]}) self.assertEquals(seq[[0, 1, 2, 3, 15, 14, 13, 9]], eseq) self.assertEquals(seq[generator()], eseq) self.assertEquals(seq[[slice(0, 4), slice(None, -4, -1), 9]], eseq) self.assertEquals(seq[ [slice(0, 4), slice(None, -4, -1), slice(9, 10)]], eseq) def test_getitem_with_iterable_of_mixed_no_positional_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id7', 'description': 'dsc7'}) def generator(): yield slice(0, 4) yield slice(200, 400) yield slice(None, -4, -1) yield 9 eseq = Sequence("0123fed9", metadata={'id': 'id7', 'description': 'dsc7'}) self.assertEquals(seq[[0, 1, 2, 3, 15, 14, 13, 9]], eseq) self.assertEquals(seq[generator()], eseq) self.assertEquals(seq[[slice(0, 4), slice(None, -4, -1), 9]], eseq) self.assertEquals(seq[ [slice(0, 4), slice(None, -4, -1), slice(9, 10)]], eseq) def test_getitem_with_numpy_index_has_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id9', 'description': 'dsc9'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("0123fed9", metadata={'id': 'id9', 'description': 'dsc9'}, positional_metadata={'quality': [0, 1, 2, 3, 15, 14, 13, 9]}) self.assertEquals(seq[np.array([0, 1, 2, 3, 15, 14, 13, 9])], eseq) def test_getitem_with_numpy_index_no_positional_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id10', 'description': 'dsc10'}) eseq = Sequence("0123fed9", metadata={'id': 'id10', 'description': 'dsc10'}) self.assertEquals(seq[np.array([0, 1, 2, 3, 15, 14, 13, 9])], eseq) def test_getitem_with_empty_indices_empty_seq_no_pos_metadata(self): s = "" seq = Sequence(s, metadata={'id': 'id10', 'description': 'dsc10'}) eseq = Sequence('', metadata={'id': 'id10', 'description': 'dsc10'}) tested = 0 for index in self.getitem_empty_indices: tested += 1 self.assertEqual(seq[index], eseq) self.assertEqual(tested, 6) def test_getitem_with_empty_indices_non_empty_seq_no_pos_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id10', 'description': 'dsc10'}) eseq = Sequence('', metadata={'id': 'id10', 'description': 'dsc10'}) tested = 0 for index in self.getitem_empty_indices: tested += 1 self.assertEqual(seq[index], eseq) self.assertEqual(tested, 6) def test_getitem_with_boolean_vector_has_qual(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id11', 'description': 'dsc11'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("13579bdf", metadata={'id': 'id11', 'description': 'dsc11'}, positional_metadata={'quality': [1, 3, 5, 7, 9, 11, 13, 15]}) self.assertEqual(seq[np.array([False, True] * 8)], eseq) self.assertEqual(seq[[False, True] * 8], eseq) def test_getitem_with_boolean_vector_no_positional_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id11', 'description': 'dsc11'}) eseq = Sequence("13579bdf", metadata={'id': 'id11', 'description': 'dsc11'}) self.assertEqual(seq[np.array([False, True] * 8)], eseq) def test_getitem_with_invalid(self): seq = Sequence("123456", metadata={'id': 'idm', 'description': 'description'}, positional_metadata={'quality': [1, 2, 3, 4, 5, 6]}) with self.assertRaises(IndexError): seq['not an index'] with self.assertRaises(IndexError): seq[['1', '2']] with self.assertRaises(IndexError): seq[[1, slice(1, 2), 'a']] with self.assertRaises(IndexError): seq[[1, slice(1, 2), True]] with self.assertRaises(IndexError): seq[True] with self.assertRaises(IndexError): seq[np.array([True, False])] with self.assertRaises(IndexError): seq[999] with self.assertRaises(IndexError): seq[0, 0, 999] # numpy 1.8.1 and 1.9.2 raise different error types # (ValueError, IndexError). with self.assertRaises(Exception): seq[100 * [True, False, True]] def test_getitem_handles_missing_metadata_efficiently(self): # there are two paths in __getitem__ we need to test for efficient # handling of missing metadata # path 1: mixed types seq = Sequence('ACGT') subseq = seq[1, 2:4] self.assertEqual(subseq, Sequence('CGT')) # metadata attributes should be None and not initialized to a "missing" # representation self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(subseq._metadata) self.assertIsNone(subseq._positional_metadata) # path 2: uniform types seq = Sequence('ACGT') subseq = seq[1:3] self.assertEqual(subseq, Sequence('CG')) self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(subseq._metadata) self.assertIsNone(subseq._positional_metadata) def test_len(self): self.assertEqual(len(Sequence("")), 0) self.assertEqual(len(Sequence("a")), 1) self.assertEqual(len(Sequence("abcdef")), 6) def test_contains(self): seq = Sequence("#@ACGT,24.13**02") tested = 0 for c in self.sequence_kinds: tested += 1 self.assertTrue(c(',24') in seq) self.assertTrue(c('*') in seq) self.assertTrue(c('') in seq) self.assertFalse(c("$") in seq) self.assertFalse(c("AGT") in seq) self.assertEqual(tested, 4) def test_contains_sequence_subclass(self): with self.assertRaises(TypeError): SequenceSubclass("A") in Sequence("AAA") self.assertTrue(SequenceSubclass("A").values in Sequence("AAA")) def test_hash(self): with self.assertRaises(TypeError): hash(Sequence("ABCDEFG")) self.assertNotIsInstance(Sequence("ABCDEFG"), Hashable) def test_iter_has_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': np.arange(10)}) for i, s in enumerate(seq): tested = True self.assertEqual(s, Sequence(str(i), metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': [i]})) self.assertTrue(tested) def test_iter_no_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}) for i, s in enumerate(seq): tested = True self.assertEqual(s, Sequence(str(i), metadata={'id': 'a', 'desc': 'b'})) self.assertTrue(tested) def test_reversed_has_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': np.arange(10)}) for i, s in enumerate(reversed(seq)): tested = True self.assertEqual(s, Sequence(str(9 - i), metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': [9 - i]})) self.assertTrue(tested) def test_reversed_no_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}) for i, s in enumerate(reversed(seq)): tested = True self.assertEqual(s, Sequence(str(9 - i), metadata={'id': 'a', 'desc': 'b'})) self.assertTrue(tested) def test_repr(self): # basic sanity checks -- more extensive testing of formatting and # special cases is performed in SequenceReprDoctests below. here we # only test that pieces of the repr are present. these tests also # exercise coverage for py2/3 since the doctests in # SequenceReprDoctests only currently run in py2. # minimal obs = repr(Sequence('')) self.assertEqual(obs.count('\n'), 4) self.assertTrue(obs.startswith('Sequence')) self.assertIn('length: 0', obs) self.assertTrue(obs.endswith('-')) # no metadata obs = repr(Sequence('ACGT')) self.assertEqual(obs.count('\n'), 5) self.assertTrue(obs.startswith('Sequence')) self.assertIn('length: 4', obs) self.assertTrue(obs.endswith('0 ACGT')) # metadata and positional metadata of mixed types obs = repr( Sequence( 'ACGT', metadata={'foo': 'bar', u'bar': 33.33, None: True, False: {}, (1, 2): 3, 'acb' * 100: "'", 10: 11}, positional_metadata={'foo': range(4), 42: ['a', 'b', [], 'c']})) self.assertEqual(obs.count('\n'), 16) self.assertTrue(obs.startswith('Sequence')) self.assertIn('None: True', obs) self.assertIn('\'foo\': \'bar\'', obs) self.assertIn('42: <dtype: object>', obs) self.assertIn('\'foo\': <dtype: int64>', obs) self.assertIn('length: 4', obs) self.assertTrue(obs.endswith('0 ACGT')) # sequence spanning > 5 lines obs = repr(Sequence('A' * 301)) self.assertEqual(obs.count('\n'), 9) self.assertTrue(obs.startswith('Sequence')) self.assertIn('length: 301', obs) self.assertIn('...', obs) self.assertTrue(obs.endswith('300 A')) def test_str(self): self.assertEqual(str(Sequence("GATTACA")), "GATTACA") self.assertEqual(str(Sequence("ACCGGTACC")), "ACCGGTACC") self.assertEqual(str(Sequence("GREG")), "GREG") self.assertEqual( str(Sequence("ABC", positional_metadata={'quality': [1, 2, 3]})), "ABC") self.assertIs(type(str(Sequence("A"))), str) def test_to_default_behavior(self): # minimal sequence, sequence with all optional attributes present, and # a subclass of Sequence for seq in (Sequence('ACGT'), Sequence('ACGT', metadata={'id': 'foo', 'desc': 'bar'}, positional_metadata={'quality': range(4)}), SequenceSubclass('ACGU', metadata={'id': 'rna seq'})): to = seq._to() self.assertEqual(seq, to) self.assertIsNot(seq, to) def test_to_update_single_attribute(self): seq = Sequence('HE..--..LLO', metadata={'id': 'hello', 'description': 'gapped hello'}, positional_metadata={'quality': range(11)}) to = seq._to(metadata={'id': 'new id'}) self.assertIsNot(seq, to) self.assertNotEqual(seq, to) self.assertEqual( to, Sequence('HE..--..LLO', metadata={'id': 'new id'}, positional_metadata={'quality': range(11)})) # metadata shouldn't have changed on the original sequence self.assertEqual(seq.metadata, {'id': 'hello', 'description': 'gapped hello'}) def test_to_update_multiple_attributes(self): seq = Sequence('HE..--..LLO', metadata={'id': 'hello', 'description': 'gapped hello'}, positional_metadata={'quality': range(11)}) to = seq._to(metadata={'id': 'new id', 'description': 'new desc'}, positional_metadata={'quality': range(20, 25)}, sequence='ACGTA') self.assertIsNot(seq, to) self.assertNotEqual(seq, to) # attributes should be what we specified in the _to call... self.assertEqual(to.metadata['id'], 'new id') npt.assert_array_equal(to.positional_metadata['quality'], np.array([20, 21, 22, 23, 24])) npt.assert_array_equal(to.values, np.array('ACGTA', dtype='c')) self.assertEqual(to.metadata['description'], 'new desc') # ...and shouldn't have changed on the original sequence self.assertEqual(seq.metadata['id'], 'hello') npt.assert_array_equal(seq.positional_metadata['quality'], range(11)) npt.assert_array_equal(seq.values, np.array('HE..--..LLO', dtype='c')) self.assertEqual(seq.metadata['description'], 'gapped hello') def test_to_invalid_kwargs(self): seq = Sequence('ACCGGTACC', metadata={'id': "test-seq", 'desc': "A test sequence"}) with self.assertRaises(TypeError): seq._to(metadata={'id': 'bar'}, unrecognized_kwarg='baz') def test_to_extra_non_attribute_kwargs(self): # test that we can pass through additional kwargs to the constructor # that aren't related to biological sequence attributes (i.e., they # aren't state that has to be copied) class SequenceSubclassWithNewSignature(Sequence): def __init__(self, sequence, metadata=None, positional_metadata=None, foo=False): super(SequenceSubclassWithNewSignature, self).__init__( sequence, metadata=metadata, positional_metadata=positional_metadata) self.foo = foo seq = SequenceSubclassWithNewSignature('ACTG', metadata={'description': 'foo'}) # _to() without specifying `foo` to = seq._to() self.assertEqual(seq, to) self.assertIsNot(seq, to) self.assertFalse(seq.foo) # `foo` should default to False self.assertFalse(to.foo) # _to() with `foo` specified to = seq._to(foo=True) self.assertEqual(seq, to) self.assertIsNot(seq, to) self.assertFalse(seq.foo) # `foo` should now be True self.assertTrue(to.foo) def test_count(self): def construct_char_array(s): return np.fromstring(s, dtype='|S1') def construct_uint8_array(s): return np.fromstring(s, dtype=np.uint8) seq = Sequence("1234567899876555") tested = 0 for c in self.sequence_kinds: tested += 1 self.assertEqual(seq.count(c('4')), 1) self.assertEqual(seq.count(c('8')), 2) self.assertEqual(seq.count(c('5')), 4) self.assertEqual(seq.count(c('555')), 1) self.assertEqual(seq.count(c('555'), 0, 4), 0) self.assertEqual(seq.count(c('555'), start=0, end=4), 0) self.assertEqual(seq.count(c('5'), start=10), 3) self.assertEqual(seq.count(c('5'), end=10), 1) with self.assertRaises(ValueError): seq.count(c('')) self.assertEquals(tested, 4) def test_count_on_subclass(self): with self.assertRaises(TypeError) as cm: Sequence("abcd").count(SequenceSubclass("a")) self.assertIn("Sequence", str(cm.exception)) self.assertIn("SequenceSubclass", str(cm.exception)) def test_distance(self): tested = 0 for constructor in self.sequence_kinds: tested += 1 seq1 = Sequence("abcdef") seq2 = constructor("12bcef") self.assertIsInstance(seq1.distance(seq1), float) self.assertEqual(seq1.distance(seq2), 2.0/3.0) self.assertEqual(tested, 4) def test_distance_arbitrary_function(self): def metric(x, y): return len(x) ** 2 + len(y) ** 2 seq1 = Sequence("12345678") seq2 = Sequence("1234") result = seq1.distance(seq2, metric=metric) self.assertIsInstance(result, float) self.assertEqual(result, 80.0) def test_distance_default_metric(self): seq1 = Sequence("abcdef") seq2 = Sequence("12bcef") seq_wrong = Sequence("abcdefghijklmnop") self.assertIsInstance(seq1.distance(seq1), float) self.assertEqual(seq1.distance(seq1), 0.0) self.assertEqual(seq1.distance(seq2), 2.0/3.0) with self.assertRaises(ValueError): seq1.distance(seq_wrong) with self.assertRaises(ValueError): seq_wrong.distance(seq1) def test_distance_on_subclass(self): seq1 = Sequence("abcdef") seq2 = SequenceSubclass("12bcef") with self.assertRaises(TypeError): seq1.distance(seq2) def test_matches(self): tested = 0 for constructor in self.sequence_kinds: tested += 1 seq1 = Sequence("AACCEEGG") seq2 = constructor("ABCDEFGH") expected = np.array([True, False] * 4) npt.assert_equal(seq1.matches(seq2), expected) self.assertEqual(tested, 4) def test_matches_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.matches(seq2) def test_matches_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.matches(seq2) def test_mismatches(self): tested = 0 for constructor in self.sequence_kinds: tested += 1 seq1 = Sequence("AACCEEGG") seq2 = constructor("ABCDEFGH") expected = np.array([False, True] * 4) npt.assert_equal(seq1.mismatches(seq2), expected) self.assertEqual(tested, 4) def test_mismatches_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.mismatches(seq2) def test_mismatches_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.mismatches(seq2) def test_mismatch_frequency(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.mismatch_frequency(seq1)), int) self.assertEqual(seq1.mismatch_frequency(seq1), 0) self.assertEqual(seq1.mismatch_frequency(seq2), 4) self.assertEqual(seq1.mismatch_frequency(seq3), 8) def test_mismatch_frequency_relative(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.mismatch_frequency(seq1, relative=True)), float) self.assertEqual(seq1.mismatch_frequency(seq1, relative=True), 0.0) self.assertEqual(seq1.mismatch_frequency(seq2, relative=True), 0.5) self.assertEqual(seq1.mismatch_frequency(seq3, relative=True), 1.0) def test_mismatch_frequency_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.mismatch_frequency(seq2) def test_mismatch_frequence_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.mismatch_frequency(seq2) def test_match_frequency(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.match_frequency(seq1)), int) self.assertEqual(seq1.match_frequency(seq1), 8) self.assertEqual(seq1.match_frequency(seq2), 4) self.assertEqual(seq1.match_frequency(seq3), 0) def test_match_frequency_relative(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.match_frequency(seq1, relative=True)), float) self.assertEqual(seq1.match_frequency(seq1, relative=True), 1.0) self.assertEqual(seq1.match_frequency(seq2, relative=True), 0.5) self.assertEqual(seq1.match_frequency(seq3, relative=True), 0.0) def test_match_frequency_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.match_frequency(seq2) def test_match_frequency_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.match_frequency(seq2) def test_index(self): tested = 0 for c in self.sequence_kinds: tested += 1 seq = Sequence("ABCDEFG@@ABCDFOO") self.assertEqual(seq.index(c("A")), 0) self.assertEqual(seq.index(c("@")), 7) self.assertEqual(seq.index(c("@@")), 7) with self.assertRaises(ValueError): seq.index("A", start=1, end=5) self.assertEqual(tested, 4) def test_index_on_subclass(self): with self.assertRaises(TypeError): Sequence("ABCDEFG").index(SequenceSubclass("A")) self.assertEqual( SequenceSubclass("ABCDEFG").index(SequenceSubclass("A")), 0) def _compare_kmers_results(self, observed, expected): for obs, exp in zip_longest(observed, expected, fillvalue=None): self.assertEqual(obs, exp) def test_iter_kmers(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) expected = [ Sequence('G', positional_metadata={'quality': [0]}), Sequence('A', positional_metadata={'quality': [1]}), Sequence('T', positional_metadata={'quality': [2]}), Sequence('T', positional_metadata={'quality': [3]}), Sequence('A', positional_metadata={'quality': [4]}), Sequence('C', positional_metadata={'quality': [5]}), Sequence('A', positional_metadata={'quality': [6]}) ] self._compare_kmers_results( seq.iter_kmers(1, overlap=False), expected) expected = [ Sequence('GA', positional_metadata={'quality': [0, 1]}), Sequence('TT', positional_metadata={'quality': [2, 3]}), Sequence('AC', positional_metadata={'quality': [4, 5]}) ] self._compare_kmers_results( seq.iter_kmers(2, overlap=False), expected) expected = [ Sequence('GAT', positional_metadata={'quality': [0, 1, 2]}), Sequence('TAC', positional_metadata={'quality': [3, 4, 5]}) ] self._compare_kmers_results( seq.iter_kmers(3, overlap=False), expected) expected = [ Sequence('GATTACA', positional_metadata={'quality': [0, 1, 2, 3, 4, 5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(7, overlap=False), expected) expected = [] self._compare_kmers_results( seq.iter_kmers(8, overlap=False), expected) self.assertIs(type(seq.iter_kmers(1)), GeneratorType) def test_iter_kmers_with_overlap(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) expected = [ Sequence('G', positional_metadata={'quality': [0]}), Sequence('A', positional_metadata={'quality': [1]}), Sequence('T', positional_metadata={'quality': [2]}), Sequence('T', positional_metadata={'quality': [3]}), Sequence('A', positional_metadata={'quality': [4]}), Sequence('C', positional_metadata={'quality': [5]}), Sequence('A', positional_metadata={'quality': [6]}) ] self._compare_kmers_results( seq.iter_kmers(1, overlap=True), expected) expected = [ Sequence('GA', positional_metadata={'quality': [0, 1]}), Sequence('AT', positional_metadata={'quality': [1, 2]}), Sequence('TT', positional_metadata={'quality': [2, 3]}), Sequence('TA', positional_metadata={'quality': [3, 4]}), Sequence('AC', positional_metadata={'quality': [4, 5]}), Sequence('CA', positional_metadata={'quality': [5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(2, overlap=True), expected) expected = [ Sequence('GAT', positional_metadata={'quality': [0, 1, 2]}), Sequence('ATT', positional_metadata={'quality': [1, 2, 3]}), Sequence('TTA', positional_metadata={'quality': [2, 3, 4]}), Sequence('TAC', positional_metadata={'quality': [3, 4, 5]}), Sequence('ACA', positional_metadata={'quality': [4, 5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(3, overlap=True), expected) expected = [ Sequence('GATTACA', positional_metadata={'quality': [0, 1, 2, 3, 4, 5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(7, overlap=True), expected) expected = [] self._compare_kmers_results( seq.iter_kmers(8, overlap=True), expected) self.assertIs(type(seq.iter_kmers(1)), GeneratorType) def test_iter_kmers_invalid_k(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) with self.assertRaises(ValueError): list(seq.iter_kmers(0)) with self.assertRaises(ValueError): list(seq.iter_kmers(-42)) def test_iter_kmers_different_sequences(self): seq = Sequence('HE..--..LLO', metadata={'id': 'hello', 'desc': 'gapped hello'}, positional_metadata={'quality': range(11)}) expected = [ Sequence('HE.', positional_metadata={'quality': [0, 1, 2]}, metadata={'id': 'hello', 'desc': 'gapped hello'}), Sequence('.--', positional_metadata={'quality': [3, 4, 5]}, metadata={'id': 'hello', 'desc': 'gapped hello'}), Sequence('..L', positional_metadata={'quality': [6, 7, 8]}, metadata={'id': 'hello', 'desc': 'gapped hello'}) ] self._compare_kmers_results(seq.iter_kmers(3, overlap=False), expected) def test_kmer_frequencies(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) # overlap = True expected = Counter('GATTACA') self.assertEqual(seq.kmer_frequencies(1, overlap=True), expected) expected = Counter(['GAT', 'ATT', 'TTA', 'TAC', 'ACA']) self.assertEqual(seq.kmer_frequencies(3, overlap=True), expected) expected = Counter([]) self.assertEqual(seq.kmer_frequencies(8, overlap=True), expected) # overlap = False expected = Counter(['GAT', 'TAC']) self.assertEqual(seq.kmer_frequencies(3, overlap=False), expected) expected = Counter(['GATTACA']) self.assertEqual(seq.kmer_frequencies(7, overlap=False), expected) expected = Counter([]) self.assertEqual(seq.kmer_frequencies(8, overlap=False), expected) def test_kmer_frequencies_relative(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) # overlap = True expected = defaultdict(float) expected['A'] = 3/7. expected['C'] = 1/7. expected['G'] = 1/7. expected['T'] = 2/7. self.assertEqual(seq.kmer_frequencies(1, overlap=True, relative=True), expected) expected = defaultdict(float) expected['GAT'] = 1/5. expected['ATT'] = 1/5. expected['TTA'] = 1/5. expected['TAC'] = 1/5. expected['ACA'] = 1/5. self.assertEqual(seq.kmer_frequencies(3, overlap=True, relative=True), expected) expected = defaultdict(float) self.assertEqual(seq.kmer_frequencies(8, overlap=True, relative=True), expected) # overlap = False expected = defaultdict(float) expected['GAT'] = 1/2. expected['TAC'] = 1/2. self.assertEqual(seq.kmer_frequencies(3, overlap=False, relative=True), expected) expected = defaultdict(float) expected['GATTACA'] = 1.0 self.assertEqual(seq.kmer_frequencies(7, overlap=False, relative=True), expected) expected = defaultdict(float) self.assertEqual(seq.kmer_frequencies(8, overlap=False, relative=True), expected) def test_kmer_frequencies_floating_point_precision(self): # Test that a sequence having no variation in k-words yields a # frequency of exactly 1.0. Note that it is important to use # self.assertEqual here instead of self.assertAlmostEqual because we # want to test for exactly 1.0. A previous implementation of # Sequence.kmer_frequencies(relative=True) added (1 / num_words) for # each occurrence of a k-word to compute the frequencies (see # https://github.com/biocore/scikit-bio/issues/801). In certain cases, # this yielded a frequency slightly less than 1.0 due to roundoff # error. The test case here uses a sequence with 10 characters that are # all identical and computes k-word frequencies with k=1. This test # case exposes the roundoff error present in the previous # implementation because there are 10 k-words (which are all # identical), so 1/10 added 10 times yields a number slightly less than # 1.0. This occurs because 1/10 cannot be represented exactly as a # floating point number. seq = Sequence('AAAAAAAAAA') self.assertEqual(seq.kmer_frequencies(1, relative=True), defaultdict(float, {'A': 1.0})) def test_find_with_regex(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) pat = re.compile('(T+A)(CA)') obs = list(seq.find_with_regex(pat)) exp = [slice(2, 5), slice(5, 7)] self.assertEqual(obs, exp) self.assertIs(type(seq.find_with_regex(pat)), GeneratorType) def test_find_with_regex_string_as_input(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) pat = '(T+A)(CA)' obs = list(seq.find_with_regex(pat)) exp = [slice(2, 5), slice(5, 7)] self.assertEqual(obs, exp) self.assertIs(type(seq.find_with_regex(pat)), GeneratorType) def test_find_with_regex_no_groups(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) pat = re.compile('(FOO)') self.assertEqual(list(seq.find_with_regex(pat)), []) def test_find_with_regex_ignore_no_difference(self): seq = Sequence('..ABCDEFG..') pat = "([A-Z]+)" exp = [slice(2, 9)] self.assertEqual(list(seq.find_with_regex(pat)), exp) obs = seq.find_with_regex( pat, ignore=np.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1], dtype=bool)) self.assertEqual(list(obs), exp) def test_find_with_regex_ignore(self): obs = Sequence('A..A..BBAAB.A..AB..A.').find_with_regex( "(A+)", ignore=np.array([0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1], dtype=bool)) self.assertEqual(list(obs), [slice(0, 4), slice(8, 10), slice(12, 16), slice(19, 20)]) def test_find_with_regex_ignore_index_array(self): obs = Sequence('A..A..BBAAB.A..AB..A.').find_with_regex( "(A+)", ignore=np.array([1, 2, 4, 5, 11, 13, 14, 17, 18, 20])) self.assertEqual(list(obs), [slice(0, 4), slice(8, 10), slice(12, 16), slice(19, 20)]) def test_iter_contiguous_index_array(self): s = Sequence("0123456789abcdef") for c in list, tuple, np.array, pd.Series: exp = [Sequence("0123"), Sequence("89ab")] obs = s.iter_contiguous(c([0, 1, 2, 3, 8, 9, 10, 11])) self.assertEqual(list(obs), exp) def test_iter_contiguous_boolean_vector(self): s = Sequence("0123456789abcdef") for c in list, tuple, np.array, pd.Series: exp = [Sequence("0123"), Sequence("89ab")] obs = s.iter_contiguous(c(([True] * 4 + [False] * 4) * 2)) self.assertEqual(list(obs), exp) def test_iter_contiguous_iterable_slices(self): def spaced_out(): yield slice(0, 4) yield slice(8, 12) def contiguous(): yield slice(0, 4) yield slice(4, 8) yield slice(12, 16) s = Sequence("0123456789abcdef") for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): exp = [Sequence("0123"), Sequence("89ab")] obs = s.iter_contiguous(c(spaced_out())) self.assertEqual(list(obs), exp) exp = [Sequence("01234567"), Sequence("cdef")] obs = s.iter_contiguous(c(contiguous())) self.assertEqual(list(obs), exp) def test_iter_contiguous_with_max_length(self): s = Sequence("0123456789abcdef") for c in list, tuple, np.array, pd.Series: exp = [Sequence("234"), Sequence("678"), Sequence("abc")] obs = s.iter_contiguous(c([True, False, True, True] * 4), min_length=3) self.assertEqual(list(obs), exp) exp = [Sequence("0"), Sequence("234"), Sequence("678"), Sequence("abc"), Sequence("ef")] obs1 = list(s.iter_contiguous(c([True, False, True, True] * 4), min_length=1)) obs2 = list(s.iter_contiguous(c([True, False, True, True] * 4))) self.assertEqual(obs1, obs2) self.assertEqual(obs1, exp) def test_iter_contiguous_with_invert(self): def spaced_out(): yield slice(0, 4) yield slice(8, 12) def contiguous(): yield slice(0, 4) yield slice(4, 8) yield slice(12, 16) s = Sequence("0123456789abcdef") for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): exp = [Sequence("4567"), Sequence("cdef")] obs = s.iter_contiguous(c(spaced_out()), invert=True) self.assertEqual(list(obs), exp) exp = [Sequence("89ab")] obs = s.iter_contiguous(c(contiguous()), invert=True) self.assertEqual(list(obs), exp) def test_has_metadata(self): # truly missing seq = Sequence('ACGT') self.assertFalse(seq.has_metadata()) # metadata attribute should be None and not initialized to a "missing" # representation self.assertIsNone(seq._metadata) # looks empty seq = Sequence('ACGT', metadata={}) self.assertFalse(seq.has_metadata()) # metadata is present seq = Sequence('ACGT', metadata={'foo': 42}) self.assertTrue(seq.has_metadata()) def test_has_positional_metadata(self): # truly missing seq = Sequence('ACGT') self.assertFalse(seq.has_positional_metadata()) # positional metadata attribute should be None and not initialized to a # "missing" representation self.assertIsNone(seq._positional_metadata) # looks empty seq = Sequence('ACGT', positional_metadata=pd.DataFrame(index=np.arange(4))) self.assertFalse(seq.has_positional_metadata()) # positional metadata is present seq = Sequence('ACGT', positional_metadata={'foo': [1, 2, 3, 4]}) self.assertTrue(seq.has_positional_metadata()) def test_copy_without_metadata(self): # shallow vs deep copy with sequence only should be equivalent. thus, # copy.copy, copy.deepcopy, and Sequence.copy(deep=True|False) should # all be equivalent for copy_method in (lambda seq: seq.copy(deep=False), lambda seq: seq.copy(deep=True), copy.copy, copy.deepcopy): seq = Sequence('ACGT') seq_copy = copy_method(seq) self.assertEqual(seq_copy, seq) self.assertIsNot(seq_copy, seq) self.assertIsNot(seq_copy._bytes, seq._bytes) # metadata attributes should be None and not initialized to a # "missing" representation self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(seq_copy._metadata) self.assertIsNone(seq_copy._positional_metadata) def test_copy_with_metadata_shallow(self): # copy.copy and Sequence.copy should behave identically for copy_method in lambda seq: seq.copy(), copy.copy: seq = Sequence('ACGT', metadata={'foo': [1]}, positional_metadata={'bar': [[], [], [], []], 'baz': [42, 42, 42, 42]}) seq_copy = copy_method(seq) self.assertEqual(seq_copy, seq) self.assertIsNot(seq_copy, seq) self.assertIsNot(seq_copy._bytes, seq._bytes) self.assertIsNot(seq_copy._metadata, seq._metadata) self.assertIsNot(seq_copy._positional_metadata, seq._positional_metadata) self.assertIsNot(seq_copy._positional_metadata.values, seq._positional_metadata.values) self.assertIs(seq_copy._metadata['foo'], seq._metadata['foo']) self.assertIs(seq_copy._positional_metadata.loc[0, 'bar'], seq._positional_metadata.loc[0, 'bar']) seq_copy.metadata['foo'].append(2) seq_copy.metadata['foo2'] = 42 self.assertEqual(seq_copy.metadata, {'foo': [1, 2], 'foo2': 42}) self.assertEqual(seq.metadata, {'foo': [1, 2]}) seq_copy.positional_metadata.loc[0, 'bar'].append(1) seq_copy.positional_metadata.loc[0, 'baz'] = 43 assert_data_frame_almost_equal( seq_copy.positional_metadata, pd.DataFrame({'bar': [[1], [], [], []], 'baz': [43, 42, 42, 42]})) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'bar': [[1], [], [], []], 'baz': [42, 42, 42, 42]})) def test_copy_with_metadata_deep(self): # copy.deepcopy and Sequence.copy(deep=True) should behave identically for copy_method in lambda seq: seq.copy(deep=True), copy.deepcopy: seq = Sequence('ACGT', metadata={'foo': [1]}, positional_metadata={'bar': [[], [], [], []], 'baz': [42, 42, 42, 42]}) seq_copy = copy_method(seq) self.assertEqual(seq_copy, seq) self.assertIsNot(seq_copy, seq) self.assertIsNot(seq_copy._bytes, seq._bytes) self.assertIsNot(seq_copy._metadata, seq._metadata) self.assertIsNot(seq_copy._positional_metadata, seq._positional_metadata) self.assertIsNot(seq_copy._positional_metadata.values, seq._positional_metadata.values) self.assertIsNot(seq_copy._metadata['foo'], seq._metadata['foo']) self.assertIsNot(seq_copy._positional_metadata.loc[0, 'bar'], seq._positional_metadata.loc[0, 'bar']) seq_copy.metadata['foo'].append(2) seq_copy.metadata['foo2'] = 42 self.assertEqual(seq_copy.metadata, {'foo': [1, 2], 'foo2': 42}) self.assertEqual(seq.metadata, {'foo': [1]}) seq_copy.positional_metadata.loc[0, 'bar'].append(1) seq_copy.positional_metadata.loc[0, 'baz'] = 43 assert_data_frame_almost_equal( seq_copy.positional_metadata, pd.DataFrame({'bar': [[1], [], [], []], 'baz': [43, 42, 42, 42]})) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'bar': [[], [], [], []], 'baz': [42, 42, 42, 42]})) def test_deepcopy_memo_is_respected(self): # basic test to ensure deepcopy's memo is passed through to recursive # deepcopy calls seq = Sequence('ACGT', metadata={'foo': 'bar'}) memo = {} copy.deepcopy(seq, memo) self.assertGreater(len(memo), 2) def test_munge_to_index_array_valid_index_array(self): s = Sequence('123456') for c in list, tuple, np.array, pd.Series: exp = np.array([1, 2, 3], dtype=int) obs = s._munge_to_index_array(c([1, 2, 3])) npt.assert_equal(obs, exp) exp = np.array([1, 3, 5], dtype=int) obs = s._munge_to_index_array(c([1, 3, 5])) npt.assert_equal(obs, exp) def test_munge_to_index_array_invalid_index_array(self): s = Sequence("12345678") for c in list, tuple, np.array, pd.Series: with self.assertRaises(ValueError): s._munge_to_index_array(c([3, 2, 1])) with self.assertRaises(ValueError): s._munge_to_index_array(c([5, 6, 7, 2])) with self.assertRaises(ValueError): s._munge_to_index_array(c([0, 1, 2, 1])) def test_munge_to_index_array_valid_bool_array(self): s = Sequence('123456') for c in list, tuple, np.array, pd.Series: exp = np.array([2, 3, 5], dtype=int) obs = s._munge_to_index_array( c([False, False, True, True, False, True])) npt.assert_equal(obs, exp) exp = np.array([], dtype=int) obs = s._munge_to_index_array( c([False] * 6)) npt.assert_equal(obs, exp) exp = np.arange(6) obs = s._munge_to_index_array( c([True] * 6)) npt.assert_equal(obs, exp) def test_munge_to_index_array_invalid_bool_array(self): s = Sequence('123456') for c in (list, tuple, lambda x: np.array(x, dtype=bool), lambda x: pd.Series(x, dtype=bool)): with self.assertRaises(ValueError): s._munge_to_index_array(c([])) with self.assertRaises(ValueError): s._munge_to_index_array(c([True])) with self.assertRaises(ValueError): s._munge_to_index_array(c([True] * 10)) def test_munge_to_index_array_valid_iterable(self): s = Sequence('') def slices_only(): return (slice(i, i+1) for i in range(0, 10, 2)) def mixed(): return (slice(i, i+1) if i % 2 == 0 else i for i in range(10)) def unthinkable(): for i in range(10): if i % 3 == 0: yield slice(i, i+1) elif i % 3 == 1: yield i else: yield np.array([i], dtype=int) for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): exp = np.arange(10, dtype=int) obs = s._munge_to_index_array(c(mixed())) npt.assert_equal(obs, exp) exp = np.arange(10, dtype=int) obs = s._munge_to_index_array(c(unthinkable())) npt.assert_equal(obs, exp) exp = np.arange(10, step=2, dtype=int) obs = s._munge_to_index_array(c(slices_only())) npt.assert_equal(obs, exp) def test_munge_to_index_array_invalid_iterable(self): s = Sequence('') def bad1(): yield "r" yield [1, 2, 3] def bad2(): yield 1 yield 'str' def bad3(): yield False yield True yield 2 def bad4(): yield np.array([False, True]) yield slice(2, 5) for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): with self.assertRaises(TypeError): s._munge_to_index_array(bad1()) with self.assertRaises(TypeError): s._munge_to_index_array(bad2()) with self.assertRaises(TypeError): s._munge_to_index_array(bad3()) with self.assertRaises(TypeError): s._munge_to_index_array(bad4()) def test_munge_to_index_array_valid_string(self): seq = Sequence('ACGTACGT', positional_metadata={'introns': [False, True, True, False, False, True, False, False]}) npt.assert_equal(np.array([1, 2, 5]), seq._munge_to_index_array('introns')) seq.positional_metadata['exons'] = ~seq.positional_metadata['introns'] npt.assert_equal(np.array([0, 3, 4, 6, 7]), seq._munge_to_index_array('exons')) def test_munge_to_index_array_invalid_string(self): seq_str = 'ACGT' seq = Sequence(seq_str, positional_metadata={'quality': range(len(seq_str))}) with self.assertRaisesRegexp(ValueError, "No positional metadata associated with " "key 'introns'"): seq._munge_to_index_array('introns') with self.assertRaisesRegexp(TypeError, "Column 'quality' in positional metadata " "does not correspond to a boolean " "vector"): seq._munge_to_index_array('quality') def test_munge_to_bytestring_return_bytes(self): seq = Sequence('') m = 'dummy_method' str_inputs = ('', 'a', 'acgt') unicode_inputs = (u'', u'a', u'acgt') byte_inputs = (b'', b'a', b'acgt') seq_inputs = (Sequence(''), Sequence('a'), Sequence('acgt')) all_inputs = str_inputs + unicode_inputs + byte_inputs + seq_inputs all_expected = [b'', b'a', b'acgt'] * 4 for input_, expected in zip(all_inputs, all_expected): observed = seq._munge_to_bytestring(input_, m) self.assertEqual(observed, expected) self.assertIs(type(observed), bytes) def test_munge_to_bytestring_unicode_out_of_ascii_range(self): seq = Sequence('') all_inputs = (u'\x80', u'abc\x80', u'\x80abc') for input_ in all_inputs: with self.assertRaisesRegexp(UnicodeEncodeError, "'ascii' codec can't encode character" ".*in position.*: ordinal not in" " range\(128\)"): seq._munge_to_bytestring(input_, 'dummy_method') # NOTE: this must be a *separate* class for doctests only (no unit tests). nose # will not run the unit tests otherwise # # these doctests exercise the correct formatting of Sequence's repr in a # variety of situations. they are more extensive than the unit tests above # (TestSequence.test_repr) but are only currently run in py2. thus, they cannot # be relied upon for coverage (the unit tests take care of this) class SequenceReprDoctests(object): r""" >>> from skbio import Sequence Empty (minimal) sequence: >>> Sequence('') Sequence ------------- Stats: length: 0 ------------- Single character sequence: >>> Sequence('G') Sequence ------------- Stats: length: 1 ------------- 0 G Multicharacter sequence: >>> Sequence('ACGT') Sequence ------------- Stats: length: 4 ------------- 0 ACGT Full single line: >>> Sequence('A' * 60) Sequence ------------------------------------------------------------------- Stats: length: 60 ------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA Full single line with 1 character overflow: >>> Sequence('A' * 61) Sequence -------------------------------------------------------------------- Stats: length: 61 -------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 A Two full lines: >>> Sequence('T' * 120) Sequence -------------------------------------------------------------------- Stats: length: 120 -------------------------------------------------------------------- 0 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT 60 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT Two full lines with 1 character overflow: >>> Sequence('T' * 121) Sequence --------------------------------------------------------------------- Stats: length: 121 --------------------------------------------------------------------- 0 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT 60 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT 120 T Five full lines (maximum amount of information): >>> Sequence('A' * 300) Sequence --------------------------------------------------------------------- Stats: length: 300 --------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 120 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 180 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 240 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA Six lines starts "summarized" output: >>> Sequence('A' * 301) Sequence --------------------------------------------------------------------- Stats: length: 301 --------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 240 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 300 A A naive algorithm would assume the width of the first column (noting position) based on the sequence's length alone. This can be off by one if the last position (in the last line) has a shorter width than the width calculated from the sequence's length. This test case ensures that only a single space is inserted between position 99960 and the first sequence chunk: >>> Sequence('A' * 100000) Sequence ----------------------------------------------------------------------- Stats: length: 100000 ----------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 99900 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 99960 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA The largest sequence that can be displayed using six chunks per line: >>> Sequence('A' * 100020) Sequence ----------------------------------------------------------------------- Stats: length: 100020 ----------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 99900 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 99960 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA A single character longer than the previous sequence causes the optimal number of chunks per line to be 5: >>> Sequence('A' * 100021) Sequence ------------------------------------------------------------- Stats: length: 100021 ------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 50 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 99950 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 100000 AAAAAAAAAA AAAAAAAAAA A Wide range of characters (locale-independent): >>> import string >>> Sequence((string.ascii_letters + string.punctuation + string.digits + ... 'a space') * 567) Sequence ----------------------------------------------------------------------- Stats: length: 57267 ----------------------------------------------------------------------- 0 abcdefghij klmnopqrst uvwxyzABCD EFGHIJKLMN OPQRSTUVWX YZ!"#$%&'( 60 )*+,-./:;< =>?@[\]^_` {|}~012345 6789a spac eabcdefghi jklmnopqrs ... 57180 opqrstuvwx yzABCDEFGH IJKLMNOPQR STUVWXYZ!" #$%&'()*+, -./:;<=>?@ 57240 [\]^_`{|}~ 0123456789 a space Supply horrendous metadata and positional metadata to exercise a variety of metadata formatting cases and rules. Sorting should be by type, then by value within each type (Python 3 doesn't allow sorting of mixed types): >>> metadata = { ... # str key, str value ... 'abc': 'some description', ... # int value ... 'foo': 42, ... # unsupported type (dict) value ... 'bar': {}, ... # int key, wrapped str (single line) ... 42: 'some words to test text wrapping and such... yada yada yada ' ... 'yada yada yada yada yada.', ... # bool key, wrapped str (multi-line) ... True: 'abc ' * 34, ... # float key, truncated str (too long) ... 42.5: 'abc ' * 200, ... # unsupported type (tuple) key, unsupported type (list) value ... ('foo', 'bar'): [1, 2, 3], ... # unicode key, single long word that wraps ... u'long word': 'abc' * 30, ... # truncated key (too long), None value ... 'too long of a key name to display in repr': None, ... # wrapped unicode value (has u'' prefix) ... 'unicode wrapped value': u'abcd' * 25, ... # float value ... 0.1: 99.9999, ... # bool value ... 43: False, ... # None key, complex value ... None: complex(-1.0, 0.0), ... # nested quotes ... 10: '"\''} ... } >>> positional_metadata = { ... # str key, int list value ... 'foo': [1, 2, 3, 4], ... # float key, float list value ... 42.5: [2.5, 3.0, 4.2, -0.00001], ... # int key, object list value ... 42: [[], 4, 5, {}], ... # truncated key (too long), bool list value ... 'abc' * 90: [True, False, False, True], ... # None key ... None: range(4)} >>> Sequence('ACGT', metadata=metadata, ... positional_metadata=positional_metadata) Sequence ----------------------------------------------------------------------- Metadata: None: (-1+0j) True: 'abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc ' 0.1: 99.9999 42.5: <type 'str'> 10: '"\'' 42: 'some words to test text wrapping and such... yada yada yada yada yada yada yada yada.' 43: False 'abc': 'some description' 'bar': <type 'dict'> 'foo': 42 <type 'str'>: None 'unicode wrapped value': u'abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd abcdabcdabcdabcdabcd' <type 'tuple'>: <type 'list'> u'long word': 'abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca bcabcabcabcabcabcabcabcabcabcabcabcabc' Positional metadata: None: <dtype: int64> 42: <dtype: object> 42.5: <dtype: float64> <type 'str'>: <dtype: bool> 'foo': <dtype: int64> Stats: length: 4 ----------------------------------------------------------------------- 0 ACGT """ pass if __name__ == "__main__": main()
bsd-3-clause
jolicloud/exponent
android/app/src/main/java/abi11_0_0/host/exp/exponent/modules/api/components/maps/AirMapManager.java
11485
package abi11_0_0.host.exp.exponent.modules.api.components.maps; import android.view.View; import abi11_0_0.com.facebook.react.bridge.Arguments; import abi11_0_0.com.facebook.react.bridge.ReactApplicationContext; import abi11_0_0.com.facebook.react.bridge.ReactContext; import abi11_0_0.com.facebook.react.bridge.ReadableArray; import abi11_0_0.com.facebook.react.bridge.ReadableMap; import abi11_0_0.com.facebook.react.bridge.WritableMap; import abi11_0_0.com.facebook.react.common.MapBuilder; import abi11_0_0.com.facebook.react.modules.core.DeviceEventManagerModule; import abi11_0_0.com.facebook.react.uimanager.LayoutShadowNode; import abi11_0_0.com.facebook.react.uimanager.ThemedReactContext; import abi11_0_0.com.facebook.react.uimanager.ViewGroupManager; import abi11_0_0.com.facebook.react.uimanager.annotations.ReactProp; import abi11_0_0.com.facebook.react.uimanager.events.RCTEventEmitter; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import java.util.Map; import javax.annotation.Nullable; public class AirMapManager extends ViewGroupManager<AirMapView> { private static final String REACT_CLASS = "AIRMap"; private static final int ANIMATE_TO_REGION = 1; private static final int ANIMATE_TO_COORDINATE = 2; private static final int FIT_TO_ELEMENTS = 3; private static final int FIT_TO_SUPPLIED_MARKERS = 4; private static final int FIT_TO_COORDINATES = 5; private final Map<String, Integer> MAP_TYPES = MapBuilder.of( "standard", GoogleMap.MAP_TYPE_NORMAL, "satellite", GoogleMap.MAP_TYPE_SATELLITE, "hybrid", GoogleMap.MAP_TYPE_HYBRID, "terrain", GoogleMap.MAP_TYPE_TERRAIN, "none", GoogleMap.MAP_TYPE_NONE ); private ReactContext reactContext; private final ReactApplicationContext appContext; protected GoogleMapOptions googleMapOptions; public AirMapManager(ReactApplicationContext context) { this.appContext = context; this.googleMapOptions = new GoogleMapOptions(); } @Override public String getName() { return REACT_CLASS; } @Override protected AirMapView createViewInstance(ThemedReactContext context) { reactContext = context; try { MapsInitializer.initialize(this.appContext); } catch (RuntimeException e) { e.printStackTrace(); emitMapError("Map initialize error", "map_init_error"); } return new AirMapView(context, this.appContext.getCurrentActivity(), this, this.googleMapOptions); } private void emitMapError(String message, String type) { WritableMap error = Arguments.createMap(); error.putString("message", message); error.putString("type", type); reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onError", error); } @ReactProp(name = "region") public void setRegion(AirMapView view, ReadableMap region) { view.setRegion(region); } @ReactProp(name = "mapType") public void setMapType(AirMapView view, @Nullable String mapType) { int typeId = MAP_TYPES.get(mapType); view.map.setMapType(typeId); } @ReactProp(name = "showsUserLocation", defaultBoolean = false) public void setShowsUserLocation(AirMapView view, boolean showUserLocation) { view.setShowsUserLocation(showUserLocation); } @ReactProp(name = "showsMyLocationButton", defaultBoolean = true) public void setShowsMyLocationButton(AirMapView view, boolean showMyLocationButton) { view.setShowsMyLocationButton(showMyLocationButton); } @ReactProp(name = "toolbarEnabled", defaultBoolean = true) public void setToolbarEnabled(AirMapView view, boolean toolbarEnabled) { view.setToolbarEnabled(toolbarEnabled); } // This is a private prop to improve performance of panDrag by disabling it when the callback is not set @ReactProp(name = "handlePanDrag", defaultBoolean = false) public void setHandlePanDrag(AirMapView view, boolean handlePanDrag) { view.setHandlePanDrag(handlePanDrag); } @ReactProp(name = "showsTraffic", defaultBoolean = false) public void setShowTraffic(AirMapView view, boolean showTraffic) { view.map.setTrafficEnabled(showTraffic); } @ReactProp(name = "showsBuildings", defaultBoolean = false) public void setShowBuildings(AirMapView view, boolean showBuildings) { view.map.setBuildingsEnabled(showBuildings); } @ReactProp(name = "showsIndoors", defaultBoolean = false) public void setShowIndoors(AirMapView view, boolean showIndoors) { view.map.setIndoorEnabled(showIndoors); } @ReactProp(name = "showsCompass", defaultBoolean = false) public void setShowsCompass(AirMapView view, boolean showsCompass) { view.map.getUiSettings().setCompassEnabled(showsCompass); } @ReactProp(name = "scrollEnabled", defaultBoolean = false) public void setScrollEnabled(AirMapView view, boolean scrollEnabled) { view.map.getUiSettings().setScrollGesturesEnabled(scrollEnabled); } @ReactProp(name = "zoomEnabled", defaultBoolean = false) public void setZoomEnabled(AirMapView view, boolean zoomEnabled) { view.map.getUiSettings().setZoomGesturesEnabled(zoomEnabled); } @ReactProp(name = "rotateEnabled", defaultBoolean = false) public void setRotateEnabled(AirMapView view, boolean rotateEnabled) { view.map.getUiSettings().setRotateGesturesEnabled(rotateEnabled); } @ReactProp(name = "cacheEnabled", defaultBoolean = false) public void setCacheEnabled(AirMapView view, boolean cacheEnabled) { view.setCacheEnabled(cacheEnabled); } @ReactProp(name = "loadingEnabled", defaultBoolean = false) public void setLoadingEnabled(AirMapView view, boolean loadingEnabled) { view.enableMapLoading(loadingEnabled); } @ReactProp(name = "moveOnMarkerPress", defaultBoolean = true) public void setMoveOnMarkerPress(AirMapView view, boolean moveOnPress) { view.setMoveOnMarkerPress(moveOnPress); } @ReactProp(name = "loadingBackgroundColor", customType = "Color") public void setLoadingBackgroundColor(AirMapView view, @Nullable Integer loadingBackgroundColor) { view.setLoadingBackgroundColor(loadingBackgroundColor); } @ReactProp(name = "loadingIndicatorColor", customType = "Color") public void setLoadingIndicatorColor(AirMapView view, @Nullable Integer loadingIndicatorColor) { view.setLoadingIndicatorColor(loadingIndicatorColor); } @ReactProp(name = "pitchEnabled", defaultBoolean = false) public void setPitchEnabled(AirMapView view, boolean pitchEnabled) { view.map.getUiSettings().setTiltGesturesEnabled(pitchEnabled); } @Override public void receiveCommand(AirMapView view, int commandId, @Nullable ReadableArray args) { Integer duration; Double lat; Double lng; Double lngDelta; Double latDelta; ReadableMap region; switch (commandId) { case ANIMATE_TO_REGION: region = args.getMap(0); duration = args.getInt(1); lng = region.getDouble("longitude"); lat = region.getDouble("latitude"); lngDelta = region.getDouble("longitudeDelta"); latDelta = region.getDouble("latitudeDelta"); LatLngBounds bounds = new LatLngBounds( new LatLng(lat - latDelta / 2, lng - lngDelta / 2), // southwest new LatLng(lat + latDelta / 2, lng + lngDelta / 2) // northeast ); view.animateToRegion(bounds, duration); break; case ANIMATE_TO_COORDINATE: region = args.getMap(0); duration = args.getInt(1); lng = region.getDouble("longitude"); lat = region.getDouble("latitude"); view.animateToCoordinate(new LatLng(lat, lng), duration); break; case FIT_TO_ELEMENTS: view.fitToElements(args.getBoolean(0)); break; case FIT_TO_SUPPLIED_MARKERS: view.fitToSuppliedMarkers(args.getArray(0), args.getBoolean(1)); break; case FIT_TO_COORDINATES: view.fitToCoordinates(args.getArray(0), args.getMap(1), args.getBoolean(2)); break; } } @Override @Nullable public Map getExportedCustomDirectEventTypeConstants() { Map<String, Map<String, String>> map = MapBuilder.of( "onMapReady", MapBuilder.of("registrationName", "onMapReady"), "onPress", MapBuilder.of("registrationName", "onPress"), "onLongPress", MapBuilder.of("registrationName", "onLongPress"), "onMarkerPress", MapBuilder.of("registrationName", "onMarkerPress"), "onMarkerSelect", MapBuilder.of("registrationName", "onMarkerSelect"), "onMarkerDeselect", MapBuilder.of("registrationName", "onMarkerDeselect"), "onCalloutPress", MapBuilder.of("registrationName", "onCalloutPress") ); map.putAll(MapBuilder.of( "onMarkerDragStart", MapBuilder.of("registrationName", "onMarkerDragStart"), "onMarkerDrag", MapBuilder.of("registrationName", "onMarkerDrag"), "onMarkerDragEnd", MapBuilder.of("registrationName", "onMarkerDragEnd"), "onPanDrag", MapBuilder.of("registrationName", "onPanDrag") )); return map; } @Override @Nullable public Map<String, Integer> getCommandsMap() { return MapBuilder.of( "animateToRegion", ANIMATE_TO_REGION, "animateToCoordinate", ANIMATE_TO_COORDINATE, "fitToElements", FIT_TO_ELEMENTS, "fitToSuppliedMarkers", FIT_TO_SUPPLIED_MARKERS, "fitToCoordinates", FIT_TO_COORDINATES ); } @Override public LayoutShadowNode createShadowNodeInstance() { // A custom shadow node is needed in order to pass back the width/height of the map to the // view manager so that it can start applying camera moves with bounds. return new SizeReportingShadowNode(); } @Override public void addView(AirMapView parent, View child, int index) { parent.addFeature(child, index); } @Override public int getChildCount(AirMapView view) { return view.getFeatureCount(); } @Override public View getChildAt(AirMapView view, int index) { return view.getFeatureAt(index); } @Override public void removeViewAt(AirMapView parent, int index) { parent.removeFeatureAt(index); } @Override public void updateExtraData(AirMapView view, Object extraData) { view.updateExtraData(extraData); } void pushEvent(View view, String name, WritableMap data) { reactContext.getJSModule(RCTEventEmitter.class) .receiveEvent(view.getId(), name, data); } }
bsd-3-clause
xklake/taotao
frontend/controllers/EmployeeCRUDController.php
3112
<?php namespace frontend\controllers; use Yii; use app\models\Employee; use frontend\controller; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * EmployeeCRUDController implements the CRUD actions for Employee model. */ class EmployeeCRUDController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all Employee models. * @return mixed */ public function actionIndex() { $searchModel = new controller(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Employee model. * @param string $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Employee model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Employee(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->Name]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Employee model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->Name]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Employee model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param string $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Employee model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return Employee the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Employee::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
bsd-3-clause
chrisblackni/onxshop
lib/onxshop.db.php
17593
<?php /** * Onxshop_Db class definition * * custom Active Record Database Pattern and simple validation * * Copyright (c) 2005-2015 Onxshop Ltd (https://onxshop.com) * Licensed under the New BSD License. See the file LICENSE.txt for details. * */ class Onxshop_Db { var $conf = array(); var $_cacheable = ONXSHOP_DB_QUERY_CACHE; var $_valid = array(); var $_class_name = ''; var $_public_attributes = array(); var $_metaData; var $db; /** * Constructor * */ function __construct() { $this->_class_name = get_class($this); $this->generic(); } /** * create table SQL */ private function createTableSql() { $sql = ""; return $sql; } /** * default method called from constructor * */ public function generic() { msg("{$this->_class_name}: Calling generic()", 'ok', 3); if (Zend_Registry::isRegistered('onxshop_db')) $this->db = Zend_Registry::get('onxshop_db'); if (Zend_Registry::isRegistered('onxshop_db_cache')) $this->cache = Zend_Registry::get('onxshop_db_cache'); $vars = get_object_vars($this); //init configuration for current model $this->conf = $this->initConfiguration(); foreach ($vars as $key => $val) { if (!preg_match('/^_/', $key) && $key != 'db' && $key != 'id' && $key != 'conf') { $this->_public_attributes[$key] = $val; } } } /** * to be implemented in all models */ static function initConfiguration() { $conf = array(); return $conf; } /** * getter * * @param string $attribute * @return string */ public function get($attribute) { msg("{$this->_class_name}: Calling get($attribute)", 'ok', 4); $value = $this->$attribute; return $value; } /** * setter * * @param string $attribute * @param string $value */ public function set($attribute, $value) { msg("{$this->_class_name}: Calling set($attribute, $value)", 'ok', 4); $validation_type = $this->_metaData[$attribute]['validation']; if ($this->_metaData[$attribute]['required'] == true || $value != '') { if ($this->validation($validation_type, $attribute, $value)) { $this->$attribute = $value; return true; } else { return false; } } else { $this->$attribute = $value; return true; } } /** * populate all fields * * @param array $data * @return boolean */ public function setAll($data) { msg("{$this->_class_name} Calling setAll(): " . print_r($data, true), 'ok', 3); $this->_valid = array();// reset previous validation if (is_array($data) && count($data) > 0) { foreach ($this->_public_attributes as $key=>$value) { if (key_exists($key, $data)) { $this->set($key, $data[$key]); } else if ($this->_metaData[$key]['required'] == true) { msg("{$this->_class_name} key $key is required, but not set", 'error', ONXSHOP_MODEL_STRICT_VALIDATION ? 1 : 2); if (ONXSHOP_MODEL_STRICT_VALIDATION) $this->setValid($key, false); } } return true; } else { $this->setValid('All attributes.', false); return false; } } /** * validation of attributes value * * @param string $validation_type * @param string $attribute * @param string $value * @return boolean */ public function validation($validation_type, $attribute, $value) { switch ($validation_type) { /* please dont' use boolean, it's not a good idea in PHP :) */ case 'boolean': if (is_bool($value)) { $this->setValid($attribute, true); return true; } else { $this->setValid($attribute, false); return false; } break; case 'int': case 'decimal': case 'numeric': if (is_numeric($value)) { $this->setValid($attribute, true); return true; } else { $this->setValid($attribute, false); return false; } break; case 'string': case 'text': case 'serialized': case 'xml': $value = trim($value); if ($value != '') { $this->setValid($attribute, true); return true; } else { if ($this->_metaData[$attribute]['required'] == true) { $this->setValid($attribute, false); /* ($this->_metaData[$attribute]['label'] == '') ? $label = $attribute: $label = $this->_metaData[$attribute]['label']; msg("$label is required","error", 0); */ return false; } } case 'xhtml': //don't do any validation if Tidy is not installed if (!function_exists('tidy_get_status')) return true; //msg($_GET['request']); //msg($value); $tidy_content = ' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>test</title></head><body>' . $value . '</body></html>'; // Specify configuration $config = array( 'show-warnings' => true, 'doctype' => 'transitional', 'indent' => true, 'output-xhtml' => true, 'wrap' => 200); // Tidy $tidy = new tidy; $tidy->parseString($tidy_content, $config, 'utf8'); //$tidy->cleanRepair(); //$tidy->diagnose(); // get result $result_status = tidy_get_status($tidy); $result_message = tidy_get_error_buffer($tidy); if ($result_status > 1) { $error = $result_message; } else if ($result_status > 0) { msg("Tidy warning: $result_message", "error", 2); } if ($error != '') { msg($error, 'error'); $this->setValid($attribute, false); return false; } else { $this->setValid($attribute, true); return true; } break; case 'datetime': //$this->setValid($attribute, true); return true; break; case 'date': // ISO date $regex = "/^\d{4}-\d{1,2}-\d{1,2}$/"; if (preg_match($regex, $value, $matches)) { $this->setValid($attribute, true); return true; } else { $this->setValid($attribute, false); return false; } break; case 'email': $regex = '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,32})$/i'; if (preg_match($regex, $value, $matches)) { $this->setValid($attribute, true); return true; } else { msg(I18N_ERROR_ENTER_VALID_EMAIL, 'error'); $this->setValid($attribute, false); return false; } break; case 'url': $regex = '/^(http:\/\/|ftp:\/\/)/i'; if (preg_match($regex, $value, $matches)) { $this->setValid($attribute, true); return true; } else { msg(I18N_ERROR_WRONG_URL, "error", 2); $this->setValid($attribute, false); return false; } break; case 'decimal': $this->setValid($attribute, true); return true; break; case 'product_code': /* * be aware of "_", in SQL LIKE (escape it, or don't use it) */ if (preg_match('/^[0-9a-zA-Z-]*$/', $pc)) { $this->setValid($attribute, true); return true; } else { msg(I18N_ERROR_INVALID_PRODUCT_CODE, 'error', 2); $this->setValid($attribute, false); return false; } break; default: $this->setValid($attribute, true); return true; break; } } /** * check if all attributes have valid values * * @return boolean */ public function getValid() { msg('Onxshop_Model.getValid', 'ok', 2); //todo: add checking if are required fields filled in $notvalid = 0; foreach ($this->_valid as $rec) { if ($rec[1] == false) { ($this->_metaData[$rec[0]]['label'] == '') ? $label = $rec[0]: $label = $this->_metaData[$rec[0]]['label']; msg(I18N_ERROR_INVALID_VALUE_FOR . $label, 'error', 1); $notvalid = 1; } } if ($notvalid == 0) { return true; } else { return false; } } /** * mark attribute validation status * * @param string $attribute * @param boolean $bool */ public function setValid($attribute, $bool) { $this->_valid[] = array($attribute, $bool); } /** * listing records * * @param string $where * @param string $order * @param string $limit * @return array */ public function listing($where = '', $order = 'id ASC', $limit = '') { msg("{$this->_class_name}: Calling listing($where, $order, $limit)", 'ok', 3); if ($where != '') $where = " WHERE $where"; if ($order != '') $order = " ORDER BY $order"; /** * prepare limit query */ if (preg_match('/[0-9]*,[0-9]*/', $limit)) { $limit = explode(',', $limit); $limit = " LIMIT {$limit[1]} OFFSET {$limit[0]}"; } else { $limit = ''; } /** * execute query */ $sql = "SELECT * FROM {$this->_class_name} $where $order $limit"; if ($this->isCacheable()) $records = $this->executeSqlCached($sql); else $records = $this->executeSql($sql); if (is_array($records)) { return $records; } else { return false; } } /** * detail of a record * * @param int $id * @return array */ public function detail($id) { msg("{$this->_class_name}: Calling detail($id)", 'ok', 3); if (!is_numeric($id)) { msg("Onxshop_Model.detail(): id of {$this->_class_name} is not numeric", 'error', 1); return false; } /** * prepare query */ $sql = "SELECT * FROM {$this->_class_name} WHERE id={$id}"; /** * execute */ if ($this->isCacheable()) $records = $this->executeSqlCached($sql); else $records = $this->executeSql($sql); $records = $records[0]; if (is_array($records)) { $this->setAll($records); return $records; } else { msg("Onxshop_Model.detail(): record id=$id does not exists in {$this->_class_name}", 'error', 1); return false; } } /** * count records * * @param string $where * @return array */ public function count($where = '') { msg("{$this->_class_name}: Calling count($where)", 'ok', 3); if ($where != '') $where = " WHERE $where"; $sql = "SELECT count(*) AS count FROM {$this->_class_name} $where"; if ($this->isCacheable()) $records = $this->executeSqlCached($sql); else $records = $this->executeSql($sql); if (is_array($records)) { return $records[0]['count']; } else { return false; } } /** * insert a record * * @param array $data * @return integer */ public function insert($data) { msg("{$this->_class_name}: Calling insert() " . print_r($data, true), 'ok', 3); if (is_array($data)) $this->setAll($data); if ($this->getValid()) { /** * try to insert */ try { $this->db->insert($this->_class_name, $data); if (is_numeric($data['id'])) { $id = $data['id']; } else { /** * PostgreSQL returns the OID from lastInsertId */ if (ONXSHOP_DB_TYPE == 'pgsql') { $id = $this->db->lastInsertId($this->_class_name, "id"); } else { $id = $this->db->lastInsertId(); } } msg("Inserting of record id:{$id} into {$this->_class_name} has been successful.", 'ok', 2); return $id; } catch (Exception $e) { msg($e->getMessage(), 'error', 1); msg("Insert(". print_r($data, true) .") to {$this->_class_name} failed: " . print_r($this->db->getConnection()->errorInfo(), true), 'error', 1); return false; } } else { return false; } } /** * update a record * * @param array $data * @return integer */ public function update($data = array()) { msg("{$this->_class_name}: Calling update() " . print_r($data, true), 'ok', 3); if (!is_numeric($data['id'])) { msg("Onxshop_Model.update: {$this->_class_name} id is not numeric", 'error'); return false; } if (is_array($data)) $this->setAll($data); if ($this->getValid()) { try { $ok = $this->db->update($this->_class_name, $data, "id = {$data['id']}"); msg("Record id:{$this->id} in {$this->_class_name} has been successfully updated.", 'ok', 2); return $data['id']; } catch (Exception $e) { msg($e->getMessage(), 'error', 1); msg("Failed to update {$this->_class_name}: " . print_r($this->db->getConnection()->errorInfo(), true), 'error', 1); return false; } } else { msg("Onxshop_Model.update: {$this->_class_name} data are not valid", 'error'); return false; } } /** * Save a record * update or insert * * @return integer */ public function save($data) { if (is_numeric($data['id'])) { return $this->update($data); } else { $id = $this->insert($data); return $id; } } /** * Delete a record * * @param int $id * @return boolean */ public function delete($id) { msg(get_class($this) . ": Calling delete($id)", 'ok', 3); if (is_numeric($id)) { try { $this->db->exec("DELETE FROM {$this->_class_name} WHERE id = {$id}"); msg("Record id:{$id} in {$this->_class_name} has been successfully deleted.", 'ok', 2); return true; } catch (Exception $e) { msg($e->getMessage(), 'error', 1); msg("Failed to delete {$this->_class_name}: " . print_r($this->db->getConnection()->errorInfo(), true), 'error', 1); return false; } } else { msg("Missing ID", 'error'); return false; } } /** * delete all records * * @return boolean */ public function deleteAll($where = '') { msg(get_class($this) . ": Calling deleteAll($where)", 'ok', 3); if ($where != '') $where_statement = "WHERE $where"; try { $this->db->exec("DELETE FROM {$this->_class_name} $where_statement"); msg("Everything from {$this->_class_name} has been successfully deleted.", 'ok', 2); return true; } catch (Exception $e) { msg($e->getMessage(), 'error', 1); msg("Failed to deleteAll {$this->_class_name}: " . print_r($this->db->getConnection()->errorInfo(), true), 'error', 1); return false; } } /** * set cacheable SQL * * @param boolean $bool */ public function setCacheable($bool = true) { $this->_cacheable = $bool; } /** * get status of cache option * * @return boolean */ function isCacheable() { return $this->_cacheable; } /** * execute sql */ public function executeSql($sql) { if ($this->isCacheable() && preg_match("/^SELECT/i", trim($sql))) return $this->executeSqlCached($sql); else return $this->executeSqlOnDatabase($sql); } /** * execute sql on database */ public function executeSqlOnDatabase($sql) { if (!$this->validateSqlQuery($sql)) return false; try { $records = $this->db->fetchAll($sql); if (is_array($records)) return $records; else return false; } catch (Exception $e) { msg($e->getMessage(), 'error', 1); msg("Failed to executeSql {$this->_class_name}: " . print_r($this->db->getConnection()->errorInfo(), true), 'error', 1); return false; } } /** * query cache */ public function executeSqlCached($sql) { // create cache key $cache_id = preg_replace('/\W/', '', $_SERVER['HTTP_HOST']) . "_SQL_{$this->_class_name}_" . md5(ONXSHOP_DB_HOST . ONXSHOP_DB_PORT . ONXSHOP_DB_NAME . $sql); // include hostname and database connection details to prevent conflict in shared cache engine environment if ($records = $this->cache->load($cache_id)) { $records = unserialize($records); } else { $records = $this->executeSqlOnDatabase($sql); $this->cache->save(serialize($records), $cache_id); } return $records; } /** * flush cache (for this object) * TODO: this should be using $this->cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('tagA', 'tagC')); * or $cache->remove('idToRemove'); * * currently only File backend deletes files related to this object and Apc and Libmemcached will flush complete DB cache */ public function flushCache() { switch (ONXSHOP_DB_QUERY_CACHE_BACKEND) { case 'Apc': case 'Libmemcached': $this->cache->clean(Zend_Cache::CLEANING_MODE_ALL); break; case 'File': default: $mask = ONXSHOP_DB_QUERY_CACHE_DIRECTORY . "zend_cache---*_SQL_{$this->_class_name}_*"; array_map("unlink", glob( $mask )); $mask = ONXSHOP_DB_QUERY_CACHE_DIRECTORY . "zend_cache---internal-metadatas---*_SQL_{$this->_class_name}_*"; array_map("unlink", glob( $mask )); break; } return true; } /** * validate SQL query */ public function validateSqlQuery($sql) { if (trim($sql) == '' || !is_string($sql)) return false; else return true; } /** * get table size */ public function getTableSize() { $sql = "SELECT pg_size_pretty(pg_total_relation_size('{$this->_class_name}')) AS total_size;"; if ($result = $this->executeSql($sql)) { return $result[0]['total_size']; } else { return false; } } /** * get table information */ public function getTableInformation($table_name) { return $this->db->describeTable($table_name); } }
bsd-3-clause
krytarowski/lumina
src-qt5/desktop-utils/lumina-terminal/i18n/lumina-terminal_bs.ts
1045
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="bs_BA"> <context> <name>TrayIcon</name> <message> <location filename="../TrayIcon.cpp" line="123"/> <source>Trigger Terminal</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TrayIcon.cpp" line="125"/> <source>Top of Screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TrayIcon.cpp" line="130"/> <source>Close Terminal</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TrayIcon.cpp" line="139"/> <source>Move To Monitor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TrayIcon.cpp" line="142"/> <source>Monitor %1</source> <translation type="unfinished"></translation> </message> </context> </TS>
bsd-3-clause
Treeway/sandbox
frontend/modules/panel/views/item/detail.php
1759
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; ?> <h1>商品详情</h1> <div> <div class="col-lg-5" style="width: 200px;"> <?php $form = ActiveForm::begin(['id' => 'form-signup']); ?> <?= $form->field($model, 'acc_id')->dropDownList($data)->label('账号名') ?> <div class="form-group"> <?= Html::submitButton('提交', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?> </div> <?php ActiveForm::end(); ?> </div> <h3><?php isset($user)?printf($user):null ?></h3> </div> <?php if(isset($req)) {?> <table class="table table-hover table-striped" style="width: 800px;"> <tbody> <tr> <th>商品标题</th> <th>商品ID</th> <th>商品外部ID</th> <th>价格</th> <th>库存数量</th> </tr> <?php foreach ($req->items->item as $item) { ?> <tr> <td> <a href="../item/modify?id=<?php echo $item->num_iid ?>&outid=<?= $outid = isset($item->outer_id)? $item->outer_id : 0; ?>&uid=<?php echo $uid ?>"> <?php echo $item->title; ?><a> </td> <td><?php echo $item->num_iid; ?></td> <td> <?php if(isset($item->outer_id)){ echo $item->outer_id; } else { echo "0"; } ?> </td> <td><?php echo $item->price; ?></td> <td><?php echo $item->num; ?></td> </tr> <?php } ?> </tbody> </table> <?php } ?>
bsd-3-clause
flip111/portia
slyd/media/js/api.js
15981
/** A Proxy to the slyd backend API. */ ASTool.SlydApi = Em.Object.extend({ /** @public The name of the current project. */ project: null, projectSpecUrl: function() { return ASTool.SlydApi.getApiUrl() + '/' + this.project + '/spec/'; }.property('project'), botUrl: function() { return ASTool.SlydApi.getApiUrl() + '/' + this.project + '/bot/'; }.property('project'), /** @public Fetches project names. @method getProjectNames @for ASTool.SlydApi @return {Promise} a promise that fulfills with an {Array} of project names. */ getProjectNames: function() { var hash = {}; hash.type = 'GET'; hash.url = ASTool.SlydApi.getApiUrl(); return this.makeAjaxCall(hash); }, /** @public Creates a new project. A project with the same name must not exist or this operation will fail. Project names must only contain alphanum, '.'s and '_'s. @method createProject @for ASTool.SlydApi @param {String} [projectName] The name of the new project. @return {Promise} a promise that fulfills when the server responds. */ createProject: function(projectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify({ cmd: 'create', args: [projectName] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, /** @public Deletes an existing project. @method deleteProject @for ASTool.SlydApi @param {String} [projectName] The name of the project to delete. @return {Promise} a promise that fulfills when the server responds. */ deleteProject: function(projectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify({ cmd: 'rm', args: [projectName] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, /** @public Renames an existing project. This operation will not overwrite existing projects. Project names must only contain alphanum, '.'s and '_'s. @method renameProject @for ASTool.SlydApi @param {String} [oldProjectName] The name of the project to rename. @param {String} [newProjectName] The new name for the project. @return {Promise} a promise that fulfills when the server responds. */ renameProject: function(oldProjectName, newProjectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify({ cmd: 'mv', args: [oldProjectName, newProjectName] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, /** @public Returns a list with the spider names for the current project. @method getSpiderNames @for ASTool.SlydApi @return {Promise} a promise that fulfills with an {Array} of spider names. */ getSpiderNames: function() { var hash = {}; hash.type = 'GET'; hash.url = this.get('projectSpecUrl') + 'spiders'; return this.makeAjaxCall(hash); }, /** @public Fetches a spider. @method loadSpider @for ASTool.SlydApi @param {String} [spiderName] The name of the spider. @return {Promise} a promise that fulfills with a JSON {Object} containing the spider spec. */ loadSpider: function(spiderName) { var hash = {}; hash.type = 'GET'; hash.url = this.get('projectSpecUrl') + 'spiders/' + spiderName; return this.makeAjaxCall(hash).then(function(spiderData) { spiderData['name'] = spiderName; spiderData['templates'] = spiderData['templates'].map(function(template) { // Assign a name to templates. This is needed as Autoscraping templates // are not named. if (Em.isEmpty(template['name'])) { template['name'] = ASTool.shortGuid(); } return ASTool.Template.create(template); }); return ASTool.Spider.create(spiderData); }); }, /** @public Fetches a template. @method loadTemplate @for ASTool.SlydApi @param {String} [spiderName] The name of the spider. @param {String} [templateName] The name of the template. @return {Promise} a promise that fulfills with a JSON {Object} containing the template spec. */ loadTemplate: function(spiderName, templateName) { var hash = {}; hash.type = 'GET'; hash.url = this.get('projectSpecUrl') + 'spiders/' + spiderName + '/' + templateName; return this.makeAjaxCall(hash).then(function(templateData) { return ASTool.Template.create(templateData); }); }, /** @public Renames an existing spider. This operation will overwrite existing spiders. Spider names must only contain alphanum, '.'s and '_'s. @method renameSpider @for ASTool.SlydApi @param {String} [oldSpiderName] The name of the spider to rename. @param {String} [newSpiderName] The new name for the spider. @return {Promise} a promise that fulfills when the server responds. */ renameSpider: function(oldSpiderName, newSpiderName) { var hash = {}; hash.type = 'POST'; hash.url = this.get('projectSpecUrl') + 'spiders'; hash.data = JSON.stringify({ cmd: 'mv', args: [oldSpiderName, newSpiderName] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, /** @public Renames an existing template. This operation will overwrite existing templates. Template names must only contain alphanum, '.'s and '_'s. @method renameTemplate @for ASTool.SlydApi @param {String} [spiderName] The name of the spider owning the template. @param {String} [oldTemplateName] The name of the template to rename. @param {String} [newTemplateName] The new name for the template. @return {Promise} a promise that fulfills when the server responds. */ renameTemplate: function(spiderName, oldTemplateName, newTemplateName) { var hash = {}; hash.type = 'POST'; hash.url = this.get('projectSpecUrl') + 'spiders'; hash.data = JSON.stringify({ cmd: 'mvt', args: [spiderName, oldTemplateName, newTemplateName] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, /** @public Saves a spider for the current project. @method saveSpider @for ASTool.SlydApi @param {String} [spiderName] the name of the spider. @param {Object} [spiderData] a JSON object containing the spider spec. @param {Bool} [excludeTemplates] if true, don't save spider templates. @return {Promise} promise that fulfills when the server responds. */ saveSpider: function(spider, excludeTemplates) { var hash = {}; hash.type = 'POST'; var spiderName = spider.get('name'); serialized = spider.serialize(); if (excludeTemplates) { delete serialized['templates']; } hash.data = JSON.stringify(serialized); hash.dataType = 'text'; hash.url = this.get('projectSpecUrl') + 'spiders/' + spiderName; return this.makeAjaxCall(hash); }, /** @public Saves a spider template for the current project. @method saveTemplate @for ASTool.SlydApi @param {String} [spiderName] the name of the spider. @param {String} [templateName] the name of the template. @param {Object} [templateData] a JSON object containing the template spec. @return {Promise} promise that fulfills when the server responds. */ saveTemplate: function(spiderName, template) { var hash = {}; hash.type = 'POST'; var templateName = template.get('name'); serialized = template.serialize(); if (template.get('_new')) { serialized['original_body'] = template.get('original_body'); template.set('_new', false); } hash.data = JSON.stringify(serialized); hash.dataType = 'text'; hash.url = this.get('projectSpecUrl') + 'spiders/' + spiderName + '/' + templateName; return this.makeAjaxCall(hash); }, /** @public Deletes an existing spider. @method deleteSpider @for ASTool.SlydApi @param {String} [spiderName] The name of the spider to delete. @return {Promise} a promise that fulfills when the server responds. */ deleteSpider: function(spiderName) { var hash = {}; hash.type = 'POST'; hash.dataType = 'text'; hash.url = this.get('projectSpecUrl') + 'spiders'; hash.data = JSON.stringify({ cmd: 'rm', args: [spiderName] }); return this.makeAjaxCall(hash); }, /** @public Deletes an existing template. @method deleteTemplate @for ASTool.SlydApi @param {String} [spiderName] The name of the spider that owns the template. @param {String} [spiderName] The name of the template to delete. @return {Promise} a promise that fulfills when the server responds. */ deleteTemplate: function(spiderName, templateName) { var hash = {}; hash.type = 'POST'; hash.dataType = 'text'; hash.url = this.get('projectSpecUrl') + 'spiders'; hash.data = JSON.stringify({ cmd: 'rmt', args: [spiderName, templateName] }); return this.makeAjaxCall(hash); }, /** @public Fetches the current project items. @method loadItems @for ASTool.SlydApi @return {Promise} a promise that fulfills with an {Array} of JSON {Object} containing the items spec. } */ loadItems: function() { var hash = {}; hash.type = 'GET'; hash.url = this.get('projectSpecUrl') + 'items'; return this.makeAjaxCall(hash).then(function(items) { items = this.dictToList(items, ASTool.Item); items.forEach(function(item) { if (item.fields) { item.fields = this.dictToList(item.fields, ASTool.ItemField); } }.bind(this)); return items; }.bind(this)); }, /** @public Saves the current project items. @method saveItems @for ASTool.SlydApi @param {Array} [items] an array of JSON {Object} containing the items spec. @return {Promise} a promise that fulfills when the server responds. */ saveItems: function(items) { items = items.map(function(item) { item = item.serialize(); if (item.fields) { item.fields = this.listToDict(item.fields); } return item; }.bind(this)); items = this.listToDict(items); var hash = {}; hash.type = 'POST'; hash.data = JSON.stringify(items); hash.dataType = 'text'; hash.url = this.get('projectSpecUrl') + 'items'; return this.makeAjaxCall(hash); }, /** @public Fetches the current project extractors. @method loadExtractors @for ASTool.SlydApi @return {Promise} a promise that fulfills with an {Array} of JSON {Object} containing the extractors spec. */ loadExtractors: function() { var hash = {}; hash.type = 'GET'; hash.url = this.get('projectSpecUrl') + 'extractors'; return this.makeAjaxCall(hash).then(function(extractors) { return this.dictToList(extractors, ASTool.Extractor); }.bind(this) ); }, /** @public Saves the current project extractors. @method saveExtractors @for ASTool.SlydApi @param {Array} [extractors] an array of JSON {Object} containing the extractors spec. @return {Promise} a promise that fulfills when the server responds. */ saveExtractors: function(extractors) { extractors = extractors.map(function(extractor) { return extractor.serialize(); }); extractors = this.listToDict(extractors); var hash = {}; hash.type = 'POST'; hash.data = JSON.stringify(extractors); hash.dataType = 'text'; hash.url = this.get('projectSpecUrl') + 'extractors'; return this.makeAjaxCall(hash); }, editProject: function(project_name, revision) { if (!ASTool.get('serverCapabilities.version_control')) { // if the server does not support version control, do // nothing. return new Em.RSVP.Promise(function(resolve, reject) { resolve(); }); } else { revision = revision ? revision : 'master'; var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'edit', args: [project_name, revision] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); } }, projectRevisions: function(projectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'revisions', args: [projectName] }); return this.makeAjaxCall(hash); }, conflictedFiles: function(projectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'conflicts', args: [projectName] }); return this.makeAjaxCall(hash); }, changedFiles: function(projectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'changes', args: [projectName] }); return this.makeAjaxCall(hash); }, publishProject: function(projectName, force) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'publish', args: [projectName, !!force] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, deployProject: function(projectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'deploy', args: [projectName] }); return this.makeAjaxCall(hash); }, discardChanges: function(projectName) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'discard', args: [projectName] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, saveFile: function(projectName, fileName, contents) { var hash = {}; hash.type = 'POST'; hash.url = ASTool.SlydApi.getApiUrl(); hash.data = JSON.stringify( { cmd: 'save', args: [projectName, fileName, contents] }); hash.dataType = 'text'; return this.makeAjaxCall(hash); }, /** @public Fetches a page using the given spider. @method fetchDocument @for ASTool.SlydApi @param {String} [pageUrl] the URL of the page to fetch. @param {String} [spiderName] the name of the spider to use. @param {String} [parentFp] the fingerprint of the parent page. @return {Promise} a promise that fulfills with an {Object} containing the document contents (page), the response data (response), the extracted items (items), the request fingerprint (fp), an error message (error) and the links that will be followed (links). */ fetchDocument: function(pageUrl, spiderName, parentFp) { var hash = {}; hash.type = 'POST'; hash.data = JSON.stringify({ spider: spiderName, request: { url: pageUrl } }); if (parentFp) { hash.data['parent_fp'] = parentFp; } hash.url = this.get('botUrl') + 'fetch'; return this.makeAjaxCall(hash); }, /** @private Transforms a list of the form: [ { name: 'obj1', x: 'a' }, { name: 'obj2', x: 'b' }] into an object of the form: { obj1: { x: 'a' }, obj2: { x: 'b' } } @method listToDict @for ASTool.SlydApi @param {Array} [list] the array to trasnform. @return {Object} the result object. */ listToDict: function(list) { var dict = {}; list.forEach(function(element) { // Don't modify the original object. element = Em.copy(element); var name = element['name']; delete element['name']; dict[name] = element; }); return dict; }, /** @private Transforms an object of the form: { obj1: { x: 'a' }, obj2: { x: 'b' } } into a list of the form: [ { name: 'obj1', x: 'a' }, { name: 'obj2', x: 'b' }] @method listToDict @for ASTool.SlydApi @param {Array} [list] the array to trasnform. @return {Object} the result object. */ dictToList: function(dict, wrappingType) { var entries = []; var keys = Object.keys(dict); keys.forEach(function(key) { var entry = dict[key]; entry['name'] = key; if (wrappingType) { entry = wrappingType.create(entry); } entries.pushObject(entry); }); return entries; }, makeAjaxCall: function(hash) { return ic.ajax(hash).catch(function(reason) { method = hash.type; title = 'Error processing ' + method + ' to ' + hash['url']; if (hash.data) { title += '\nwith data ' + hash.data; } msg = '\n The server returned ' + reason['textStatus'] + '(' + reason['errorThrown'] + ')' + '\n' + reason['jqXHR'].responseText; err = new Error(msg); err.title = title; err.name = 'HTTPError'; err.reason = reason; throw err; }); }, }); ASTool.SlydApi.reopenClass ({ getApiUrl: function() { return (SLYD_URL || window.location.protocol + '//' + window.location.host) + '/projects'; }, });
bsd-3-clause
croxsanchez/yii2build
backend/views/seller/indice.php
2202
<?php use Yii; use yii\helpers\Html; use yii\grid\GridView; use \yii\bootstrap\Collapse; use common\models\PermissionHelpers; use yii\data\ActiveDataProvider; use yii\db\mysql\QueryBuilder; use yii\db\Query; use backend\models\Seller; /* @var $this yii\web\View */ /* @var $searchModel backend\models\search\SellerSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $condition = 'seller.parent_id = '. Yii::$app->user->id; $query = (new Query()) ->select(['user.id AS userIdLink', 'user.username AS userLink', '(SELECT username FROM user where seller.parent_id = user.id) AS parentUserLink']) ->from('user') ->leftJoin('seller', 'seller.user_id = user.id') ->where($condition); // Crear un comando. Se puede obtener la consulta SQL actual utilizando $command->sql $command = $query->createCommand(); // Ejecutar el comando: $rows = $command->queryAll(); $provider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 3, ], 'sort' => [ 'attributes' => ['userIdLink','userLink', 'parentUserLink'], ], ]); $this->title = 'Mi organización'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="seller-index"> <h1><?= Html::encode($this->title).'. Vendedor: '.Html::encode(Yii::$app->user->identity->username); ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <?php if (PermissionHelpers::requireMinimumRole('Seller') && PermissionHelpers::requireStatus('Active')){ ?> <p> <?= Html::a('Create Seller', ['create'], ['class' => 'btn btn-success']) ?> </p> <?php } ?> <?= GridView::widget([ 'dataProvider' => $provider, 'filterModel' => $searchModel, 'columns' => [ // 'id', ['class' => 'yii\grid\SerialColumn'], ['attribute'=>'userIdLink', 'format'=>'raw'], ['attribute'=>'userLink', 'format'=>'raw'], ['attribute'=>'parentUserLink', 'format'=>'raw'], //'username', //'parentUsername', //'user', //'parent', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
bsd-3-clause
SteveMcGrath/pySecurityCenter
examples/sc4/average_time_to_mitigate/avg_ttm.py
597
import securitycenter HOST = 'HOSTNAME or IP_ADDRESS' USER = 'USERNAME' PASS = 'PASSWORD' ASSET_ID = 81 def get_ttm(**filters): sc = securitycenter.SecurityCenter4(HOST) sc.login(USER, PASS) data = sc.query('vulndetails', source='patched', **filters) agg = 0 for item in data: agg += int(item['lastSeen']) - int(item['firstSeen']) avg = float(agg) / len(data) print 'Average Hours to Mitigate : %d' % int(avg / 3600) print 'Average Days to Mitigate : %s' % int(avg / 3600 / 24) if __name__ == '__main__': get_ttm(assetID=ASSET_ID, severity='4,3,2,1')
bsd-3-clause