answer
stringlengths
15
1.25M
<?php namespace Doctrine\ORM\Query\AST; class <API key> extends Node { /** * @var Join */ public $join; /** * @var IndexBy|null */ public $indexBy; /** * Constructor. * * @param Join $join * @param IndexBy|null $indexBy */ public function __construct($join, $indexBy) { $this->join = $join; $this->indexBy = $indexBy; } /** * {@inheritdoc} */ public function dispatch($walker) { return $walker-><API key>($this); } }
'use strict'; import H from './Globals.js'; import Point from './Point.js'; import U from './Utilities.js'; var seriesType = U.seriesType; var seriesTypes = H.seriesTypes; /** * The ohlc series type. * * @private * @class * @name Highcharts.seriesTypes.ohlc * * @augments Highcharts.Series */ seriesType('ohlc', 'column' /** * An OHLC chart is a style of financial chart used to describe price * movements over time. It displays open, high, low and close values per * data point. * * @sample stock/demo/ohlc/ * OHLC chart * * @extends plotOptions.column * @excluding borderColor, borderRadius, borderWidth, crisp, stacking, * stack * @product highstock * @optionparent plotOptions.ohlc */ , { /** * The approximate pixel width of each group. If for example a series * with 30 points is displayed over a 600 pixel wide plot area, no * grouping is performed. If however the series contains so many points * that the spacing is less than the groupPixelWidth, Highcharts will * try to group it into appropriate groups so that each is more or less * two pixels wide. Defaults to `5`. * * @type {number} * @default 5 * @product highstock * @apioption plotOptions.ohlc.dataGrouping.groupPixelWidth */ /** * The pixel width of the line/border. Defaults to `1`. * * @sample {highstock} stock/plotoptions/ohlc-linewidth/ * A greater line width * * @type {number} * @default 1 * @product highstock * * @private */ lineWidth: 1, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span> ' + '<b> {series.name}</b><br/>' + 'Open: {point.open}<br/>' + 'High: {point.high}<br/>' + 'Low: {point.low}<br/>' + 'Close: {point.close}<br/>' }, threshold: null, states: { /** * @extends plotOptions.column.states.hover * @product highstock */ hover: { /** * The pixel width of the line representing the OHLC point. * * @type {number} * @default 3 * @product highstock */ lineWidth: 3 } }, /** * Determines which one of `open`, `high`, `low`, `close` values should * be represented as `point.y`, which is later used to set dataLabel * position and [compare](#plotOptions.series.compare). * * @sample {highstock} stock/plotoptions/ohlc-pointvalkey/ * Possible values * * @type {string} * @default close * @validvalue ["open", "high", "low", "close"] * @product highstock * @apioption plotOptions.ohlc.pointValKey */ /** * @default close * @apioption plotOptions.ohlc.colorKey */ /** * Line color for up points. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highstock * @apioption plotOptions.ohlc.upColor */ stickyTracking: true }, /** * @lends Highcharts.seriesTypes.ohlc */ { /* eslint-disable valid-jsdoc */ directTouch: false, pointArrayMap: ['open', 'high', 'low', 'close'], toYData: function (point) { // return a plain array for speedy calculation return [point.open, point.high, point.low, point.close]; }, pointValKey: 'close', pointAttrToOptions: { stroke: 'color', 'stroke-width': 'lineWidth' }, /** * @private * @function Highcarts.seriesTypes.ohlc#init * @return {void} */ init: function () { seriesTypes.column.prototype.init.apply(this, arguments); this.options.stacking = void 0; // #8817 }, /** * Postprocess mapping between options and SVG attributes * * @private * @function Highcharts.seriesTypes.ohlc#pointAttribs * @param {Highcharts.OHLCPoint} point * @param {string} state * @return {Highcharts.SVGAttributes} */ pointAttribs: function (point, state) { var attribs = seriesTypes.column.prototype.pointAttribs.call(this, point, state), options = this.options; delete attribs.fill; if (!point.options.color && options.upColor && point.open < point.close) { attribs.stroke = options.upColor; } return attribs; }, /** * Translate data points from raw values x and y to plotX and plotY * * @private * @function Highcharts.seriesTypes.ohlc#translate * @return {void} */ translate: function () { var series = this, yAxis = series.yAxis, hasModifyValue = !!series.modifyValue, translated = [ 'plotOpen', 'plotHigh', 'plotLow', 'plotClose', 'yBottom' ]; // translate OHLC for seriesTypes.column.prototype.translate.apply(series); // Do the translation series.points.forEach(function (point) { [point.open, point.high, point.low, point.close, point.low] .forEach(function (value, i) { if (value !== null) { if (hasModifyValue) { value = series.modifyValue(value); } point[translated[i]] = yAxis.toPixels(value, true); } }); // Align the tooltip to the high value to avoid covering the // point point.tooltipPos[1] = point.plotHigh + yAxis.pos - series.chart.plotTop; }); }, /** * Draw the data points * * @private * @function Highcharts.seriesTypes.ohlc#drawPoints * @return {void} */ drawPoints: function () { var series = this, points = series.points, chart = series.chart, /** * Extend vertical stem to open and close values. */ extendStem = function (path, halfStrokeWidth, openOrClose) { var start = path[0]; var end = path[1]; // We don't need to worry about crisp - openOrClose value // is already crisped and halfStrokeWidth should remove it. if (typeof start[2] === 'number') { start[2] = Math.max(openOrClose + halfStrokeWidth, start[2]); } if (typeof end[2] === 'number') { end[2] = Math.min(openOrClose - halfStrokeWidth, end[2]); } }; points.forEach(function (point) { var plotOpen, plotClose, crispCorr, halfWidth, path, graphic = point.graphic, crispX, isNew = !graphic, strokeWidth; if (typeof point.plotY !== 'undefined') { // Create and/or update the graphic if (!graphic) { point.graphic = graphic = chart.renderer.path() .add(series.group); } if (!chart.styledMode) { graphic.attr(series.pointAttribs(point, (point.selected && 'select'))); // #3897 } // crisp vector coordinates strokeWidth = graphic.strokeWidth(); crispCorr = (strokeWidth % 2) / 2; // #2596: crispX = Math.round(point.plotX) - crispCorr; halfWidth = Math.round(point.shapeArgs.width / 2); // the vertical stem path = [ ['M', crispX, Math.round(point.yBottom)], ['L', crispX, Math.round(point.plotHigh)] ]; // open if (point.open !== null) { plotOpen = Math.round(point.plotOpen) + crispCorr; path.push(['M', crispX, plotOpen], ['L', crispX - halfWidth, plotOpen]); extendStem(path, strokeWidth / 2, plotOpen); } // close if (point.close !== null) { plotClose = Math.round(point.plotClose) + crispCorr; path.push(['M', crispX, plotClose], ['L', crispX + halfWidth, plotClose]); extendStem(path, strokeWidth / 2, plotClose); } graphic[isNew ? 'attr' : 'animate']({ d: path }) .addClass(point.getClassName(), true); } }); }, animate: null // Disable animation /* eslint-enable valid-jsdoc */ }, /** * @lends Highcharts.seriesTypes.ohlc.prototype.pointClass.prototype */ { /* eslint-disable valid-jsdoc */ /** * Extend the parent method by adding up or down to the class name. * @private * @function Highcharts.seriesTypes.ohlc#getClassName * @return {string} */ getClassName: function () { return Point.prototype.getClassName.call(this) + (this.open < this.close ? ' highcharts-point-up' : ' <API key>'); } /* eslint-enable valid-jsdoc */ }); /** * A `ohlc` series. If the [type](#series.ohlc.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.ohlc * @excluding dataParser, dataURL * @product highstock * @apioption series.ohlc */ /** * An array of data points for the series. For the `ohlc` series type, * points can be given in the following ways: * * 1. An array of arrays with 5 or 4 values. In this case, the values correspond * to `x,open,high,low,close`. If the first value is a string, it is applied * as the name of the point, and the `x` value is inferred. The `x` value can * also be omitted, in which case the inner arrays should be of length 4\. * Then the `x` value is automatically calculated, either starting at 0 and * incremented by 1, or from `pointStart` and `pointInterval` given in the * series options. * ```js * data: [ * [0, 6, 5, 6, 7], * [1, 9, 4, 8, 2], * [2, 6, 3, 4, 10] * ] * ``` * * 2. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.ohlc.turboThreshold), this option is not * available. * ```js * data: [{ * x: 1, * open: 3, * high: 4, * low: 5, * close: 2, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * open: 4, * high: 3, * low: 6, * close: 7, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Array<(number|string),number,number,number>|Array<(number|string),number,number,number,number>|*>} * @extends series.arearange.data * @excluding y, marker * @product highstock * @apioption series.ohlc.data */ /** * The closing value of each data point. * * @type {number} * @product highstock * @apioption series.ohlc.data.close */ /** * The opening value of each data point. * * @type {number} * @product highstock * @apioption series.ohlc.data.open */ ''; // adds doclets above to transpilat
# -*- coding: utf-8 -*- # This file is part of weboob. # weboob is free software: you can redistribute it and/or modify # (at your option) any later version. # weboob is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the import random import urllib from urlparse import urlsplit from weboob.deprecated.browser import Browser, BrowserHTTPNotFound from .pages.index import IndexPage from .pages.torrents import TorrentPage, TorrentsPage __all__ = ['PiratebayBrowser'] class PiratebayBrowser(Browser): ENCODING = 'utf-8' DOMAINS = ['thepiratebay.vg', 'thepiratebay.la', 'thepiratebay.mn', 'thepiratebay.gd'] def __init__(self, url, *args, **kwargs): url = url or 'https://%s/' % random.choice(self.DOMAINS) url_parsed = urlsplit(url) self.PROTOCOL = url_parsed.scheme self.DOMAIN = url_parsed.netloc self.PAGES = { '%s://%s/' % (self.PROTOCOL, self.DOMAIN): IndexPage, '%s://%s/search/.*/0/7/0' % (self.PROTOCOL, self.DOMAIN): TorrentsPage, '%s://%s/torrent/.*' % (self.PROTOCOL, self.DOMAIN): TorrentPage } Browser.__init__(self, *args, **kwargs) def iter_torrents(self, pattern): self.location('%s://%s/search/%s/0/7/0' % (self.PROTOCOL, self.DOMAIN, urllib.quote_plus(pattern.encode('utf-8')))) assert self.is_on_page(TorrentsPage) return self.page.iter_torrents() def get_torrent(self, _id): try: self.location('%s://%s/torrent/%s/' % (self.PROTOCOL, self.DOMAIN, _id)) except BrowserHTTPNotFound: return if self.is_on_page(TorrentPage): return self.page.get_torrent(_id)
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>rgaa22 Test.03021 NMI 07</title> </head> <body> <div> <h1>rgaa22 Test.03021 NMI 07</h1> <div class="test-detail" lang="fr"> Présence d’information préalable sur le caractère obligatoire de certains champs de saisie et du type/format de saisie attendue si nécessaire </div> <div class="testcase"> <form action="mock_action"> <p> <textarea cols="100" rows="4"></textarea> <input name="submit" type="submit" value="Action" /> </p> </form> </div> <div class="test-explanation">NMI : The page contains at least one form that needs to be manually checked</div> </div> </body> </html>
package org.opennms.core.tasks; import org.springframework.util.Assert; /** * <p>AsyncTask class.</p> * * @author ranger * @version $Id: $ */ public class AsyncTask<T> extends AbstractTask { private final Async<T> m_async; private final Callback<T> m_callback; /** * <p>Constructor for AsyncTask.</p> * * @param coordinator a {@link org.opennms.core.tasks.TaskCoordinator} object. * @param parent a {@link org.opennms.core.tasks.ContainerTask} object. * @param async a {@link org.opennms.core.tasks.Async} object. * @param <T> a T object. */ public AsyncTask(TaskCoordinator coordinator, ContainerTask<?> parent, Async<T> async) { this(coordinator, parent, async, null); } /** * <p>Constructor for AsyncTask.</p> * * @param coordinator a {@link org.opennms.core.tasks.TaskCoordinator} object. * @param parent a {@link org.opennms.core.tasks.ContainerTask} object. * @param async a {@link org.opennms.core.tasks.Async} object. * @param callback a {@link org.opennms.core.tasks.Callback} object. */ public AsyncTask(TaskCoordinator coordinator, ContainerTask<?> parent, Async<T> async, Callback<T> callback) { super(coordinator, parent); Assert.notNull(async, "async parameter must not be null"); m_async = async; m_callback = callback; } /** {@inheritDoc} */ @Override public String toString() { return String.valueOf(m_async); } /** {@inheritDoc} */ @Override protected void doSubmit() { Callback<T> callback = callback(); try { m_async.<API key>(callback); } catch (Throwable t) { callback.handleException(t); } } /** * <p>markTaskAsCompleted</p> */ private final void markTaskAsCompleted() { getCoordinator().markTaskAsCompleted(this); } private Callback<T> callback() { return new Callback<T>() { @Override public void accept(T t) { try { if (m_callback != null) { m_callback.accept(t); } } finally { markTaskAsCompleted(); } } @Override public T apply(Throwable t) { try { if (m_callback != null) { m_callback.handleException(t); } } finally { markTaskAsCompleted(); } return null; } }; } }
# <API key>: true class Settings::<API key> < <API key> layout 'admin' before_action :authenticate_user! def show; end def update user_settings.update(<API key>.to_h) if current_user.update(user_params) I18n.locale = current_user.locale redirect_to <API key>, notice: I18n.t('generic.changes_saved_msg') else render :show end end private def user_settings <API key>.new(current_user) end def user_params params.require(:user).permit( :locale, filtered_languages: [] ) end def <API key> params.require(:user).permit( :<API key>, :setting_boost_modal, :<API key>, notification_emails: %i(follow follow_request reblog favourite mention digest), interactions: %i(must_be_follower must_be_following) ) end end
<?php // created: 2015-12-11 14:01:20 $dictionary['Contact']['fields']['salutation']['len']=100; $dictionary['Contact']['fields']['salutation']['inline_edit']=true; $dictionary['Contact']['fields']['salutation']['comments']='Contact salutation (e.g., Mr, Ms)'; $dictionary['Contact']['fields']['salutation']['merge_filter']='disabled'; ?>
#include "db_config.h" #include "db_int.h" /* * __os_rmdir -- * Remove a directory. */ int __os_rmdir(env, name) ENV *env; const char *name; { DB_ENV *dbenv; _TCHAR *tname; int ret; dbenv = env == NULL ? NULL : env->dbenv; if (dbenv != NULL && FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS | DB_VERB_FILEOPS_ALL)) __db_msg(env, DB_STR_A("0240", "fileops: rmdir %s", "%s"), name); TO_TSTRING(env, name, tname, ret); if (ret != 0) return (ret); RETRY_CHK(!RemoveDirectory(tname), ret); FREE_STRING(env, tname); if (ret != 0) return (__os_posix_err(ret)); return (ret); }
"""This module implement decorators for wrapping data sources so as to simplify their construction and attribution of properties. """ import functools def <API key>(name=None, **properties): """Decorator for applying to a simple data source which directly returns an iterable/generator with the metrics for each sample. The function the decorator is applied to must take no arguments. """ def _decorator(func): @functools.wraps(func) def _properties(settings): def _factory(environ): return func d = dict(properties) d['name'] = name d['factory'] = _factory return d return _properties return _decorator def data_source_factory(name=None, **properties): """Decorator for applying to a data source defined as a factory. The decorator can be applied to a class or a function. The class constructor or function must accept arguments of 'settings', being configuration settings for the data source, and 'environ' being information about the context in which the data source is being used. The resulting object must be a callable which directly returns an iterable/generator with the metrics for each sample. """ def _decorator(func): @functools.wraps(func) def _properties(settings): def _factory(environ): return func(settings, environ) d = dict(properties) d['name'] = name d['factory'] = _factory return d return _properties return _decorator
<?php if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } /** * Predefined logic hooks * after_ui_frame * after_ui_footer * after_save * before_save * before_retrieve * after_retrieve * process_record * before_delete * after_delete * before_restore * after_restore * server_roundtrip * before_logout * after_logout * before_login * after_login * login_failed * after_session_start * after_entry_point * * @api */ class LogicHook { public $bean = null; public function __construct() { } /** * Static Function which returns and instance of LogicHook * * @return unknown */ public static function initialize() { if (empty($GLOBALS['logic_hook'])) { $GLOBALS['logic_hook'] = new LogicHook(); } return $GLOBALS['logic_hook']; } public function setBean($bean) { $this->bean = $bean; return $this; } protected $hook_map = array(); protected $hookscan = array(); public function getHooksMap() { return $this->hook_map; } public function getHooksList() { return $this->hookscan; } public function scanHooksDir($extpath) { if (is_dir($extpath)) { $dir = dir($extpath); while ($entry = $dir->read()) { if ($entry != '.' && $entry != '..' && strtolower(substr($entry, -4)) == ".php" && is_file($extpath.'/'.$entry)) { unset($hook_array); include($extpath.'/'.$entry); if (!empty($hook_array)) { foreach ($hook_array as $type => $hookg) { foreach ($hookg as $index => $hook) { $this->hookscan[$type][] = $hook; $idx = count($this->hookscan[$type])-1; $this->hook_map[$type][$idx] = array("file" => $extpath.'/'.$entry, "index" => $index); } } } } } } } protected static $hooks = array(); public static function refreshHooks() { self::$hooks = array(); } public function loadHooks($module_dir) { $hook_array = array(); if (!empty($module_dir)) { $custom = "custom/modules/$module_dir"; } else { $custom = "custom/modules"; } if (file_exists("$custom/logic_hooks.php")) { if (isset($GLOBALS['log'])) { $GLOBALS['log']->debug('Including module specific hook file for '.$custom); } include("$custom/logic_hooks.php"); } if (empty($module_dir)) { $custom = "custom/application"; } if (file_exists("$custom/Ext/LogicHooks/logichooks.ext.php")) { if (isset($GLOBALS['log'])) { $GLOBALS['log']->debug('Including Ext hook file for '.$custom); } include("$custom/Ext/LogicHooks/logichooks.ext.php"); } return $hook_array; } public function getHooks($module_dir, $refresh = false) { if ($refresh || !isset(self::$hooks[$module_dir])) { self::$hooks[$module_dir] = $this->loadHooks($module_dir); } return self::$hooks[$module_dir]; } /** * Provide a means for developers to create upgrade safe business logic hooks. * If the bean is null, then we assume this call was not made from a SugarBean Object and * therefore we do not pass it to the method call. * * @param string $module_dir * @param string $event * @param array $arguments * @param SugarBean $bean */ public function call_custom_logic($module_dir, $event, $arguments = null) { // declare the hook array variable, it will be defined in the included file. $hook_array = null; if (isset($GLOBALS['log'])) { $GLOBALS['log']->debug("Hook called: $module_dir::$event"); } if (!empty($module_dir)) { // This will load an array of the hooks to process $hooks = $this->getHooks($module_dir); if (!empty($hooks)) { $this->process_hooks($hooks, $event, $arguments); } } $hooks = $this->getHooks(''); if (!empty($hooks)) { $this->process_hooks($hooks, $event, $arguments); } } /** * This is called from call_custom_logic and actually performs the action as defined in the * logic hook. If the bean is null, then we assume this call was not made from a SugarBean Object and * therefore we do not pass it to the method call. * * @param array $hook_array * @param string $event * @param array $arguments * @param SugarBean $bean */ public function process_hooks($hook_array, $event, $arguments) { // Now iterate through the array for the appropriate hook if (!empty($hook_array[$event])) { // Apply sorting to the hooks using the sort index. // Hooks with matching sort indexes will be processed in no particular order. $sorted_indexes = array(); foreach ($hook_array[$event] as $idx => $hook_details) { $order_idx = $hook_details[0]; $sorted_indexes[$idx] = $order_idx; } asort($sorted_indexes); $process_order = array_keys($sorted_indexes); foreach ($process_order as $hook_index) { $hook_details = $hook_array[$event][$hook_index]; if (!file_exists($hook_details[2])) { if (isset($GLOBALS['log'])) { $GLOBALS['log']->error('Unable to load custom logic file: '.$hook_details[2]); } continue; } include_once($hook_details[2]); $hook_class = $hook_details[3]; $hook_function = $hook_details[4]; // Make a static call to the function of the specified class //TODO Make a factory for these classes. Cache instances accross uses if ($hook_class == $hook_function) { if (isset($GLOBALS['log'])) { $GLOBALS['log']->debug('Creating new instance of hook class '.$hook_class.' with parameters'); } if (!is_null($this->bean)) { $class = new $hook_class($this->bean, $event, $arguments); } else { $class = new $hook_class($event, $arguments); } } else { if (isset($GLOBALS['log'])) { $GLOBALS['log']->debug('Creating new instance of hook class '.$hook_class.' without parameters'); } $class = new $hook_class(); if (!is_null($this->bean)) { $class->$hook_function($this->bean, $event, $arguments); } else { $class->$hook_function($event, $arguments); } } } } } }
package tc.oc.api.ocn; import java.util.Collection; import javax.inject.Singleton; import com.google.common.util.concurrent.ListenableFuture; import tc.oc.api.docs.MapRating; import tc.oc.api.docs.virtual.MapDoc; import tc.oc.api.docs.virtual.UserDoc; import tc.oc.api.exceptions.NotFound; import tc.oc.api.http.HttpOption; import tc.oc.api.maps.MapRatingsRequest; import tc.oc.api.maps.MapRatingsResponse; import tc.oc.api.maps.MapService; import tc.oc.api.maps.UpdateMapsResponse; import tc.oc.api.model.HttpModelService; import tc.oc.commons.core.concurrent.FutureUtils; import tc.oc.commons.core.stream.Collectors; @Singleton class OCNMapService extends HttpModelService<MapDoc, MapDoc> implements MapService { public ListenableFuture<Object> rate(MapRating rating) { return this.client().post(memberUri(rating.map_id, "rate"), rating, Object.class, HttpOption.INFINITE_RETRY); } public ListenableFuture<MapRatingsResponse> getRatings(MapRatingsRequest request) { return this.client().post(memberUri(request.map_id, "get_ratings"), request, MapRatingsResponse.class, HttpOption.INFINITE_RETRY); } public UpdateMapsResponse updateMaps(Collection<? extends MapDoc> maps) { final ListenableFuture<<API key>> future = updateMulti(maps, <API key>.class); return new UpdateMapsResponse( (ListenableFuture) future, maps.stream() .flatMap(MapDoc::<API key>) .distinct() .collect(Collectors.mappingTo(uuid -> FutureUtils.mapSync( future, response -> { final UserDoc.Identity user = response.users_by_uuid.get(uuid); if(user != null) return user; throw new NotFound(); } ))) ); } }
tc.gam.<API key> = function(options) { var self = { currentHash: window.location.hash, previousHash: null }; self._setHash = function(hash) { if (hash === self.currentHash) { tc.jQ(window).trigger('hashchange'); } else { //This will trigger the 'hashchange' event because the hash is different window.location.hash = hash; } }; self._getHash = function() { return window.location.hash.substring(1, window.location.hash.length); }; self._goHome = function() { self._setHash('show,home'); }; self.<API key> = function(action, widget, id) { tc.jQ(tc).trigger(action + '-project-widget', [widget, id]); }; self._onHashChange = function(event) { var action, widget; self.previousHash = self.currentHash; self.currentHash = self._getHash(); // For project-home hash, fire goHome. if (!self.currentHash || self.currentHash === 'project-home') { self._goHome(); } else { action = self.currentHash.split(',')[0]; widget = self.currentHash.split(',')[1]; id = self.currentHash.split(',')[2]; } tc.util.log('&&& hashchange: ' + action + ', ' + widget); self.<API key>(action, widget, id); }; var bindEvents = function() { tc.jQ(window).bind('hashchange', self._onHashChange); }; var init = function() { bindEvents(); if (self.currentHash) { self._setHash(self.currentHash); } else { self._goHome(); } }; init(); return self; };
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Rgaa30 Test.10.4.2 Failed 03_3</title> <style type="text/css"> @media tv { h1{ font-size: 15mm; } } </style> </head> <body> <div> <h1>Rgaa30 Test.10.4.2 Failed 03_3</h1> <div class="test-detail" lang="fr"> Dans les <a href="http://references.modernisation.gouv.fr/<API key>#mFeuilleStyle">feuilles de styles</a> du <a href="http://references.modernisation.gouv.fr/<API key> <code>screen</code>, <code>tv</code>, <code>handheld</code>, <code>projection</code>, les tailles de caractères utilisent-elles uniquement des <a href="http://references.modernisation.gouv.fr/<API key> </div> <p class="test-explanation"> Failed: The pc unit is used on a font-size property of a css rule applied to the &quot;tv&quot; media. </p> </div> </body> </html>
//$Id: style.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef STYLE_HPP #define STYLE_HPP // mapnik #include <mapnik/color.hpp> #include <mapnik/symbolizer.hpp> // boost #include <boost/shared_ptr.hpp> // stl #include <vector> #include <algorithm> #include <functional> namespace mapnik { } #endif //STYLE_HPP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <! This library is part of OpenCms - the Open Source Content Management System Copyright (c) Alkacon Software GmbH (http: This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. For further information about Alkacon Software GmbH, please see the company website: http: For further information about OpenCms, please see the project website: http: You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA </head> <body bgcolor="white"> Contains server side classes for the XML content editor.<p> <!-- Put @see and @since tags down here. --> @since 8.5.0 </body> </html>
package org.opencms.workplace.tools.content; import org.opencms.file.CmsProperty; import org.opencms.file.<API key>; import org.opencms.file.CmsResource; import org.opencms.file.CmsVfsException; import org.opencms.i18n.CmsMessages; import org.opencms.jsp.CmsJspActionElement; import org.opencms.lock.CmsLock; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.workplace.CmsDialog; import org.opencms.workplace.CmsWorkplace; import org.opencms.workplace.<API key>; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; /** * Provides methods for the delete property definition dialog.<p> * * @since 6.0.0 */ public class CmsPropertyDelete extends CmsDialog { /** Value for the action: delete cascade. */ public static final int <API key> = 100; /** Request parameter value for the action: delete cascade. */ public static final String <API key> = "deletecascade"; /** The dialog type. */ public static final String DIALOG_TYPE = "propertydelete"; /** Request parameter name for the property name. */ public static final String PARAM_PROPERTYNAME = "propertyname"; private String m_paramPropertyName; /** * Public constructor with JSP action element.<p> * * @param jsp an initialized JSP action element */ public CmsPropertyDelete(CmsJspActionElement jsp) { super(jsp); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsPropertyDelete(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * Deletes the property definition.<p> * * @throws JspException if problems including sub-elements occur */ public void actionDelete() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(<API key>, this); try { getCms().<API key>(<API key>()); // close the dialog actionCloseDialog(); } catch (Throwable e) { // error while deleting property definition, show error dialog includeErrorpage(this, e); } } /** * Deletes the property definition by cascading the properties on resources.<p> * * @throws JspException if problems including sub-elements occur */ public void actionDeleteCascade() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(<API key>, this); try { // list of all resources containing this propertydefinition List <API key> = getCms().<API key>(<API key>()); // list of all resources locked by another user, containing this propertydefinition List <API key> = <API key>(<API key>); // do the following operations only if all of the resources are not locked by another user if (<API key>.isEmpty()) { // save the site root String storedSiteRoot = getCms().getRequestContext().getSiteRoot(); try { // change to the root site getCms().getRequestContext().setSiteRoot("/"); Iterator i = <API key>.iterator(); while (i.hasNext()) { CmsResource resource = (CmsResource)i.next(); // read the property object CmsProperty property = getCms().readPropertyObject( resource.getRootPath(), <API key>(), false); // try to delete the property if it is not the NULL PROPERTY // if the property is the NULL PROPERTY, it only had a shared // value which was deleted at a sibling which was already processed if (!property.isNullProperty()) { CmsLock lock = getCms().getLock(resource); if (lock.isUnlocked()) { // lock the resource for the current (Admin) user getCms().lockResource(resource.getRootPath()); } property.setStructureValue(CmsProperty.DELETE_VALUE); property.setResourceValue(CmsProperty.DELETE_VALUE); // write the property with the null value to the resource and cascade it from the definition getCms().writePropertyObject(resource.getRootPath(), property); // unlock the resource getCms().unlockResource(resource.getRootPath()); } } // delete the property definition at last getCms().<API key>(<API key>()); } finally { // restore the siteroot getCms().getRequestContext().setSiteRoot(storedSiteRoot); // close the dialog actionCloseDialog(); } } else { StringBuffer reason = new StringBuffer(); reason.append(dialogWhiteBoxStart()); reason.append(buildResourceList(<API key>, true)); reason.append(dialogWhiteBoxEnd()); throw new CmsVfsException(Messages.get().container( Messages.<API key>, reason.toString())); } } catch (Throwable e) { // error while deleting property definition, show error dialog includeErrorpage(this, e); } } /** * Builds a HTML list of Resources that use the specified property.<p> * * @throws CmsException if operation was not successful * * @return the HTML String for the Resource list */ public String buildResourceList() throws CmsException { List <API key> = getCms().<API key>(<API key>()); return buildResourceList(<API key>, false); } /** * Builds a HTML list of Resources.<p> * * Columns: Type, Name, Uri, Value of the property, locked by(optional).<p> * * @param resourceList a list of resources * @param lockInfo a boolean to decide if the locked info should be shown or not * @throws CmsException if operation was not successful * * @return the HTML String for the Resource list */ public String buildResourceList(List resourceList, boolean lockInfo) throws CmsException { // reverse the resource list Collections.reverse(resourceList); CmsMessages messages = Messages.get().getBundle(getLocale()); StringBuffer result = new StringBuffer(); result.append("<table border=\"0\" width=\"100%\" cellpadding=\"1\" cellspacing=\"1\">\n"); result.append("<tr>\n"); // Type result.append("\t<td style=\"width:5%;\" class=\"textbold\">"); result.append(messages.key(Messages.GUI_INPUT_TYPE_0)); result.append("</td>\n"); // Uri result.append("\t<td style=\"width:40%;\" class=\"textbold\">"); result.append(messages.key(Messages.GUI_INPUT_ADRESS_0)); result.append("</td>\n"); // Name result.append("\t<td style=\"width:25%;\" class=\"textbold\">"); result.append(messages.key(Messages.GUI_INPUT_TITLE_0)); result.append("</td>\n"); if (!lockInfo) { // Property value result.append("\t<td style=\"width:30%;\" class=\"textbold\">"); result.append(messages.key(Messages.<API key>)); result.append("</td>\n"); } if (lockInfo) { // Property value result.append("\t<td style=\"width:30%;\" class=\"textbold\">"); result.append(messages.key(Messages.<API key>)); result.append("</td>\n"); result.append("</tr>\n"); } result.append("</tr>\n"); result.append("<tr><td colspan=\"4\"><span style=\"height: 6px;\">&nbsp;</span></td></tr>\n"); String storedSiteRoot = getCms().getRequestContext().getSiteRoot(); try { getCms().getRequestContext().setSiteRoot("/"); Iterator i = resourceList.iterator(); while (i.hasNext()) { CmsResource resource = (CmsResource)i.next(); String filetype = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getTypeName(); result.append("<tr>\n"); // file type result.append("\t<td>"); result.append("<img src=\""); result.append(getSkinUri()); result.append(CmsWorkplace.RES_PATH_FILETYPES); result.append(filetype); result.append(".gif\">"); result.append("</td>\n"); // file address result.append("\t<td>"); result.append(resource.getRootPath()); result.append("</td>\n"); // title result.append("\t<td>"); result.append(getJsp().property(<API key>.PROPERTY_TITLE, resource.getRootPath(), "")); result.append("</td>\n"); // current value of the property if (!lockInfo) { result.append("\t<td>"); result.append(getJsp().property(<API key>(), resource.getRootPath())); result.append("</td>\n"); } // locked by user if (lockInfo) { CmsLock lock = getCms().getLock(resource); result.append("\t<td>"); result.append(getCms().readUser(lock.getUserId()).getName()); result.append("</td>\n"); } result.append("</tr>\n"); } result.append("</table>\n"); } finally { getCms().getRequestContext().setSiteRoot(storedSiteRoot); } return result.toString(); } /** * Builds the html for the property definition select box.<p> * * @param attributes optional attributes for the &lt;select&gt; tag * @return the html for the property definition select box */ public String buildSelectProperty(String attributes) { return CmsPropertyChange.buildSelectProperty(getCms(), Messages.get().getBundle(getLocale()).key( Messages.GUI_PLEASE_SELECT_0), attributes, ""); } /** * Returns the value of the propertyname parameter.<p> * * @return the value of the propertyname parameter */ public String <API key>() { return m_paramPropertyName; } /** * Sets the value of the propertyname parameter.<p> * * @param paramPropertyName the value of the propertyname parameter */ public void <API key>(String paramPropertyName) { m_paramPropertyName = paramPropertyName; } /** * @see org.opencms.workplace.CmsWorkplace#<API key>(org.opencms.workplace.<API key>, javax.servlet.http.HttpServletRequest) */ protected void <API key>(<API key> settings, HttpServletRequest request) { // fill the parameter values in the get/set methods fillParamValues(request); // set the dialog type setParamDialogtype(DIALOG_TYPE); // set the action for the JSP switch if (DIALOG_OK.equals(getParamAction())) { setAction(ACTION_OK); setParamTitle(Messages.get().getBundle(getLocale()).key(Messages.<API key>) + ": " + <API key>()); } else if (DIALOG_CANCEL.equals(getParamAction())) { setAction(ACTION_CANCEL); } else if (<API key>.equals(getParamAction())) { setAction(<API key>); } else { setAction(ACTION_DEFAULT); // build title for change property value dialog setParamTitle(Messages.get().getBundle(getLocale()).key(Messages.<API key>)); } } /** * Returns a list of resources that are locked by another user as the current user.<p> * * @param resourceList the list of all (mixed) resources * * @return a list of resources that are locked by another user as the current user * @throws CmsException if the getLock operation fails */ private List <API key>(List resourceList) throws CmsException { List <API key> = new ArrayList(); Iterator i = resourceList.iterator(); while (i.hasNext()) { CmsResource resource = (CmsResource)i.next(); // get the lock state for the resource CmsLock lock = getCms().getLock(resource); // add this resource to the list if this is locked by another user if (!lock.isUnlocked() && !lock.isOwnedBy(getCms().getRequestContext().getCurrentUser())) { <API key>.add(resource); } } return <API key>; } }
class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): """ Return the dictionary of configure options. """ return self._configs def extend(self, translator): """ Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass
#!/usr/bin/python import math import Sofa def tostr(L): return str(L).replace('[', '').replace("]", '').replace(",", ' ') def transform(T,p): return [T[0][0]*p[0]+T[0][1]*p[1]+T[0][2]*p[2]+T[1][0],T[0][3]*p[0]+T[0][4]*p[1]+T[0][5]*p[2]+T[1][1],T[0][6]*p[0]+T[0][7]*p[1]+T[0][8]*p[2]+T[1][2]] def transformF(T,F): return [T[0][0]*F[0]+T[0][1]*F[3]+T[0][2]*F[6],T[0][0]*F[1]+T[0][1]*F[4]+T[0][2]*F[7],T[0][0]*F[2]+T[0][1]*F[5]+T[0][2]*F[8],T[0][3]*F[0]+T[0][4]*F[3]+T[0][5]*F[6],T[0][3]*F[1]+T[0][4]*F[4]+T[0][5]*F[7],T[0][3]*F[2]+T[0][4]*F[5]+T[0][5]*F[8],T[0][6]*F[0]+T[0][7]*F[3]+T[0][8]*F[6],T[0][6]*F[1]+T[0][7]*F[4]+T[0][8]*F[7],T[0][6]*F[2]+T[0][7]*F[5]+T[0][8]*F[8]] def compare(p1,p2): res = 0 for i,P1 in enumerate(p1): for j,item in enumerate(P1): res = res+ (item-p2[i][j])*(item-p2[i][j]) return res ERRORTOL = 1e-5 T = [[2,0,0,0,2,0,0,0,2],[0,0,0]] #T = [[0.8,1.2,0.3,0,1.9,0.45,0.5,2.8,0.2],[5,2,8]] samples= [[0.5,0.5,0.5], [0.23,0.5,0.8], [0,0.12,0], [0.8,0,0.58]] # scene creation method def createScene(rootNode): rootNode.createObject('RequiredPlugin', pluginName="Flexible") rootNode.createObject('VisualStyle', displayFlags="showBehaviorModels") restpos = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]] pos = [transform(T,item) for item in restpos] simNode = rootNode.createChild('Hexa_barycentric') simNode.createObject('MeshTopology', name="mesh", position=tostr(restpos), hexahedra="0 1 3 2 4 5 7 6") simNode.createObject('MechanicalObject', template="Vec3d", name="parent", rest_position="@mesh.position",position=tostr(pos) ) simNode.createObject('<API key>', position="@parent.rest_position", nbRef="8") childNode = simNode.createChild('childP') childNode.createObject('MechanicalObject', template="Vec3d", name="child", position=tostr(samples) , showObject="1") childNode.createObject('LinearMapping', template="Vec3d,Vec3d") childNode = simNode.createChild('childF') childNode.createObject('GaussPointContainer', position=tostr(samples)) childNode.createObject('MechanicalObject', template="F331", name="child") childNode.createObject('LinearMapping', template="Vec3d,F331", <API key>="1") childNode = simNode.createChild('Visu') childNode.createObject('VisualModel', color="8e-1 8e-1 1 1e-1") childNode.createObject('IdentityMapping') childNode = simNode.createChild('Visu2') childNode.createObject('VisualStyle', displayFlags="showWireframe") childNode.createObject('VisualModel', color="8e-1 8e-1 1 1") childNode.createObject('IdentityMapping') simNode.createObject('<API key>',filename="FEM.py", classname="Controller") simNode = rootNode.createChild('Tetra_barycentric') simNode.createObject('MeshTopology', name="mesh", position=tostr(restpos), tetrahedra="0 5 1 7 0 1 2 7 1 2 7 3 7 2 0 6 7 6 0 5 6 5 4 0") simNode.createObject('MechanicalObject', template="Vec3d", name="parent", rest_position="@mesh.position",position=tostr(pos) ) simNode.createObject('<API key>', position="@parent.rest_position", nbRef="4") childNode = simNode.createChild('childP') childNode.createObject('MechanicalObject', template="Vec3d", name="child", position=tostr(samples) , showObject="1") childNode.createObject('LinearMapping', template="Vec3d,Vec3d") childNode = simNode.createChild('childF') childNode.createObject('GaussPointContainer', position=tostr(samples)) childNode.createObject('MechanicalObject', template="F331", name="child") childNode.createObject('LinearMapping', template="Vec3d,F331") simNode.createObject('<API key>',filename="FEM.py", classname="Controller") simNode = rootNode.createChild('Hexa_shepard') simNode.createObject('MeshTopology', name="mesh", position=tostr(restpos), hexahedra="0 1 3 2 4 5 7 6") simNode.createObject('MechanicalObject', template="Vec3d", name="parent", rest_position="@mesh.position",position=tostr(pos) ) simNode.createObject('<API key>', position="@parent.rest_position", power="2") childNode = simNode.createChild('childP') childNode.createObject('MechanicalObject', template="Vec3d", name="child", position=tostr(samples) , showObject="1") childNode.createObject('LinearMapping', template="Vec3d,Vec3d") childNode = simNode.createChild('childF') childNode.createObject('GaussPointContainer', position=tostr(samples)) childNode.createObject('MechanicalObject', template="F331", name="child") childNode.createObject('LinearMapping', template="Vec3d,F331") simNode.createObject('<API key>',filename="FEM.py", classname="Controller") rootNode.animate=1 return rootNode class Controller(Sofa.<API key>): def createGraph(self,node): self.node=node self.done=0 return 0 def onEndAnimationStep(self,dt): if self.done==0: print "TEST "+self.node.name+":" # test points restpos = self.node.getObject('childP/child').findData('rest_position').value refpos = [transform(T,item) for item in restpos] pos = self.node.getObject('childP/child').findData('position').value error = compare(refpos,pos) if error>ERRORTOL : print "\t"+"\033[91m"+"[FAILED]"+"\033[0m"+" error on P= "+str(error) else : print "\t"+"\033[92m"+"[OK]"+"\033[0m"+" error on P= "+str(error) # test defo gradients restpos = [1,0,0,0,1,0,0,0,1] pos = self.node.getObject('childF/child').findData('position').value refpos = [transformF(T,restpos) for item in pos] error = compare(refpos,pos) if error>ERRORTOL : print "\t"+"\033[91m"+"[FAILED]"+"\033[0m"+" error on F= "+str(error) else : print "\t"+"\033[92m"+"[OK]"+"\033[0m"+" error on F= "+str(error) self.done=1 return 0
#ifndef <API key> #define <API key> #include "<API key>.h" QT_BEGIN_NAMESPACE class <API key>; QT_END_NAMESPACE namespace QmlDesigner { namespace Internal { class <API key> : public <API key> { public: typedef QSharedPointer<<API key>> Pointer; typedef QWeakPointer<<API key>> WeakPointer; static Pointer create(QObject *objectToBeWrapped); void setPropertyVariant(const PropertyName &name, const QVariant &value); void setPropertyBinding(const PropertyName &name, const QString &expression); bool isPositioner() const; bool isResizable() const; void refreshPositioner(); protected: <API key>(<API key> *item); <API key> *positioner() const; }; } // namespace Internal } // namespace QmlDesigner #endif // <API key>
#include "config.h" #include <lxc/lxccontainer.h> #include <unistd.h> #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <errno.h> #define MYNAME "lxctest1" int main(int argc, char *argv[]) { struct lxc_container *c; int ret = 1; if ((c = lxc_container_new(MYNAME, NULL)) == NULL) { fprintf(stderr, "%d: error opening lxc_container %s\n", __LINE__, MYNAME); ret = 1; goto out; } if (c->is_defined(c)) { fprintf(stderr, "%d: %s thought it was defined\n", __LINE__, MYNAME); goto out; } if (!c->set_config_item(c, "lxc.net.0.type", "veth")) { fprintf(stderr, "%d: failed to set network type\n", __LINE__); goto out; } c->set_config_item(c, "lxc.net.0.link", "lxcbr0"); c->set_config_item(c, "lxc.net.0.flags", "up"); if (!c->createl(c, "busybox", NULL, NULL, 0, NULL)) { fprintf(stderr, "%d: failed to create a container\n", __LINE__); goto out; } if (!c->is_defined(c)) { fprintf(stderr, "%d: %s thought it was not defined\n", __LINE__, MYNAME); goto out; } c->clear_config(c); c->load_config(c, NULL); c->want_daemonize(c, true); if (!c->startl(c, 0, NULL)) { fprintf(stderr, "%d: failed to start %s\n", __LINE__, MYNAME); goto out; } /* Wait for init to be ready for SIGPWR */ sleep(20); if (!c->shutdown(c, 120)) { fprintf(stderr, "%d: failed to shut down %s\n", __LINE__, MYNAME); if (!c->stop(c)) fprintf(stderr, "%d: failed to kill %s\n", __LINE__, MYNAME); goto out; } if (!c->destroy(c)) { fprintf(stderr, "%d: error deleting %s\n", __LINE__, MYNAME); goto out; } if (c->is_defined(c)) { fprintf(stderr, "%d: %s thought it was defined\n", __LINE__, MYNAME); goto out; } fprintf(stderr, "all lxc_container tests passed for %s\n", c->name); ret = 0; out: if (c && c->is_defined(c)) c->destroy(c); lxc_container_put(c); exit(ret); }
# <API key>: (Apache-2.0 OR MIT) from spack import * class Serf(SConsPackage): """Apache Serf - a high performance C-based HTTP client library built upon the Apache Portable Runtime (APR) library""" homepage = 'https://serf.apache.org/' url = 'https://archive.apache.org/dist/serf/serf-1.3.9.tar.bz2' maintainers = ['cosmicexplorer'] version('1.3.9', sha256='<SHA256-like>') version('1.3.8', sha256='<SHA256-like>') variant('debug', default=False, description='Enable debugging info and strict compile warnings') depends_on('apr') depends_on('apr-util') depends_on('openssl') depends_on('python+pythoncmd', type='build') depends_on('scons@2.3.0:', type='build') depends_on('uuid') depends_on('zlib') patch('py3syntax.patch') patch('py3-hashbang.patch') def build_args(self, spec, prefix): args = { 'PREFIX': prefix, 'APR': spec['apr'].prefix, 'APU': spec['apr-util'].prefix, 'OPENSSL': spec['openssl'].prefix, 'ZLIB': spec['zlib'].prefix, 'DEBUG': 'yes' if '+debug' in spec else 'no', } # SCons doesn't pass Spack environment variables to the # execution environment. Therefore, we can't use Spack's compiler # wrappers. Use the actual compilers. SCons seems to RPATH things # on its own anyway. args['CC'] = self.compiler.cc # Old versions of serf ignore the ZLIB variable on non-Windows platforms. # Also, there is no UUID variable to specify its installation location. # Pass explicit link flags for both. library_dirs = [] include_dirs = [] for dep in spec.dependencies(deptype='link'): query = self.spec[dep.name] library_dirs.extend(query.libs.directories) include_dirs.extend(query.headers.directories) rpath = self.compiler.cc_rpath_arg args['LINKFLAGS'] = '-L' + ' -L'.join(library_dirs) args['LINKFLAGS'] += ' ' + rpath + (' ' + rpath).join(library_dirs) args['CPPFLAGS'] = '-I' + ' -I'.join(include_dirs) return [key + '=' + value for key, value in args.items()] def build_test(self): # FIXME: Several test failures: # There were 14 failures: # 1) <API key> # 2) <API key> # 3) <API key> # 4) <API key> # 5) <API key> # 6) <API key> # 7) <API key> # 8) <API key> # 9) <API key> # 10) <API key> # 11) <API key><API key> # 12) <API key><API key> # 13) <API key><API key> # 14) <API key> # These seem to be related to: scons('check')
/* * Expected: 'i_first' 'c_first' * Not expected: 'i_second' 'c_second' 'f_second' */ typedef struct { int i_first; char c_first; } S1; typedef struct { int i_second; char c_second; float f_second; } S2; void foo() { S1 s; s.<<<<; }
\hypertarget{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}{}\section{Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor Class Reference} \label{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}\index{Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}} An Akka.\+Net based I\+Event\+Handler that handles the \hyperlink{<API key>}{Hello\+World\+Replied\+To}. Inheritance diagram for Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor\+:\begin{figure}[H] \begin{center} \leavevmode \includegraphics[height=2.000000cm]{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor} \end{center} \end{figure} \subsection*{Public Member Functions} \begin{DoxyCompactItemize} \item void \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a9d843860260cd66f8354b9df234a1663_a9d843860260cd66f8354b9df234a1663}{Handle} (\hyperlink{<API key>}{Hello\+World\+Replied\+To} message) \begin{DoxyCompactList}\small\item\em Responds to the provided {\itshape message} . \end{DoxyCompactList}\item \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a174cd0183fbe16aaa74f18320e871a5f_a174cd0183fbe16aaa74f18320e871a5f}{Hello\+World\+Replied\+To\+Event\+Handler\+Actor} (I\+Logger logger, I\+Correlation\+Id\+Helper correlation\+Id\+Helper, \hyperlink{interfaceCqrs_1_1<API key>}{I\+Authentication\+Token\+Helper}$<$ Guid $>$ authentication\+Token\+Helper) \begin{DoxyCompactList}\small\item\em Instantiates a new instance of \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}. \end{DoxyCompactList}\end{DoxyCompactItemize} \subsection*{Additional Inherited Members} \subsection{Detailed Description} An Akka.\+Net based I\+Event\+Handler that handles the \hyperlink{<API key>}{Hello\+World\+Replied\+To}. \subsection{Constructor \& Destructor Documentation} \mbox{\Hypertarget{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a174cd0183fbe16aaa74f18320e871a5f_a174cd0183fbe16aaa74f18320e871a5f}\label{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a174cd0183fbe16aaa74f18320e871a5f_a174cd0183fbe16aaa74f18320e871a5f}} \index{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}!Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}} \index{Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}!Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}} \subsubsection{\texorpdfstring{Hello\+World\+Replied\+To\+Event\+Handler\+Actor()}{<API key>()}} {\footnotesize\ttfamily Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor (\begin{DoxyParamCaption}\item[{I\+Logger}]{logger, }\item[{I\+Correlation\+Id\+Helper}]{correlation\+Id\+Helper, }\item[{\hyperlink{interfaceCqrs_1_1<API key>}{I\+Authentication\+Token\+Helper}$<$ Guid $>$}]{authentication\+Token\+Helper }\end{DoxyParamCaption})} Instantiates a new instance of \hyperlink{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor}{Hello\+World\+Replied\+To\+Event\+Handler\+Actor}. \subsection{Member Function Documentation} \mbox{\Hypertarget{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a9d843860260cd66f8354b9df234a1663_a9d843860260cd66f8354b9df234a1663}\label{classCqrs_1_1Akka_1_1Tests_1_1Unit_1_1Events_1_1Handlers_1_1HelloWorldRepliedToEventHandlerActor_a9d843860260cd66f8354b9df234a1663_a9d843860260cd66f8354b9df234a1663}} \index{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}!Handle@{Handle}} \index{Handle@{Handle}!Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor@{Cqrs\+::\+Akka\+::\+Tests\+::\+Unit\+::\+Events\+::\+Handlers\+::\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor}} \subsubsection{\texorpdfstring{Handle()}{Handle()}} {\footnotesize\ttfamily void Cqrs.\+Akka.\+Tests.\+Unit.\+Events.\+Handlers.\+Hello\+World\+Replied\+To\+Event\+Handler\+Actor.\+Handle (\begin{DoxyParamCaption}\item[{\hyperlink{<API key>}{Hello\+World\+Replied\+To}}]{message }\end{DoxyParamCaption})} Responds to the provided {\itshape message} . \begin{DoxyParams}{Parameters} {\em message} & The \hyperlink{<API key>}{Hello\+World\+Replied\+To} to respond to or \char`\"{}handle\char`\"{}\\ \hline \end{DoxyParams}
#include "qmlconsoleview.h" #include "<API key>.h" #include "qmlconsoleitemmodel.h" #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/manhattanstyle.h> #include <utils/hostosinfo.h> #include <QMouseEvent> #include <QPainter> #include <QApplication> #include <QClipboard> #include <QAbstractProxyModel> #include <QFileInfo> #include <QScrollBar> #include <QStyleFactory> #include <QString> #include <QUrl> using namespace QmlJS; namespace QmlJSTools { namespace Internal { class QmlConsoleViewStyle : public ManhattanStyle { public: QmlConsoleViewStyle(const QString &baseStyleName) : ManhattanStyle(baseStyleName) {} void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const { if (element != QStyle::PE_PanelItemViewRow) ManhattanStyle::drawPrimitive(element, option, painter, widget); } int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const { if (hint == <API key>) return 0; else return ManhattanStyle::styleHint(hint, option, widget, returnData); } }; // QmlConsoleView QmlConsoleView::QmlConsoleView(QWidget *parent) : Utils::TreeView(parent) { setFrameStyle(QFrame::NoFrame); setHeaderHidden(true); setRootIsDecorated(false); <API key>(true); setEditTriggers(QAbstractItemView::AllEditTriggers); setStyleSheet(QLatin1String("QTreeView::branch:has-siblings:!adjoins-item {" "border-image: none;" "image: none; }" "QTreeView::branch:has-siblings:adjoins-item {" "border-image: none;" "image: none; }" "QTreeView::branch:!has-children:!has-siblings:adjoins-item {" "border-image: none;" "image: none; }" "QTreeView::branch:has-children:!has-siblings:closed," "QTreeView::branch:closed:has-children:has-siblings {" "border-image: none;" "image: none; }" "QTreeView::branch:open:has-children:!has-siblings," "QTreeView::branch:open:has-children:has-siblings {" "border-image: none;" "image: none; }")); QString baseName = QApplication::style()->objectName(); if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost() && baseName == QLatin1String("windows")) { // Sometimes we get the standard windows 95 style as a fallback if (QStyleFactory::keys().contains(QLatin1String("Fusion"))) { baseName = QLatin1String("fusion"); // Qt5 } else { // Qt4 // e.g. if we are running on a KDE4 desktop QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION"); if (desktopEnvironment == "kde") baseName = QLatin1String("plastique"); else baseName = QLatin1String("cleanlooks"); } } QmlConsoleViewStyle *style = new QmlConsoleViewStyle(baseName); setStyle(style); style->setParent(this); <API key>(Qt::ScrollBarAlwaysOff); <API key>(Qt::ScrollBarAlwaysOn); <API key>(QAbstractItemView::ScrollPerPixel); horizontalScrollBar()->setSingleStep(20); verticalScrollBar()->setSingleStep(20); connect(this, SIGNAL(activated(QModelIndex)), SLOT(onRowActivated(QModelIndex))); } void QmlConsoleView::onScrollToBottom() { // Keep scrolling to bottom if scroll bar is not at maximum() if (verticalScrollBar()->value() != verticalScrollBar()->maximum()) scrollToBottom(); } void QmlConsoleView::mousePressEvent(QMouseEvent *event) { QPoint pos = event->pos(); QModelIndex index = indexAt(pos); if (index.isValid()) { ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data( QmlConsoleItemModel::TypeRole).toInt(); bool handled = false; if (type == ConsoleItem::UndefinedType) { bool showTypeIcon = index.parent() == QModelIndex(); <API key> positions(visualRect(index), viewOptions().font, showTypeIcon, true); if (positions.expandCollapseIcon().contains(pos)) { if (isExpanded(index)) setExpanded(index, false); else setExpanded(index, true); handled = true; } } if (!handled) Utils::TreeView::mousePressEvent(event); } else { selectionModel()->setCurrentIndex(model()->index(model()->rowCount() - 1, 0), QItemSelectionModel::ClearAndSelect); } } void QmlConsoleView::resizeEvent(QResizeEvent *e) { static_cast<<API key> *>(itemDelegate())->emitSizeHintChanged( selectionModel()->currentIndex()); Utils::TreeView::resizeEvent(e); } void QmlConsoleView::drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const { static_cast<<API key> *>(itemDelegate())->drawBackground(painter, rect, index, false); Utils::TreeView::drawBranches(painter, rect, index); } void QmlConsoleView::contextMenuEvent(QContextMenuEvent *event) { QModelIndex itemIndex = indexAt(event->pos()); QMenu menu; QAction *copy = new QAction(tr("&Copy"), this); copy->setEnabled(itemIndex.isValid()); menu.addAction(copy); QAction *show = new QAction(tr("&Show in Editor"), this); show->setEnabled(<API key>(itemIndex)); menu.addAction(show); menu.addSeparator(); QAction *clear = new QAction(tr("C&lear"), this); menu.addAction(clear); QAction *a = menu.exec(event->globalPos()); if (a == 0) return; if (a == copy) { copyToClipboard(itemIndex); } else if (a == show) { onRowActivated(itemIndex); } else if (a == clear) { QAbstractProxyModel *proxyModel = qobject_cast<QAbstractProxyModel *>(model()); QmlConsoleItemModel *handler = qobject_cast<QmlConsoleItemModel *>( proxyModel->sourceModel()); handler->clear(); } } void QmlConsoleView::onRowActivated(const QModelIndex &index) { if (!index.isValid()) return; // See if we have file and line Info QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString(); const QUrl fileUrl = QUrl(filePath); if (fileUrl.isLocalFile()) filePath = fileUrl.toLocalFile(); if (!filePath.isEmpty()) { QFileInfo fi(filePath); if (fi.exists() && fi.isFile() && fi.isReadable()) { int line = model()->data(index, QmlConsoleItemModel::LineRole).toInt(); Core::EditorManager::openEditorAt(fi.canonicalFilePath(), line); } } } void QmlConsoleView::copyToClipboard(const QModelIndex &index) { if (!index.isValid()) return; QString contents = model()->data(index, QmlConsoleItemModel::ExpressionRole).toString(); // See if we have file and line Info QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString(); const QUrl fileUrl = QUrl(filePath); if (fileUrl.isLocalFile()) filePath = fileUrl.toLocalFile(); if (!filePath.isEmpty()) { contents = QString::fromLatin1("%1 %2: %3").arg(contents).arg(filePath).arg( model()->data(index, QmlConsoleItemModel::LineRole).toString()); } QClipboard *cb = QApplication::clipboard(); cb->setText(contents); } bool QmlConsoleView::<API key>(const QModelIndex &index) { if (!index.isValid()) return false; // See if we have file and line Info QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString(); const QUrl fileUrl = QUrl(filePath); if (fileUrl.isLocalFile()) filePath = fileUrl.toLocalFile(); if (!filePath.isEmpty()) { QFileInfo fi(filePath); if (fi.exists() && fi.isFile() && fi.isReadable()) return true; } return false; } } // Internal } // QmlJSTools
/* Projeto: Biblioteca ZeusDFe */ /* Biblioteca C# para auxiliar no desenvolvimento das demais bibliotecas DFe */ /* Zeusdev Tecnologia LTDA ME */ /* Zeusdev Tecnologia LTDA ME - adenilton@zeusautomacao.com.br */ using System.Xml.Serialization; namespace DFe.Classes.Assinatura { public class Transform { <summary> XS13 - Atributos válidos Algorithm do Transform: <para>http: <para>http://www.w3.org/2000/09/xmldsig#enveloped-signature</para> </summary> [XmlAttribute] public string Algorithm { get; set; } } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LCOV - doc-coverage.info - Ninject/Azure/Cqrs.Ninject.Azure.BlobStorage/Configuration/<API key>.cs</title> <link rel="stylesheet" type="text/css" href="../../../../gcov.css"> </head> <body> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="title">LCOV - code coverage report</td></tr> <tr><td class="ruler"><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr> <tr> <td width="100%"> <table cellpadding=1 border=0 width="100%"> <tr> <td width="10%" class="headerItem">Current view:</td> <td width="35%" class="headerValue"><a href="../../../../index.html">top level</a> - <a href="index.html">Ninject/Azure/Cqrs.Ninject.Azure.BlobStorage/Configuration</a> - <API key>.cs</td> <td width="5%"></td> <td width="15%"></td> <td width="10%" class="headerCovTableHead">Hit</td> <td width="10%" class="headerCovTableHead">Total</td> <td width="15%" class="headerCovTableHead">Coverage</td> </tr> <tr> <td class="headerItem">Test:</td> <td class="headerValue">doc-coverage.info</td> <td></td> <td class="headerItem">Lines:</td> <td class="headerCovTableEntry">4</td> <td class="headerCovTableEntry">5</td> <td class="<API key>">80.0 %</td> </tr> <tr> <td class="headerItem">Date:</td> <td class="headerValue">2017-07-26</td> <td></td> </tr> <tr><td><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr> </table> </td> </tr> <tr><td class="ruler"><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr> </table> <table cellpadding=0 cellspacing=0 border=0> <tr> <td><br></td> </tr> <tr> <td> <pre class="sourceHeading"> Line data Source code</pre> <pre class="source"> <span class="lineNum"> 1 </span> : <span class="lineNum"> 2 </span> : <span class="lineNum"> 3 </span> : <span class="lineNum"> 4 </span> : <span class="lineNum"> 5 </span> : <span class="lineNum"> 6 </span> : <span class="lineNum"> 7 </span> : #endregion <span class="lineNum"> 8 </span> : <span class="lineNum"> 9 </span> : using Cqrs.Azure.BlobStorage.DataStores; <span class="lineNum"> 10 </span> : using Ninject.Modules; <span class="lineNum"> 11 </span> : <span class="lineNum"> 12 </span> : namespace Cqrs.Ninject.Azure.BlobStorage.Configuration <span class="lineNum"> 13 </span> : { <span class="lineNum"> 14 </span> : public class <API key> : NinjectModule <span class="lineNum"> 15 </span><span class="lineNoCov"> 0 : {</span> <span class="lineNum"> 16 </span> : #region Overrides of NinjectModule <span class="lineNum"> 17 </span> : <span class="lineNum"> 18 </span> : /// &lt;summary&gt; <span class="lineNum"> 19 </span> : /// Loads the module into the kernel. <span class="lineNum"> 20 </span> : /// &lt;/summary&gt; <span class="lineNum"> 21 </span><span class="lineCov"> 1 : public override void Load()</span> <span class="lineNum"> 22 </span> : { <span class="lineNum"> 23 </span> : RegisterFactories(); <span class="lineNum"> 24 </span> : RegisterServices(); <span class="lineNum"> 25 </span> : <API key>(); <span class="lineNum"> 26 </span> : } <span class="lineNum"> 27 </span> : <span class="lineNum"> 28 </span> : #endregion <span class="lineNum"> 29 </span> : <span class="lineNum"> 30 </span> : /// &lt;summary&gt; <span class="lineNum"> 31 </span> : /// Register the all services <span class="lineNum"> 32 </span> : /// &lt;/summary&gt; <span class="lineNum"> 33 </span><span class="lineCov"> 1 : public virtual void RegisterServices()</span> <span class="lineNum"> 34 </span> : { <span class="lineNum"> 35 </span> : } <span class="lineNum"> 36 </span> : <span class="lineNum"> 37 </span> : /// &lt;summary&gt; <span class="lineNum"> 38 </span> : /// Register the all factories <span class="lineNum"> 39 </span> : /// &lt;/summary&gt; <span class="lineNum"> 40 </span><span class="lineCov"> 1 : public virtual void RegisterFactories()</span> <span class="lineNum"> 41 </span> : { <span class="lineNum"> 42 </span> : Bind&lt;<API key>&gt;() <span class="lineNum"> 43 </span> : .To&lt;<API key>&gt;() <span class="lineNum"> 44 </span> : .InSingletonScope(); <span class="lineNum"> 45 </span> : } <span class="lineNum"> 46 </span> : <span class="lineNum"> 47 </span> : /// &lt;summary&gt; <span class="lineNum"> 48 </span> : /// Register the all Cqrs command handlers <span class="lineNum"> 49 </span> : /// &lt;/summary&gt; <span class="lineNum"> 50 </span><span class="lineCov"> 1 : public virtual void <API key>()</span> <span class="lineNum"> 51 </span> : { <span class="lineNum"> 52 </span> : } <span class="lineNum"> 53 </span> : } <span class="lineNum"> 54 </span> : } </pre> </td> </tr> </table> <br> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="ruler"><img src="../../../../glass.png" width=3 height=3 alt=""></td></tr> <tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.10</a></td></tr> </table> <br> </body> </html>
// This file is part of the deal.II library. // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // the top level of the deal.II distribution. // make sure only one processor finds a locally-owned cell around a point #include "../tests.h" #include "coarse_grid_common.h" #include <deal.II/base/logstream.h> #include <deal.II/base/tensor.h> #include <deal.II/grid/tria.h> #include <deal.II/distributed/tria.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_out.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/base/utilities.h> #include <fstream> template<int dim> void test() { unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); if (true) { if (Utilities::MPI::this_mpi_process (MPI_COMM_WORLD) == 0) deallog << "hyper_cube" << std::endl; parallel::distributed::Triangulation<dim> tr(MPI_COMM_WORLD); GridGenerator::hyper_cube(tr); tr.refine_global(2); // choose a point that is guaranteed to lie in the domain but not // at the interface between cells Point<dim> p; for (unsigned int d=0; d<dim; ++d) p[d] = 1./3; typename parallel::distributed::Triangulation<dim>::<API key> cell = GridTools::<API key> (tr, p); const unsigned int n_locally_owned = Utilities::MPI::sum (cell->is_locally_owned() ? 1 : 0, MPI_COMM_WORLD); const unsigned int <API key> = Utilities::MPI::sum (!cell->is_artificial() ? 1 : 0, MPI_COMM_WORLD); if (myid == 0) deallog << "Locally owned: " << n_locally_owned << std::endl << "Locally owned or ghost: " << <API key> << std::endl; } } int main(int argc, char *argv[]) { Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); deallog.push(Utilities::int_to_string(myid)); if (myid == 0) { std::ofstream logfile("output"); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); deallog.push("2d"); test<2>(); deallog.pop(); deallog.push("3d"); test<3>(); deallog.pop(); } else { test<2>(); test<3>(); } }
#include "qnamepool_p.h" #include "<API key>.h" QT_BEGIN_NAMESPACE using namespace QPatternist; <API key>::<API key>(const NamespaceResolver::Ptr &resolver) : m_nsResolver(resolver) { Q_ASSERT(m_nsResolver); } <API key>::<API key>(const NamespaceResolver::Ptr &ns, const Bindings &overrides) : m_nsResolver(ns) , m_bindings(overrides) { Q_ASSERT(m_nsResolver); } QXmlName::NamespaceCode <API key>::lookupNamespaceURI(const QXmlName::PrefixCode prefix) const { const QXmlName::NamespaceCode val(m_bindings.value(prefix, NoBinding)); if(val == NoBinding) return m_nsResolver->lookupNamespaceURI(prefix); else return val; } NamespaceResolver::Bindings <API key>::bindings() const { Bindings bs(m_nsResolver->bindings()); const Bindings::const_iterator end(m_bindings.constEnd()); Bindings::const_iterator it(m_bindings.constBegin()); for(; it != end; ++it) bs.insert(it.key(), it.value()); return bs; } void <API key>::addBinding(const QXmlName nb) { if(nb.namespaceURI() == StandardNamespaces::UndeclarePrefix) m_bindings.remove(nb.prefix()); else m_bindings.insert(nb.prefix(), nb.namespaceURI()); } QT_END_NAMESPACE
#ifndef H_RED_TIME #define H_RED_TIME #include <time.h> static inline uint64_t red_now(void) { struct timespec time; clock_gettime(CLOCK_MONOTONIC, &time); return ((uint64_t) time.tv_sec) * 1000000000 + time.tv_nsec; } #endif
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="../fast/js/resources/js-test-style.css"/> <script src="resources/audio-testing.js"></script> <script src="../fast/js/resources/js-test-pre.js"></script> <script src="resources/biquad-testing.js"></script> </head> <body> <div id="description"></div> <div id="console"></div> <script> description("Tests Biquad peaking filter."); function runTest() { if (window.testRunner) { testRunner.dumpAsText(); testRunner.waitUntilDone(); } window.jsTestIsAsync = true; // Create offline audio context. var context = new <API key>(2, sampleRate * renderLengthSeconds, sampleRate); // Dummy filter to get filter type constant var f = context.createBiquadFilter(); // The filters we want to test. var filterParameters = [{cutoff : 0, q : 10, gain : 10 }, {cutoff : 1, q : 10, gain : 10 }, {cutoff : .5, q : 0, gain : 10 }, {cutoff : 0.25, q : 10, gain : 10 }, ]; createTestAndRun(context, f.PEAKING, filterParameters); } runTest(); successfullyParsed = true; </script> <script src="../fast/js/resources/js-test-post.js"></script> </body> </html>
# <API key>: (Apache-2.0 OR MIT) from spack import * class Qnnpack(CMakePackage): """QNNPACK (Quantized Neural Networks PACKage) is a mobile-optimized library for low-precision high-performance neural network inference. QNNPACK provides implementation of common neural network operators on quantized 8-bit tensors.""" homepage = "https://github.com/pytorch/QNNPACK" git = "https://github.com/pytorch/QNNPACK.git" version('master', branch='master') version('2019-08-28', commit='<SHA1-like>') # py-torch@1.3:1.9 version('2018-12-27', commit='<SHA1-like>') # py-torch@1.2 version('2018-12-04', commit='<SHA1-like>') # py-torch@1.0:1.1 depends_on('cmake@3.5:', type='build') depends_on('ninja', type='build') depends_on('python', type='build') resource( name='cpuinfo', git='https://github.com/Maratyszcza/cpuinfo.git', destination='deps', placement='cpuinfo' ) resource( name='fp16', git='https://github.com/Maratyszcza/FP16.git', destination='deps', placement='fp16' ) resource( name='fxdiv', git='https://github.com/Maratyszcza/FXdiv.git', destination='deps', placement='fxdiv' ) resource( name='googlebenchmark', url='https://github.com/google/benchmark/archive/v1.4.1.zip', sha256='<SHA256-like>', destination='deps', placement='googlebenchmark', ) resource( name='googletest', url='https://github.com/google/googletest/archive/release-1.8.0.zip', sha256='<SHA256-like>', destination='deps', placement='googletest', ) resource( name='psimd', git='https://github.com/Maratyszcza/psimd.git', destination='deps', placement='psimd' ) resource( name='pthreadpool', git='https://github.com/Maratyszcza/pthreadpool.git', destination='deps', placement='pthreadpool' ) generator = 'Ninja' def cmake_args(self): return [ self.define('CPUINFO_SOURCE_DIR', join_path(self.stage.source_path, 'deps', 'cpuinfo')), self.define('FP16_SOURCE_DIR', join_path(self.stage.source_path, 'deps', 'fp16')), self.define('FXDIV_SOURCE_DIR', join_path(self.stage.source_path, 'deps', 'fxdiv')), self.define('PSIMD_SOURCE_DIR', join_path(self.stage.source_path, 'deps', 'psimd')), self.define('<API key>', join_path(self.stage.source_path, 'deps', 'pthreadpool')), self.define('<API key>', join_path(self.stage.source_path, 'deps', 'googlebenchmark')), self.define('<API key>', join_path(self.stage.source_path, 'deps', 'googletest')), ]
/* * nudgeunix.c: nudges a target Linux process * * XXX: share code with DRcontrol.c? */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stddef.h> #include <unistd.h> #include <sys/syscall.h> #include <assert.h> #include "configure.h" #include "globals_shared.h" extern bool <API key>(siginfo_t *info OUT, uint action_mask, client_id_t client_id, uint64 client_arg); static const char *usage_str = "usage: nudgeunix [-help] [-v] [-pid <pid>] [-type <type>] [-client <ID> <arg>]\n" " -help Display this usage information\n" " -v Display version information\n" " -pid <pid> Nudge the process with id <pid>\n" " -client <ID> <arg>\n" " Nudge the client with ID <ID> in the process specified\n" " with -pid <pid>, and pass <arg> as an argument to the\n" " client's nudge callback. <ID> must be the 8-digit hex\n" " ID of the target client. <arg> should be a hex\n" " literal (0, 1, 3f etc.).\n" " -type <type>\n" " Send a nudge of type <type> to the process specified\n" " with -pid <pid>. Type can be a numeric value or a\n" " symbolic name. This argument can be repeated.\n" " E.g., \"-type reset -type stats\".\n" ; static int usage(void) { fprintf(stderr, "%s", usage_str); return 1; } int main(int argc, const char *argv[]) { process_id_t target_pid = 0; uint action_mask = 0; client_id_t client_id = 0; uint64 client_arg = 0; int i; siginfo_t info; int arg_offs = 1; bool success; /* parse command line */ if (argc <= 1) return usage(); while (arg_offs < argc && argv[arg_offs][0] == '-') { if (strcmp(argv[arg_offs], "-help") == 0) { return usage(); } else if (strcmp(argv[arg_offs], "-v") == 0) { printf("nudgeunix version %s -- build %d\n", STRINGIFY(VERSION_NUMBER), BUILD_NUMBER); exit(0); } else if (strcmp(argv[arg_offs], "-pid") == 0) { if (argc <= arg_offs+1) return usage(); target_pid = strtoul(argv[arg_offs+1], NULL, 10); arg_offs += 2; } else if (strcmp(argv[arg_offs], "-client") == 0) { if (argc <= arg_offs+2) return usage(); action_mask |= NUDGE_GENERIC(client); client_id = strtoul(argv[arg_offs+1], NULL, 16); client_arg = strtoull(argv[arg_offs+2], NULL, 16); arg_offs += 3; } else if (strcmp(argv[arg_offs], "-type") == 0) { int type_numeric; if (argc <= arg_offs+1) return usage(); type_numeric = strtoul(argv[arg_offs+1], NULL, 10); action_mask |= type_numeric; /* compare against symbolic names */ { int found = 0; #define NUDGE_DEF(name, comment) \ if (strcmp(#name, argv[arg_offs+1]) == 0) { \ found = 1; \ action_mask |= NUDGE_GENERIC(name); \ } NUDGE_DEFINITIONS(); #undef NUDGE_DEF if (!found && type_numeric == 0) { fprintf(stderr, "ERROR: unknown -nudge %s\n", argv[arg_offs+1]); return usage(); } } arg_offs += 2; } else return usage(); } if (arg_offs < argc) return usage(); /* construct the payload */ success = <API key>(&info, action_mask, client_id, client_arg); assert(success); /* failure means kernel's sigqueueinfo has changed */ /* send the nudge */ i = syscall(SYS_rt_sigqueueinfo, target_pid, NUDGESIG_SIGNUM, &info); if (i < 0) fprintf(stderr, "nudge FAILED with error %d\n", i); return i; }
#ifndef <API key> #define <API key> // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif // boost/core/<API key>.hpp // <API key>, <API key>, <API key> // (glenjofe@gmail.com) #include <boost/core/lightweight_test.hpp> #include <boost/core/type_name.hpp> #include <boost/core/is_same.hpp> #include <boost/config.hpp> namespace boost { namespace detail { template< class T > inline void test_trait_impl( char const * trait, void (*)( T ), bool expected, char const * file, int line, char const * function ) { if( T::value == expected ) { test_results(); } else { <API key> << file << "(" << line << "): predicate '" << trait << "' [" << boost::core::type_name<T>() << "]" << " test failed in function '" << function << "' (should have been " << ( expected? "true": "false" ) << ")" << std::endl; ++test_results().errors(); } } template<class T> inline bool <API key>( T ) { return T::value; } template<class T1, class T2> inline void <API key>( char const * types, boost::core::is_same<T1, T2> same, char const * file, int line, char const * function ) { if( <API key>( same ) ) { test_results(); } else { <API key> << file << "(" << line << "): test 'is_same<" << types << ">'" << " failed in function '" << function << "' ('" << boost::core::type_name<T1>() << "' != '" << boost::core::type_name<T2>() << "')" << std::endl; ++test_results().errors(); } } } // namespace detail } // namespace boost #define <API key>(type) ( ::boost::detail::test_trait_impl(#type, (void(*)type)0, true, __FILE__, __LINE__, <API key>) ) #define <API key>(type) ( ::boost::detail::test_trait_impl(#type, (void(*)type)0, false, __FILE__, __LINE__, <API key>) ) #if defined(__GNUC__) // ignoring -Wvariadic-macros with #pragma doesn't work under GCC # pragma GCC system_header #endif #define <API key>(...) ( ::boost::detail::<API key>(#__VA_ARGS__, ::boost::core::is_same<__VA_ARGS__>(), __FILE__, __LINE__, <API key>) ) #endif // #ifndef <API key>
package org.auscope.portal.core.util; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.<API key>; import javax.xml.transform.<API key>; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.<API key>; import javax.xml.xpath.XPathFactory; import org.auscope.portal.core.test.PortalTestClass; import org.junit.Assert; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * Unit tests for DOMUtil * * @author Josh Vote * */ public class TestDOMUtil extends PortalTestClass { /** * Simple test to ensure that the 2 DOM util methods are reversible * @throws SAXException * @throws IOException * @throws <API key> * @throws <API key> */ @Test public void <API key>() throws <API key>, IOException, SAXException, <API key> { final String originalXmlString = ResourceUtil .<API key>("org/auscope/portal/core/test/xml/<API key>.xml"); final Document doc = DOMUtil.buildDomFromString(originalXmlString); final String newXmlString = DOMUtil.buildStringFromDom(doc, false); Assert.assertEquals(originalXmlString, newXmlString); } /** * Namespace for use with src/test/resources/<API key>.xml * * @author vot002 * */ public class SimpleXMLNamespace implements NamespaceContext { private Map<String, String> map; public SimpleXMLNamespace() { map = new HashMap<>(); map.put("test", "http://test.namespace"); map.put("test2", "http://test2.namespace"); } /** * This method returns the uri for all prefixes needed. * * @param prefix * @return uri */ @Override public String getNamespaceURI(final String prefix) { if (prefix == null) throw new <API key>("No prefix provided!"); if (map.containsKey(prefix)) return map.get(prefix); else return XMLConstants.NULL_NS_URI; } @Override public String getPrefix(final String namespaceURI) { // Not needed in this context. return null; } @Override public Iterator<String> getPrefixes(final String namespaceURI) { // Not needed in this context. return null; } } /** * Simple test to ensure that the DOM object is namespace aware * @throws <API key> * @throws IOException * @throws SAXException * @throws <API key> */ @Test public void <API key>() throws <API key>, IOException, <API key>, SAXException { //Build our DOM final String originalXmlString = ResourceUtil .<API key>("org/auscope/portal/core/test/xml/<API key>.xml"); final Document doc = DOMUtil.buildDomFromString(originalXmlString); //Build our queries (namespace aware) final XPathFactory factory = XPathFactory.newDefaultInstance(); final XPath xPath = factory.newXPath(); xPath.setNamespaceContext(new SimpleXMLNamespace()); final XPathExpression getChild1Expr = xPath.compile("test:root/test2:child1"); final XPathExpression getChild2Expr = xPath.compile("test:root/test2:child2"); final XPathExpression failingExpr = xPath.compile("root/child1"); Node testNode = (Node) getChild1Expr.evaluate(doc, XPathConstants.NODE); Assert.assertNotNull(testNode); Assert.assertEquals("child1Value", testNode.getTextContent()); testNode = (Node) getChild2Expr.evaluate(doc, XPathConstants.NODE); Assert.assertNotNull(testNode); Assert.assertEquals("child2Value", testNode.getTextContent()); //This should fail (no namespace specified) testNode = (Node) failingExpr.evaluate(doc, XPathConstants.NODE); Assert.assertNull(testNode); } }
import unittest from ctypes import * from struct import calcsize import _testcapi class SubclassesTest(unittest.TestCase): def test_subclass(self): class X(Structure): _fields_ = [("a", c_int)] class Y(X): _fields_ = [("b", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [("a", c_int)]) self.assertEqual(Y._fields_, [("b", c_int)]) self.assertEqual(Z._fields_, [("a", c_int)]) def <API key>(self): class X(Structure): pass self.assertEqual(sizeof(X), 0) X._fields_ = [("a", c_int)] class Y(X): pass self.assertEqual(sizeof(Y), sizeof(X)) Y._fields_ = [("b", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [("a", c_int)]) self.assertEqual(Y._fields_, [("b", c_int)]) self.assertEqual(Z._fields_, [("a", c_int)]) class StructureTestCase(unittest.TestCase): formats = {"c": c_char, "b": c_byte, "B": c_ubyte, "h": c_short, "H": c_ushort, "i": c_int, "I": c_uint, "l": c_long, "L": c_ulong, "q": c_longlong, "Q": c_ulonglong, "f": c_float, "d": c_double, } def test_simple_structs(self): for code, tp in self.formats.items(): class X(Structure): _fields_ = [("x", c_char), ("y", tp)] self.assertEqual((sizeof(X), code), (calcsize("c%c0%c" % (code, code)), code)) def test_unions(self): for code, tp in self.formats.items(): class X(Union): _fields_ = [("x", c_char), ("y", tp)] self.assertEqual((sizeof(X), code), (calcsize("%c" % (code)), code)) def <API key>(self): class X(Structure): _fields_ = [("x", c_char * 3)] self.assertEqual(alignment(X), calcsize("s")) self.assertEqual(sizeof(X), calcsize("3s")) class Y(Structure): _fields_ = [("x", c_char * 3), ("y", c_int)] self.assertEqual(alignment(Y), calcsize("i")) self.assertEqual(sizeof(Y), calcsize("3si")) class SI(Structure): _fields_ = [("a", X), ("b", Y)] self.assertEqual(alignment(SI), max(alignment(Y), alignment(X))) self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i")) class IS(Structure): _fields_ = [("b", Y), ("a", X)] self.assertEqual(alignment(SI), max(alignment(X), alignment(Y))) self.assertEqual(sizeof(IS), calcsize("3si 3s 0i")) class XX(Structure): _fields_ = [("a", X), ("b", X)] self.assertEqual(alignment(XX), alignment(X)) self.assertEqual(sizeof(XX), calcsize("3s 3s 0s")) def test_emtpy(self): # I had problems with these # Although these are patological cases: Empty Structures! class X(Structure): _fields_ = [] class Y(Union): _fields_ = [] # Is this really the correct alignment, or should it be 0? self.assertTrue(alignment(X) == alignment(Y) == 1) self.assertTrue(sizeof(X) == sizeof(Y) == 0) class XX(Structure): _fields_ = [("a", X), ("b", X)] self.assertEqual(alignment(XX), 1) self.assertEqual(sizeof(XX), 0) def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. class X(Structure): _fields_ = [("x", c_int), ("y", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, sizeof(c_int)) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92) class X(Union): _fields_ = [("x", c_int), ("y", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, 0) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92) # XXX Should we check nested data types also? # offset is always relative to the class... def test_packed(self): class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 1 self.assertEqual(sizeof(X), 9) self.assertEqual(X.b.offset, 1) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 2 self.assertEqual(sizeof(X), 10) self.assertEqual(X.b.offset, 2) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 4 self.assertEqual(sizeof(X), 12) self.assertEqual(X.b.offset, 4) import struct longlong_size = struct.calcsize("q") longlong_align = struct.calcsize("bq") - longlong_size class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 8 self.assertEqual(sizeof(X), longlong_align + longlong_size) self.assertEqual(X.b.offset, min(8, longlong_align)) d = {"_fields_": [("a", "b"), ("b", "q")], "_pack_": -1} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) # Issue 15989 d = {"_fields_": [("a", c_byte)], "_pack_": _testcapi.INT_MAX + 1} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) d = {"_fields_": [("a", c_byte)], "_pack_": _testcapi.UINT_MAX + 2} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) def test_initializers(self): class Person(Structure): _fields_ = [("name", c_char*6), ("age", c_int)] self.assertRaises(TypeError, Person, 42) self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj") self.assertRaises(TypeError, Person, "Name", "HI") # short enough self.assertEqual(Person(b"12345", 5).name, b"12345") # exact fit self.assertEqual(Person(b"123456", 5).name, b"123456") # too long self.assertRaises(ValueError, Person, b"1234567", 5) def <API key>(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] # conflicting positional and keyword args self.assertRaises(TypeError, POINT, 2, 3, x=4) self.assertRaises(TypeError, POINT, 2, 3, y=4) # too many initializers self.assertRaises(TypeError, POINT, 2, 3, 4) def <API key>(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] pt = POINT(1, 2) self.assertEqual((pt.x, pt.y), (1, 2)) pt = POINT(y=2, x=1) self.assertEqual((pt.x, pt.y), (1, 2)) def <API key>(self): class POINT(Structure): pass self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)]) def test_invalid_name(self): # field name must be string def declare_with_name(name): class S(Structure): _fields_ = [(name, c_int)] self.assertRaises(TypeError, declare_with_name, b"x") def <API key>(self): class SomeInts(Structure): _fields_ = [("a", c_int * 4)] # can use tuple to initialize array (but not list!) self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1]) self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0]) self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2]) self.assertEqual(SomeInts((1, 2)).a[6:4:-1], []) self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4]) self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4]) # too long # XXX Should raise ValueError?, not RuntimeError self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5)) def <API key>(self): # test initializing nested structures class Phone(Structure): _fields_ = [("areacode", c_char*6), ("number", c_char*12)] class Person(Structure): _fields_ = [("name", c_char * 12), ("phone", Phone), ("age", c_int)] p = Person(b"Someone", (b"1234", b"5678"), 5) self.assertEqual(p.name, b"Someone") self.assertEqual(p.phone.areacode, b"1234") self.assertEqual(p.phone.number, b"5678") self.assertEqual(p.age, 5) def <API key>(self): try: c_wchar except NameError: return # no unicode class PersonW(Structure): _fields_ = [("name", c_wchar * 12), ("age", c_int)] p = PersonW("Someone \xe9") self.assertEqual(p.name, "Someone \xe9") self.assertEqual(PersonW("1234567890").name, "1234567890") self.assertEqual(PersonW("12345678901").name, "12345678901") # exact fit self.assertEqual(PersonW("123456789012").name, "123456789012") #too long self.assertRaises(ValueError, PersonW, "1234567890123") def test_init_errors(self): class Phone(Structure): _fields_ = [("areacode", c_char*6), ("number", c_char*12)] class Person(Structure): _fields_ = [("name", c_char * 12), ("phone", Phone), ("age", c_int)] cls, msg = self.get_except(Person, b"Someone", (1, 2)) self.assertEqual(cls, RuntimeError) self.assertEqual(msg, "(Phone) <class 'TypeError'>: " "expected string, int found") cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c")) self.assertEqual(cls, RuntimeError) if issubclass(Exception, object): self.assertEqual(msg, "(Phone) <class 'TypeError'>: too many initializers") else: self.assertEqual(msg, "(Phone) TypeError: too many initializers") def <API key>(self): # issue12881: segfault with large structure field names def create_class(length): class S(Structure): _fields_ = [('x' * length, c_int)] for length in [10 ** i for i in range(0, 8)]: try: create_class(length) except MemoryError: # MemoryErrors are OK, we just don't want to segfault pass def get_except(self, func, *args): try: func(*args) except Exception as detail: return detail.__class__, str(detail) ## def <API key>(self): ## meta = type(Structure) ## # same as 'class X(Structure): pass' ## # fails, since we need either a _fields_ or a _abstract_ attribute ## cls, msg = self.get_except(meta, "X", (Structure,), {}) ## self.assertEqual((cls, msg), ## (AttributeError, "class must define a '_fields_' attribute")) def test_abstract_class(self): class X(Structure): _abstract_ = "something" # try 'X()' cls, msg = self.get_except(eval, "X()", locals()) self.assertEqual((cls, msg), (TypeError, "abstract class")) def test_methods(self): ## class X(Structure): ## _fields_ = [] self.assertTrue("in_dll" in dir(type(Structure))) self.assertTrue("from_address" in dir(type(Structure))) self.assertTrue("in_dll" in dir(type(Structure))) def <API key>(self): class W(Structure): _fields_ = [("a", c_int), ("b", c_int)] class X(W): _fields_ = [("c", c_int)] class Y(X): pass class Z(Y): _fields_ = [("d", c_int), ("e", c_int), ("f", c_int)] z = Z(1, 2, 3, 4, 5, 6) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 2, 3, 4, 5, 6)) z = Z(1) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 0, 0, 0, 0, 0)) self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7)) class <API key>(unittest.TestCase): def test(self): # a Structure with a POINTER field class S(Structure): _fields_ = [("array", POINTER(c_int))] s = S() # We can assign arrays of the correct type s.array = (c_int * 3)(1, 2, 3) items = [s.array[i] for i in range(3)] self.assertEqual(items, [1, 2, 3]) # The following are bugs, but are included here because the unittests # also describe the current behaviour. # This fails with SystemError: bad arg to internal function # or with IndexError (with a patch I have) s.array[0] = 42 items = [s.array[i] for i in range(3)] self.assertEqual(items, [42, 2, 3]) s.array[0] = 1 ## s.array[1] = 42 items = [s.array[i] for i in range(3)] self.assertEqual(items, [1, 2, 3]) def <API key>(self): class S(Structure): _fields_ = [("x", c_int), ("p", POINTER(c_int))] s = S() s.x = 12345678 s.p = None self.assertEqual(s.x, 12345678) class <API key>(unittest.TestCase): def <API key>(self): class Recursive(Structure): pass try: Recursive._fields_ = [("next", Recursive)] except AttributeError as details: self.assertTrue("Structure or union cannot contain itself" in str(details)) else: self.fail("Structure or union cannot contain itself") def test_vice_versa(self): class First(Structure): pass class Second(Structure): pass First._fields_ = [("second", Second)] try: Second._fields_ = [("first", First)] except AttributeError as details: self.assertTrue("_fields_ is final" in str(details)) else: self.fail("AttributeError not raised") if __name__ == '__main__': unittest.main()
package debugstatus_test import ( "encoding/json" "net/http" jc "github.com/juju/testing/checkers" "github.com/juju/testing/httptesting" "github.com/juju/utils/debugstatus" "github.com/julienschmidt/httprouter" gc "gopkg.in/check.v1" "gopkg.in/errgo.v1" "github.com/juju/httprequest" ) var errorMapper httprequest.ErrorMapper = func(err error) (httpStatus int, errorBody interface{}) { return http.<API key>, httprequest.RemoteError{ Message: err.Error(), } } type handlerSuite struct { } var _ = gc.Suite(&handlerSuite{}) var errUnauthorized = errgo.New("you shall not pass!") func newHTTPHandler(h *debugstatus.Handler) http.Handler { errMapper := httprequest.ErrorMapper(func(err error) (httpStatus int, errorBody interface{}) { code, status := "", http.<API key> switch errgo.Cause(err) { case errUnauthorized: code, status = "unauthorized", http.StatusUnauthorized case debugstatus.<API key>: code, status = "forbidden", http.StatusForbidden case debugstatus.<API key>: code, status = "forbidden", http.StatusForbidden } return status, httprequest.RemoteError{ Code: code, Message: err.Error(), } }) handlers := errMapper.Handlers(func(httprequest.Params) (*debugstatus.Handler, error) { return h, nil }) r := httprouter.New() for _, h := range handlers { r.Handle(h.Method, h.Path, h.Handle) } return r } func (s *handlerSuite) <API key>(c *gc.C) { httpHandler := newHTTPHandler(&debugstatus.Handler{ Check: func() map[string]debugstatus.CheckResult { return debugstatus.Check(debugstatus.ServerStartTime) }, }) httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: httpHandler, URL: "/debug/status", ExpectBody: httptesting.BodyAsserter(func(c *gc.C, body json.RawMessage) { var result map[string]debugstatus.CheckResult err := json.Unmarshal(body, &result) c.Assert(err, gc.IsNil) for k, v := range result { v.Duration = 0 result[k] = v } c.Assert(result, jc.DeepEquals, map[string]debugstatus.CheckResult{ "server_started": { Name: "Server started", Value: debugstatus.StartTime.String(), Passed: true, }, }) }), }) } func (s *handlerSuite) <API key>(c *gc.C) { httpHandler := newHTTPHandler(&debugstatus.Handler{}) httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: httpHandler, URL: "/debug/status", ExpectBody: map[string]debugstatus.CheckResult{}, }) } func (s *handlerSuite) TestServeDebugInfo(c *gc.C) { version := debugstatus.Version{ GitCommit: "some-git-status", Version: "a-version", } httpHandler := newHTTPHandler(&debugstatus.Handler{ Version: version, }) httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: httpHandler, URL: "/debug/info", ExpectStatus: http.StatusOK, ExpectBody: version, }) } var debugPprofPaths = []string{ "/debug/pprof/", "/debug/pprof/cmdline", "/debug/pprof/profile?seconds=1", "/debug/pprof/symbol", "/debug/pprof/goroutine", } func (s *handlerSuite) TestServeDebugPprof(c *gc.C) { httpHandler := newHTTPHandler(&debugstatus.Handler{ CheckPprofAllowed: func(req *http.Request) error { if req.Header.Get("Authorization") == "" { return errUnauthorized } return nil }, }) authHeader := make(http.Header) authHeader.Set("Authorization", "let me in") for i, path := range debugPprofPaths { c.Logf("%d. %s", i, path) httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: httpHandler, URL: path, ExpectStatus: http.StatusUnauthorized, ExpectBody: httprequest.RemoteError{ Code: "unauthorized", Message: "you shall not pass!", }, }) rr := httptesting.DoRequest(c, httptesting.DoRequestParams{ Handler: httpHandler, URL: path, Header: authHeader, }) c.Assert(rr.Code, gc.Equals, http.StatusOK) } } func (s *handlerSuite) <API key>(c *gc.C) { httpHandler := newHTTPHandler(&debugstatus.Handler{}) httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: httpHandler, URL: "/debug/pprof/", ExpectStatus: http.StatusForbidden, ExpectBody: httprequest.RemoteError{ Code: "forbidden", Message: "no pprof access configured", }, }) } var debugTracePaths = []string{ "/debug/events", "/debug/requests", } func (s *handlerSuite) <API key>(c *gc.C) { httpHandler := newHTTPHandler(&debugstatus.Handler{ CheckTraceAllowed: func(req *http.Request) (bool, error) { if req.Header.Get("Authorization") == "" { return false, errUnauthorized } return false, nil }, }) authHeader := make(http.Header) authHeader.Set("Authorization", "let me in") for i, path := range debugTracePaths { c.Logf("%d. %s", i, path) httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: httpHandler, URL: path, ExpectStatus: http.StatusUnauthorized, ExpectBody: httprequest.RemoteError{ Code: "unauthorized", Message: "you shall not pass!", }, }) rr := httptesting.DoRequest(c, httptesting.DoRequestParams{ Handler: httpHandler, URL: path, Header: authHeader, }) c.Assert(rr.Code, gc.Equals, http.StatusOK) } } func (s *handlerSuite) <API key>(c *gc.C) { httpHandler := newHTTPHandler(&debugstatus.Handler{}) httptesting.AssertJSONCall(c, httptesting.JSONCallParams{ Handler: httpHandler, URL: "/debug/events", ExpectStatus: http.StatusForbidden, ExpectBody: httprequest.RemoteError{ Code: "forbidden", Message: "no trace access configured", }, }) }
package org.auscope.portal.core.services.responses.vocab; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.parsers.<API key>; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathException; import org.auscope.portal.core.services.namespaces.<API key>; import org.auscope.portal.core.test.PortalTestClass; import org.auscope.portal.core.util.DOMUtil; import org.auscope.portal.core.util.ResourceUtil; import org.junit.Assert; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * Unit tests for ConceptFactory * * @author Josh Vote * */ public class TestConceptFactory extends PortalTestClass { private void assertSameConcept(Concept[] expected, Concept[] actual, List<String> traversedUrns) { String errMsg = String.format("%1$s != %2$s", Arrays.toString(expected), Arrays.toString(actual)); Assert.assertArrayEquals(errMsg, expected, actual); for (int i = 0; i < expected.length; i++) { assertSameConcept(expected[i], actual[i], traversedUrns); } } private void assertSameConcept(Concept expected, Concept actual, List<String> traversedUrns) { String errMsg = String.format("%1$s != %2$s", expected, actual); Assert.assertEquals(errMsg, expected, actual); Assert.assertEquals(errMsg, expected.getLabel(), actual.getLabel()); Assert.assertEquals(errMsg, expected.getPreferredLabel(), actual.getPreferredLabel()); Assert.assertEquals(errMsg, expected.isHref(), actual.isHref()); Assert.assertEquals(errMsg, expected.getDefinition(), actual.getDefinition()); //To deal with cycles in the hierarchy if (traversedUrns.contains(expected.getUrn())) { return; } else { traversedUrns.add(expected.getUrn()); } assertSameConcept(expected.getBroader(), actual.getBroader(), traversedUrns); assertSameConcept(expected.getNarrower(), actual.getNarrower(), traversedUrns); assertSameConcept(expected.getRelated(), actual.getRelated(), traversedUrns); } /** * Runs the factory through a standard SISSVoc response XML * @throws IOException * @throws SAXException * @throws <API key> * @throws XPathException */ @Test public void testSISSVocRDF() throws IOException, <API key>, SAXException, XPathException { //Build our expectation Concept concept1 = new Concept("urn:concept:1"); Concept concept2 = new Concept("urn:concept:2"); Concept concept3 = new Concept("urn:concept:3"); Concept concept4 = new Concept("urn:concept:4"); NamedIndividual ni1 = new NamedIndividual("urn:ni:1"); NamedIndividual ni2 = new NamedIndividual("urn:ni:2"); NamedIndividual ni3 = new NamedIndividual("urn:ni:3"); concept1.setNarrower(new Concept[] {concept2, concept3, ni2}); concept1.setLabel("LabelConcept1"); concept1.setPreferredLabel("PrefLabelConcept1"); concept2.setBroader(new Concept[] {concept1}); concept2.setRelated(new Concept[] {concept3}); concept2.setLabel("LabelConcept2"); concept2.setPreferredLabel("PrefLabelConcept2"); concept2.setDefinition("DefinitionConcept2"); concept3.setBroader(new Concept[] {concept1}); concept3.setRelated(new Concept[] {concept2}); concept3.setNarrower(new Concept[] {ni1}); concept3.setLabel("LabelConcept3"); concept3.setPreferredLabel("PrefLabelConcept3"); concept4.setNarrower(new Concept[] {ni3}); concept4.setLabel("LabelConcept4"); concept4.setPreferredLabel("PrefLabelConcept4"); concept4.setDefinition("DefinitionConcept4"); ni1.setBroader(new Concept[] {concept3}); ni1.setLabel("<API key>"); ni1.setPreferredLabel("<API key>"); ni2.setBroader(new Concept[] {concept1}); ni2.setLabel("<API key>"); ni2.setPreferredLabel("<API key>"); ni3.setBroader(new Concept[] {concept4}); ni3.setLabel("<API key>"); ni3.setPreferredLabel("<API key>"); Concept[] expectation = new Concept[] {concept1, concept4}; //Build our actual list String responseXml = ResourceUtil .<API key>("org/auscope/portal/core/test/responses/sissvoc/SISSVocResponse.xml"); Document responseDoc = DOMUtil.buildDomFromString(responseXml); Node rdfNode = (Node) DOMUtil.compileXPathExpr("rdf:RDF", new <API key>()).evaluate(responseDoc, XPathConstants.NODE); ConceptFactory cf = new ConceptFactory(); Concept[] actualConcepts = cf.parseFromRDF(rdfNode); Assert.assertNotNull(actualConcepts); assertSameConcept(expectation, actualConcepts, new ArrayList<String>()); } /** * This is a legacy test for the older <API key>.xml * * It tests our concepts still return EVEN if we don't define top level concepts * @throws IOException * @throws SAXException * @throws <API key> * @throws XPathException */ @Test public void testGetConcepts() throws IOException, <API key>, SAXException, XPathException { String responseXml = ResourceUtil .<API key>("org/auscope/portal/core/test/responses/sissvoc/<API key>.xml"); Document responseDoc = DOMUtil.buildDomFromString(responseXml); Node rdfNode = (Node) DOMUtil.compileXPathExpr("rdf:RDF", new <API key>()).evaluate(responseDoc, XPathConstants.NODE); ConceptFactory cf = new ConceptFactory(); Concept[] actualConcepts = cf.parseFromRDF(rdfNode); Assert.assertEquals("There are 27 concepts", 27, actualConcepts.length); //Must contain: Siltstone - concrete aggregate boolean found = false; for (Concept concept : actualConcepts) { if (concept.getPreferredLabel().equals("Siltstone - concrete aggregate")) { found = true; break; } } Assert.assertTrue("Must contain: Siltstone - concrete aggregate", found); //Must contain: Gneiss - crusher dust found = false; for (Concept concept : actualConcepts) { if (concept.getPreferredLabel().equals("Gneiss - crusher dust")) { found = true; break; } } Assert.assertTrue("Must contain: Gneiss - crusher dust", found); } }
// obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // included in all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Schema { internal class JsonSchemaWriter { private readonly JsonWriter _writer; private readonly JsonSchemaResolver _resolver; public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver) { ValidationUtils.ArgumentNotNull(writer, "writer"); _writer = writer; _resolver = resolver; } private void <API key>(JsonSchema schema) { if (schema.Id != null && _resolver.GetSchema(schema.Id) != null) { _writer.WriteStartObject(); _writer.WritePropertyName(JsonSchemaConstants.<API key>); _writer.WriteValue(schema.Id); _writer.WriteEndObject(); } else { WriteSchema(schema); } } public void WriteSchema(JsonSchema schema) { ValidationUtils.ArgumentNotNull(schema, "schema"); if (!_resolver.LoadedSchemas.Contains(schema)) _resolver.LoadedSchemas.Add(schema); _writer.WriteStartObject(); <API key>(_writer, JsonSchemaConstants.IdPropertyName, schema.Id); <API key>(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title); <API key>(_writer, JsonSchemaConstants.<API key>, schema.Description); <API key>(_writer, JsonSchemaConstants.<API key>, schema.Optional); <API key>(_writer, JsonSchemaConstants.<API key>, schema.ReadOnly); <API key>(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden); <API key>(_writer, JsonSchemaConstants.<API key>, schema.Transient); if (schema.Type != null) WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value); if (!schema.<API key>) { _writer.WritePropertyName(JsonSchemaConstants.<API key>); _writer.WriteValue(schema.<API key>); } else { if (schema.<API key> != null) { _writer.WritePropertyName(JsonSchemaConstants.<API key>); <API key>(schema.<API key>); } } if (schema.Properties != null) { _writer.WritePropertyName(JsonSchemaConstants.<API key>); _writer.WriteStartObject(); foreach (KeyValuePair<string, JsonSchema> property in schema.Properties) { _writer.WritePropertyName(property.Key); <API key>(property.Value); } _writer.WriteEndObject(); } WriteItems(schema); <API key>(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum); <API key>(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum); <API key>(_writer, JsonSchemaConstants.<API key>, schema.MinimumLength); <API key>(_writer, JsonSchemaConstants.<API key>, schema.MaximumLength); <API key>(_writer, JsonSchemaConstants.<API key>, schema.MinimumItems); <API key>(_writer, JsonSchemaConstants.<API key>, schema.MaximumItems); <API key>(_writer, JsonSchemaConstants.<API key>, schema.MaximumDecimals); <API key>(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format); <API key>(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern); if (schema.Enum != null) { _writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName); _writer.WriteStartArray(); foreach (JToken token in schema.Enum) { token.WriteTo(_writer); } _writer.WriteEndArray(); } if (schema.Default != null) { _writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName); schema.Default.WriteTo(_writer); } if (schema.Options != null) { _writer.WritePropertyName(JsonSchemaConstants.OptionsPropertyName); _writer.WriteStartArray(); foreach (KeyValuePair<JToken, string> option in schema.Options) { _writer.WriteStartObject(); _writer.WritePropertyName(JsonSchemaConstants.<API key>); option.Key.WriteTo(_writer); if (option.Value != null) { _writer.WritePropertyName(JsonSchemaConstants.<API key>); _writer.WriteValue(option.Value); } _writer.WriteEndObject(); } _writer.WriteEndArray(); } if (schema.Disallow != null) WriteType(JsonSchemaConstants.<API key>, _writer, schema.Disallow.Value); if (schema.Extends != null) { _writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName); <API key>(schema.Extends); } _writer.WriteEndObject(); } private void WriteItems(JsonSchema schema) { if (CollectionUtils.IsNullOrEmpty(schema.Items)) return; _writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName); if (schema.Items.Count == 1) { <API key>(schema.Items[0]); return; } _writer.WriteStartArray(); foreach (JsonSchema itemSchema in schema.Items) { <API key>(itemSchema); } _writer.WriteEndArray(); } private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type) { IList<JsonSchemaType> types; if (System.Enum.IsDefined(typeof(JsonSchemaType), type)) types = new List<JsonSchemaType> { type }; else types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList(); if (types.Count == 0) return; writer.WritePropertyName(propertyName); if (types.Count == 1) { writer.WriteValue(JsonSchemaBuilder.MapType(types[0])); return; } writer.WriteStartArray(); foreach (JsonSchemaType jsonSchemaType in types) { writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType)); } writer.WriteEndArray(); } private void <API key>(JsonWriter writer, string propertyName, object value) { if (value != null) { writer.WritePropertyName(propertyName); writer.WriteValue(value); } } } }
package org.fnlp.util.exception; import java.io.<API key>; import java.io.IOException; public class LoadModelException extends Exception { private static final long serialVersionUID = -<API key>; public LoadModelException(Exception e, String file) { super(e); if( e instanceof <API key>) { System.out.println(" "+ file); } else if (e instanceof <API key>) { System.out.println(""); } else if (e instanceof IOException) { System.out.println(" "+file); } e.printStackTrace(); } public LoadModelException(String msg) { super(msg); printStackTrace(); } }
// a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // included in all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // System.Runtime.InteropServices/DESCKIND.cs // Paolo Molaro (lupus@ximian.com) using System; namespace System.Runtime.InteropServices { [Obsolete] [Serializable] public enum DESCKIND { DESCKIND_NONE = 0, DESCKIND_FUNCDESC = 1, DESCKIND_VARDESC = 2, DESCKIND_TYPECOMP = 3, <API key> = 4, DESCKIND_MAX = 5 } }
namespace StockSharp.Algo.Export { using System; using System.Collections.Generic; using System.Linq; using System.Xml; using Ecng.Common; using StockSharp.BusinessEntities; using StockSharp.Messages; <summary> Ýêñïîðò â xml. </summary> public class XmlExporter : BaseExporter { private const string _timeFormat = "yyyy-MM-dd HH:mm:ss.fff zzz"; <summary> Ñîçäàòü <see cref="XmlExporter"/>. </summary> <param name="security">Èíñòðóìåíò.</param> <param name="arg">Ïàðàìåòð äàííûõ.</param> <param name="isCancelled">Îáðàáîò÷èê, âîçâðàùàþùèé ïðèçíàê ïðåðûâàíèÿ ýêñïîðòà.</param> <param name="fileName">Ïóòü ê ôàéëó.</param> public XmlExporter(Security security, object arg, Func<int, bool> isCancelled, string fileName) : base(security, arg, isCancelled, fileName) { } <summary> Ýêñïîðòèðîâàòü <see cref="ExecutionMessage"/>. </summary> <param name="messages">Ñîîáùåíèÿ.</param> protected override void Export(IEnumerable<ExecutionMessage> messages) { switch ((ExecutionTypes)Arg) { case ExecutionTypes.Tick: { Do(messages, "trades", (writer, trade) => { writer.WriteStartElement("trade"); writer.WriteAttribute("id", trade.TradeId == null ? trade.TradeStringId : trade.TradeId.To<string>()); writer.WriteAttribute("serverTime", trade.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", trade.LocalTime.ToString(_timeFormat)); writer.WriteAttribute("price", trade.TradePrice); writer.WriteAttribute("volume", trade.Volume); if (trade.OriginSide != null) writer.WriteAttribute("originSide", trade.OriginSide.Value); if (trade.OpenInterest != null) writer.WriteAttribute("openInterest", trade.OpenInterest.Value); if (trade.IsUpTick != null) writer.WriteAttribute("isUpTick", trade.IsUpTick.Value); writer.WriteEndElement(); }); break; } case ExecutionTypes.OrderLog: { Do(messages, "orderLog", (writer, item) => { writer.WriteStartElement("item"); writer.WriteAttribute("id", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>()); writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat)); writer.WriteAttribute("price", item.Price); writer.WriteAttribute("volume", item.Volume); writer.WriteAttribute("side", item.Side); writer.WriteAttribute("state", item.OrderState); writer.WriteAttribute("timeInForce", item.TimeInForce); writer.WriteAttribute("isSystem", item.IsSystem); if (item.TradePrice != null) { writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>()); writer.WriteAttribute("tradePrice", item.TradePrice); if (item.OpenInterest != null) writer.WriteAttribute("openInterest", item.OpenInterest.Value); } writer.WriteEndElement(); }); break; } case ExecutionTypes.Order: case ExecutionTypes.Trade: { Do(messages, "executions", (writer, item) => { writer.WriteStartElement("item"); writer.WriteAttribute("serverTime", item.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", item.LocalTime.ToString(_timeFormat)); writer.WriteAttribute("portfolio", item.PortfolioName); writer.WriteAttribute("transactionId", item.TransactionId); writer.WriteAttribute("id", item.OrderId == null ? item.OrderStringId : item.OrderId.To<string>()); writer.WriteAttribute("price", item.Price); writer.WriteAttribute("volume", item.Volume); writer.WriteAttribute("balance", item.Balance); writer.WriteAttribute("side", item.Side); writer.WriteAttribute("type", item.OrderType); writer.WriteAttribute("state", item.OrderState); writer.WriteAttribute("tradeId", item.TradeId == null ? item.TradeStringId : item.TradeId.To<string>()); writer.WriteAttribute("tradePrice", item.TradePrice); writer.WriteEndElement(); }); break; } default: throw new <API key>(); } } <summary> Ýêñïîðòèðîâàòü <see cref="QuoteChangeMessage"/>. </summary> <param name="messages">Ñîîáùåíèÿ.</param> protected override void Export(IEnumerable<QuoteChangeMessage> messages) { Do(messages, "depths", (writer, depth) => { writer.WriteStartElement("depth"); writer.WriteAttribute("serverTime", depth.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", depth.LocalTime.ToString(_timeFormat)); foreach (var quote in depth.Bids.Concat(depth.Asks).OrderByDescending(q => q.Price)) { writer.WriteStartElement("quote"); writer.WriteAttribute("price", quote.Price); writer.WriteAttribute("volume", quote.Volume); writer.WriteAttribute("side", quote.Side); writer.WriteEndElement(); } writer.WriteEndElement(); }); } <summary> Ýêñïîðòèðîâàòü <see cref="Level1ChangeMessage"/>. </summary> <param name="messages">Ñîîáùåíèÿ.</param> protected override void Export(IEnumerable<Level1ChangeMessage> messages) { Do(messages, "messages", (writer, message) => { writer.WriteStartElement("message"); writer.WriteAttribute("serverTime", message.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", message.LocalTime.ToString(_timeFormat)); foreach (var pair in message.Changes) writer.WriteAttribute(pair.Key.ToString(), pair.Value is DateTime ? ((DateTime)pair.Value).ToString(_timeFormat) : pair.Value); writer.WriteEndElement(); }); } <summary> Ýêñïîðòèðîâàòü <see cref="CandleMessage"/>. </summary> <param name="messages">Ñîîáùåíèÿ.</param> protected override void Export(IEnumerable<CandleMessage> messages) { Do(messages, "candles", (writer, candle) => { writer.WriteStartElement("candle"); writer.WriteAttribute("openTime", candle.OpenTime.ToString(_timeFormat)); writer.WriteAttribute("closeTime", candle.CloseTime.ToString(_timeFormat)); writer.WriteAttribute("O", candle.OpenPrice); writer.WriteAttribute("H", candle.HighPrice); writer.WriteAttribute("L", candle.LowPrice); writer.WriteAttribute("C", candle.ClosePrice); writer.WriteAttribute("V", candle.TotalVolume); if (candle.OpenInterest != null) writer.WriteAttribute("openInterest", candle.OpenInterest.Value); writer.WriteEndElement(); }); } <summary> Ýêñïîðòèðîâàòü <see cref="NewsMessage"/>. </summary> <param name="messages">Ñîîáùåíèÿ.</param> protected override void Export(IEnumerable<NewsMessage> messages) { Do(messages, "news", (writer, n) => { writer.WriteStartElement("item"); if (!n.Id.IsEmpty()) writer.WriteAttribute("id", n.Id); writer.WriteAttribute("serverTime", n.ServerTime.ToString(_timeFormat)); writer.WriteAttribute("localTime", n.LocalTime.ToString(_timeFormat)); if (n.SecurityId != null) writer.WriteAttribute("securityCode", n.SecurityId.Value.SecurityCode); if (!n.BoardCode.IsEmpty()) writer.WriteAttribute("boardCode", n.BoardCode); writer.WriteAttribute("headline", n.Headline); if (!n.Source.IsEmpty()) writer.WriteAttribute("source", n.Source); if (n.Url != null) writer.WriteAttribute("board", n.Url); if (!n.Story.IsEmpty()) writer.WriteCData(n.Story); writer.WriteEndElement(); }); } <summary> Ýêñïîðòèðîâàòü <see cref="SecurityMessage"/>. </summary> <param name="messages">Ñîîáùåíèÿ.</param> protected override void Export(IEnumerable<SecurityMessage> messages) { Do(messages, "securities", (writer, security) => { writer.WriteStartElement("security"); writer.WriteAttribute("code", security.SecurityId.SecurityCode); writer.WriteAttribute("board", security.SecurityId.BoardCode); if (!security.Name.IsEmpty()) writer.WriteAttribute("name", security.Name); if (!security.ShortName.IsEmpty()) writer.WriteAttribute("shortName", security.ShortName); if (security.PriceStep != null) writer.WriteAttribute("priceStep", security.PriceStep.Value); if (security.VolumeStep != null) writer.WriteAttribute("volumeStep", security.VolumeStep.Value); if (security.Multiplier != null) writer.WriteAttribute("multiplier", security.Multiplier.Value); if (security.Decimals != null) writer.WriteAttribute("decimals", security.Decimals.Value); if (security.Currency != null) writer.WriteAttribute("currency", security.Currency.Value); if (security.SecurityType != null) writer.WriteAttribute("type", security.SecurityType.Value); if (security.OptionType != null) writer.WriteAttribute("optionType", security.OptionType.Value); if (security.Strike != null) writer.WriteAttribute("strike", security.Strike.Value); if (!security.BinaryOptionType.IsEmpty()) writer.WriteAttribute("binaryOptionType", security.BinaryOptionType); if (!security.<API key>.IsEmpty()) writer.WriteAttribute("<API key>", security.<API key>); if (security.ExpiryDate != null) writer.WriteAttribute("expiryDate", security.ExpiryDate.Value.ToString("yyyy-MM-dd")); if (security.SettlementDate != null) writer.WriteAttribute("settlementDate", security.SettlementDate.Value.ToString("yyyy-MM-dd")); if (!security.SecurityId.Bloomberg.IsEmpty()) writer.WriteAttribute("bloomberg", security.SecurityId.Bloomberg); if (!security.SecurityId.Cusip.IsEmpty()) writer.WriteAttribute("cusip", security.SecurityId.Cusip); if (!security.SecurityId.IQFeed.IsEmpty()) writer.WriteAttribute("iqfeed", security.SecurityId.IQFeed); if (security.SecurityId.InteractiveBrokers != null) writer.WriteAttribute("ib", security.SecurityId.InteractiveBrokers); if (!security.SecurityId.Isin.IsEmpty()) writer.WriteAttribute("isin", security.SecurityId.Isin); if (!security.SecurityId.Plaza.IsEmpty()) writer.WriteAttribute("plaza", security.SecurityId.Plaza); if (!security.SecurityId.Ric.IsEmpty()) writer.WriteAttribute("ric", security.SecurityId.Ric); if (!security.SecurityId.Sedol.IsEmpty()) writer.WriteAttribute("sedol", security.SecurityId.Sedol); writer.WriteEndElement(); }); } private void Do<TValue>(IEnumerable<TValue> values, string rootElem, Action<XmlWriter, TValue> action) { using (var writer = XmlWriter.Create(Path, new XmlWriterSettings { Indent = true })) { writer.WriteStartElement(rootElem); foreach (var value in values) { if (!CanProcess()) break; action(writer, value); } writer.WriteEndElement(); } } } }
/** @defgroup httpconsts HTTP constants to be used with HTTP client or HTTP server * @brief Provides HTTP constants * @ingroup httpserver * @ingroup httpclient * @{ */ #ifndef <API key> #define <API key> #define MIME_TYPE_MAP(XX) \ /* Type, extension start, Mime type */ \ \ /* Texts */ \ XX(HTML, "htm", "text/html") \ XX(TEXT, "txt", "text/plain") \ XX(JS, "js", "text/javascript") \ XX(CSS, "css", "text/css") \ XX(XML, "xml", "text/xml") \ XX(JSON, "json", "application/json") \ \ /* Images */ \ XX(JPEG, "jpg", "image/jpeg") \ XX(GIF, "git", "image/gif") \ XX(PNG, "png", "image/png") \ XX(SVG, "svg", "image/svg+xml") \ XX(ICO, "ico", "image/x-icon") \ \ /* Archives */ \ XX(GZIP, "gzip", "application/x-gzip") \ XX(ZIP, "zip", "application/zip") \ \ /* Binary and Form */ \ XX(BINARY, "", "application/octet-stream") \ XX(FORM_URL_ENCODED, "", "application/<API key>") \ XX(FORM_MULTIPART, "", "multipart/form-data") \ enum MimeType { #define XX(name, extensionStart, mime) MIME_##name, MIME_TYPE_MAP(XX) #undef XX }; namespace ContentType { static const char* fromFileExtension(const String extension) { String ext = extension; ext.toLowerCase(); #define XX(name, extensionStart, mime) if(ext.startsWith(extensionStart)) { return mime; } MIME_TYPE_MAP(XX) #undef XX // Unknown return "<unknown>"; } static const char *toString(enum MimeType m) { #define XX(name, extensionStart, mime) if(MIME_##name == m) { return mime; } MIME_TYPE_MAP(XX) #undef XX // Unknown return "<unknown>"; } static const char* fromFullFileName(const String fileName) { int p = fileName.lastIndexOf('.'); if (p != -1) { String ext = fileName.substring(p + 1); const char *mime = ContentType::fromFileExtension(ext); return mime; } return NULL; } }; #endif /* <API key> */
#include "gsl__config.h" #include <stdlib.h> #include <math.h> #include "gsl_errno.h" #include "gsl_linalg__tridiag.h" #include "gsl_linalg.h" /* for description of method see [Engeln-Mullges + Uhlig, p. 92] * * diag[0] offdiag[0] 0 ..... * offdiag[0] diag[1] offdiag[1] ..... * 0 offdiag[1] diag[2] * 0 0 offdiag[2] ..... */ static int solve_tridiag( const double diag[], size_t d_stride, const double offdiag[], size_t o_stride, const double b[], size_t b_stride, double x[], size_t x_stride, size_t N) { int status = GSL_SUCCESS; double *gamma = (double *) malloc (N * sizeof (double)); double *alpha = (double *) malloc (N * sizeof (double)); double *c = (double *) malloc (N * sizeof (double)); double *z = (double *) malloc (N * sizeof (double)); if (gamma == 0 || alpha == 0 || c == 0 || z == 0) { GSL_ERROR("failed to allocate working space", GSL_ENOMEM); } else { size_t i, j; /* Cholesky decomposition A = L.D.L^t lower_diag(L) = gamma diag(D) = alpha */ alpha[0] = diag[0]; gamma[0] = offdiag[0] / alpha[0]; if (alpha[0] == 0) { status = GSL_EZERODIV; } for (i = 1; i < N - 1; i++) { alpha[i] = diag[d_stride * i] - offdiag[o_stride*(i - 1)] * gamma[i - 1]; gamma[i] = offdiag[o_stride * i] / alpha[i]; if (alpha[i] == 0) { status = GSL_EZERODIV; } } if (N > 1) { alpha[N - 1] = diag[d_stride * (N - 1)] - offdiag[o_stride*(N - 2)] * gamma[N - 2]; } /* update RHS */ z[0] = b[0]; for (i = 1; i < N; i++) { z[i] = b[b_stride * i] - gamma[i - 1] * z[i - 1]; } for (i = 0; i < N; i++) { c[i] = z[i] / alpha[i]; } /* backsubstitution */ x[x_stride * (N - 1)] = c[N - 1]; if (N >= 2) { for (i = N - 2, j = 0; j <= N - 2; j++, i { x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)]; } } } if (z != 0) free (z); if (c != 0) free (c); if (alpha != 0) free (alpha); if (gamma != 0) free (gamma); if (status == GSL_EZERODIV) { GSL_ERROR ("matrix must be positive definite", status); } return status; } /* plain gauss elimination, only not bothering with the zeroes * * diag[0] abovediag[0] 0 ..... * belowdiag[0] diag[1] abovediag[1] ..... * 0 belowdiag[1] diag[2] * 0 0 belowdiag[2] ..... */ static int <API key>( const double diag[], size_t d_stride, const double abovediag[], size_t a_stride, const double belowdiag[], size_t b_stride, const double rhs[], size_t r_stride, double x[], size_t x_stride, size_t N) { int status = GSL_SUCCESS; double *alpha = (double *) malloc (N * sizeof (double)); double *z = (double *) malloc (N * sizeof (double)); if (alpha == 0 || z == 0) { GSL_ERROR("failed to allocate working space", GSL_ENOMEM); } else { size_t i, j; /* Bidiagonalization (eliminating belowdiag) & rhs update diag' = alpha rhs' = z */ alpha[0] = diag[0]; z[0] = rhs[0]; if (alpha[0] == 0) { status = GSL_EZERODIV; } for (i = 1; i < N; i++) { const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1]; alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)]; z[i] = rhs[r_stride*i] - t*z[i-1]; if (alpha[i] == 0) { status = GSL_EZERODIV; } } /* backsubstitution */ x[x_stride * (N - 1)] = z[N - 1]/alpha[N - 1]; if (N >= 2) { for (i = N - 2, j = 0; j <= N - 2; j++, i { x[x_stride * i] = (z[i] - abovediag[a_stride*i] * x[x_stride * (i + 1)])/alpha[i]; } } } if (z != 0) free (z); if (alpha != 0) free (alpha); if (status == GSL_EZERODIV) { GSL_ERROR ("matrix must be positive definite", status); } return status; } /* for description of method see [Engeln-Mullges + Uhlig, p. 96] * * diag[0] offdiag[0] 0 ..... offdiag[N-1] * offdiag[0] diag[1] offdiag[1] ..... * 0 offdiag[1] diag[2] * 0 0 offdiag[2] ..... * ... ... * offdiag[N-1] ... * */ static int solve_cyc_tridiag( const double diag[], size_t d_stride, const double offdiag[], size_t o_stride, const double b[], size_t b_stride, double x[], size_t x_stride, size_t N) { int status = GSL_SUCCESS; double * delta = (double *) malloc (N * sizeof (double)); double * gamma = (double *) malloc (N * sizeof (double)); double * alpha = (double *) malloc (N * sizeof (double)); double * c = (double *) malloc (N * sizeof (double)); double * z = (double *) malloc (N * sizeof (double)); if (delta == 0 || gamma == 0 || alpha == 0 || c == 0 || z == 0) { GSL_ERROR("failed to allocate working space", GSL_ENOMEM); } else { size_t i, j; double sum = 0.0; /* factor */ if (N == 1) { x[0] = b[0] / diag[0]; return GSL_SUCCESS; } alpha[0] = diag[0]; gamma[0] = offdiag[0] / alpha[0]; delta[0] = offdiag[o_stride * (N-1)] / alpha[0]; if (alpha[0] == 0) { status = GSL_EZERODIV; } for (i = 1; i < N - 2; i++) { alpha[i] = diag[d_stride * i] - offdiag[o_stride * (i-1)] * gamma[i - 1]; gamma[i] = offdiag[o_stride * i] / alpha[i]; delta[i] = -delta[i - 1] * offdiag[o_stride * (i-1)] / alpha[i]; if (alpha[i] == 0) { status = GSL_EZERODIV; } } for (i = 0; i < N - 2; i++) { sum += alpha[i] * delta[i] * delta[i]; } alpha[N - 2] = diag[d_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * gamma[N - 3]; gamma[N - 2] = (offdiag[o_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * delta[N - 3]) / alpha[N - 2]; alpha[N - 1] = diag[d_stride * (N - 1)] - sum - alpha[(N - 2)] * gamma[N - 2] * gamma[N - 2]; /* update */ z[0] = b[0]; for (i = 1; i < N - 1; i++) { z[i] = b[b_stride * i] - z[i - 1] * gamma[i - 1]; } sum = 0.0; for (i = 0; i < N - 2; i++) { sum += delta[i] * z[i]; } z[N - 1] = b[b_stride * (N - 1)] - sum - gamma[N - 2] * z[N - 2]; for (i = 0; i < N; i++) { c[i] = z[i] / alpha[i]; } /* backsubstitution */ x[x_stride * (N - 1)] = c[N - 1]; x[x_stride * (N - 2)] = c[N - 2] - gamma[N - 2] * x[x_stride * (N - 1)]; if (N >= 3) { for (i = N - 3, j = 0; j <= N - 3; j++, i { x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)] - delta[i] * x[x_stride * (N - 1)]; } } } if (z != 0) free (z); if (c != 0) free (c); if (alpha != 0) free (alpha); if (gamma != 0) free (gamma); if (delta != 0) free (delta); if (status == GSL_EZERODIV) { GSL_ERROR ("matrix must be positive definite", status); } return status; } /* solve following system w/o the corner elements and then use * Sherman-Morrison formula to compensate for them * * diag[0] abovediag[0] 0 ..... belowdiag[N-1] * belowdiag[0] diag[1] abovediag[1] ..... * 0 belowdiag[1] diag[2] * 0 0 belowdiag[2] ..... * ... ... * abovediag[N-1] ... */ static int <API key>( const double diag[], size_t d_stride, const double abovediag[], size_t a_stride, const double belowdiag[], size_t b_stride, const double rhs[], size_t r_stride, double x[], size_t x_stride, size_t N) { int status = GSL_SUCCESS; double *alpha = (double *) malloc (N * sizeof (double)); double *zb = (double *) malloc (N * sizeof (double)); double *zu = (double *) malloc (N * sizeof (double)); double *w = (double *) malloc (N * sizeof (double)); if (alpha == 0 || zb == 0 || zu == 0 || w == 0) { GSL_ERROR("failed to allocate working space", GSL_ENOMEM); } else { double beta; /* Bidiagonalization (eliminating belowdiag) & rhs update diag' = alpha rhs' = zb rhs' for Aq=u is zu */ zb[0] = rhs[0]; if (diag[0] != 0) beta = -diag[0]; else beta = 1; { const double q = 1 - abovediag[0]*belowdiag[0]/(diag[0]*diag[d_stride]); if (fabs(q/beta) > 0.5 && fabs(q/beta) < 2) { beta *= (fabs(q/beta) < 1) ? 0.5 : 2; } } zu[0] = beta; alpha[0] = diag[0] - beta; if (alpha[0] == 0) { status = GSL_EZERODIV; } { size_t i; for (i = 1; i+1 < N; i++) { const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1]; alpha[i] = diag[d_stride*i] - t*abovediag[a_stride*(i - 1)]; zb[i] = rhs[r_stride*i] - t*zb[i-1]; zu[i] = -t*zu[i-1]; /* FIXME!!! */ if (alpha[i] == 0) { status = GSL_EZERODIV; } } } { const size_t i = N-1; const double t = belowdiag[b_stride*(i - 1)]/alpha[i-1]; alpha[i] = diag[d_stride*i] - abovediag[a_stride*i]*belowdiag[b_stride*i]/beta - t*abovediag[a_stride*(i - 1)]; zb[i] = rhs[r_stride*i] - t*zb[i-1]; zu[i] = abovediag[a_stride*i] - t*zu[i-1]; /* FIXME!!! */ if (alpha[i] == 0) { status = GSL_EZERODIV; } } /* backsubstitution */ { size_t i, j; w[N-1] = zu[N-1]/alpha[N-1]; x[N-1] = zb[N-1]/alpha[N-1]; for (i = N - 2, j = 0; j <= N - 2; j++, i { w[i] = (zu[i] - abovediag[a_stride*i] * w[i+1])/alpha[i]; x[i*x_stride] = (zb[i] - abovediag[a_stride*i] * x[x_stride*(i + 1)])/alpha[i]; } } /* Sherman-Morrison */ { const double vw = w[0] + belowdiag[b_stride*(N - 1)]/beta * w[N-1]; const double vx = x[0] + belowdiag[b_stride*(N - 1)]/beta * x[x_stride*(N - 1)]; /* FIXME!!! */ if (vw + 1 == 0) { status = GSL_EZERODIV; } { size_t i; for (i = 0; i < N; i++) x[i] -= vx/(1 + vw)*w[i]; } } } if (zb != 0) free (zb); if (zu != 0) free (zu); if (w != 0) free (w); if (alpha != 0) free (alpha); if (status == GSL_EZERODIV) { GSL_ERROR ("matrix must be positive definite", status); } return status; } int <API key>( const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (offdiag->size != rhs->size-1) { GSL_ERROR ("size of offdiag must match rhs-1", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else { return solve_tridiag(diag->data, diag->stride, offdiag->data, offdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } } int <API key>( const gsl_vector * diag, const gsl_vector * abovediag, const gsl_vector * belowdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (abovediag->size != rhs->size-1) { GSL_ERROR ("size of abovediag must match rhs-1", GSL_EBADLEN); } else if (belowdiag->size != rhs->size-1) { GSL_ERROR ("size of belowdiag must match rhs-1", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else { return <API key>(diag->data, diag->stride, abovediag->data, abovediag->stride, belowdiag->data, belowdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } } int <API key>( const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (offdiag->size != rhs->size) { GSL_ERROR ("size of offdiag must match rhs", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else if (diag->size < 3) { GSL_ERROR ("size of cyclic system must be 3 or more", GSL_EBADLEN); } else { return solve_cyc_tridiag(diag->data, diag->stride, offdiag->data, offdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } } int <API key>( const gsl_vector * diag, const gsl_vector * abovediag, const gsl_vector * belowdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size) { GSL_ERROR ("size of diag must match rhs", GSL_EBADLEN); } else if (abovediag->size != rhs->size) { GSL_ERROR ("size of abovediag must match rhs", GSL_EBADLEN); } else if (belowdiag->size != rhs->size) { GSL_ERROR ("size of belowdiag must match rhs", GSL_EBADLEN); } else if (solution->size != rhs->size) { GSL_ERROR ("size of solution must match rhs", GSL_EBADLEN); } else if (diag->size < 3) { GSL_ERROR ("size of cyclic system must be 3 or more", GSL_EBADLEN); } else { return <API key>(diag->data, diag->stride, abovediag->data, abovediag->stride, belowdiag->data, belowdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } }
'use strict'; angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) .provider('$typeahead', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'typeahead', prefixEvent: '$typeahead', placement: 'bottom-left', template: 'typeahead/typeahead.tpl.html', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, minLength: 1, filter: 'filter', limit: 6 }; this.$get = function($window, $rootScope, $tooltip) { var bodyEl = angular.element($window.document.body); function TypeaheadFactory(element, controller, config) { var $typeahead = {}; // Common vars var options = angular.extend({}, defaults, config); $typeahead = $tooltip(element, options); var parentScope = config.scope; var scope = $typeahead.$scope; scope.$resetMatches = function(){ scope.$matches = []; scope.$activeIndex = 0; }; scope.$resetMatches(); scope.$activate = function(index) { scope.$$postDigest(function() { $typeahead.activate(index); }); }; scope.$select = function(index, evt) { scope.$$postDigest(function() { $typeahead.select(index); }); }; scope.$isVisible = function() { return $typeahead.$isVisible(); }; // Public methods $typeahead.update = function(matches) { scope.$matches = matches; if(scope.$activeIndex >= matches.length) { scope.$activeIndex = 0; } }; $typeahead.activate = function(index) { scope.$activeIndex = index; }; $typeahead.select = function(index) { var value = scope.$matches[index].value; controller.$setViewValue(value); controller.$render(); scope.$resetMatches(); if(parentScope) parentScope.$digest(); // Emit event scope.$emit(options.prefixEvent + '.select', value, index); }; // Protected methods $typeahead.$isVisible = function() { if(!options.minLength || !controller) { return !!scope.$matches.length; } // minLength support return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength; }; $typeahead.$getIndex = function(value) { var l = scope.$matches.length, i = l; if(!l) return; for(i = l; i if(scope.$matches[i].value === value) break; } if(i < 0) return; return i; }; $typeahead.$onMouseDown = function(evt) { // Prevent blur on mousedown evt.preventDefault(); evt.stopPropagation(); }; $typeahead.$onKeyDown = function(evt) { if(!/(38|40|13)/.test(evt.keyCode)) return; // Let ngSubmit pass if the typeahead tip is hidden if($typeahead.$isVisible()) { evt.preventDefault(); evt.stopPropagation(); } // Select with enter if(evt.keyCode === 13 && scope.$matches.length) { $typeahead.select(scope.$activeIndex); } // Navigate with keyboard else if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; scope.$digest(); }; // Overrides var show = $typeahead.show; $typeahead.show = function() { show(); setTimeout(function() { $typeahead.$element.on('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.on('keydown', $typeahead.$onKeyDown); } }); }; var hide = $typeahead.hide; $typeahead.hide = function() { $typeahead.$element.off('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.off('keydown', $typeahead.$onKeyDown); } hide(); }; return $typeahead; } TypeaheadFactory.defaults = defaults; return TypeaheadFactory; }; }) .directive('bsTypeahead', function($window, $parse, $q, $typeahead, $parseOptions) { var defaults = $typeahead.defaults; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { // Directive options var options = {scope: scope}; angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode'], function(key) { if(angular.isDefined(attr[key])) options[key] = attr[key]; }); // Build proper ngOptions var filter = options.filter || defaults.filter; var limit = options.limit || defaults.limit; var ngOptions = attr.ngOptions; if(filter) ngOptions += ' | ' + filter + ':$viewValue'; if(limit) ngOptions += ' | limitTo:' + limit; var parsedOptions = $parseOptions(ngOptions); // Initialize typeahead var typeahead = $typeahead(element, controller, options); // Watch options on demand if(options.watchOptions) { // Watch ngOptions values before filtering for changes, drop function calls var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim(); scope.$watch(watchedOptions, function (newValue, oldValue) { // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); parsedOptions.valuesFn(scope, controller).then(function (values) { typeahead.update(values); controller.$render(); }); }, true); } // Watch model for changes scope.$watch(attr.ngModel, function(newValue, oldValue) { // console.warn('$watch', element.attr('ng-model'), newValue); scope.$modelValue = newValue; // Publish modelValue on scope for custom templates parsedOptions.valuesFn(scope, controller) .then(function(values) { // Prevent input with no future prospect if selectMode is truthy // @TODO test selectMode if(options.selectMode && !values.length && newValue.length > 0) { controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1)); return; } if(values.length > limit) values = values.slice(0, limit); var isVisible = typeahead.$isVisible(); isVisible && typeahead.update(values); // Do not re-queue an update if a correct value has been selected if(values.length === 1 && values[0].value === newValue) return; !isVisible && typeahead.update(values); // Queue a new rendering that will leverage collection loading controller.$render(); }); }); // Model rendering in view controller.$render = function () { // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); if(controller.$isEmpty(controller.$viewValue)) return element.val(''); var index = typeahead.$getIndex(controller.$modelValue); var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue; selected = angular.isObject(selected) ? selected.label : selected; element.val(selected.replace(/<(?:.|\n)*?>/gm, '').trim()); }; // Garbage collection scope.$on('$destroy', function() { if (typeahead) typeahead.destroy(); options = null; typeahead = null; }); } }; });
namespace TinderApp.Library.Controls { public interface IApp { <API key> RootFrameInstance { get; } void Logout(); } }
#!/bin/bash set -x set -e resources/Datasources/hbase/createHbaseTables.sh wait hbase org.apache.hadoop.hbase.mapreduce.ImportTsv -Dmapred.map.tasks.speculative.execution=false -Dmapred.reduce.tasks.speculative.execution=false -Dimporttsv.columns=HBASE_ROW_KEY,onecf:name,twocf:age,twocf:registration,threecf:contributions,threecf:voterzone,fourcf:create_date voter /drill/testdata/hbase/votertab hbase org.apache.hadoop.hbase.mapreduce.ImportTsv -Dmapred.map.tasks.speculative.execution=false -Dmapred.reduce.tasks.speculative.execution=false -Dimporttsv.columns=HBASE_ROW_KEY,onecf:name,twocf:age,threecf:gpa,fourcf:studentnum,fivecf:create_date student /drill/testdata/hbase/studenttab set +x
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::get_parent_node; use clippy_utils::source::<API key>; use clippy_utils::sugg; use clippy_utils::ty::is_copy; use rustc_errors::Applicability; use rustc_hir::{BindingAnnotation, Expr, ExprKind, MatchSource, Node, PatKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, adjustment::Adjust}; use rustc_span::symbol::{sym, Symbol}; use super::CLONE_DOUBLE_REF; use super::CLONE_ON_COPY; Checks for the `CLONE_ON_COPY` lint. #[allow(clippy::too_many_lines)] pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, method_name: Symbol, args: &[Expr<'_>]) { let arg = match args { [arg] if method_name == sym::clone => arg, _ => return, }; if cx .typeck_results() .<API key>(expr.hir_id) .and_then(|id| cx.tcx.trait_of_item(id)) .zip(cx.tcx.lang_items().clone_trait()) .map_or(true, |(x, y)| x != y) { return; } let arg_adjustments = cx.typeck_results().expr_adjustments(arg); let arg_ty = arg_adjustments .last() .map_or_else(|| cx.typeck_results().expr_ty(arg), |a| a.target); let ty = cx.typeck_results().expr_ty(expr); if let ty::Ref(_, inner, _) = arg_ty.kind() { if let ty::Ref(_, innermost, _) = inner.kind() { span_lint_and_then( cx, CLONE_DOUBLE_REF, expr.span, &format!( "using `clone` on a double-reference; \ this will copy the reference of type `{}` instead of cloning the inner type", ty ), |diag| { if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) { let mut ty = innermost; let mut n = 0; while let ty::Ref(_, inner, _) = ty.kind() { ty = inner; n += 1; } let refs = "&".repeat(n + 1); let derefs = "*".repeat(n); let explicit = format!("<{}{}>::clone({})", refs, ty, snip); diag.span_suggestion( expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()), Applicability::MaybeIncorrect, ); diag.span_suggestion( expr.span, "or try being explicit if you are sure, that you want to clone a reference", explicit, Applicability::MaybeIncorrect, ); } }, ); return; // don't report clone_on_copy } } if is_copy(cx, ty) { let <API key> = match get_parent_node(cx.tcx, expr.hir_id) { Some(Node::Expr(parent)) => match parent.kind { // &*x is a nop, &x.clone() is not ExprKind::AddrOf(..) => return, // (*x).func() is useless, x.clone().func() can work in case func borrows self ExprKind::MethodCall(_, _, [self_arg, ..], _) if expr.hir_id == self_arg.hir_id && ty != cx.typeck_results().expr_ty_adjusted(expr) => { return; }, ExprKind::MethodCall(_, _, [self_arg, ..], _) if expr.hir_id == self_arg.hir_id => true, ExprKind::Match(_, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar) | ExprKind::Field(..) | ExprKind::Index(..) => true, _ => false, }, // local binding capturing a reference Some(Node::Local(l)) if matches!( l.pat.kind, PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) ) => { return; }, _ => false, }; let mut app = Applicability::MachineApplicable; let snip = <API key>(cx, arg.span, expr.span.ctxt(), "_", &mut app).0; let deref_count = arg_adjustments .iter() .take_while(|adj| matches!(adj.kind, Adjust::Deref(_))) .count(); let (help, sugg) = if deref_count == 0 { ("try removing the `clone` call", snip.into()) } else if <API key> { ("try dereferencing it", format!("({}{})", "*".repeat(deref_count), snip)) } else { ("try dereferencing it", format!("{}{}", "*".repeat(deref_count), snip)) }; span_lint_and_sugg( cx, CLONE_ON_COPY, expr.span, &format!("using `clone` on type `{}` which implements the `Copy` trait", ty), help, sugg, app, ); } }
// file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. fn foo<T>(o: myoption<T>) -> int { let mut x: int = 5; match o { none::<T> => { } some::<T>(_t) => { x += 1; } } return x; } enum myoption<T> { none, some(T), } pub fn main() { info!("{}", 5); }
package org.apereo.cas.authentication; import com.google.common.base.Splitter; import org.apereo.cas.authentication.principal.Principal; import org.apereo.cas.services.Multifactor<API key>; import org.apereo.cas.services.RegisteredService; import org.apereo.cas.services.<API key>; import org.apereo.cas.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * Default MFA Trigger selection strategy. This strategy looks for valid triggers in the following order: request * parameter, RegisteredService policy, principal attribute. * * @author Daniel Frett * @since 5.0.0 */ public class <API key> implements <API key> { private static final Splitter ATTR_NAMES = Splitter.on(',').trimResults().omitEmptyStrings(); private final String requestParameter; private final String <API key>; public <API key>(final String <API key>, final String requestParameter) { this.<API key> = <API key>; this.requestParameter = requestParameter; } @Override public Optional<String> resolve(final Collection<Multifactor<API key>> providers, final HttpServletRequest request, final RegisteredService service, final Principal principal) { Optional<String> provider = Optional.empty(); // short-circuit if we don't have any available MFA providers if (providers == null || providers.isEmpty()) { return provider; } final Set<String> validProviderIds = providers.stream() .map(Multifactor<API key>::getId) .collect(Collectors.toSet()); // check for an opt-in provider id parameter trigger, we only care about the first value if (!provider.isPresent() && request != null) { provider = Optional.ofNullable(request.getParameter(requestParameter)) .filter(validProviderIds::contains); } // check for a RegisteredService configured trigger if (!provider.isPresent() && service != null) { final <API key> policy = service.<API key>(); if (<API key>(policy, principal)) { provider = policy.getMultifactor<API key>().stream() .filter(validProviderIds::contains) .findFirst(); } } // check for principal attribute trigger if (!provider.isPresent() && principal != null && StringUtils.hasText(<API key>)) { provider = StreamSupport.stream(ATTR_NAMES.split(<API key>).spliterator(), false) // principal.getAttribute(name).values .map(principal.getAttributes()::get).filter(Objects::nonNull) .map(CollectionUtils::toCollection).flatMap(Set::stream) // validProviderIds.contains((String) value) .filter(String.class::isInstance).map(String.class::cast).filter(validProviderIds::contains) .findFirst(); } // return the resolved trigger return provider; } private static boolean <API key>(final <API key> policy, final Principal principal) { final String attrName = policy.<API key>(); final String attrValue = policy.<API key>(); // Principal attribute name and/or value is not defined if (!StringUtils.hasText(attrName) || !StringUtils.hasText(attrValue)) { return true; } // no Principal, we should enforce policy if (principal == null) { return true; } // check to see if any of the specified attributes match the attrValue pattern final Predicate<String> attrValuePredicate = Pattern.compile(attrValue).asPredicate(); return StreamSupport.stream(ATTR_NAMES.split(attrName).spliterator(), false) .map(principal.getAttributes()::get) .filter(Objects::nonNull) .map(CollectionUtils::toCollection) .flatMap(Set::stream) .filter(String.class::isInstance) .map(String.class::cast) .anyMatch(attrValuePredicate); } }
{% extends 'base.html' %} {% block main %} {% include "project/databases/_create_database.html" %} {% endblock %}
package org.camunda.bpm.model.bpmn.impl.instance.camunda; import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.<API key>; import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_NS; import org.camunda.bpm.model.bpmn.impl.instance.<API key>; import org.camunda.bpm.model.bpmn.instance.camunda.CamundaConnector; import org.camunda.bpm.model.bpmn.instance.camunda.CamundaConnectorId; import org.camunda.bpm.model.bpmn.instance.camunda.CamundaInputOutput; import org.camunda.bpm.model.xml.ModelBuilder; import org.camunda.bpm.model.xml.impl.instance.<API key>; import org.camunda.bpm.model.xml.type.<API key>; import org.camunda.bpm.model.xml.type.<API key>.<API key>; import org.camunda.bpm.model.xml.type.child.ChildElement; import org.camunda.bpm.model.xml.type.child.SequenceBuilder; /** * The BPMN connector camunda extension element * * @author Sebastian Menski */ public class <API key> extends <API key> implements CamundaConnector { protected static ChildElement<CamundaConnectorId> <API key>; protected static ChildElement<CamundaInputOutput> <API key>; public static void registerType(ModelBuilder modelBuilder) { <API key> typeBuilder = modelBuilder.defineType(CamundaConnector.class, <API key>) .namespaceUri(CAMUNDA_NS) .instanceProvider(new <API key><CamundaConnector>() { public CamundaConnector newInstance(<API key> instanceContext) { return new <API key>(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); <API key> = sequenceBuilder.element(CamundaConnectorId.class) .required() .build(); <API key> = sequenceBuilder.element(CamundaInputOutput.class) .build(); typeBuilder.build(); } public <API key>(<API key> instanceContext) { super(instanceContext); } public CamundaConnectorId <API key>() { return <API key>.getChild(this); } public void <API key>(CamundaConnectorId camundaConnectorId) { <API key>.setChild(this, camundaConnectorId); } public CamundaInputOutput <API key>() { return <API key>.getChild(this); } public void <API key>(CamundaInputOutput camundaInputOutput) { <API key>.setChild(this, camundaInputOutput); } }
// file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. use std::old_io::{Command, IoError, OtherIoError}; use target::TargetOptions; use self::Arch::*; #[allow(<API key>)] #[derive(Copy)] pub enum Arch { Armv7, Armv7s, Arm64, I386, X86_64 } impl Arch { pub fn to_string(&self) -> &'static str { match self { &Armv7 => "armv7", &Armv7s => "armv7s", &Arm64 => "arm64", &I386 => "i386", &X86_64 => "x86_64" } } } pub fn get_sdk_root(sdk_name: &str) -> String { let res = Command::new("xcrun") .arg("--show-sdk-path") .arg("-sdk") .arg(sdk_name) .spawn() .and_then(|c| c.wait_with_output()) .and_then(|output| { if output.status.success() { Ok(String::from_utf8(output.output).unwrap()) } else { Err(IoError { kind: OtherIoError, desc: "process exit with error", detail: String::from_utf8(output.error).ok()}) } }); match res { Ok(output) => output.trim().to_string(), Err(e) => panic!("failed to get {} SDK path: {}", sdk_name, e) } } fn pre_link_args(arch: Arch) -> Vec<String> { let sdk_name = match arch { Armv7 | Armv7s | Arm64 => "iphoneos", I386 | X86_64 => "iphonesimulator" }; let arch_name = arch.to_string(); vec!["-arch".to_string(), arch_name.to_string(), "-Wl,-syslibroot".to_string(), get_sdk_root(sdk_name)] } fn target_cpu(arch: Arch) -> String { match arch { Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher Armv7s => "cortex-a9", Arm64 => "cyclone", I386 => "generic", X86_64 => "x86-64", }.to_string() } pub fn opts(arch: Arch) -> TargetOptions { TargetOptions { cpu: target_cpu(arch), dynamic_linking: false, executables: true, // Although there is an experimental implementation of LLVM which // supports SS on armv7 it wasn't approved by Apple, see: // It looks like it might be never accepted to upstream LLVM. // SS might be also enabled on Arm64 as it has builtin support in LLVM // but I haven't tested it through yet morestack: false, pre_link_args: pre_link_args(arch), .. super::apple_base::opts() } }
{{{ "title": "Getting Started with GitLab - Blueprint", "date": "05-14-2015", "author": "<a href='https://twitter.com/KeithResar'>@KeithResar</a>", "attachments": [], "contentIsHTML": false }}} Description <img alt="GitLab Logo" src="/knowledge-base/images/bitnami_logos/<API key>.png" style="border:0;float:right;max-width:250px"> After reading this article, the reader should feel comfortable deploying the GitLab stack (version 7.10.1-0) by Bitnami. <a href="https: The GitLab open source edition is a developer tool that allows users to collaborate on code, create new projects, manage repositories, and perform code reviews. When using GitLab, users can keep their code on their own servers, either in the cloud or on-premise. For additional peace of mind, the free community edition even features enterprise-grade features such as a mature user permissions scheme and support for high availability. This GitLab stack is bundled with GitLab CI, a continuous integration server. Just point your projects at the CI server and automate all your tests. Audience CenturyLink Cloud Users Deploying GitLab on a New Server GitLab is available as a Blueprint for deployment on a **new server**. # Steps 1. **Locate the Blueprint in the Blueprint Library** Starting from the CenturyLink Control Panel, navigate to the Blueprints Library. Search for **GitLab on Linux** in the keyword search on the right side of the page. 2. **Click the Deploy Blueprint button.** 3. **Set Required parameters.** Set the following parameters in addition to those associated with your server itself (password, network, group, etc.): * **Apache server SSL port** - default 443 * **Redis port** - Redis Server port default 6379 * **Apache server port** - default 80 * **Service Password** - Provide service password 6 chars or more * **User's name** - Users Name 5. **Review and Confirm the Blueprint** 6. **Deploy the Blueprint** Once verified, click on the `deploy blueprint` button. You will see the deployment details stating the Blueprint is queued for execution. This will kick off the Blueprint deploy process and load a page where you can track the deployment progress. Deployment will typically complete within five minutes. 7. **Deployment Complete** Once the Blueprint has finished executing on your server you may access GitLab by navigating to your server via http. 8. **Enable public access** (optional) Servers are built using private IPs only with access with client or IPSEC VPN. For inbound access from the Internet add a public IP to your master server. <a href="../../Network/<API key>.md"> <img style="border:0;width:50px;vertical-align:middle;" src="../../images/shared_assets/fw_icon.png"> Adding a public IP to your virtual machine </a> Deploying GitLab on an existing server (alternate option) GitLab is available as a Blueprint Package for deployment on an existing server based on your own sizing requirements or to support more advanced configurations such as customized Blueprint Workflows to repeatably deploy multiple stacks on the same machines # Steps 1. **Deploy or Identify an Existing Server** Identify the server targeted for GitLab installation. Operating sustem must be linux. See the [Creating a new enterprise cloud server](../../Servers/<API key>.md) KB for more information on completing this step. 2. **Select to Execute the Package on a Server Group** Packages can be executed on one more more servers in a group. Search for the public script package named **Install GitLab on Linux**. See the [using group tasks to install scripts on groups](../../Servers/<API key>.md) KB for more information on how to complete the next few steps. 3. **Set Parameters** Set the following parameters: * **Apache server SSL port** - default 443 * **Redis port** - Redis Server port default 6379 * **Apache server port** - default 80 * **Service Password** - Provide service password 6 chars or more * **User's name** - Users Name 4. **Deploy the Blueprint** Once verified, click on the `execute package` button. You will see the deployment details stating the Blueprint is queued for execution. This will kick off the Blueprint deploy process and load a page where you can track the deployment progress. Deployment will typically complete within five minutes. 5. **Deployment Complete** Once the Blueprint has finished executing on your server you may access GitLab by navigating to your server via http. 6. **Enable public access** (optional) Servers are built using private IPs only with access with client or IPSEC VPN. For inbound access from the Internet add a public IP to your master server. <a href="../../Network/<API key>.md"> <img style="border:0;width:50px;vertical-align:middle;" src="../../images/shared_assets/fw_icon.png"> Adding a public IP to your virtual machine </a> Pricing The costs listed above in the above steps are for the infrastructure only. About Bitnami CenturyLink Cloud works with [Bitnami](http: Frequently Asked Questions **Who should I contact for support?** * For issues related to cloud infrastructure, please open a ticket using the [CenturyLink Cloud Support Process](../../Support/<API key>.md). * For issues related to deploying the Bitnami Blueprint on CenturyLink Cloud, Licensing or Accessing the deployed software, please visit the [Bitnami Support website](http: **How do I access GitLab for the first time?** Nearly all Bitnami stacks can be accessed and configured by navigating to your server with a web browser.
///<reference path="app.js" /> define(['Dexie', 'Dexie.Observable', './console'], function (Dexie, DexieObservable, console) { // Declare Dexie instance and explicitely apply the addon: var db = new Dexie("appdb2", { addons: [DexieObservable] }); // Define database schema db.version(1).stores({ contacts: '++id,first,last' }); // Populate ground data db.on('populate', function () { console.log("Populating data first time"); // Populate a contact db.contacts.add({ first: 'Arnold', last: 'Fitzgerald' }); }); // Open database db.open(); return db; });
// file at the top-level directory of this distribution and at // option. This file may not be copied, modified, or distributed // except according to those terms. enum Test { DivZero = 1/0, //~^ attempt to divide by zero //~| ERROR evaluation of constant value failed RemZero = 1%0, //~^ attempt to calculate the remainder with a divisor of zero //~| ERROR evaluation of constant value failed } fn main() {}
package foo; public class ControllerB2 extends grails.TopB { public void foo() { super.foo(); System.out.println("ControllerB.foo() running again!"); } }
#include "modules/rtp_rtcp/source/rtp_format_h264.h" namespace webrtc { void FuzzOneInput(const uint8_t* data, size_t size) { RtpDepacketizerH264 depacketizer; RtpDepacketizer::ParsedPayload parsed_payload; depacketizer.Parse(&parsed_payload, data, size); } } // namespace webrtc
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>selenium.webdriver.remote.webelement &mdash; Selenium 2.0 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var <API key> = { URL_ROOT: '../', VERSION: '2.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="top" title="Selenium 2.0 documentation" href="../index.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="../index.html">Selenium 2.0 documentation</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="module-selenium.webdriver.remote.webelement"> <span id="<API key>"></span><h1>selenium.webdriver.remote.webelement<a class="headerlink" href=" <dl class="class"> <dt id="selenium.webdriver.remote.webelement.WebElement"> <em class="property">class </em><tt class="descclassname">selenium.webdriver.remote.webelement.</tt><tt class="descname">WebElement</tt><big>(</big><em>parent</em>, <em>id_</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Represents a DOM element.</p> <p>Generally, all interesting operations that interact with a document will be performed through this interface.</p> <p>All method calls will do a freshness check to ensure that the element reference is still valid. This essentially determines whether or not the element is still attached to the DOM. If this test fails, then an <tt class="docutils literal"><span class="pre"><API key></span></tt> is thrown, and all future calls to this instance will fail.</p> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.clear"> <tt class="descname">clear</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Clears the text if it&#8217;s a text entry element.</p> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.click"> <tt class="descname">click</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Clicks the element.</p> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.find_element"> <tt class="descname">find_element</tt><big>(</big><em>by='id'</em>, <em>value=None</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd></dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element within this element&#8217;s children by class name.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>name - class name to search for.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>css_selector</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element within this element&#8217;s children by CSS selector.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>css_selector - CSS selctor string, ex: &#8216;a.nav#home&#8217;</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.find_element_by_id"> <tt class="descname">find_element_by_id</tt><big>(</big><em>id_</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element within this element&#8217;s children by ID.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li><a href="#id1"><span class="problematic" id="id2">id_</span></a> - ID of child element to locate.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element within this element&#8217;s children by visible link text.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>link_text - Link text string to search for.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element within this element&#8217;s children by name.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>name - name property of the element to find.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element within this element&#8217;s children by partially visible link text.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>link_text - Link text string to search for.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element within this element&#8217;s children by tag name.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>name - name of html tag (eg: h1, a, span)</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>xpath</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds element by xpath.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body">xpath - xpath of element to locate. &#8220;//input[&#64;class=&#8217;myelement&#8217;]&#8221;</td> </tr> </tbody> </table> <p>Note: The base path will be relative to this element&#8217;s location.</p> <p>This will select the first link under this element.</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n"><API key></span><span class="p">(</span><span class="s">&quot;.//a&quot;</span><span class="p">)</span> </pre></div> </div> <p>However, this will select the first link on the page.</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n"><API key></span><span class="p">(</span><span class="s">&quot;//a&quot;</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.find_elements"> <tt class="descname">find_elements</tt><big>(</big><em>by='id'</em>, <em>value=None</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd></dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds a list of elements within this element&#8217;s children by class name.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>name - class name to search for.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>css_selector</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds a list of elements within this element&#8217;s children by CSS selector.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>css_selector - CSS selctor string, ex: &#8216;a.nav#home&#8217;</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.find_elements_by_id"> <tt class="descname">find_elements_by_id</tt><big>(</big><em>id_</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds a list of elements within this element&#8217;s children by ID.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li><a href="#id3"><span class="problematic" id="id4">id_</span></a> - Id of child element to find.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds a list of elements within this element&#8217;s children by visible link text.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>link_text - Link text string to search for.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds a list of elements within this element&#8217;s children by name.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>name - name property to search for.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>link_text</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds a list of elements within this element&#8217;s children by link text.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>link_text - Link text string to search for.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds a list of elements within this element&#8217;s children by tag name.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>name - name of html tag (eg: h1, a, span)</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>xpath</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Finds elements within the element by xpath.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>xpath - xpath locator string.</li> </ul> </td> </tr> </tbody> </table> <p>Note: The base path will be relative to this element&#8217;s location.</p> <p>This will select all links under this element.</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n"><API key></span><span class="p">(</span><span class="s">&quot;.//a&quot;</span><span class="p">)</span> </pre></div> </div> <p>However, this will select all links in the page itself.</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">myelement</span><span class="o">.</span><span class="n"><API key></span><span class="p">(</span><span class="s">&quot;//a&quot;</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.get_attribute"> <tt class="descname">get_attribute</tt><big>(</big><em>name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Gets the given attribute or property of the element.</p> <p>This method will first try to return the value of a property with the given name. If a property with that name doesn&#8217;t exist, it returns the value of the attribute with the same name. If there&#8217;s no attribute with that name, <tt class="docutils literal"><span class="pre">None</span></tt> is returned.</p> <p>Values which are considered truthy, that is equals &#8220;true&#8221; or &#8220;false&#8221;, are returned as booleans. All other non-<tt class="docutils literal"><span class="pre">None</span></tt> values are returned as strings. For attributes or properties which do not exist, <tt class="docutils literal"><span class="pre">None</span></tt> is returned.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first last simple"> <li>name - Name of the attribute/property to retrieve.</li> </ul> </td> </tr> </tbody> </table> <p>Example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># Check if the &quot;active&quot; CSS class is applied to an element.</span> <span class="n">is_active</span> <span class="o">=</span> <span class="s">&quot;active&quot;</span> <span class="ow">in</span> <span class="n">target_element</span><span class="o">.</span><span class="n">get_attribute</span><span class="p">(</span><span class="s">&quot;class&quot;</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.id"> <tt class="descname">id</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Internal ID used by selenium.</p> <p>This is mainly for internal use. Simple use cases such as checking if 2 webelements refer to the same element, can be done using <tt class="docutils literal"><span class="pre">==</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">element1</span> <span class="o">==</span> <span class="n">element2</span><span class="p">:</span> <span class="k">print</span><span class="p">(</span><span class="s">&quot;These 2 are equal&quot;</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.is_displayed"> <tt class="descname">is_displayed</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Whether the element is visible to a user.</p> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.is_enabled"> <tt class="descname">is_enabled</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Returns whether the element is enabled.</p> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.is_selected"> <tt class="descname">is_selected</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Returns whether the element is selected.</p> <p>Can be used to check if a checkbox or radio button is selected.</p> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.location"> <tt class="descname">location</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>The location of the element in the renderable canvas.</p> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view.</p> <p>Returns the top lefthand corner location on the screen, or <tt class="docutils literal"><span class="pre">None</span></tt> if the element is not visible.</p> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.parent"> <tt class="descname">parent</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Internal reference to the WebDriver instance this element was found from.</p> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.rect"> <tt class="descname">rect</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>A dictionary with the size and location of the element.</p> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.send_keys"> <tt class="descname">send_keys</tt><big>(</big><em>*value</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Simulates typing into the element.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Args :</th><td class="field-body"><ul class="first simple"> <li>value - A string for typing, or setting form fields. For setting</li> </ul> <p class="last">file inputs, this could be a local file path.</p> </td> </tr> </tbody> </table> <p>Use this to send simple key events or to fill out form fields:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">form_textfield</span> <span class="o">=</span> <span class="n">driver</span><span class="o">.</span><span class="n"><API key></span><span class="p">(</span><span class="s">&#39;username&#39;</span><span class="p">)</span> <span class="n">form_textfield</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s">&quot;admin&quot;</span><span class="p">)</span> </pre></div> </div> <p>This can also be used to set file inputs.</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">file_input</span> <span class="o">=</span> <span class="n">driver</span><span class="o">.</span><span class="n"><API key></span><span class="p">(</span><span class="s">&#39;profilePic&#39;</span><span class="p">)</span> <span class="n">file_input</span><span class="o">.</span><span class="n">send_keys</span><span class="p">(</span><span class="s">&quot;path/to/profilepic.gif&quot;</span><span class="p">)</span> <span class="c"># Generally it&#39;s better to wrap the file path in one of the methods</span> <span class="c"># in os.path to return the actual path to support cross OS testing.</span> <span class="c"># file_input.send_keys(os.path.abspath(&quot;path/to/profilepic.gif&quot;))</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.size"> <tt class="descname">size</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>The size of the element.</p> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.submit"> <tt class="descname">submit</tt><big>(</big><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>Submits a form.</p> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.tag_name"> <tt class="descname">tag_name</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>This element&#8217;s <tt class="docutils literal"><span class="pre">tagName</span></tt> property.</p> </dd></dl> <dl class="attribute"> <dt id="selenium.webdriver.remote.webelement.WebElement.text"> <tt class="descname">text</tt><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>The text of the element.</p> </dd></dl> <dl class="method"> <dt id="selenium.webdriver.remote.webelement.WebElement.<API key>"> <tt class="descname"><API key></tt><big>(</big><em>property_name</em><big>)</big><a class="reference internal" href="../_modules/selenium/webdriver/remote/webelement.html <dd><p>The value of a CSS property.</p> </dd></dl> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="<API key>"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/webdriver_remote/selenium.webdriver.remote.webelement.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="../index.html">Selenium 2.0 documentation</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2011, plightbo, simon.m.stewart, hbchai, jrhuggins, et al.. </div> </body> </html>
<!DOCTYPE html> <html> <head> <script> function loadHandler() { if (opener) { // opener.console.log("oauth callback href:", location.href); if (location.hash) { opener.require("esri/kernel").id.<API key>(location.hash); close(); } } else { close(); } } </script> </head> <body onload="loadHandler();"> </body> </html>
<!DOCTYPE html> <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <a action="TestAction" controller="TestController" _arg="args">Text</a> </body> </html>
require_relative '../../puppet_x/puppetlabs/property/tag.rb' require_relative '../../puppet_x/puppetlabs/property/region.rb' require_relative '../../puppet_x/puppetlabs/<API key>' Puppet::Type.newtype(:ec2_securitygroup) do @doc = 'type representing an EC2 security group' ensurable newparam(:name, namevar: true) do desc 'the name of the security group' validate do |value| fail 'security groups must have a name' if value == '' fail 'name should be a String' unless value.is_a?(String) end end newproperty(:region, :parent => PuppetX::Property::AwsRegion) do desc 'the region in which to launch the security group' end newproperty(:ingress, :array_matching => :all) do desc 'rules for ingress traffic' def insync?(is) for_comparison = Marshal.load(Marshal.dump(should)) parser = PuppetX::Puppetlabs::<API key>.new(for_comparison) to_create = parser.rules_to_create(is) to_delete = parser.rules_to_delete(is) to_create.empty? && to_delete.empty? end validate do |value| fail 'ingress should be a Hash' unless value.is_a?(Hash) end end newproperty(:tags, :parent => PuppetX::Property::AwsTag) do desc 'the tags for the security group' end newproperty(:description) do desc 'a short description of the group' validate do |value| fail 'description cannot be blank' if value == '' fail 'description should be a String' unless value.is_a?(String) end end newproperty(:vpc) do desc 'A VPC to which the group should be associated' validate do |value| fail 'vpc should be a String' unless value.is_a?(String) end end newproperty(:id) do desc 'The unique identifier for the security group' end autorequire(:ec2_vpc) do self[:vpc] end end
# ./darwinpush/xb/raw/sm.py # -*- coding: utf-8 -*- # PyXB bindings for NM:<SHA1-like> # Generated 2015-04-23 16:42:14.513978 by PyXB version 1.2.4 using Python 3.4.1.final.0 from __future__ import unicode_literals import pyxb import pyxb.binding import pyxb.binding.saxer import io import pyxb.utils.utility import pyxb.utils.domutils import sys import pyxb.utils.six as _six # Unique identifier for bindings created at the same time _GenerationUID = pyxb.utils.utility.UniqueIdentifier('urn:uuid:<API key>') # Version of PyXB used to generate the bindings _PyXBVersion = '1.2.4' # Generated bindings are not compatible across PyXB versions if pyxb.__version__ != _PyXBVersion: raise pyxb.PyXBVersionError(_PyXBVersion) # Import bindings for namespaces imported into schema import pyxb.binding.datatypes import darwinpush.xb.ct as <API key> # NOTE: All namespace declarations are reserved within the binding Namespace = pyxb.namespace.NamespaceForURI('http: Namespace.configureCategories(['typeBinding', 'elementBinding']) def CreateFromDocument (xml_text, default_namespace=None, location_base=None): """Parse the given XML and use the document element to create a Python instance. @param xml_text An XML document. This should be data (Python 2 str or Python 3 bytes), or a text (Python 2 unicode or Python 3 str) in the L{pyxb._InputEncoding} encoding. @keyword default_namespace The L{pyxb.Namespace} instance to use as the default namespace where there is no default namespace in scope. If unspecified or C{None}, the namespace of the module containing this function will be used. @keyword location_base: An object to be recorded as the base of all L{pyxb.utils.utility.Location} instances associated with events and objects handled by the parser. You might pass the URI from which the document was obtained. """ if pyxb.XMLStyle_saxer != pyxb._XMLStyle: dom = pyxb.utils.domutils.StringToDOM(xml_text) return CreateFromDOM(dom.documentElement, default_namespace=default_namespace) if default_namespace is None: default_namespace = Namespace.fallbackNamespace() saxer = pyxb.binding.saxer.make_parser(fallback_namespace=default_namespace, location_base=location_base) handler = saxer.getContentHandler() xmld = xml_text if isinstance(xmld, _six.text_type): xmld = xmld.encode(pyxb._InputEncoding) saxer.parse(io.BytesIO(xmld)) instance = handler.rootObject() return instance def CreateFromDOM (node, default_namespace=None): """Create a Python instance from the given DOM node. The node tag must correspond to an element declaration in this module. @deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}.""" if default_namespace is None: default_namespace = Namespace.fallbackNamespace() return pyxb.binding.basis.element.AnyCreateFromDOM(node, default_namespace) class MsgCategoryType (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): """The category of operator message""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'MsgCategoryType') _XSDLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 15, 1) _Documentation = 'The category of operator message' MsgCategoryType._CF_enumeration = pyxb.binding.facets.CF_enumeration(value_datatype=MsgCategoryType, enum_prefix=None) MsgCategoryType.Train = MsgCategoryType._CF_enumeration.addEnumeration(unicode_value='Train', tag='Train') MsgCategoryType.Station = MsgCategoryType._CF_enumeration.addEnumeration(unicode_value='Station', tag='Station') MsgCategoryType.Connections = MsgCategoryType._CF_enumeration.addEnumeration(unicode_value='Connections', tag='Connections') MsgCategoryType.System = MsgCategoryType._CF_enumeration.addEnumeration(unicode_value='System', tag='System') MsgCategoryType.Misc = MsgCategoryType._CF_enumeration.addEnumeration(unicode_value='Misc', tag='Misc') MsgCategoryType.PriorTrains = MsgCategoryType._CF_enumeration.addEnumeration(unicode_value='PriorTrains', tag='PriorTrains') MsgCategoryType.PriorOther = MsgCategoryType._CF_enumeration.addEnumeration(unicode_value='PriorOther', tag='PriorOther') MsgCategoryType._InitializeFacetMap(MsgCategoryType._CF_enumeration) Namespace.addCategoryObject('typeBinding', 'MsgCategoryType', MsgCategoryType) class MsgSeverityType (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): """The severity of operator message""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'MsgSeverityType') _XSDLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 29, 1) _Documentation = 'The severity of operator message' MsgSeverityType._CF_enumeration = pyxb.binding.facets.CF_enumeration(value_datatype=MsgSeverityType, enum_prefix=None) MsgSeverityType.n0 = MsgSeverityType._CF_enumeration.addEnumeration(unicode_value='0', tag='n0') MsgSeverityType.n1 = MsgSeverityType._CF_enumeration.addEnumeration(unicode_value='1', tag='n1') MsgSeverityType.n2 = MsgSeverityType._CF_enumeration.addEnumeration(unicode_value='2', tag='n2') MsgSeverityType.n3 = MsgSeverityType._CF_enumeration.addEnumeration(unicode_value='3', tag='n3') MsgSeverityType._InitializeFacetMap(MsgSeverityType._CF_enumeration) Namespace.addCategoryObject('typeBinding', 'MsgSeverityType', MsgSeverityType) # Complex type [anonymous] with content type MIXED class CTD_ANON (pyxb.binding.basis.<API key>): """The content of the message""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.<API key>._CT_MIXED _Abstract = False _ExpandedName = None _XSDLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 58, 4) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.anyType __p = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'p'), 'p', '__httpwww_thalesgroup_comrttiPushPortStationMessagesv1_CTD_ANON_httpwww_thalesgroup_comrttiPushPortStationMessagesv1p', True, pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 84, 1), ) p = property(__p.value, __p.set, None, 'Defines an HTML paragraph') __a = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'a'), 'a', '__httpwww_thalesgroup_comrttiPushPortStationMessagesv1_CTD_ANON_httpwww_thalesgroup_comrttiPushPortStationMessagesv1a', True, pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 94, 1), ) a = property(__a.value, __a.set, None, 'Defines an HTML anchor') _ElementMap.update({ __p.name() : __p, __a.name() : __a }) _AttributeMap.update({ }) # Complex type [anonymous] with content type MIXED class CTD_ANON_ (pyxb.binding.basis.<API key>): """Defines an HTML paragraph""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.<API key>._CT_MIXED _Abstract = False _ExpandedName = None _XSDLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 88, 2) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.anyType __a = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'a'), 'a', '__httpwww_thalesgroup_comrttiPushPortStationMessagesv1_CTD_ANON__httpwww_thalesgroup_comrttiPushPortStationMessagesv1a', True, pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 94, 1), ) a = property(__a.value, __a.set, None, 'Defines an HTML anchor') _ElementMap.update({ __a.name() : __a }) _AttributeMap.update({ }) # Complex type [anonymous] with content type SIMPLE class CTD_ANON_2 (pyxb.binding.basis.<API key>): """Defines an HTML anchor""" _TypeDefinition = pyxb.binding.datatypes.string _ContentTypeTag = pyxb.binding.basis.<API key>._CT_SIMPLE _Abstract = False _ExpandedName = None _XSDLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 98, 2) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.string # Attribute href uses Python identifier href __href = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'href'), 'href', '<API key>', pyxb.binding.datatypes.string, required=True) __href.<API key> = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 101, 5) __href._UseLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 101, 5) href = property(__href.value, __href.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __href.name() : __href }) class StationMessage (pyxb.binding.basis.<API key>): """Darwin Workstation Station Message""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.<API key>._CT_ELEMENT_ONLY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'StationMessage') _XSDLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 41, 1) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.anyType __Station = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'Station'), 'Station', '__httpwww_thalesgroup_comrttiPushPortStationMessagesv1_StationMessage_httpwww_thalesgroup_comrttiPushPortStationMessagesv1Station', True, pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 46, 3), ) Station = property(__Station.value, __Station.set, None, 'The Stations the message is being applied to') __Msg = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'Msg'), 'Msg', '__httpwww_thalesgroup_comrttiPushPortStationMessagesv1_StationMessage_httpwww_thalesgroup_comrttiPushPortStationMessagesv1Msg', False, pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 54, 3), ) Msg = property(__Msg.value, __Msg.set, None, 'The content of the message') # Attribute id uses Python identifier id __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '<API key>', pyxb.binding.datatypes.int, required=True) __id.<API key> = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 66, 2) __id._UseLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 66, 2) id = property(__id.value, __id.set, None, None) # Attribute cat uses Python identifier cat __cat = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'cat'), 'cat', '<API key>', MsgCategoryType, required=True) __cat.<API key> = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 67, 2) __cat._UseLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 67, 2) cat = property(__cat.value, __cat.set, None, 'The category of message') # Attribute sev uses Python identifier sev __sev = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'sev'), 'sev', '<API key>', MsgSeverityType, required=True) __sev.<API key> = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 72, 2) __sev._UseLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 72, 2) sev = property(__sev.value, __sev.set, None, 'The severity of the message') # Attribute suppress uses Python identifier suppress __suppress = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'suppress'), 'suppress', '<API key>', pyxb.binding.datatypes.boolean, unicode_default='false') __suppress.<API key> = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 77, 2) __suppress._UseLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 77, 2) suppress = property(__suppress.value, __suppress.set, None, 'Whether the train running information is suppressed to the public') _ElementMap.update({ __Station.name() : __Station, __Msg.name() : __Msg }) _AttributeMap.update({ __id.name() : __id, __cat.name() : __cat, __sev.name() : __sev, __suppress.name() : __suppress }) Namespace.addCategoryObject('typeBinding', 'StationMessage', StationMessage) # Complex type [anonymous] with content type EMPTY class CTD_ANON_3 (pyxb.binding.basis.<API key>): """The Stations the message is being applied to""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.<API key>._CT_EMPTY _Abstract = False _ExpandedName = None _XSDLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 50, 4) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.anyType # Attribute crs uses Python identifier crs __crs = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'crs'), 'crs', '<API key>', <API key>.CrsType, required=True) __crs.<API key> = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 51, 5) __crs._UseLocation = pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 51, 5) crs = property(__crs.value, __crs.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __crs.name() : __crs }) p = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'p'), CTD_ANON_, documentation='Defines an HTML paragraph', location=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 84, 1)) Namespace.addCategoryObject('elementBinding', p.name().localName(), p) a = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'a'), CTD_ANON_2, documentation='Defines an HTML anchor', location=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 94, 1)) Namespace.addCategoryObject('elementBinding', a.name().localName(), a) CTD_ANON._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'p'), CTD_ANON_, scope=CTD_ANON, documentation='Defines an HTML paragraph', location=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 84, 1))) CTD_ANON._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'a'), CTD_ANON_2, scope=CTD_ANON, documentation='Defines an HTML anchor', location=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 94, 1))) def _BuildAutomaton (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton del _BuildAutomaton import pyxb.utils.fac as fac counters = set() cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 60, 6)) counters.add(cc_0) cc_1 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 61, 6)) counters.add(cc_1) states = [] final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(CTD_ANON._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'p')), pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 60, 6)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, <API key>=False) states.append(st_0) final_update = set() final_update.add(fac.UpdateInstruction(cc_1, False)) symbol = pyxb.binding.content.ElementUse(CTD_ANON._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'a')), pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 61, 6)) st_1 = fac.State(symbol, is_initial=True, final_update=final_update, <API key>=False) states.append(st_1) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) st_0._set_transitionSet(transitions) transitions = [] transitions.append(fac.Transition(st_1, [ fac.UpdateInstruction(cc_1, True) ])) st_1._set_transitionSet(transitions) return fac.Automaton(states, counters, True, containing_state=None) CTD_ANON._Automaton = _BuildAutomaton() CTD_ANON_._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'a'), CTD_ANON_2, scope=CTD_ANON_, documentation='Defines an HTML anchor', location=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 94, 1))) def _BuildAutomaton_ (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton_ del _BuildAutomaton_ import pyxb.utils.fac as fac counters = set() cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 90, 4)) counters.add(cc_0) states = [] final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(CTD_ANON_._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'a')), pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 90, 4)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, <API key>=False) states.append(st_0) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) st_0._set_transitionSet(transitions) return fac.Automaton(states, counters, True, containing_state=None) CTD_ANON_._Automaton = _BuildAutomaton_() StationMessage._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'Station'), CTD_ANON_3, scope=StationMessage, documentation='The Stations the message is being applied to', location=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 46, 3))) StationMessage._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'Msg'), CTD_ANON, scope=StationMessage, documentation='The content of the message', location=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 54, 3))) def _BuildAutomaton_2 (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton_2 del _BuildAutomaton_2 import pyxb.utils.fac as fac counters = set() cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 46, 3)) counters.add(cc_0) states = [] final_update = None symbol = pyxb.binding.content.ElementUse(StationMessage._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'Station')), pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 46, 3)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, <API key>=False) states.append(st_0) final_update = set() symbol = pyxb.binding.content.ElementUse(StationMessage._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'Msg')), pyxb.utils.utility.Location('/home/gberg/code/src/fstr/darwinpush/xsd/<API key>.xsd', 54, 3)) st_1 = fac.State(symbol, is_initial=True, final_update=final_update, <API key>=False) states.append(st_1) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_1, [ fac.UpdateInstruction(cc_0, False) ])) st_0._set_transitionSet(transitions) transitions = [] st_1._set_transitionSet(transitions) return fac.Automaton(states, counters, False, containing_state=None) StationMessage._Automaton = _BuildAutomaton_2()
#ifndef <API key> #define <API key> #ifndef NRFX_CONFIG_H__ #error "This file should not be included directly. Include nrfx_config.h instead." #endif // <<< Use Configuration Wizard in Context Menu >>>\n // <h> nRF_Drivers // <e> NRFX_CLOCK_ENABLED - nrfx_clock - CLOCK peripheral driver #ifndef NRFX_CLOCK_ENABLED #define NRFX_CLOCK_ENABLED 0 #endif // <o> <API key> - LF Clock Source // <0=> RC // <1=> XTAL // <2=> Synth // <131073=> External Low Swing // <196609=> External Full Swing #ifndef <API key> #define <API key> 1 #endif // <q> <API key> - Enables LF Clock Calibration Support #ifndef <API key> #define <API key> 0 #endif // <q> <API key> - Enables two-stage LFXO start procedure // <i> If set to a non-zero value, LFRC will be started before LFXO and corresponding // <i> event will be generated. It means that CPU will be woken up when LFRC // <i> oscillator starts, but user callback will be invoked only after LFXO // <i> finally starts. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_COMP_ENABLED - nrfx_comp - COMP peripheral driver #ifndef NRFX_COMP_ENABLED #define NRFX_COMP_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_EGU_ENABLED - nrfx_egu - EGU peripheral driver. #ifndef NRFX_EGU_ENABLED #define NRFX_EGU_ENABLED 0 #endif // <q> NRFX_EGU0_ENABLED - Enable EGU0 instance. #ifndef NRFX_EGU0_ENABLED #define NRFX_EGU0_ENABLED 0 #endif // <q> NRFX_EGU1_ENABLED - Enable EGU1 instance. #ifndef NRFX_EGU1_ENABLED #define NRFX_EGU1_ENABLED 0 #endif // <q> NRFX_EGU2_ENABLED - Enable EGU2 instance. #ifndef NRFX_EGU2_ENABLED #define NRFX_EGU2_ENABLED 0 #endif // <q> NRFX_EGU3_ENABLED - Enable EGU3 instance. #ifndef NRFX_EGU3_ENABLED #define NRFX_EGU3_ENABLED 0 #endif // <q> NRFX_EGU4_ENABLED - Enable EGU4 instance. #ifndef NRFX_EGU4_ENABLED #define NRFX_EGU4_ENABLED 0 #endif // <q> NRFX_EGU5_ENABLED - Enable EGU5 instance. #ifndef NRFX_EGU5_ENABLED #define NRFX_EGU5_ENABLED 0 #endif // <o> <API key> - Interrupt priority. // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> NRFX_GPIOTE_ENABLED - nrfx_gpiote - GPIOTE peripheral driver #ifndef NRFX_GPIOTE_ENABLED #define NRFX_GPIOTE_ENABLED 0 #endif // <o> <API key> - Number of lower power input pins #ifndef <API key> #define <API key> 1 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_NVMC_ENABLED - nrfx_nvmc - NVMC peripheral driver #ifndef NRFX_NVMC_ENABLED #define NRFX_NVMC_ENABLED 0 #endif // <e> NRFX_POWER_ENABLED - nrfx_power - POWER peripheral driver #ifndef NRFX_POWER_ENABLED #define NRFX_POWER_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> NRFX_PPI_ENABLED - nrfx_ppi - PPI peripheral allocator #ifndef NRFX_PPI_ENABLED #define NRFX_PPI_ENABLED 0 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_PRS_ENABLED - nrfx_prs - Peripheral Resource Sharing module #ifndef NRFX_PRS_ENABLED #define NRFX_PRS_ENABLED 0 #endif // <q> <API key> - Enables box 0 in the module. #ifndef <API key> #define <API key> 0 #endif // <q> <API key> - Enables box 1 in the module. #ifndef <API key> #define <API key> 0 #endif // <q> <API key> - Enables box 2 in the module. #ifndef <API key> #define <API key> 0 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_QDEC_ENABLED - nrfx_qdec - QDEC peripheral driver #ifndef NRFX_QDEC_ENABLED #define NRFX_QDEC_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_RNG_ENABLED - nrfx_rng - RNG peripheral driver #ifndef NRFX_RNG_ENABLED #define NRFX_RNG_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_RTC_ENABLED - nrfx_rtc - RTC peripheral driver #ifndef NRFX_RTC_ENABLED #define NRFX_RTC_ENABLED 0 #endif // <q> NRFX_RTC0_ENABLED - Enable RTC0 instance #ifndef NRFX_RTC0_ENABLED #define NRFX_RTC0_ENABLED 0 #endif // <q> NRFX_RTC1_ENABLED - Enable RTC1 instance #ifndef NRFX_RTC1_ENABLED #define NRFX_RTC1_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_SPIM_ENABLED - nrfx_spim - SPIM peripheral driver #ifndef NRFX_SPIM_ENABLED #define NRFX_SPIM_ENABLED 0 #endif // <q> NRFX_SPIM0_ENABLED - Enable SPIM0 instance #ifndef NRFX_SPIM0_ENABLED #define NRFX_SPIM0_ENABLED 0 #endif // <q> NRFX_SPIM1_ENABLED - Enable SPIM1 instance #ifndef NRFX_SPIM1_ENABLED #define NRFX_SPIM1_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_SPIS_ENABLED - nrfx_spis - SPIS peripheral driver #ifndef NRFX_SPIS_ENABLED #define NRFX_SPIS_ENABLED 0 #endif // <q> NRFX_SPIS0_ENABLED - Enable SPIS0 instance #ifndef NRFX_SPIS0_ENABLED #define NRFX_SPIS0_ENABLED 0 #endif // <q> NRFX_SPIS1_ENABLED - Enable SPIS1 instance #ifndef NRFX_SPIS1_ENABLED #define NRFX_SPIS1_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_SPI_ENABLED - nrfx_spi - SPI peripheral driver #ifndef NRFX_SPI_ENABLED #define NRFX_SPI_ENABLED 0 #endif // <q> NRFX_SPI0_ENABLED - Enable SPI0 instance #ifndef NRFX_SPI0_ENABLED #define NRFX_SPI0_ENABLED 0 #endif // <q> NRFX_SPI1_ENABLED - Enable SPI1 instance #ifndef NRFX_SPI1_ENABLED #define NRFX_SPI1_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <q> <API key> - nrfx_systick - ARM(R) SysTick driver #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_TEMP_ENABLED - nrfx_temp - TEMP peripheral driver #ifndef NRFX_TEMP_ENABLED #define NRFX_TEMP_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> NRFX_TIMER_ENABLED - nrfx_timer - TIMER periperal driver #ifndef NRFX_TIMER_ENABLED #define NRFX_TIMER_ENABLED 0 #endif // <q> NRFX_TIMER0_ENABLED - Enable TIMER0 instance #ifndef NRFX_TIMER0_ENABLED #define NRFX_TIMER0_ENABLED 0 #endif // <q> NRFX_TIMER1_ENABLED - Enable TIMER1 instance #ifndef NRFX_TIMER1_ENABLED #define NRFX_TIMER1_ENABLED 0 #endif // <q> NRFX_TIMER2_ENABLED - Enable TIMER2 instance #ifndef NRFX_TIMER2_ENABLED #define NRFX_TIMER2_ENABLED 0 #endif // <q> NRFX_TIMER3_ENABLED - Enable TIMER3 instance #ifndef NRFX_TIMER3_ENABLED #define NRFX_TIMER3_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_TWIM_ENABLED - nrfx_twim - TWIM peripheral driver #ifndef NRFX_TWIM_ENABLED #define NRFX_TWIM_ENABLED 0 #endif // <q> NRFX_TWIM0_ENABLED - Enable TWIM0 instance #ifndef NRFX_TWIM0_ENABLED #define NRFX_TWIM0_ENABLED 0 #endif // <q> NRFX_TWIM1_ENABLED - Enable TWIM1 instance #ifndef NRFX_TWIM1_ENABLED #define NRFX_TWIM1_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_TWIS_ENABLED - nrfx_twis - TWIS peripheral driver #ifndef NRFX_TWIS_ENABLED #define NRFX_TWIS_ENABLED 0 #endif // <q> NRFX_TWIS0_ENABLED - Enable TWIS0 instance #ifndef NRFX_TWIS0_ENABLED #define NRFX_TWIS0_ENABLED 0 #endif // <q> NRFX_TWIS1_ENABLED - Enable TWIS1 instance #ifndef NRFX_TWIS1_ENABLED #define NRFX_TWIS1_ENABLED 0 #endif // <q> <API key> - Assume that any instance would be initialized only once // <i> Optimization flag. Registers used by TWIS are shared by other peripherals. Normally, during initialization driver tries to clear all registers to known state before doing the initialization itself. This gives initialization safe procedure, no matter when it would be called. If you activate TWIS only once and do never uninitialize it - set this flag to 1 what gives more optimal code. #ifndef <API key> #define <API key> 0 #endif // <q> <API key> - Remove support for synchronous mode // <i> Synchronous mode would be used in specific situations. And it uses some additional code and data memory to safely process state machine by polling it in status functions. If this functionality is not required it may be disabled to free some resources. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_TWI_ENABLED - nrfx_twi - TWI peripheral driver #ifndef NRFX_TWI_ENABLED #define NRFX_TWI_ENABLED 0 #endif // <q> NRFX_TWI0_ENABLED - Enable TWI0 instance #ifndef NRFX_TWI0_ENABLED #define NRFX_TWI0_ENABLED 0 #endif // <q> NRFX_TWI1_ENABLED - Enable TWI1 instance #ifndef NRFX_TWI1_ENABLED #define NRFX_TWI1_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_UARTE_ENABLED - nrfx_uarte - UARTE peripheral driver #ifndef NRFX_UARTE_ENABLED #define NRFX_UARTE_ENABLED 0 #endif // <q> NRFX_UARTE0_ENABLED - Enable UARTE0 instance #ifndef NRFX_UARTE0_ENABLED #define NRFX_UARTE0_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_UART_ENABLED - nrfx_uart - UART peripheral driver #ifndef NRFX_UART_ENABLED #define NRFX_UART_ENABLED 0 #endif // <q> NRFX_UART0_ENABLED - Enable UART0 instance #ifndef NRFX_UART0_ENABLED #define NRFX_UART0_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_USBD_ENABLED - nrfx_usbd - USBD peripheral driver #ifndef NRFX_USBD_ENABLED #define NRFX_USBD_ENABLED 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <q> <API key> - Give priority to isochronous transfers // <i> This option gives priority to isochronous transfers. // <i> Enabling it assures that isochronous transfers are always processed, // <i> even if multiple other transfers are pending. // <i> Isochronous endpoints are prioritized before the <API key> // <i> function is called, so the option is independent of the algorithm chosen. #ifndef <API key> #define <API key> 1 #endif // <q> <API key> - Respond to an IN token on ISO IN endpoint with ZLP when no data is ready // <i> If set, ISO IN endpoint will respond to an IN token with ZLP when no data is ready to be sent. // <i> Else, there will be no response. #ifndef <API key> #define <API key> 0 #endif // <e> <API key> - Enable logging in the module #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <e> NRFX_WDT_ENABLED - nrfx_wdt - WDT peripheral driver #ifndef NRFX_WDT_ENABLED #define NRFX_WDT_ENABLED 0 #endif // <q> NRFX_WDT0_ENABLED - Enable WDT0 instance #ifndef NRFX_WDT0_ENABLED #define NRFX_WDT0_ENABLED 0 #endif // <o> <API key> - Remove WDT IRQ handling from WDT driver // <0=> Include WDT IRQ handling // <1=> Remove WDT IRQ handling #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Interrupt priority // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef <API key> #define <API key> 7 #endif // <e> <API key> - Enables logging in the module. #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef <API key> #define <API key> 3 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif // <o> <API key> - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef <API key> #define <API key> 0 #endif #endif // <API key>
FROM java:openjdk-8-jre MAINTAINER Martijn Koster "mak-docker@greenhills.co.uk" ENV SOLR_VERSION 5.2.1 ENV SOLR solr-$SOLR_VERSION ENV SOLR_USER solr RUN export DEBIAN_FRONTEND=noninteractive && \ apt-get update && \ apt-get -y install lsof && \ groupadd -r $SOLR_USER && \ useradd -r -g $SOLR_USER $SOLR_USER && \ mkdir -p /opt && \ wget -nv --output-document=/opt/$SOLR.tgz http: tar -C /opt --extract --file /opt/$SOLR.tgz && \ rm /opt/$SOLR.tgz && \ ln -s /opt/$SOLR /opt/solr && \ chown -R $SOLR_USER:$SOLR_USER /opt/solr /opt/$SOLR EXPOSE 8983 WORKDIR /opt/solr USER $SOLR_USER CMD ["/bin/bash", "-c", "/opt/solr/bin/solr -f"]
SELECT * FROM tbl1_ts; \c db_ts; \l+; SELECT * FROM tbl2_ts; select spcname from pg_tablespace where spcname='ts';
from urlparse import urlparse from api_tests.nodes.views.<API key> import NodeCRUDTestCase from nose.tools import * # flake8: noqa from api.base.settings.defaults import API_BASE from framework.auth.core import Auth from tests.base import fake from osf_tests.factories import ( ProjectFactory, CommentFactory, RegistrationFactory, <API key>, ) class <API key>(NodeCRUDTestCase): def setUp(self): super(<API key>, self).setUp() self.registration = RegistrationFactory(creator=self.user, project=self.public_project) self.<API key> = <API key>(registration=self.registration, user=self.registration.creator) self.<API key> = ProjectFactory(is_public=True) self.public_pointer = self.public_project.add_pointer(self.<API key>, auth=Auth(self.user), save=True) self.withdrawn_url = '/{}registrations/{}/?version=2.2'.format(API_BASE, self.registration._id) self.<API key>.justification = 'We made a major error.' self.<API key>.save() def <API key>(self): url = '/{}registrations/{}/contributors/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 200) def <API key>(self): url = '/{}registrations/{}/children/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def <API key>(self): self.public_project = ProjectFactory(is_public=True, creator=self.user) self.public_comment = CommentFactory(node=self.public_project, user=self.user) url = '/{}registrations/{}/comments/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def <API key>(self): url = '/{}registrations/{}/contributors/{}/'.format(API_BASE, self.registration._id, self.user._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 200) def <API key>(self): url = '/{}nodes/{}/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 404) def <API key>(self): url = '/{}registrations/{}/'.format(API_BASE, self.registration._id) res = self.app.delete_json_api(url, auth=self.user.auth, expect_errors=True) self.registration.reload() assert_equal(res.status_code, 405) def <API key>(self): url = '/{}registrations/{}/files/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def <API key>(self): url = '/{}registrations/{}/node_links/{}/'.format(API_BASE, self.registration._id, self.public_pointer._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def <API key>(self): url = '/{}registrations/{}/node_links/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def <API key>(self): self.public_project = ProjectFactory(is_public=True, creator=self.user) url = '/{}registrations/{}/logs/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def <API key>(self): self.registration.save() url = '/{}registrations/{}/registrations/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def <API key>(self): registration = self.registration res = self.app.get(self.withdrawn_url, auth=self.user.auth) assert_equal(res.status_code, 200) attributes = res.json['data']['attributes'] registration.reload() expected_attributes = { 'title': registration.title, 'description': registration.description, 'date_created': registration.date_created.isoformat().replace('+00:00', 'Z'), 'date_registered': registration.registered_date.isoformat().replace('+00:00', 'Z'), 'date_modified': registration.date_modified.isoformat().replace('+00:00', 'Z'), '<API key>': registration.retraction.justification, 'public': None, 'category': None, 'registration': True, 'fork': None, 'collection': None, 'tags': None, 'withdrawn': True, 'pending_withdrawal': None, '<API key>': None, '<API key>': None, 'embargo_end_date': None, 'registered_meta': None, '<API key>': None, '<API key>': registration.registered_schema.first().name } for attribute in expected_attributes: assert_equal(expected_attributes[attribute], attributes[attribute]) contributors = urlparse(res.json['data']['relationships']['contributors']['links']['related']['href']).path assert_equal(contributors, '/{}registrations/{}/contributors/'.format(API_BASE, registration._id)) assert_not_in('children', res.json['data']['relationships']) assert_not_in('comments', res.json['data']['relationships']) assert_not_in('node_links', res.json['data']['relationships']) assert_not_in('registrations', res.json['data']['relationships']) assert_not_in('parent', res.json['data']['relationships']) assert_not_in('forked_from', res.json['data']['relationships']) assert_not_in('files', res.json['data']['relationships']) assert_not_in('logs', res.json['data']['relationships']) assert_not_in('registered_by', res.json['data']['relationships']) assert_not_in('registered_from', res.json['data']['relationships']) assert_not_in('root', res.json['data']['relationships']) def test_field_specific_related_counts_ignored_if_hidden_field_on_withdrawn_registration(self): url = '/{}registrations/{}/?related_counts=children'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_not_in('children', res.json['data']['relationships']) assert_in('contributors', res.json['data']['relationships']) def test_field_specific_related_counts_retrieved_if_visible_field_on_withdrawn_registration(self): url = '/{}registrations/{}/?related_counts=contributors'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.json['data']['relationships']['contributors']['links']['related']['meta']['count'], 1)
if (!this["output"]) output = print; var passed = 0; var failed = 0; function is(got, expected, msg) { if (got == expected) { output("OK: " + msg); ++passed; } else { output("FAIL: " + msg); output("Expected |" + expected + "|"); output(" Got |" + got + "|"); ++failed; } } function complete() { output("\nTests Complete"); output(" output("Passed: " + passed); output("Failed: " + failed); output("\n"); } // test our internal functions function <API key>() { is(isObjectOrArray({}), true, "isObjectOrArray detects an object"); is(isObjectOrArray([]), true, "isObjectOrArray detects an array"); is(isObjectOrArray("foo"), false, "isObjectOrArray shouldn't detect string"); is(isObjectOrArray(4), false, "isObjectOrArray shouldn't detect integer"); is(isObjectOrArray(5.5), false, "isObjectOrArray shouldn't detect float"); is(isObjectOrArray(undefined), false, "isObjectOrArray shouldn't detect undefined"); is(isObjectOrArray(null), false, "isObjectOrArray shouldn't detect null"); } function <API key>() { var suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmm"}, {"a": 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 0, "shouldn't be any suspects for matching primitives"); suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmm"}, {"a": 1, "b": 3, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect edited primitives"); suspects = identifySuspects({"a": 1, "b": {}, "c": 3, "d": "hmm"}, {"a": 1, "b": {}, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect matching objects"); suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmm"}, {"a": "1", "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect primitive type change"); suspects = identifySuspects({"a": 1, "b": 2, "c": 3, "d": "hmmm"}, {"a": 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 1, "should detect string edit"); suspects = identifySuspects({"xxx": 1, "b": 2, "c": 3, "d": "hmm"}, {"yyy": 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 2, "should detect differing keys"); suspects = identifySuspects({"0": 1, "b": 2, "c": 3, "d": "hmm"}, {0: 1, "b": 2, "c": 3, "d": "hmm"}); is(suspects.length, 0, "should not detect key type changes"); } function test_created() { var record = created(["foo"], {}); is(record.length, 1, "created empty object is length 1"); record = created(["foo"], 1); is(record.length, 1, "created primitive is length 1"); record = created(["foo"], {"bar":"baz"}); is(record.length, 2, "created populated object is length 2"); record = created(["foo"], {"bar":"baz", "qux":"baz"}); is(record.length, 3, "created populated object is length 3"); is(record[0].action, "create", "create action is correct"); is(record[0].path.length, 1, "creation paths in preorder"); is(record[1].path.length, 2, "creation paths in preorder"); is(record[1].value, "baz", "create has correct value"); is(record[2].path.length, 2, "creation paths in preorder"); is(record[2].value, "baz", "create has correct value"); } function test_removed() { var record = removed(["foo"], {}); is(record.length, 1, "removed empty object is length 1"); record = removed(["foo"], 1); is(record.length, 1, "removed primitive is length 1"); record = removed(["foo"], {"bar":"baz"}); is(record.length, 2, "removed populated object is length 2"); record = removed(["foo"], {"bar":"baz", "qux":"baz"}); is(record.length, 3, "removed populated object is length 3"); is(record[0].action, "remove", "remove action is correct"); is(record[0].path.length, 2, "removal paths in postorder"); is(record[1].path.length, 2, "removal paths in postorder"); is(record[2].path.length, 1, "removal paths in postorder"); } function test_edited() { var record = edited(["foo"], 5, 3); is(record.length, 1, "primitive edit is length 1"); is(record[0].action, "edit", "edit action is correct"); is(record[0].value, 3, "edit has correct value"); is(record[0].path.length, 1, "edit path is correct"); record = edited(["foo"], {"bar": "baz"}, 3); is(record.length, 2, "obj2primitive contains removals"); is(record[0].action, "edit", "edits precede removals"); is(record[1].action, "remove", "remove action is there"); record = edited(["foo"], 3, {"bar": "baz"}); is(record.length, 2, "primitive2object contains creations"); is(record[0].action, "edit", "edits precede creations"); is(record[1].action, "create", "create action is there"); }; // A snapshot, followed by four non-conflicting replicas var snap = { "foo": 1, "bar": 1, "baz": 1, "qux": 1 } var replica1 = { "foo": 0, "bar": 1, "baz": 1, "qux": 1 } var replica2 = { "foo": 1, "bar": 0, "baz": 1, "qux": 1 } var replica3 = { "foo": 1, "bar": 1, "baz": 0, "qux": 1 } var replica4 = { "foo": 1, "bar": 1, "baz": 1, "qux": 0 } function test_detectUpdates() { function checkReplica(name, replica) { var updateList = detectUpdates(snap, replica); is(updateList.length, 1, name + " has correct number of updates"); is(updateList[0].action, "edit", name + " should have an edit"); is(updateList[0].value, 0, name + " should have value 0"); } checkReplica("replica1", replica1); checkReplica("replica2", replica2); checkReplica("replica3", replica3); checkReplica("replica4", replica4); } function test_orderUpdates() { } function test_Command() { var x = new Command("edit", ["foo"], 5); var y = new Command("edit", ["foo"], 5); is(x instanceof Command, true, "instanceof"); is(x.equals(y), true, "equals method of Command works"); x.value = "5"; y.value = 5; is(x.equals(y), false, "equals method of Command detects type changes"); x.value = {}; y.value = {}; is(x.equals(y), true, "equals method of Command matches {} values"); x.value = []; y.value = []; is(x.equals(y), true, "equals method of Command matches [] values"); x.value = "5"; y.value = []; is(x.equals(y), false, "equals method of Command detects obj vs. primitive"); var z = new Command("edit", ["foo","bar"], 5); is(x.isParentOf(z), true, "check for parents"); } function test_commandInList() { var x = new Command("edit", ["foo"], 5); var y = new Command("remove", ["bar"]); var commandList = [new Command("edit", ["foo"], 5), new Command("remove", ["bar"])]; is(commandInList(x, commandList), true, "commandInList matches identical"); is(commandInList(y, commandList), true, "commandInList matches removes"); is(commandInList(new Command("edit", ["foo"], "bar"), [new Command("edit", ["foo"], "bar")]), true, "edits match"); is(commandInList(new Command("edit", ["foo"], 6), commandList), false, "commandInList fails differing values"); } function test_doesConflict() { var x = new Command("edit", ["foo"], 1); var y = new Command("edit", ["foo"], 2); is(doesConflict(x, y), true, "doesConflict finds identical paths with different values"); y.path = ["bar"]; is(doesConflict(x, y), false, "doesConflict ignores mismatched paths"); var a = new Command("remove", ["foo"]); var b = new Command("edit", ["foo","bar"], 42); is(doesConflict(a, b), true, "doesConflict catches edit under remove"); is(doesConflict(b, a), true, "doesConflict catches edit under remove"); } function test_applyCommand() { var c = new Command("edit", ["foo"], "bar"); var target = {foo: "qux"}; applyCommand(target, c); is(target.foo, "bar", "applying edit commands works"); } function <API key>() { var syncdata = reconcile([detectUpdates(snap, replica1), detectUpdates(snap, replica2), detectUpdates(snap, replica3), detectUpdates(snap, replica4)]); is(syncdata.propagations.length, 4, "correct number of propogation arrays"); is(syncdata.propagations[0].length, 3, "correct number of commands to exec"); is(syncdata.propagations[0][0].action, "edit", "is it an edit?"); applyCommands(replica1, syncdata.propagations[0]); applyCommands(replica2, syncdata.propagations[1]); applyCommands(replica3, syncdata.propagations[2]); applyCommands(replica4, syncdata.propagations[3]); forEach([replica1, replica2, replica3, replica4], function (replica) { is(replica.foo, 0, "replica.foo is zero"); is(replica.baz, 0, "replica.bar is zero"); is(replica.bar, 0, "replica.baz is zero"); is(replica.qux, 0, "replica.qux is zero"); } ); } function pathToArray(path) { return path == "/" ? [] : path.split("/").slice(1); } function commandFromArray(key, array) { var c = array.filter( function(c) { return ("/" + c.path.join("/")) == key; } ); return c[0]; } function checkUpdate(list, path, expectAction, expectValue) { var x = commandFromArray(path, list); is(x.action, expectAction, path + " action"); if (isObjectOrArray(expectValue)) is(x.value.constructor, expectValue.constructor, path + " value"); else is(x.value, expectValue, path + " value"); is(arrayEqual(x.path, pathToArray(path)), true, path + " path"); } function checkSync(obj1, obj2, path, value) { field1 = pathToReference(obj1, pathToArray(path)); field2 = pathToReference(obj2, pathToArray(path)); is(field1, field2, path + " in sync"); is(field1, value, path + " correct value"); } // the README examples var snapshotJSON = { "x": 42, "a": 1, "b": { "c": 2, "d": { "e": 3, "f": 4 }, "g": 5 }, "h": 6.6, "i": [7, 8, 9], "j": 10, "k": { "m": 11 }, "n": 66, } var currentJSON = { "x": 43, /* edited */ "a": 1, "new": 11, /* created */ "b": { "c": 2, "new2": 22, /* created */ "d": { "e": 3, /*"f": 4*/ /* removed */ }, "g": 55, /* edited */ }, /* "h": 6.6, */ /* removed */ "i": [7, 8, 9, 99], /* added array element */ "j": 10, "k": 42, /* replaced object with primitive */ "n": { "new3": 77 }, /* replaced primitive with object */ } function <API key>() { var updates = detectUpdates(snapshotJSON, currentJSON); is(updates.length, 11, "detect correct number of updates"); checkUpdate(updates, "/x", "edit", 43); checkUpdate(updates, "/new", "create", 11); checkUpdate(updates, "/b/new2", "create", 22); checkUpdate(updates, "/b/d/f", "remove", undefined); checkUpdate(updates, "/b/g", "edit", 55); checkUpdate(updates, "/h", "remove", undefined); checkUpdate(updates, "/i/3", "create", 99); checkUpdate(updates, "/k/m", "remove", undefined); checkUpdate(updates, "/k", "edit", 42); checkUpdate(updates, "/n", "edit", {}); checkUpdate(updates, "/n/new3", "create", 77); // now we check against an object that contains edits to other // fields, or identical edits. var otherJSON = { "x": 43, /* edited to the same value */ "a": 100, /* non-conflicting edit */ "new": 11, /* created to the same value */ "b": { /*"c": 2,*/ /* non-conflicting remove */ "d": { "e": 3, /*"f": 4*/ /* removed same value */ }, "g": 5, /* didn't edit */ "foo": 555 /* non-conflicting create */ }, "h": 6.6, /* didn't remove */ "i": [7, 8, 9, 99], /* added same array element */ "j": 10, "k": { "m": 11 }, /* didn't touch */ "n": 66 /* didn't touch */ } var otherUpdates = detectUpdates(snapshotJSON, otherJSON); checkUpdate(otherUpdates, "/x", "edit", 43); checkUpdate(otherUpdates, "/a", "edit", 100); checkUpdate(otherUpdates, "/b/c", "remove", undefined); checkUpdate(otherUpdates, "/b/d/f", "remove", undefined); checkUpdate(otherUpdates, "/i/3", "create", 99); var syncdata = reconcile([updates, otherUpdates]); applyCommands(currentJSON, syncdata.propagations[0]); applyCommands(otherJSON, syncdata.propagations[1]); checkSync(currentJSON, otherJSON, "/x", 43); checkSync(currentJSON, otherJSON, "/a", 100); checkSync(currentJSON, otherJSON, "/new", 11); checkSync(currentJSON, otherJSON, "/b/c", undefined); checkSync(currentJSON, otherJSON, "/b/new2", 22); checkSync(currentJSON, otherJSON, "/b/d/f", undefined); checkSync(currentJSON, otherJSON, "/b/g", 55); checkSync(currentJSON, otherJSON, "/b/foo", 555); checkSync(currentJSON, otherJSON, "/h", undefined); checkSync(currentJSON, otherJSON, "/i/3", 99); checkSync(currentJSON, otherJSON, "/k", 42); checkSync(currentJSON, otherJSON, "/n/new3", 77); checkSync(currentJSON, otherJSON, "/j", 10); } function <API key>() { var originalJSON = {"foo": {"bar": "baz"}, "toBeRemoved":"goner", "someArray":["tobeEdited"]}; var clientJSON = {"foo": {"bar": "baz"}, "toBeRemoved":"goner", "someArray":["tobeEdited"]}; var serverJSON = {"foo": {"bar": "baz"}, "toBeRemoved":"goner", "someArray":["tobeEdited"]}; clientJSON["foo"]["clientAddition"] = "the client added this"; serverJSON["foo"]["serverAddition"] = "the server added this"; delete clientJSON["toBeRemoved"]; delete serverJSON["toBeRemoved"]; clientJSON["someArray"][0] = "been edited"; serverJSON["someArray"][0] = "been edited"; var syncdata = reconcile([detectUpdates(originalJSON, clientJSON), detectUpdates(originalJSON, serverJSON)]); applyCommands(clientJSON, syncdata.propagations[0]); applyCommands(serverJSON, syncdata.propagations[1]); is(clientJSON["foo"]["bar"] == serverJSON["foo"]["bar"], true, "unchanged fields remain"); is(serverJSON["foo"]["clientAddition"], clientJSON["foo"]["clientAddition"], "server has client addition"); is(clientJSON["foo"]["serverAddition"], serverJSON["foo"]["serverAddition"], "client has server addition"); is(clientJSON["toBeRemoved"] == undefined, true, "removed from client"); is(serverJSON["toBeRemoved"] == undefined, true, "removed from server"); is(clientJSON["someArray"][0] == serverJSON["someArray"][0], true, "identically edited array ok"); /* now all the fields are the same */ originalJSON = { "foo": {"bar":"baz", "clientAddition":"the client added this", "serverAddition":"the server added this"}, "someArray":["been edited"]} ; clientJSON["someArray"][0] = "edited again"; serverJSON["foo"]["bar"] = "edit some other field"; syncdata = reconcile([detectUpdates(originalJSON, clientJSON), detectUpdates(originalJSON, serverJSON)]); applyCommands(clientJSON, syncdata.propagations[0]); applyCommands(serverJSON, syncdata.propagations[1]); is(serverJSON["someArray"][0], "edited again", "repeated edit works"); is(serverJSON["foo"]["bar"], "edit some other field", "repeated edit works"); } function <API key>() { var conflictList = <API key>(new Command("edit", ["f"], "b"), [new Command("edit", ["f"], "b")]); is(conflictList.conflicts.length, 0, "identical commands don't conflict"); } function test_basicConflicts() { // conflicting edits var snap = {"foo":"bar"} var clientJSON = {"foo":"baz"} var serverJSON = {"foo":"qux"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); // should have zero propagations and one conflict is(syncdata.propagations[0].length, 0, "complete edit conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete edit conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "single edit field conflicting should have one conflict"); is(syncdata.conflicts[1].length, 1, "single edit field conflicting should have one conflict"); // conflicting creates var snap = {"foo":"bar"} var clientJSON = {"foo":"bar","baz":"qux"} var serverJSON = {"foo":"bar","baz":"quux"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); // should have zero propagations and one conflict is(syncdata.propagations[0].length, 0, "complete create conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete create conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "single create field conflicting should have one conflict"); is(syncdata.conflicts[1].length, 1, "single create field conflicting should have one conflict"); // edit that conflicts with a remove of its parent var snap = {"foo":{"bar":"baz"}, "xuq":"xuuq"} var clientJSON = {"xuq":"xuuq"} var serverJSON = {"foo":{"bar":"qux"}, "xuq":"xuuq"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: the edit to /foo/bar"); is(syncdata.conflicts[1].length, 2, "the server gets two conflicts: both of the removals"); // edit that conflicts with an empty object var snap = {"foo":{"bar":"baz"}} var clientJSON = {} var serverJSON = {"foo":{"bar":"qux"}} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: the edit to /foo/bar"); is(syncdata.conflicts[1].length, 2, "the server gets two conflicts: both of the removals"); // hierarchical create conflict var snap = {"foo":"bar"} var clientJSON = {"foo":"bar", "baz":{"qux":"quux"}} var serverJSON = {"foo":"bar", "baz":"b"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: creation of /baz"); is(syncdata.conflicts[1].length, 2, "the server gets two conflicts: both of the client creates"); // edited to primitive var snap = {"foo":"bar", "baz":{}} var clientJSON = {"foo":"bar", "baz":{"qux":"quux"}} var serverJSON = {"foo":"bar", "baz":"b"} var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); is(syncdata.propagations[0].length, 0, "complete remove conflict should have no propagations"); is(syncdata.propagations[1].length, 0, "complete remove conflict should have no propagations"); is(syncdata.conflicts[0].length, 1, "the client gets one conflict: edit of /baz"); is(syncdata.conflicts[1].length, 1, "the server gets one conflict: the creation of /baz/qux"); } function test_arrayMerging() { var snap = { "foo": [ {"a": "1"}, {"b": "2"}, {"c": "3"} ] } var clientJSON = { "foo": [ {"a": "1"}, {"b": "2"}, {"b2": "2b"}, {"c": "3"} ] } var serverJSON = { "foo": [ {"a": "1"}, {"a1": "1a"}, {"b": "2"}, {"c": "3"} ] } var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); // The result we end up with here is a little counter-intuitive. // The object with keys "b" and "b2" both end up being creates // underneath /foo/2. This illustrates the need to let clients // define properties that serve as identifiers. is(syncdata.propagations[0].length, 3, "move the indexes up"); is(syncdata.propagations[1].length, 1, "apply a create inside /foo/2"); is(syncdata.conflicts[0].length, 0, "no conflicts in array merging"); is(syncdata.conflicts[0].length, 0, "no conflicts in array merging"); applyCommands(clientJSON, syncdata.propagations[0]); applyCommands(serverJSON, syncdata.propagations[1]); checkSync(clientJSON, serverJSON, "/foo/0/a", "1"); checkSync(clientJSON, serverJSON, "/foo/1/a1", "1a"); checkSync(clientJSON, serverJSON, "/foo/2/b", "2"); checkSync(clientJSON, serverJSON, "/foo/2/b2", "2b"); checkSync(clientJSON, serverJSON, "/foo/3/c", "3"); } function <API key>() { var snap = { "foo": [ {"a": "1"}, {"b": "2"}, {"c": "3"} ] } var clientJSON = { "foo": [ {"a": "1"}, {"b": "2"}, {"b2": "2b"}, {"c": "3"} ] } var serverJSON = { "foo": [ {"a": "1"}, {"a1": "1a"}, {"b": "2"}, {"c": "3"} ] } var syncdata = reconcile([detectUpdates(snap, clientJSON), detectUpdates(snap, serverJSON)]); output(syncdata.propagations[0].length + " " + syncdata.propagations[1].length) output(syncdata.conflicts[0].length + " " + syncdata.conflicts[1].length) forEach(syncdata.propagations[0], function(x) { output(x.action + " " + x.path + " = " + x.value)}) output(" forEach(syncdata.propagations[1], function(x) { output(x.action + " " + x.path + " = " + x.value)}) } function <API key>() { var snap = { "foo": { "bar": "baz", "bar2": "baz2" }, "foo2": { "hmm1": { "hmm": "yeah", "hm1": "hmmm", "hm2": "hmmmmmm" }, "foo3": { "bar3": ["hmm", "yeah", "ok"], "baz3": [ {"a": "1"}, {"b": "2"}, {"c": "3"} ] } } } var clientJSON = { "foo": { "bar": "baz1", /* conflict */ "bar2": "baz2", "fff": "ggg" /* no conflict create */ }, "foo2": { "hmm1": { "hmm": "yeah", "hm1": "hmmm", "hm2": "hmmmmmm" }, "foo3": { "bar3": ["hmm", "yeah", "ok"], "baz3": [ {"a": "1"}, {"a2": "12"}, {"b": "2"}, {"c": "3"} ] } } } var serverJSON = { "foo": { "bar": "asdfasdf", /* conflict */ "bar2": "baz2", "fff": "ggg", /* no conflict create */ "fff2": "ggg2" /* no conflict create */ }, "foo2": { "hmm1": { "hmm": "yeah", "hm1": "hmmm", "hm2": "hmmmmmm" }, "foo3": { "bar3": ["hmm", "yeah", "ok"], "baz3": [ {"a": "1"}, {"b": "2"}, {"b2": "2b"}, {"c": "3"} ] } } } } function runTests() { output("\n\nTests Starting"); output(" <API key>(); <API key>(); test_created(); test_removed(); test_edited(); test_detectUpdates(); test_orderUpdates(); test_Command(); test_commandInList(); test_doesConflict(); test_applyCommand(); <API key>(); <API key>(); <API key>(); <API key>(); test_basicConflicts(); test_arrayMerging(); //<API key>(); complete(); } if (this["document"]) { window.onload = runTests; } else { runTests(); }
//where /** Generate code to create an array with given element type and number * of dimensions. */ Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { try { DEBUG.P(this,"makeNewArray(3)"); DEBUG.P("type="+type); DEBUG.P("ndims="+ndims); Type elemtype = types.elemtype(type); if (types.dimensions(elemtype) + ndims > ClassFile.MAX_DIMENSIONS) { log.error(pos, "limit.dimensions"); nerrs++; } int elemcode = Code.arraycode(elemtype); DEBUG.P("elemcode="+elemcode); if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { code.emitAnewarray(makeRef(pos, elemtype), type); } else if (elemcode == 1) { code.emitMultianewarray(ndims, makeRef(pos, type), type); } else { code.emitNewarray(elemcode, type); } return items.makeStackItem(type); }finally{ DEBUG.P(0,this,"makeNewArray(3)"); } }
import * as _ from 'lodash'; interface <API key> { getApplications(context: any): Promise<any>; } /** Backend service communications. */ export class ApplicationsService implements <API key> { public static $inject = ['$filter', '$q', 'DataService']; private $filter: any; private $q: any; private DataService: any; constructor ($filter: any, $q: any, DataService: any) { this.$filter = $filter; this.$q = $q; this.DataService = DataService; } public getApplications(context: any): Promise<any> { var deferred: any = this.$q.defer(); var promises: any = []; // Load all the "application" types promises.push(this.DataService.list('deploymentconfigs', context)); promises.push(this.DataService.list('<API key>', context)); promises.push(this.DataService.list({group: 'apps', resource: 'deployments'}, context)); promises.push(this.DataService.list({group: 'extensions', resource: 'replicasets'}, context)); promises.push(this.DataService.list({group: 'apps', resource: 'statefulsets'}, context)); this.$q.all(promises).then(_.spread((<API key>: any, <API key>: any, deploymentData: any, replicaSetData: any, statefulSetData: any) => { var deploymentConfigs: any = _.toArray(<API key>.by('metadata.name')); var <API key>: any = _.reject(<API key>.by('metadata.name'), this.$filter('hasDeploymentConfig')); var deployments: any = _.toArray(deploymentData.by('metadata.name')); var replicaSets: any = _.reject(replicaSetData.by('metadata.name'), this.$filter('hasDeployment')); var statefulSets: any = _.toArray(statefulSetData.by('metadata.name')); var apiObjects: any = deploymentConfigs.concat(deployments) .concat(<API key>) .concat(replicaSets) .concat(statefulSets); deferred.resolve(_.sortBy(apiObjects, ['metadata.name', 'kind'])); }), function(e: any) { deferred.reject(e); }); return deferred.promise; } }
Imports System.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Delegate Function GenerateMethodBody(method As EEMethodSymbol, diagnostics As DiagnosticBag) As BoundStatement Friend NotInheritable Class EEMethodSymbol Inherits MethodSymbol Friend ReadOnly TypeMap As TypeSubstitution Friend ReadOnly <API key> As MethodSymbol Friend ReadOnly Locals As ImmutableArray(Of LocalSymbol) Friend ReadOnly LocalsForBinding As ImmutableArray(Of LocalSymbol) Private ReadOnly _compilation As <API key> Private ReadOnly _container As EENamedTypeSymbol Private ReadOnly _name As String Private ReadOnly _locations As ImmutableArray(Of Location) Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _meParameter As ParameterSymbol Private ReadOnly <API key> As ImmutableDictionary(Of String, <API key>) Private ReadOnly _voidType As NamedTypeSymbol ''' <summary> ''' Invoked at most once to generate the method body. ''' (If the compilation has no errors, it will be invoked ''' exactly once, otherwise it may be skipped.) ''' </summary> Private ReadOnly _generateMethodBody As GenerateMethodBody Private _lazyReturnType As TypeSymbol ' NOTE: This is only used for asserts, so it could be conditional on DEBUG. Private ReadOnly _allTypeParameters As ImmutableArray(Of TypeParameterSymbol) Friend Sub New( compilation As <API key>, container As EENamedTypeSymbol, name As String, location As Location, sourceMethod As MethodSymbol, sourceLocals As ImmutableArray(Of LocalSymbol), <API key> As ImmutableArray(Of LocalSymbol), <API key> As ImmutableDictionary(Of String, <API key>), voidType As NamedTypeSymbol, generateMethodBody As GenerateMethodBody) Debug.Assert(sourceMethod.IsDefinition) Debug.Assert(sourceMethod.ContainingSymbol = container.<API key>.OriginalDefinition) Debug.Assert(sourceLocals.All(Function(l) l.ContainingSymbol = sourceMethod)) _compilation = compilation _container = container _name = name _locations = ImmutableArray.Create(location) _voidType = voidType ' What we want is to map all original type parameters to the corresponding new type parameters ' (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: ' 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. ' 2) The map cannot be constructed until all new type parameters exist. ' Our solution is to pass each new type parameter a lazy reference to the type map. We then ' initialize the map as soon as the new type parameters are available - and before they are ' handed out - so that there is never a period where they can require the type map and find ' it uninitialized. Dim <API key> = sourceMethod.TypeParameters Dim <API key> = container.<API key>.Concat(<API key>) Dim getTypeMap As New Func(Of TypeSubstitution)(Function() TypeMap) _typeParameters = <API key>.SelectAsArray( Function(tp As TypeParameterSymbol, i As Integer, arg As Object) DirectCast(New <API key>(Me, tp, i, getTypeMap), TypeParameterSymbol), DirectCast(Nothing, Object)) _allTypeParameters = container.TypeParameters.Concat(_typeParameters) Me.TypeMap = TypeSubstitution.Create(sourceMethod, <API key>, <API key>.Cast(Of TypeParameterSymbol, TypeSymbol)(_allTypeParameters)) EENamedTypeSymbol.<API key>(Me, _typeParameters) Dim <API key> = container.<API key> Me.<API key> = sourceMethod.AsMember(<API key>) If _typeParameters.Any() Then Me.<API key> = Me.<API key>.Construct(_typeParameters.As(Of TypeSymbol)()) End If <API key>.Check(Me.<API key>, _allTypeParameters) ' Create a map from original parameter to target parameter. Dim parameterBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim <API key> = Me.<API key>.MeParameter Dim <API key> = <API key> IsNot Nothing If <API key> Then _meParameter = MakeParameterSymbol(0, GeneratedNames.<API key>(), <API key>) ' NOTE: Name doesn't actually matter. Debug.Assert(_meParameter.Type = Me.<API key>.ContainingType) parameterBuilder.Add(_meParameter) End If Dim ordinalOffset = If(<API key>, 1, 0) For Each <API key> In Me.<API key>.Parameters Dim ordinal = <API key>.Ordinal + ordinalOffset Debug.Assert(ordinal = parameterBuilder.Count) Dim parameter = MakeParameterSymbol(ordinal, <API key>.Name, <API key>) parameterBuilder.Add(parameter) Next _parameters = parameterBuilder.ToImmutableAndFree() Dim localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim localsMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() For Each sourceLocal In sourceLocals Dim local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) localsBuilder.Add(local) Next Me.Locals = localsBuilder.ToImmutableAndFree() localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each sourceLocal In <API key> Dim local As LocalSymbol = Nothing If Not localsMap.TryGetValue(sourceLocal, local) Then local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) End If localsBuilder.Add(local) Next Me.LocalsForBinding = localsBuilder.ToImmutableAndFree() ' Create a map from variable name to display class field. Dim <API key> = PooledDictionary(Of String, <API key>).GetInstance() For Each pair In <API key> Dim variable = pair.Value Dim <API key> = TryCast(variable.<API key>, <API key>) Dim <API key> = If(<API key> Is Nothing, DirectCast(New <API key>(Me.Parameters(0)), <API key>), New <API key>(DirectCast(localsMap(<API key>.Local), EELocalSymbol))) variable = variable.SubstituteFields(<API key>, Me.TypeMap) <API key>.Add(pair.Key, variable) Next <API key> = <API key>.<API key>() <API key>.Free() localsMap.Free() _generateMethodBody = generateMethodBody End Sub Private Function MakeParameterSymbol(ordinal As Integer, name As String, sourceParameter As ParameterSymbol) As ParameterSymbol Return New <API key>( Me, sourceParameter.Type, ordinal, sourceParameter.IsByRef, name, sourceParameter.CustomModifiers, sourceParameter.<API key>) End Function Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property <API key> As <API key> Get Return Nothing End Get End Property Friend Overrides ReadOnly Property <API key> As Boolean Get Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides Function <API key>() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property <API key> As <API key> Get Return Nothing End Get End Property Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean meParameter = Nothing Return True End Function Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return ReturnType.SpecialType = SpecialType.System_Void End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get If _lazyReturnType Is Nothing Then Throw New <API key>() End If Return _lazyReturnType End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return <API key>.Cast(Of TypeParameterSymbol, TypeSymbol)(_typeParameters) End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property <API key> As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property <API key> As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides Function <API key>() As ImmutableArray(Of String) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property CallingConvention As Cci.CallingConvention Get Debug.Assert(Me.IsShared) Dim cc = Cci.CallingConvention.Default If Me.IsVararg Then cc = cc Or Cci.CallingConvention.ExtraArguments End If If Me.IsGenericMethod Then cc = cc Or Cci.CallingConvention.Generic End If Return cc End Get End Property Friend Overrides ReadOnly Property <API key> As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _locations End Get End Property Public Overrides ReadOnly Property <API key> As ImmutableArray(Of SyntaxReference) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property <API key> As Accessibility Get Return Accessibility.Internal End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property <API key> As <API key> Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property <API key> As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Syntax As <API key> Get Return Nothing End Get End Property #Disable Warning RS0010 ''' <remarks> ''' The corresponding C# method, ''' <see cref="M:Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EEMethodSymbol.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.<API key>,Microsoft.CodeAnalysis.DiagnosticBag)"/>, ''' invokes the <see cref="LocalRewriter"/> and the <see cref="LambdaRewriter"/> explicitly. ''' In VB, the caller (of this method) does that.
-- Database: mssql -- Change Parameter: column1Name=first_name -- Change Parameter: column2Name=last_name -- Change Parameter: finalColumnName=full_name -- Change Parameter: finalColumnType=varchar(255) -- Change Parameter: tableName=person ALTER TABLE person ADD full_name varchar(255); UPDATE person SET full_name = first_name + 'null' + last_name; ALTER TABLE person DROP COLUMN first_name; ALTER TABLE person DROP COLUMN last_name;
<html><body> <style> body, h1, h2, h3, div, span, p, pre, a { margin: 0; padding: 0; border: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; vertical-align: baseline; } body { font-size: 13px; padding: 1em; } h1 { font-size: 26px; margin-bottom: 1em; } h2 { font-size: 24px; margin-bottom: 1em; } h3 { font-size: 20px; margin-bottom: 1em; margin-top: 1em; } pre, code { line-height: 1.5; font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Lucida Console', monospace; } pre { margin-top: 0.5em; } h1, h2, h3, p { font-family: Arial, sans serif; } h1, h2, h3 { border-bottom: solid #CCC 1px; } .toc_element { margin-top: 0.5em; } .firstline { margin-left: 2 em; } .method { margin-top: 1em; border: solid 1px #CCC; padding: 1em; background: #EEE; } .details { font-weight: bold; font-size: 14px; } </style> <h1><a href="<API key>.html">Cloud Video Intelligence API</a> . <a href="<API key>.operations.html">operations</a> . <a href="<API key>.operations.projects.html">projects</a> . <a href="<API key>.operations.projects.locations.html">locations</a></h1> <h2>Instance Methods</h2> <p class="toc_element"> <code><a href="<API key>.operations.projects.locations.operations.html">operations()</a></code> </p> <p class="firstline">Returns the operations Resource.</p> <p class="toc_element"> <code><a href="#close">close()</a></code></p> <p class="firstline">Close httplib2 connections.</p> <h3>Method Details</h3> <div class="method"> <code class="details" id="close">close()</code> <pre>Close httplib2 connections.</pre> </div> </body></html>
package org.eclipse.bpel.ui.adapters; import java.util.List; import org.eclipse.bpel.model.BPELPackage; import org.eclipse.bpel.model.MessageExchanges; import org.eclipse.bpel.ui.BPELUIPlugin; import org.eclipse.bpel.ui.IBPELUIConstants; import org.eclipse.bpel.ui.adapters.delegates.ReferenceContainer; import org.eclipse.bpel.ui.editparts.<API key>; import org.eclipse.bpel.ui.editparts.OutlineTreeEditPart; import org.eclipse.bpel.ui.properties.<API key>; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartFactory; import org.eclipse.swt.graphics.Image; import org.eclipse.bpel.ui.Messages; /** * * @author Miriam Grundig (MGrundig@de.ibm.com) */ public class <API key> extends ContainerAdapter implements EditPartFactory, ILabeledElement, <API key>, <API key> { public <API key>() { super(); } /* IContainer delegate */ public IContainer <API key>() { return new ReferenceContainer(BPELPackage.eINSTANCE.<API key>()); } /* EditPartFactory */ public EditPart createEditPart(EditPart context, Object model) { <API key> result = new <API key>(); result.setLabelProvider(<API key>.getInstance()); result.setModel(model); return result; } /* <API key> */ public EditPart createTrayEditPart(EditPart context, Object model) { return createEditPart(context, model); } /* ILabeledElement */ public Image getSmallImage(Object object) { return BPELUIPlugin.INSTANCE.getImage(IBPELUIConstants.<API key>); } public Image getLargeImage(Object object) { return BPELUIPlugin.INSTANCE.getImage(IBPELUIConstants.<API key>); } public String getTypeLabel(Object object) { return Messages.<API key>; } public String getLabel(Object object) { return Messages.<API key>; } /* <API key> */ public EditPart <API key>(EditPart context, final Object model) { EditPart result = new OutlineTreeEditPart(){ protected List getModelChildren() { MessageExchanges messageExchanges = (MessageExchanges) model; List list = messageExchanges.getChildren(); return list; } }; result.setModel(model); return result; } }
package com.webtrends.harness.command.typed import akka.actor.{Actor, ActorRef, Props} import akka.pattern._ import akka.util.Timeout import com.webtrends.harness.HarnessConstants import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future} trait TypedCommandHelper { this: Actor => var typedCommandManager: Option[ActorRef] = None implicit def ec: ExecutionContext = context.dispatcher def <API key>[T<:TypedCommand[_,_]](name: String, actorClass: Class[T], checkHealth: Boolean = false): Future[ActorRef] = { implicit val timeout = Timeout(2 seconds) getManager().flatMap { cm => (cm ? RegisterCommand(name, Props(actorClass), checkHealth)).mapTo[ActorRef] } } protected def getManager(): Future[ActorRef] = { typedCommandManager match { case Some(cm) => Future.successful(cm) case None => context.system.actorSelection(HarnessConstants.<API key>).resolveOne()(2 seconds).map { s => typedCommandManager = Some(s) s } } } }
from collections import OrderedDict from app.master.atom_grouper import AtomGrouper class <API key>(object): BIG_CHUNK_FRACTION = 0.8 def __init__(self, atoms, max_executors, atom_time_map, project_directory): """ :param atoms: the list of atoms for this build :type atoms: list[app.master.atom.Atom] :param max_executors: the maximum number of executors for this build :type max_executors: int :param atom_time_map: a dictionary containing the historic times for atoms for this particular job :type atom_time_map: dict[str, float] :type project_directory: str """ self._atoms = atoms self._max_executors = max_executors self._atom_time_map = atom_time_map self._project_directory = project_directory def groupings(self): """ Group the atoms into subjobs using historic timing data. :return: a list of lists of atoms :rtype: list[list[app.master.atom.Atom]] """ # 1). Coalesce the atoms with historic atom times, and also get total estimated runtime try: <API key> = self.<API key>( self._atoms, self._atom_time_map, self._project_directory) except <API key>: grouper = AtomGrouper(self._atoms, self._max_executors) return grouper.groupings() # 2). Sort them by decreasing time, and add them to an OrderedDict <API key> = sorted(self._atoms, key=lambda atom: atom.expected_time, reverse=True) <API key> = OrderedDict([(atom, atom.expected_time) for atom in <API key>]) # 3). Group them! # Calculate what the target 'big subjob' time is going to be for each executor's initial subjob big_subjob_time = (<API key> * self.BIG_CHUNK_FRACTION) / self._max_executors # Calculate what the target 'small subjob' time is going to be small_subjob_time = (<API key> * (1.0 - self.BIG_CHUNK_FRACTION)) / (2 * self._max_executors) # <API key>() will remove elements from <API key>. subjobs = self.<API key>(<API key>, big_subjob_time, self._max_executors) small_subjobs = self.<API key>(<API key>, small_subjob_time, None) subjobs.extend(small_subjobs) return subjobs def <API key>(self, new_atoms, <API key>, project_directory): """ Set the expected runtime (new_atom.expected_time) of each atom in new_atoms using historic timing data. Additionally, return the total estimated serial-runtime for this build. Although this seems like an odd thing for this method to return, it is done here for efficiency. There can be thousands of atoms, and iterating through them multiple times seems inefficient. :param new_atoms: the list of atoms that will be run in this build :type new_atoms: list[app.master.atom.Atom] :param <API key>: a dictionary containing the historic times for atoms for this particular job :type <API key>: dict[str, float] :type project_directory: str :return: the total estimated runtime in seconds :rtype: float """ <API key> = [] total_time = 0 max_atom_time = 0 # Generate list for atoms that have timing data for new_atom in new_atoms: if new_atom.command_string not in <API key>: <API key>.append(new_atom) continue new_atom.expected_time = <API key>[new_atom.command_string] # Discover largest single atom time to use as conservative estimates for atoms with unknown times if max_atom_time < new_atom.expected_time: max_atom_time = new_atom.expected_time # We want to return the atom with the project directory still in it, as this data will directly be # sent to the slave to be run. total_time += new_atom.expected_time # For the atoms without historic timing data, assign them the largest atom time we have for new_atom in <API key>: new_atom.expected_time = max_atom_time if len(new_atoms) == len(<API key>): raise <API key> total_time += (max_atom_time * len(<API key>)) return total_time def <API key>(self, <API key>, target_group_time, <API key>): """ Given a sorted dictionary (Python FTW) of [atom, time] pairs in variable <API key>, return a list of lists of atoms that each are estimated to take target_group_time seconds. This method will generate at most <API key> groupings, and will return once this limit is reached or when <API key> is empty. Note, this method will modify <API key>'s state by removing elements as needed (often from the middle of the collection). :param <API key>: the sorted (longest first), double-ended queue containing [atom, time] pairs. This OrderedDict will have elements removed from this method. :type <API key>: OrderedDict[app.master.atom.Atom, float] :param target_group_time: how long each subjob should approximately take :type target_group_time: float :param <API key>: the maximum number of subjobs to create. Once <API key> limit is reached, this method will return the subjobs that have already been grouped. If set to None, then there is no limit. :type <API key>: int|None :return: the groups of grouped atoms, with each group taking an estimated target_group_time :rtype: list[list[app.master.atom.Atom]] """ subjobs = [] subjob_time_so_far = 0 subjob_atoms = [] while (<API key> is None or len(subjobs) < <API key>) and len(<API key>) > 0: for atom, time in <API key>.items(): if len(subjob_atoms) == 0 or (time + subjob_time_so_far) <= target_group_time: subjob_time_so_far += time subjob_atoms.append(atom) <API key>.pop(atom) # If (number of subjobs created so far + atoms left) is less than or equal to the total number of # subjobs we need to create, then have each remaining atom be a subjob and return. # The "+ 1" is here to account for the current subjob being generated, but that hasn't been # appended to subjobs yet. if <API key> is not None and (len(subjobs) + len(<API key>) + 1) <= <API key>: subjobs.append(subjob_atoms) for atom, _ in <API key>.items(): <API key>.pop(atom) subjobs.append([atom]) return subjobs subjobs.append(subjob_atoms) subjob_atoms = [] subjob_time_so_far = 0 return subjobs class <API key>(Exception): """ An exception to represent the case where the atom timing data is either not present or incorrect. """
/** * Purpose of package - find largest number from 2 and 3 numbers. * @since 1.0 * @author skuznetsov * @version 2.0 */ package ru.skuznetsov;
package gw.internal.gosu.parser; import gw.lang.reflect.IMethodInfo; public class <API key> extends <API key> implements <API key> { private IMethodInfo _targetMethodInfo; <API key>(<API key> dfs) { super( dfs ); _targetMethodInfo = dfs.getMi(); } @Override public IMethodInfo getTargetMethodInfo() { return _targetMethodInfo; } }
""" Tests for the integration test suite itself. """ import logging import os import subprocess from collections import defaultdict from pathlib import Path from typing import Set import yaml from get_test_group import patterns_from_group __maintainer__ = 'adam' __contact__ = 'tools-infra-team@mesosphere.io' log = logging.getLogger(__file__) def _tests_from_pattern(ci_pattern: str) -> Set[str]: """ From a CI pattern, get all tests ``pytest`` would collect. """ tests = set([]) # type: Set[str] args = [ 'pytest', '--<API key>', '--collect-only', ci_pattern, '-q', ] # Test names will not be in ``stderr`` so we ignore that. result = subprocess.run( args=args, stdout=subprocess.PIPE, env={**os.environ, **{'PYTHONIOENCODING': 'UTF-8'}}, ) output = result.stdout for line in output.splitlines(): if b'error in' in line: message = ( 'Error collecting tests for pattern "{ci_pattern}". ' 'Full output:\n' '{output}' ).format( ci_pattern=ci_pattern, output=output, ) raise Exception(message) # Whitespace is important to avoid confusing pytest warning messages # with test names. For example, the pytest output may contain '3 tests # deselected' which would conflict with a test file called # <API key>.py if we ignored whitespace. if ( line and # Some tests show warnings on collection. b' warnings' not in line and # Some tests are skipped on collection. b'skipped in' not in line and # Some tests are deselected by the ``pytest.ini`` configuration. b' deselected' not in line and not line.startswith(b'no tests ran in') ): tests.add(line.decode()) return tests def test_test_groups() -> None: """ The test suite is split into various "groups". This test confirms that the groups together contain all tests, and each test is collected only once. """ test_group_file = Path('test_groups.yaml') <API key> = test_group_file.read_text() test_groups = yaml.load(<API key>)['groups'] test_patterns = [] for group in test_groups: test_patterns += patterns_from_group(group_name=group) # Turn this into a list otherwise we can't cannonically state whether every test was collected _exactly_ once :-) tests_to_patterns = defaultdict(list) # type: Mapping[str, List] for pattern in test_patterns: tests = _tests_from_pattern(ci_pattern=pattern) for test in tests: tests_to_patterns[test].append(pattern) errs = [] for test_name, patterns in tests_to_patterns.items(): message = ( 'Test "{test_name}" will be run once for each pattern in ' '{patterns}. ' 'Each test should be run only once.' ).format( test_name=test_name, patterns=patterns, ) if len(patterns) != 1: assert len(patterns) != 1, message errs.append(message) if errs: for message in errs: log.error(message) raise Exception("Some tests are not collected exactly once, see errors.") all_tests = _tests_from_pattern(ci_pattern='') assert tests_to_patterns.keys() - all_tests == set() assert all_tests - tests_to_patterns.keys() == set()
/* eslint-env node */ /* vim: set ts=2 ft=javascript: */ <reference types="../node_modules/@types/node/" /> const n = "xlsx"; import X = require("xlsx"); import 'exit-on-epipe'; import * as fs from 'fs'; import program = require('commander'); program .version(X.version) .usage('[options] <file> [sheetname]') .option('-f, --file <file>', 'use specified workbook') .option('-s, --sheet <sheet>', 'print specified sheet (default first sheet)') .option('-N, --sheet-index <idx>', 'use specified sheet index (0-based)') .option('-p, --password <pw>', 'if file is encrypted, try with specified pw') .option('-l, --list-sheets', 'list sheet names and exit') .option('-o, --output <file>', 'output to specified file') .option('-B, --xlsb', 'emit XLSB to <sheetname> or <file>.xlsb') .option('-M, --xlsm', 'emit XLSM to <sheetname> or <file>.xlsm') .option('-X, --xlsx', 'emit XLSX to <sheetname> or <file>.xlsx') .option('-I, --xlam', 'emit XLAM to <sheetname> or <file>.xlam') .option('-Y, --ods', 'emit ODS to <sheetname> or <file>.ods') .option('-8, --xls', 'emit XLS to <sheetname> or <file>.xls (BIFF8)') .option('-5, --biff5','emit XLS to <sheetname> or <file>.xls (BIFF5)') .option('-2, --biff2','emit XLS to <sheetname> or <file>.xls (BIFF2)') .option('-i, --xla', 'emit XLA to <sheetname> or <file>.xla') .option('-6, --xlml', 'emit SSML to <sheetname> or <file>.xls (2003 XML)') .option('-T, --fods', 'emit FODS to <sheetname> or <file>.fods (Flat ODS)') .option('-S, --formulae', 'emit list of values and formulae') .option('-j, --json', 'emit formatted JSON (all fields text)') .option('-J, --raw-js', 'emit raw JS object (raw numbers)') .option('-A, --arrays', 'emit rows as JS objects (raw numbers)') .option('-H, --html', 'emit HTML to <sheetname> or <file>.html') .option('-D, --dif', 'emit DIF to <sheetname> or <file>.dif (Lotus DIF)') .option('-U, --dbf', 'emit DBF to <sheetname> or <file>.dbf (MSVFP DBF)') .option('-K, --sylk', 'emit SYLK to <sheetname> or <file>.slk (Excel SYLK)') .option('-P, --prn', 'emit PRN to <sheetname> or <file>.prn (Lotus PRN)') .option('-E, --eth', 'emit ETH to <sheetname> or <file>.eth (Ethercalc)') .option('-t, --txt', 'emit TXT to <sheetname> or <file>.txt (UTF-8 TSV)') .option('-r, --rtf', 'emit RTF to <sheetname> or <file>.txt (Table RTF)') .option('-z, --dump', 'dump internal representation as JSON') .option('--props', 'dump workbook properties as CSV') .option('-F, --field-sep <sep>', 'CSV field separator', ",") .option('-R, --row-sep <sep>', 'CSV row separator', "\n") .option('-n, --sheet-rows <num>', 'Number of rows to process (0=all rows)') .option('--codepage <cp>', 'default to specified codepage when ambiguous') .option('--req <module>', 'require module before processing') .option('--sst', 'generate shared string table for XLS* formats') .option('--compress', 'use compression when writing XLSX/M/B and ODS') .option('--read', 'read but do not generate output') .option('--book', 'for single-sheet formats, emit a file per worksheet') .option('--all', 'parse everything; write as much as possible') .option('--dev', 'development mode') .option('--sparse', 'sparse mode') .option('-q, --quiet', 'quiet mode'); program.on('--help', function() { console.log(' Default output format is CSV'); console.log(' Support email: dev@sheetjs.com'); console.log(' Web Demo: http://oss.sheetjs.com/js-'+n+'/'); }); /* flag, bookType, default ext */ const workbook_formats = [ ['xlsx', 'xlsx', 'xlsx'], ['xlsm', 'xlsm', 'xlsm'], ['xlam', 'xlam', 'xlam'], ['xlsb', 'xlsb', 'xlsb'], ['xls', 'xls', 'xls'], ['xla', 'xla', 'xla'], ['biff5', 'biff5', 'xls'], ['ods', 'ods', 'ods'], ['fods', 'fods', 'fods'] ]; const wb_formats_2 = [ ['xlml', 'xlml', 'xls'] ]; program.parse(process.argv); let filename = '', sheetname = ''; if(program.args[0]) { filename = program.args[0]; if(program.args[1]) sheetname = program.args[1]; } if(program.sheet) sheetname = program.sheet; if(program.file) filename = program.file; if(!filename) { console.error(n + ": must specify a filename"); process.exit(1); } if(!fs.existsSync(filename)) { console.error(n + ": " + filename + ": No such file or directory"); process.exit(2); } const opts: X.ParsingOptions = {}; let wb: X.WorkBook; if(program.listSheets) opts.bookSheets = true; if(program.sheetRows) opts.sheetRows = program.sheetRows; if(program.password) opts.password = program.password; let seen = false; function wb_fmt() { seen = true; opts.cellFormula = true; opts.cellNF = true; if(program.output) sheetname = program.output; } function isfmt(m: string): boolean { if(!program.output) return false; const t = m.charAt(0) === "." ? m : "." + m; return program.output.slice(-t.length) === t; } workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } }); wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } }); if(seen) { } else if(program.formulae) opts.cellFormula = true; else opts.cellFormula = false; const wopts: X.WritingOptions = ({WTF:opts.WTF, bookSST:program.sst}/*:any*/); if(program.compress) wopts.compression = true; if(program.all) { opts.cellFormula = true; opts.bookVBA = true; opts.cellNF = true; opts.cellHTML = true; opts.cellStyles = true; opts.sheetStubs = true; opts.cellDates = true; wopts.cellStyles = true; wopts.bookVBA = true; } if(program.sparse) opts.dense = false; else opts.dense = true; if(program.codepage) opts.codepage = +program.codepage; if(program.dev) { opts.WTF = true; wb = X.readFile(filename, opts); } else try { wb = X.readFile(filename, opts); } catch(e) { let msg = (program.quiet) ? "" : n + ": error parsing "; msg += filename + ": " + e; console.error(msg); process.exit(3); } if(program.read) process.exit(0); if(!wb) { console.error(n + ": error parsing " + filename + ": empty workbook"); process.exit(0); } /*:: if(!wb) throw new Error("unreachable"); */ if(program.listSheets) { console.log((wb.SheetNames||[]).join("\n")); process.exit(0); } if(program.dump) { console.log(JSON.stringify(wb)); process.exit(0); } if(program.props) { dump_props(wb); process.exit(0); } /* full workbook formats */ workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wopts.bookType = <X.BookType>(m[1]); X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts); process.exit(0); } }); wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wopts.bookType = <X.BookType>(m[1]); X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts); process.exit(0); } }); let target_sheet = sheetname || ''; if(target_sheet === '') { if(program.sheetIndex < (wb.SheetNames||[]).length) target_sheet = wb.SheetNames[program.sheetIndex]; else target_sheet = (wb.SheetNames||[""])[0]; } let ws: X.WorkSheet; try { ws = wb.Sheets[target_sheet]; if(!ws) { console.error("Sheet " + target_sheet + " cannot be found"); process.exit(3); } } catch(e) { console.error(n + ": error parsing "+filename+" "+target_sheet+": " + e); process.exit(4); } if(!program.quiet && !program.book) console.error(target_sheet); /* single worksheet file formats */ [ ['biff2', '.xls'], ['biff3', '.xls'], ['biff4', '.xls'], ['sylk', '.slk'], ['html', '.html'], ['prn', '.prn'], ['eth', '.eth'], ['rtf', '.rtf'], ['txt', '.txt'], ['dbf', '.dbf'], ['dif', '.dif'] ].forEach(function(m) { if(program[m[0]] || isfmt(m[1])) { wopts.bookType = <X.BookType>(m[0]); X.writeFile(wb, program.output || sheetname || ((filename || "") + m[1]), wopts); process.exit(0); } }); let oo = "", strm = false; if(!program.quiet) console.error(target_sheet); if(program.formulae) oo = X.utils.sheet_to_formulae(ws).join("\n"); else if(program.json) oo = JSON.stringify(X.utils.sheet_to_json(ws)); else if(program.rawJs) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true})); else if(program.arrays) oo = JSON.stringify(X.utils.sheet_to_json(ws,{raw:true, header:1})); else { strm = true; const stream: NodeJS.ReadableStream = X.stream.to_csv(ws, {FS:program.fieldSep, RS:program.rowSep}); if(program.output) stream.pipe(fs.createWriteStream(program.output)); else stream.pipe(process.stdout); } if(!strm) { if(program.output) fs.writeFileSync(program.output, oo); else console.log(oo); } function dump_props(wb: X.WorkBook) { let propaoa: any[][] = []; propaoa = (<any>Object).entries({...wb.Props, ...wb.Custprops}); console.log(X.utils.sheet_to_csv(X.utils.aoa_to_sheet(propaoa))); }
namespace DTcms.Web.admin.manager { public partial class role_edit { <summary> form1 </summary> <remarks> </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; <summary> ddlRoleType </summary> <remarks> </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlRoleType; <summary> txtRoleName </summary> <remarks> </remarks> protected global::System.Web.UI.WebControls.TextBox txtRoleName; <summary> rptList </summary> <remarks> </remarks> protected global::System.Web.UI.WebControls.Repeater rptList; <summary> btnSubmit </summary> <remarks> </remarks> protected global::System.Web.UI.WebControls.Button btnSubmit; } }
#!/bin/sh while [ "1" == "1" ] do uptime sleep 1 done
package org.apereo.cas.ticket.registry; import org.apereo.cas.ticket.Ticket; import org.infinispan.Cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.concurrent.TimeUnit; public class <API key> extends <API key> { private static final Logger LOGGER = LoggerFactory.getLogger(<API key>.class); private Cache<String, Ticket> cache; /** * Instantiates a new Infinispan ticket registry. * * @param cache the cache */ public <API key>(final Cache<String, Ticket> cache) { this.cache = cache; LOGGER.info("Setting up Infinispan Ticket Registry..."); } @Override public Ticket updateTicket(final Ticket ticket) { this.cache.put(ticket.getId(), ticket); return ticket; } @Override public void addTicket(final Ticket ticketToAdd) { final Ticket ticket = encodeTicket(ticketToAdd); final long idleTime = ticket.getExpirationPolicy().getTimeToIdle() <= 0 ? ticket.getExpirationPolicy().getTimeToLive() : ticket.getExpirationPolicy().getTimeToIdle(); LOGGER.debug("Adding ticket [{}] to cache store to live [{}] seconds and stay idle for [{}]", ticket.getId(), ticket.getExpirationPolicy().getTimeToLive(), idleTime); this.cache.put(ticket.getId(), ticket, ticket.getExpirationPolicy().getTimeToLive(), TimeUnit.SECONDS, idleTime, TimeUnit.SECONDS); } @Override public Ticket getTicket(final String ticketId) { final String encTicketId = encodeTicketId(ticketId); if (ticketId == null) { return null; } return Ticket.class.cast(cache.get(encTicketId)); } @Override public boolean deleteSingleTicket(final String ticketId) { this.cache.remove(ticketId); return getTicket(ticketId) == null; } @Override public long deleteAll() { final int size = this.cache.size(); this.cache.clear(); return size; } /** * Retrieve all tickets from the registry. * <p> * Note! Usage of this method can be computational and I/O intensive and should not be used for other than * debugging. * * @return collection of tickets currently stored in the registry. Tickets * might or might not be valid i.e. expired. */ @Override public Collection<Ticket> getTickets() { return decodeTickets(this.cache.values()); } }
// This source file is part of the Swift.org open source project // Swift ABI describing "status records", the mechanism by which // tasks track dynamic information about their child tasks, custom // cancellation hooks, and other information which may need to be exposed // asynchronously outside of the task. #ifndef <API key> #define <API key> #include "swift/ABI/MetadataValues.h" #include "swift/ABI/Task.h" namespace swift { The abstract base class for all status records. TaskStatusRecords are typically allocated on the stack (possibly in the task context), partially initialized, and then atomically added to the task with `<API key>`. While registered with the task, a status record should only be modified in ways that respect the possibility of asynchronous access by a cancelling thread. In particular, the chain of status records must not be disturbed. When the task leaves the scope that requires the status record, the record can be unregistered from the task with `removeStatusRecord`, at which point the memory can be returned to the system. class TaskStatusRecord { public: <API key> Flags; TaskStatusRecord *Parent; TaskStatusRecord(<API key> kind, TaskStatusRecord *parent = nullptr) : Flags(kind) { resetParent(parent); } TaskStatusRecord(const TaskStatusRecord &) = delete; TaskStatusRecord &operator=(const TaskStatusRecord &) = delete; <API key> getKind() const { return Flags.getKind(); } TaskStatusRecord *getParent() const { return Parent; } Change the parent of this unregistered status record to the given record. This should be used when the record has been previously initialized without knowing what the true parent is. If we decide to cache important information (e.g. the earliest timeout) in the innermost status record, this is the method that should fill that in from the parent. void resetParent(TaskStatusRecord *newParent) { Parent = newParent; // TODO: cache } Splice a record out of the status-record chain. Unlike resetParent, this assumes that it's just removing one or more records from the chain and that there's no need to do any extra cache manipulation. void spliceParent(TaskStatusRecord *newParent) { Parent = newParent; } }; A deadline for the task. If this is reached, the task will be automatically cancelled. The deadline can also be queried and used in other ways. struct TaskDeadline { // FIXME: I don't really know what this should look like right now. // It's probably target-specific. uint64_t Value; bool operator==(const TaskDeadline &other) const { return Value == other.Value; } bool operator<(const TaskDeadline &other) const { return Value < other.Value; } }; A status record which states that there's an active deadline within the task. class <API key> : public TaskStatusRecord { TaskDeadline Deadline; public: <API key>(TaskDeadline deadline) : TaskStatusRecord(<API key>::Deadline), Deadline(deadline) {} TaskDeadline getDeadline() const { return Deadline; } static bool classof(const TaskStatusRecord *record) { return record->getKind() == <API key>::Deadline; } }; A status record which states that a task has one or more active child tasks. class <API key> : public TaskStatusRecord { AsyncTask *FirstChild; public: <API key>(AsyncTask *child) : TaskStatusRecord(<API key>::ChildTask), FirstChild(child) {} <API key>(AsyncTask *child, <API key> kind) : TaskStatusRecord(kind), FirstChild(child) { assert(kind == <API key>::ChildTask); assert(!child-><API key>() && "Group child tasks must be tracked in their respective " "<API key>, and not as independent " "<API key> " "records."); } Return the first child linked by this record. This may be null; if not, it (and all of its successors) are guaranteed to satisfy `isChildTask()`. AsyncTask *getFirstChild() const { return FirstChild; } static AsyncTask *getNextChildTask(AsyncTask *task) { return task->childFragment()->getNextChild(); } using child_iterator = LinkedListIterator<AsyncTask, getNextChildTask>; llvm::iterator_range<child_iterator> children() const { return child_iterator::rangeBeginning(getFirstChild()); } static bool classof(const TaskStatusRecord *record) { return record->getKind() == <API key>::ChildTask; } }; A status record which states that a task has a task group. A record always is a specific `TaskGroupImpl`. The child tasks are stored as an invasive single-linked list, starting from `FirstChild` and continuing through the `NextChild` pointers of all the linked children. All children of the specific `Group` are stored "by" this record, so that they may be cancelled when this task becomes cancelled. When the group exits, it may simply remove this single record from the task running it. As it has guaranteed that the tasks have already completed. Group child tasks DO NOT have their own `<API key>` entries, and are only tracked by their respective `<API key>`. class <API key> : public TaskStatusRecord { AsyncTask *FirstChild; AsyncTask *LastChild; public: <API key>() : TaskStatusRecord(<API key>::TaskGroup), FirstChild(nullptr), LastChild(nullptr) { } <API key>(AsyncTask *child) : TaskStatusRecord(<API key>::TaskGroup), FirstChild(child), LastChild(child) { assert(!LastChild || !LastChild->childFragment()->getNextChild()); } TaskGroup *getGroup() { return reinterpret_cast<TaskGroup *>(this); } Return the first child linked by this record. This may be null; if not, it (and all of its successors) are guaranteed to satisfy `isChildTask()`. AsyncTask *getFirstChild() const { return FirstChild; } Attach the passed in `child` task to this group. void attachChild(AsyncTask *child) { assert(child-><API key>()); assert(child->groupChildFragment()->getGroup() == getGroup()); auto oldLastChild = LastChild; LastChild = child; if (!FirstChild) { // This is the first child we ever attach, so store it as FirstChild. FirstChild = child; return; } oldLastChild->childFragment()->setNextChild(child); } void detachChild(AsyncTask *child) { assert(child && "cannot remove a null child from group"); if (FirstChild == child) { FirstChild = getNextChildTask(child); if (FirstChild == nullptr) { LastChild = nullptr; } return; } AsyncTask *prev = FirstChild; // Remove the child from the linked list, i.e.: // prev -> afterPrev -> afterChild // child -> afterChild // Becomes: while (prev) { auto afterPrev = getNextChildTask(prev); if (afterPrev == child) { auto afterChild = getNextChildTask(child); prev->childFragment()->setNextChild(afterChild); if (child == LastChild) { LastChild = prev; } return; } prev = afterPrev; } } static AsyncTask *getNextChildTask(AsyncTask *task) { return task->childFragment()->getNextChild(); } using child_iterator = LinkedListIterator<AsyncTask, getNextChildTask>; llvm::iterator_range<child_iterator> children() const { return child_iterator::rangeBeginning(getFirstChild()); } static bool classof(const TaskStatusRecord *record) { return record->getKind() == <API key>::TaskGroup; } }; A cancellation record which states that a task has an arbitrary function that needs to be called if the task is cancelled. The end of any call to the function will be ordered before the end of a call to unregister this record from the task. That is, code may call `removeStatusRecord` and freely assume after it returns that this function will not be subsequently used. class <API key> : public TaskStatusRecord { public: using FunctionType = SWIFT_CC(swift) void(SWIFT_CONTEXT void *); private: FunctionType *__ptr<API key> Function; void *Argument; public: <API key>(FunctionType *fn, void *arg) : TaskStatusRecord(<API key>::<API key>), Function(fn), Argument(arg) {} void run() { Function(Argument); } static bool classof(const TaskStatusRecord *record) { return record->getKind() == <API key>::<API key>; } }; A status record which says that a task has an arbitrary function that needs to be called if the task's priority is escalated. The end of any call to the function will be ordered before the end of a call to unregister this record from the task. That is, code may call `removeStatusRecord` and freely assume after it returns that this function will not be subsequently used. class <API key> : public TaskStatusRecord { public: using FunctionType = void(void *, JobPriority); private: FunctionType *__ptr<API key> Function; void *Argument; public: <API key>(FunctionType *fn, void *arg) : TaskStatusRecord(<API key>::<API key>), Function(fn), Argument(arg) {} void run(JobPriority newPriority) { Function(Argument, newPriority); } static bool classof(const TaskStatusRecord *record) { return record->getKind() == <API key>::<API key>; } }; } // end namespace swift #endif
'use strict'; module.exports = function (math) { var util = require('../../util/index'), BigNumber = math.type.BigNumber, collection = require('../../type/collection'), isNumber = util.number.isNumber, isBoolean = util['boolean'].isBoolean, isInteger = util.number.isInteger, isCollection = collection.isCollection; /** * Compute the factorial of a value * * Factorial only supports an integer value as argument. * For matrices, the function is evaluated element wise. * * Syntax: * * math.factorial(n) * * Examples: * * math.factorial(5); // returns 120 * math.factorial(3); // returns 6 * * See also: * * combinations, permutations * * @param {Number | BigNumber | Array | Matrix} n An integer number * @return {Number | BigNumber | Array | Matrix} The factorial of `n` */ math.factorial = function factorial (n) { var value, res; if (arguments.length != 1) { throw new math.error.ArgumentsError('factorial', arguments.length, 1); } if (isNumber(n)) { if (!isInteger(n) || n < 0) { throw new TypeError('Positive integer value expected in function factorial'); } value = n - 1; res = n; while (value > 1) { res *= value; value } if (res == 0) { res = 1; // 0! is per definition 1 } return res; } if (n instanceof BigNumber) { if (!(isPositiveInteger(n))) { throw new TypeError('Positive integer value expected in function factorial'); } var one = new BigNumber(1); value = n.minus(one); res = n; while (value.gt(one)) { res = res.times(value); value = value.minus(one); } if (res.equals(0)) { res = one; // 0! is per definition 1 } return res; } if (isBoolean(n)) { return 1; // factorial(1) = 1, factorial(0) = 1 } if (isCollection(n)) { return collection.deepMap(n, factorial); } throw new math.error.<API key>('factorial', math['typeof'](n)); }; /** * Test whether BigNumber n is a positive integer * @param {BigNumber} n * @returns {boolean} isPositiveInteger */ var isPositiveInteger = function(n) { return n.isInteger() && n.gte(0); }; };
/* This file is automatically generated. DO NOT EDIT! */ /* Generated from: NetBSD: mknative-gcc,v 1.59 2011/07/03 06:47:12 mrg Exp */ /* Generated from: NetBSD: mknative.common,v 1.9 2007/02/05 18:26:01 apb Exp */ /* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define if the compiler has a thread header that is non single. */ #define HAVE_GTHR_DEFAULT 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <sched.h> header file. */ #define HAVE_SCHED_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Define to 1 if your C compiler doesn't accept -c and -o together. */ /* #undef NO_MINUS_C_MINUS_O */ /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "package-unused" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "package-unused version-unused" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libobjc" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "version-unused" /* Define if the compiler is configured for setjmp/longjmp exceptions. */ /* #undef SJLJ_EXCEPTIONS */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1
.enyo-hflexbox, .enyo-vflexbox { display: -webkit-box; -webkit-box-sizing: border-box; } .enyo-hflexbox { -webkit-box-orient: horizontal; } .enyo-vflexbox { -webkit-box-orient: vertical; }
module ActionMailer # Returns the version of the currently loaded ActionMailer as a <tt>Gem::Version</tt> def self.gem_version Gem::Version.new VERSION::STRING end module VERSION MAJOR = 4 MINOR = 1 TINY = 6 PRE = nil STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end end
package org.elasticsearch.xpack.security.authc.support.mapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.<API key>; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.support.<API key>; import org.elasticsearch.client.Client; import org.elasticsearch.common.CheckedBiConsumer; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.<API key>; import org.elasticsearch.common.xcontent.<API key>; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.script.ScriptService; import org.elasticsearch.xpack.core.security.ScrollHelper; import org.elasticsearch.xpack.core.security.action.realm.<API key>; import org.elasticsearch.xpack.core.security.action.realm.<API key>; import org.elasticsearch.xpack.core.security.action.rolemapping.<API key>; import org.elasticsearch.xpack.core.security.action.rolemapping.<API key>; import org.elasticsearch.xpack.core.security.authc.support.mapper.<API key>; import org.elasticsearch.xpack.core.security.authc.support.mapper.expressiondsl.ExpressionModel; import org.elasticsearch.xpack.core.security.index.<API key>; import org.elasticsearch.xpack.security.authc.support.CachingRealm; import org.elasticsearch.xpack.security.authc.support.UserRoleMapper; import org.elasticsearch.xpack.security.support.<API key>; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.<API key>; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.elasticsearch.action.DocWriteResponse.Result.CREATED; import static org.elasticsearch.action.DocWriteResponse.Result.DELETED; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.mapper.MapperService.SINGLE_MAPPING_NAME; import static org.elasticsearch.search.SearchService.<API key>; import static org.elasticsearch.xpack.core.ClientHelper.SECURITY_ORIGIN; import static org.elasticsearch.xpack.core.ClientHelper.<API key>; import static org.elasticsearch.xpack.core.security.index.<API key>.SECURITY_MAIN_ALIAS; import static org.elasticsearch.xpack.security.support.<API key>.isIndexDeleted; import static org.elasticsearch.xpack.security.support.<API key>.<API key>; /** * This store reads + writes {@link <API key> role mappings} in an Elasticsearch * {@link <API key>#SECURITY_MAIN_ALIAS index}. * <br> * The store is responsible for all read and write operations as well as * {@link #resolveRoles(UserData, ActionListener) resolving roles}. * <p> * No caching is done by this class, it is handled at a higher level and no polling for changes * is done by this class. Modification operations make a best effort attempt to clear the cache * on all nodes for the user that was modified. */ public class <API key> implements UserRoleMapper { private static final Logger logger = LogManager.getLogger(<API key>.class); static final String DOC_TYPE_FIELD = "doc_type"; static final String <API key> = "role-mapping"; private static final String ID_PREFIX = <API key> + "_"; private static final ActionListener<Object> <API key> = new ActionListener<Object>() { @Override public void onResponse(Object o) { // nothing } @Override public void onFailure(Exception e) { // nothing } }; private final Settings settings; private final Client client; private final <API key> securityIndex; private final ScriptService scriptService; private final List<String> realmsToRefresh = new <API key><>(); public <API key>(Settings settings, Client client, <API key> securityIndex, ScriptService scriptService) { this.settings = settings; this.client = client; this.securityIndex = securityIndex; this.scriptService = scriptService; } private String getNameFromId(String id) { assert id.startsWith(ID_PREFIX); return id.substring(ID_PREFIX.length()); } private String getIdForName(String name) { return ID_PREFIX + name; } /** * Loads all mappings from the index. * <em>package private</em> for unit testing */ protected void loadMappings(ActionListener<List<<API key>>> listener) { if (securityIndex.isIndexUpToDate() == false) { listener.onFailure(new <API key>( "Security index is not on the current version - the native realm will not be operational until " + "the upgrade API is run on the security index")); return; } final QueryBuilder query = QueryBuilders.termQuery(DOC_TYPE_FIELD, <API key>); final Supplier<ThreadContext.StoredContext> supplier = client.threadPool().getThreadContext().<API key>(false); try (ThreadContext.StoredContext ignore = client.threadPool().getThreadContext().stashWithOrigin(SECURITY_ORIGIN)) { SearchRequest request = client.prepareSearch(SECURITY_MAIN_ALIAS) .setScroll(<API key>.get(settings)) .setQuery(query) .setSize(1000) .setFetchSource(true) .request(); request.indicesOptions().ignoreUnavailable(); ScrollHelper.fetchAllByEntity(client, request, new <API key><>(supplier, ActionListener.wrap((Collection<<API key>> mappings) -> listener.onResponse(mappings.stream().filter(Objects::nonNull).collect(Collectors.toList())), ex -> { logger.error(new <API key>("failed to load role mappings from index [{}] skipping all mappings.", SECURITY_MAIN_ALIAS), ex); listener.onResponse(Collections.emptyList()); })), doc -> buildMapping(getNameFromId(doc.getId()), doc.getSourceRef())); } } protected <API key> buildMapping(String id, BytesReference source) { try (InputStream stream = source.streamInput(); XContentParser parser = XContentType.JSON.xContent() .createParser(<API key>.EMPTY, <API key>.INSTANCE, stream)) { return <API key>.parse(id, parser); } catch (Exception e) { logger.warn(new <API key>("Role mapping [{}] cannot be parsed and will be skipped", id), e); return null; } } /** * Stores (create or update) a single mapping in the index */ public void putRoleMapping(<API key> request, ActionListener<Boolean> listener) { modifyMapping(request.getName(), this::innerPutMapping, request, listener); } /** * Deletes a named mapping from the index */ public void deleteRoleMapping(<API key> request, ActionListener<Boolean> listener) { modifyMapping(request.getName(), this::innerDeleteMapping, request, listener); } private <Request, Result> void modifyMapping(String name, CheckedBiConsumer<Request, ActionListener<Result>, Exception> inner, Request request, ActionListener<Result> listener) { if (securityIndex.isIndexUpToDate() == false) { listener.onFailure(new <API key>( "Security index is not on the current version - the native realm will not be operational until " + "the upgrade API is run on the security index")); } else { try { inner.accept(request, ActionListener.wrap(r -> refreshRealms(listener, r), listener::onFailure)); } catch (Exception e) { logger.error(new <API key>("failed to modify role-mapping [{}]", name), e); listener.onFailure(e); } } } private void innerPutMapping(<API key> request, ActionListener<Boolean> listener) { final <API key> mapping = request.getMapping(); securityIndex.<API key>(listener::onFailure, () -> { final XContentBuilder xContentBuilder; try { xContentBuilder = mapping.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS, true); } catch (IOException e) { listener.onFailure(e); return; } <API key>(client.threadPool().getThreadContext(), SECURITY_ORIGIN, client.prepareIndex(SECURITY_MAIN_ALIAS, SINGLE_MAPPING_NAME, getIdForName(mapping.getName())) .setSource(xContentBuilder) .setRefreshPolicy(request.getRefreshPolicy()) .request(), new ActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse indexResponse) { boolean created = indexResponse.getResult() == CREATED; listener.onResponse(created); } @Override public void onFailure(Exception e) { logger.error(new <API key>("failed to put role-mapping [{}]", mapping.getName()), e); listener.onFailure(e); } }, client::index); }); } private void innerDeleteMapping(<API key> request, ActionListener<Boolean> listener) { final <API key> frozenSecurityIndex = securityIndex.freeze(); if (frozenSecurityIndex.indexExists() == false) { listener.onResponse(false); } else if (securityIndex.isAvailable() == false) { listener.onFailure(frozenSecurityIndex.<API key>()); } else { securityIndex.<API key>(listener::onFailure, () -> { <API key>(client.threadPool().getThreadContext(), SECURITY_ORIGIN, client.prepareDelete(SECURITY_MAIN_ALIAS, SINGLE_MAPPING_NAME, getIdForName(request.getName())) .setRefreshPolicy(request.getRefreshPolicy()) .request(), new ActionListener<DeleteResponse>() { @Override public void onResponse(DeleteResponse deleteResponse) { boolean deleted = deleteResponse.getResult() == DELETED; listener.onResponse(deleted); } @Override public void onFailure(Exception e) { logger.error(new <API key>("failed to delete role-mapping [{}]", request.getName()), e); listener.onFailure(e); } }, client::delete); }); } } /** * Retrieves one or more mappings from the index. * If <code>names</code> is <code>null</code> or {@link Set#isEmpty empty}, then this retrieves all mappings. * Otherwise it retrieves the specified mappings by name. */ public void getRoleMappings(Set<String> names, ActionListener<List<<API key>>> listener) { if (names == null || names.isEmpty()) { getMappings(listener); } else { getMappings(new ActionListener<List<<API key>>>() { @Override public void onResponse(List<<API key>> mappings) { final List<<API key>> filtered = mappings.stream() .filter(m -> names.contains(m.getName())) .collect(Collectors.toList()); listener.onResponse(filtered); } @Override public void onFailure(Exception e) { listener.onFailure(e); } }); } } private void getMappings(ActionListener<List<<API key>>> listener) { if (securityIndex.isAvailable()) { loadMappings(listener); } else { logger.info("The security index is not yet available - no role mappings can be loaded"); if (logger.isDebugEnabled()) { logger.debug("Security Index [{}] [exists: {}] [available: {}] [mapping up to date: {}]", SECURITY_MAIN_ALIAS, securityIndex.indexExists(), securityIndex.isAvailable(), securityIndex.isMappingUpToDate() ); } listener.onResponse(Collections.emptyList()); } } /** * Provides usage statistics for this store. * The resulting map contains the keys * <ul> * <li><code>size</code> - The total number of mappings stored in the index</li> * <li><code>enabled</code> - The number of mappings that are * {@link <API key>#isEnabled() enabled}</li> * </ul> */ public void usageStats(ActionListener<Map<String, Object>> listener) { if (securityIndex.isAvailable() == false) { reportStats(listener, Collections.emptyList()); } else { getMappings(ActionListener.wrap(mappings -> reportStats(listener, mappings), listener::onFailure)); } } private void reportStats(ActionListener<Map<String, Object>> listener, List<<API key>> mappings) { Map<String, Object> usageStats = new HashMap<>(); usageStats.put("size", mappings.size()); usageStats.put("enabled", mappings.stream().filter(<API key>::isEnabled).count()); listener.onResponse(usageStats); } public void <API key>(<API key>.State previousState, <API key>.State currentState) { if (<API key>(previousState, currentState) || isIndexDeleted(previousState, currentState) || previousState.isIndexUpToDate != currentState.isIndexUpToDate) { refreshRealms(<API key>, null); } } private <Result> void refreshRealms(ActionListener<Result> listener, Result result) { if (realmsToRefresh.isEmpty()) { listener.onResponse(result); return; } final String[] realmNames = this.realmsToRefresh.toArray(Strings.EMPTY_ARRAY); <API key>(client, SECURITY_ORIGIN, <API key>.INSTANCE, new <API key>().realms(realmNames), ActionListener.wrap( response -> { logger.debug((org.apache.logging.log4j.util.Supplier<?>) () -> new <API key>( "Cleared cached in realms [{}] due to role mapping change", Arrays.toString(realmNames))); listener.onResponse(result); }, ex -> { logger.warn(new <API key>("Failed to clear cache for realms [{}]", Arrays.toString(realmNames)), ex); listener.onFailure(ex); })); } @Override public void resolveRoles(UserData user, ActionListener<Set<String>> listener) { getRoleMappings(null, ActionListener.wrap( mappings -> { final ExpressionModel model = user.asModel(); final Set<String> roles = mappings.stream() .filter(<API key>::isEnabled) .filter(m -> m.getExpression().match(model)) .flatMap(m -> { final Set<String> roleNames = m.getRoleNames(scriptService, model); logger.trace("Applying role-mapping [{}] to user-model [{}] produced role-names [{}]", m.getName(), model, roleNames); return roleNames.stream(); }) .collect(Collectors.toSet()); logger.debug("Mapping user [{}] to roles [{}]", user, roles); listener.onResponse(roles); }, listener::onFailure )); } /** * Indicates that the provided realm should have its cache cleared if this store is updated * (that is, {@link #putRoleMapping(<API key>, ActionListener)} or * {@link #deleteRoleMapping(<API key>, ActionListener)} are called). * @see <API key> */ @Override public void <API key>(CachingRealm realm) { realmsToRefresh.add(realm.name()); } }
# This is the Ruby 2.0-specific kernel file. # Currently, all 1.9 features are in 2.0. We will need to # differentiate when there are features from 1.9 removed # in 2.0. # These are loads so they don't pollute LOADED_FEATURES load 'jruby/kernel19.rb' load 'jruby/kernel20/enumerable.rb' load 'jruby/kernel20/range.rb' load 'jruby/kernel20/load_error.rb'
package depends import ( "fmt" "sync" logutil "github.com/docker/infrakit/pkg/log" "github.com/docker/infrakit/pkg/types" ) var log = logutil.New("module", "run/depends") // ParseDependsFunc returns a list of dependencies of this spec. type ParseDependsFunc func(types.Spec) (Runnables, error) var ( parsers = map[string]map[types.InterfaceSpec]ParseDependsFunc{} lock = sync.RWMutex{} ) // Register registers a helper for parsing for dependencies based on a key (e.g. 'group') // and interface spec (Group/1.0) func Register(key string, interfaceSpec types.InterfaceSpec, f ParseDependsFunc) { lock.Lock() defer lock.Unlock() if _, has := parsers[key]; !has { parsers[key] = map[types.InterfaceSpec]ParseDependsFunc{} } if _, has := parsers[key][interfaceSpec]; has { panic(fmt.Errorf("duplicate depdency parser for %v / %v", key, interfaceSpec)) } parsers[key][interfaceSpec] = f } // Resolve returns the dependencies listed in the spec as well as inside the properties. // InterfaceSpec is optional. If nil, the first match by key (kind) is used. If nothing is registered, returns nil // and no error. Error is returned for exceptions (eg. parsing, etc.) func Resolve(spec types.Spec, key string, interfaceSpec *types.InterfaceSpec) (Runnables, error) { lock.RLock() defer lock.RUnlock() m, has := parsers[key] if !has { return nil, nil } if interfaceSpec == nil { for _, parse := range m { // First match return parse(spec) } } parse, has := m[*interfaceSpec] if !has { return nil, nil } return parse(spec) }
/** * Timeline.css */ *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body, html { font-size: 100%; padding: 0; margin: 0; } .main a{ color:#0085a1; } .main a:hover { /*color: #000;*/ /*text-decoration: none;*/ } .main, .container > header { width: 90%; max-width: 69em; margin: 0 auto; padding: 0 1.375em; } @font-face { font-family: 'huxico'; src:url('../fonts/huxico.eot'); src:url('../fonts/huxico.eot?#iefix') format('embedded-opentype'), url('../fonts/huxico.woff') format('woff'), url('../fonts/huxico.ttf') format('truetype'), url('../fonts/huxico.svg#huxico') format('svg'); font-weight: normal; font-style: normal; } .cbp_tmtimeline { padding: 0; list-style: none; position: relative; max-width: 600px; margin: 0 auto; margin-top: -120px; } .cbp_tmtimeline > li { position: relative; box-sizing: border-box; display: inline-block; vertical-align: top; width: 100%; } /* The date/time */ .cbp_tmlabel time { font-size: 1.0em; position: absolute; top: 0px; line-height: 64px; right: 5px; margin-right: 1em; color: #a5a7aa; } /* The Duoshuo */ .cbp_tmlabel .comment{ padding: 0 1.5em 0.5em; } /* The card */ .cbp_tmtimeline > li .cbp_tmlabel { background: white; color: rgb(78, 78, 78); /* line-height: 1.4; */ position: relative; border-radius: 3px; border: 1px solid #edeeee; margin: 0 0 30px 0; font-weight: 400; font-size: 95%; } .cbp_tmtimeline > li .cbp_tmlabel h2 { font-weight: bold; font-size: 15px; padding: 14px 20px; margin: 0; height: 64px; line-height: 36px; } .cbp_tmtimeline > li:nth-child(odd) .cbp_tmlabel:after { border-right-color: #FFFFFF; display: no; } /* The icons */ .cbp_tmtimeline > li .cbp_tmicon { width: 40px; height: 40px; font-family: 'huxico'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; font-size: 1.4em; line-height: 40px; -<API key>: antialiased; position: absolute; color: #fff; background: #46a4da; border-radius: 50%; box-shadow: 0 0 0 8px #afdcf8; text-align: center; left: 20%; top: 0; margin: 0 0 0 -25px; } .cbp_tmicon-phone:before { content: "\e004"; font-family: 'huxico'; } .cbp_tmicon-screen:before { content: "\e005"; font-family: 'huxico'; } .cbp_tmicon-html:before { content: "\e001"; font-family: 'huxico'; } .cbp_tmicon-video:before { content: "\e002"; font-family: 'huxico'; } .cbp_tmicon-font:before { content: "\e003"; font-family: 'huxico'; } /** Venders Logo **/ .i-vue:before { content: ""; display: block; width: 40px; height: 40px; background: url("../images/logo-vue.png") 50% 50% no-repeat; background-size: 20px; } .i-kissy:before { content: ""; display: block; width: 40px; height: 40px; background: url("../images/logo-kissy.png") 50% 50% no-repeat; background-size: 20px; } .i-jquery:before { content: ""; display: block; width: 40px; height: 40px; background: url("../images/logo-jquery.png") 50% 50% no-repeat; background-size: 20px; } .i-react:before { content: ""; display: block; width: 40px; height: 40px; background: url("../images/logo-react.png") 50% 50% no-repeat; background-size: 22px; } html{ font-size: 90%; } body{ background: #fafafa; } header{ background: #6ca8fb; text-align: center; height: 620px; min-width: 100%; padding: 5em 0px !important; position: relative; border-bottom: 1px solid #edeeee; } header h1 { font-size: 70px; color: white; font-weight: 100; margin-top: 26px; margin-bottom: 10px; line-height: 1; letter-spacing: 0.1em; } header p{ text-align: center; color: white; font-size: 16px; line-height: 1.6em; letter-spacing: 1px; font-weight: 300; margin: 1.7em; } header img{ width: 190px; } .cbp_tmlabel .hux_ul{ border:none; padding:0; margin:0; } .cbp_tmlabel .hux_ul li{ padding:0; margin: 0; list-style: none; } .cbp_tmlabel img{ width: 100%; margin-bottom: 1em; border-top: 1px solid #eeefef; border-bottom: 1px solid #eeefef; } .cbp_tmlabel p{ padding: 1em 0; /*text-indent: 2em;*/ margin: 0 1.5em; border-top: 1px solid rgba(255,255,255,0.4); } .cbp_tmlabel ul{ padding: 0em 0; margin: 0 1.5em; list-style: none; } .cbp_tmlabel ul li{ padding: 0.5em 0; } .cbp_tmlabel ul li.skill{ overflow: auto; margin-top: 9px; border-top: 1px solid #eeefef; } .cbp_tmlabel ul li.skill>span, .cbp_tmlabel ul li.skill>a{ display: block; float: left; font-size: 1.3rem; width: 40px; height: 40px; text-align: center; line-height: 40px; margin-right: 8px; color: #a5a7aa; transition: all 0.3s ease; } .cbp_tmlabel ul li a:hover{ background: rgba(0,0,0,0.05); border-radius: 50%; } .cbp_tmlabel ul li.skill>span:nth-child(1){ margin-left: -7px; } .cbp_tmlabel ul li.skill span:before{ line-height: 40px; } .cbp_tmlabel ul li.skill span.link{ float: right; font-size: 0.8em; line-height: 30px; width: auto; padding: 0 11px; min-width: 70px; box-sizing: border-box; height: 32px; border-radius: 3px; background: white; border: 1px solid #D5D6D8; margin: 4px 0px; } .cbp_tmlabel ul li.skill span.link:active{ background: #eee; } .cbp_tmlabel ul li.skill span.link a { color: #a5a7aa; display: block; width: 100%; height: 100%; font-size: 14px; font-weight: bold; } @media screen and (max-width: 400px) { .main{ width: 100%; padding-bottom: 0px; } html{ font-size: 90%; } header p{ font-size: 1.05em; letter-spacing: 0px; margin: 1.5em; } .cbp_tmlabel ul li.skill>span, .cbp_tmlabel ul li.skill>a{ margin-right: 2px; } }
package com.griddynamics.jagger.dbapi.parameter; import com.google.common.base.Objects; public class GroupKey { private String upperName; private String leftName; public GroupKey(String upperName) { this.upperName = upperName; this.leftName = upperName; } public GroupKey(String upperName, String leftName) { this.upperName = upperName; this.leftName = leftName; } public String getUpperName() { return upperName; } public String getLeftName() { return leftName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupKey groupKey = (GroupKey) o; if (leftName != null ? !leftName.equals(groupKey.leftName) : groupKey.leftName != null) return false; if (upperName != null ? !upperName.equals(groupKey.upperName) : groupKey.upperName != null) return false; return true; } @Override public int hashCode() { int result = upperName != null ? upperName.hashCode() : 0; result = 31 * result + (leftName != null ? leftName.hashCode() : 0); return result; } @Override public String toString() { return Objects.toStringHelper(this) .add("upperName", upperName) .add("leftName", leftName) .toString(); } }
using Newtonsoft.Json.Linq; using System; namespace Kudu.Core.Functions { public interface IKeyJsonOps<T> { int <API key> { get; } // key generation is based on run time string GenerateKeyJson(Tuple<string,string>[] keyPairs, string functionRt, out string unencryptedKey); // read existing key file based on the content format, not the run time version string GetKeyValueFromJson(string json, out bool isEncrypted); T GenerateKeyObject(string functionKey, string functionName); } }
@echo off set <API key>=C:\Program Files (x86)\Microsoft Visual Studio 14.0 call "%<API key>%\VC\vcvarsall.bat" x86_amd64 powershell -ExecutionPolicy RemoteSigned -File <API key>.ps1
require 'chef/knife/base_sync' require 'chef/knife/core/object_loader' class Chef class Knife class PackSync < Chef::Knife include ::BaseSync <API key> = 'enableForOrg' banner "Loads packs into OneOps.\nUsage:\n circuit pack [OPTIONS] [PACKS...]" option :all, :short => "-a", :long => "--all", :description => "Sync all packs" option :register, :short => "-r REGISTER", :long => "--register REGISTER", :description => "Specify the source register name to use during sync" option :version, :short => "-v VERSION", :long => "--version VERSION", :description => "Specify the source register version to use during sync" option :pack_path, :short => "-o PATH:PATH", :long => "--pack-path PATH:PATH", :description => "A colon-separated path to look for packs in", :proc => lambda {|o| o.split(":")} option :reload, :long => "--reload", :description => "Force pack sync even if digest signatue has not changed (not applicable for packs with semantic versioning)" option :clean, :long => "--clean", :description => "Remove the current pack (and corresponding namespace) and then sync - 'fresh start' (not applicable for packs with semantic versioning)" option :semver, :long => "--semver", :description => "Creates new patch version for each change" def run t1 = Time.now ENV['CMS_TRACE'] = 'true' if config[:cms_trace] config[:pack_path] ||= Chef::Config[:pack_path] config[:register] ||= Chef::Config[:register] config[:version] ||= Chef::Config[:version] config[:semver] ||= ENV['SEMVER'].present? Chef::Pack.config = config @packs_loader ||= Knife::Core::ObjectLoader.new(Chef::Pack, ui) validate_packs # safety measure: make sure no packs conflict in scope circuit_ns_path = get_packs_ns unless Cms::Namespace.first(:params => {:nsPath => circuit_ns_path}) ui.error("Can't find namespace #{circuit_ns_path}. Please register your source first with the register command.") exit 1 end if config[:all]
// Use of this source code is governed by a BSD-style package archive import ( "archive/tar" "bufio" "compress/gzip" "fmt" "io" "os" "path/filepath" "strings" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/system" "github.com/sirupsen/logrus" ) const ( // Uncompressed represents the uncompressed. Uncompressed Compression = iota // Bzip2 is bzip2 compression algorithm. Bzip2 // Gzip is gzip compression algorithm. Gzip // Xz is xz compression algorithm. Xz ) const ( modeISDIR = 040000 // Directory modeISFIFO = 010000 // FIFO modeISREG = 0100000 // Regular file modeISLNK = 0120000 // Symbolic link modeISBLK = 060000 // Block special file modeISCHR = 020000 // Character special file modeISSOCK = 0140000 // Socket ) // Compression is the state represents if compressed or not. type Compression int // Extension returns the extension of a file that uses the specified compression algorithm. func (compression *Compression) Extension() string { switch *compression { case Uncompressed: return "tar" case Bzip2: return "tar.bz2" case Gzip: return "tar.gz" case Xz: return "tar.xz" } return "" } // WhiteoutFormat is the format of whiteouts unpacked type WhiteoutFormat int // TarOptions wraps the tar options. type TarOptions struct { IncludeFiles []string ExcludePatterns []string Compression Compression NoLchown bool UIDMaps []idtools.IDMap GIDMaps []idtools.IDMap ChownOpts *idtools.Identity IncludeSourceDir bool // WhiteoutFormat is the expected on disk format for whiteout files. // This format will be converted to the standard format on pack // and from the standard format on unpack. WhiteoutFormat WhiteoutFormat // When unpacking, specifies whether overwriting a directory with a // non-directory is allowed and vice versa. <API key> bool // For each include when creating an archive, the included name will be // replaced with the matching name from this map. RebaseNames map[string]string InUserNS bool } // TarWithOptions creates an archive from the directory at `path`, only including files whose relative // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { // Fix the source path to work with long path names. This is a no-op // on platforms other than Windows. srcPath = fixVolumePathPrefix(srcPath) pm, err := fileutils.NewPatternMatcher(options.ExcludePatterns) if err != nil { return nil, err } pipeReader, pipeWriter := io.Pipe() compressWriter, err := CompressStream(pipeWriter, options.Compression) if err != nil { return nil, err } go func() { ta := newTarAppender( idtools.<API key>(options.UIDMaps, options.GIDMaps), compressWriter, options.ChownOpts, ) ta.WhiteoutConverter = <API key>(options.WhiteoutFormat) defer func() { // Make sure to check the error on Close. if err := ta.TarWriter.Close(); err != nil { logrus.Errorf("Can't close tar writer: %s", err) } if err := compressWriter.Close(); err != nil { logrus.Errorf("Can't close compress writer: %s", err) } if err := pipeWriter.Close(); err != nil { logrus.Errorf("Can't close pipe writer: %s", err) } }() // this buffer is needed for the duration of this piped stream defer pools.BufioWriter32KPool.Put(ta.Buffer) // In general we log errors here but ignore them because // during e.g. a diff operation the container can continue // mutating the filesystem and we can see transient errors // from this stat, err := os.Lstat(srcPath) if err != nil { return } if !stat.IsDir() { // We can't later join a non-dir with any includes because the // 'walk' will error if "file/." is stat-ed and "file" is not a // directory. So, we must split the source path and use the // basename as the include. if len(options.IncludeFiles) > 0 { logrus.Warn("Tar: Can't archive a file with includes") } dir, base := SplitPathDirEntry(srcPath) srcPath = dir options.IncludeFiles = []string{base} } if len(options.IncludeFiles) == 0 { options.IncludeFiles = []string{"."} } seen := make(map[string]bool) for _, include := range options.IncludeFiles { rebaseName := options.RebaseNames[include] walkRoot := getWalkRoot(srcPath, include) filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { if err != nil { logrus.Errorf("Tar: Can't stat file %s to tar: %s", srcPath, err) return nil } relFilePath, err := filepath.Rel(srcPath, filePath) if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { // Error getting relative path OR we are looking // at the source directory path. Skip in both situations. return nil } if options.IncludeSourceDir && include == "." && relFilePath != "." { relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) } skip := false // If "include" is an exact match for the current file // then even if there's an "excludePatterns" pattern that // matches it, don't skip it. IOW, assume an explicit 'include' // is asking for that file no matter what - which is true // for some files, like .dockerignore and Dockerfile (sometimes) if include != relFilePath { skip, err = pm.Matches(relFilePath) if err != nil { logrus.Errorf("Error matching %s: %v", relFilePath, err) return err } } if skip { // If we want to skip this file and its a directory // then we should first check to see if there's an // excludes pattern (e.g. !dir/file) that starts with this // dir. If so then we can't skip this dir. // Its not a dir then so we can just return/skip. if !f.IsDir() { return nil } // No exceptions (!...) in patterns so just skip dir if !pm.Exclusions() { return filepath.SkipDir } dirSlash := relFilePath + string(filepath.Separator) for _, pat := range pm.Patterns() { if !pat.Exclusion() { continue } if strings.HasPrefix(pat.String()+string(filepath.Separator), dirSlash) { // found a match - so can't skip this dir return nil } } // No matching exclusion dir so just skip dir return filepath.SkipDir } if seen[relFilePath] { return nil } seen[relFilePath] = true // Rename the base resource. if rebaseName != "" { var replacement string if rebaseName != string(filepath.Separator) { // Special case the root directory to replace with an // empty string instead so that we don't end up with // double slashes in the paths. replacement = rebaseName } relFilePath = strings.Replace(relFilePath, include, replacement, 1) } if err := ta.addTarFile(filePath, relFilePath); err != nil { logrus.Errorf("Can't add file %s to tar: %s", filePath, err) // if pipe is broken, stop writing tar stream to it if err == io.ErrClosedPipe { return err } } return nil }) } }() return pipeReader, nil } // CompressStream compresses the dest with specified compression algorithm. func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) { p := pools.BufioWriter32KPool buf := p.Get(dest) switch compression { case Uncompressed: writeBufWrapper := p.<API key>(buf, buf) return writeBufWrapper, nil case Gzip: gzWriter := gzip.NewWriter(dest) writeBufWrapper := p.<API key>(buf, gzWriter) return writeBufWrapper, nil case Bzip2, Xz: // archive/bzip2 does not support writing, and there is no xz support at all // However, this is not a problem as docker only currently generates gzipped tars return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) default: return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) } } type <API key> interface { ConvertWrite(*tar.Header, string, os.FileInfo) (*tar.Header, error) ConvertRead(*tar.Header, string) (bool, error) } type tarAppender struct { TarWriter *tar.Writer Buffer *bufio.Writer // for hardlink mapping SeenFiles map[uint64]string IdentityMapping *idtools.IdentityMapping ChownOpts *idtools.Identity // For packing and unpacking whiteout files in the // non standard format. The whiteout files defined // by the AUFS standard are used as the tar whiteout // standard. WhiteoutConverter <API key> } func newTarAppender(idMapping *idtools.IdentityMapping, writer io.Writer, chownOpts *idtools.Identity) *tarAppender { return &tarAppender{ SeenFiles: make(map[uint64]string), TarWriter: tar.NewWriter(writer), Buffer: pools.BufioWriter32KPool.Get(nil), IdentityMapping: idMapping, ChownOpts: chownOpts, } } // addTarFile adds to the tar archive a file from `path` as `name` func (ta *tarAppender) addTarFile(path, name string) error { fi, err := os.Lstat(path) if err != nil { return err } var link string if fi.Mode()&os.ModeSymlink != 0 { var err error link, err = os.Readlink(path) if err != nil { return err } } hdr, err := FileInfoHeader(name, fi, link) if err != nil { return err } if err := <API key>(path, hdr); err != nil { return err } // if it's not a directory and has more than 1 link, // it's hard linked, so set the type flag accordingly if !fi.IsDir() && hasHardlinks(fi) { inode, err := getInodeFromStat(fi.Sys()) if err != nil { return err } // a link should have a name that it links too // and that linked name should be first in the tar archive if oldpath, ok := ta.SeenFiles[inode]; ok { hdr.Typeflag = tar.TypeLink hdr.Linkname = oldpath hdr.Size = 0 // This Must be here for the writer math to add up! } else { ta.SeenFiles[inode] = name } } //check whether the file is overlayfs whiteout //if yes, skip re-mapping container ID mappings. isOverlayWhiteout := fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 //handle re-mapping container ID mappings back to host ID mappings before //writing tar headers/files. We skip whiteout files because they were written //by the kernel and already have proper ownership relative to the host if !isOverlayWhiteout && !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && !ta.IdentityMapping.Empty() { fileIdentity, err := getFileIdentity(fi.Sys()) if err != nil { return err } hdr.Uid, hdr.Gid, err = ta.IdentityMapping.ToContainer(fileIdentity) if err != nil { return err } } // explicitly override with ChownOpts if ta.ChownOpts != nil { hdr.Uid = ta.ChownOpts.UID hdr.Gid = ta.ChownOpts.GID } if ta.WhiteoutConverter != nil { wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, path, fi) if err != nil { return err } // If a new whiteout file exists, write original hdr, then // replace hdr with wo to be written after. Whiteouts should // always be written after the original. Note the original // hdr may have been updated to be a whiteout with returning // a whiteout header if wo != nil { if err := ta.TarWriter.WriteHeader(hdr); err != nil { return err } if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { return fmt.Errorf("tar: cannot use whiteout for non-empty file") } hdr = wo } } if err := ta.TarWriter.WriteHeader(hdr); err != nil { return err } if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { // We use system.OpenSequential to ensure we use sequential file // access on Windows to avoid depleting the standby list. // On Linux, this equates to a regular os.Open. file, err := system.OpenSequential(path) if err != nil { return err } ta.Buffer.Reset(ta.TarWriter) defer ta.Buffer.Reset(nil) _, err = io.Copy(ta.Buffer, file) file.Close() if err != nil { return err } err = ta.Buffer.Flush() if err != nil { return err } } return nil } // <API key> reads security.capability xattr from filesystem // to a tar header func <API key>(path string, hdr *tar.Header) error { capability, _ := system.Lgetxattr(path, "security.capability") if capability != nil { hdr.Xattrs = make(map[string]string) hdr.Xattrs["security.capability"] = string(capability) } return nil } // FileInfoHeader creates a populated Header from fi. // Compared to archive pkg this function fills in more information. // Also, regardless of Go version, this function fills file type bits (e.g. hdr.Mode |= modeISDIR), // which have been deleted since Go 1.9 archive/tar. func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, error) { hdr, err := tar.FileInfoHeader(fi, link) if err != nil { return nil, err } hdr.Mode = <API key>(int64(chmodTarEntry(os.FileMode(hdr.Mode))), fi) name, err = canonicalTarName(name, fi.IsDir()) if err != nil { return nil, fmt.Errorf("tar: cannot canonicalize path: %v", err) } hdr.Name = name if err := <API key>(hdr, name, fi.Sys()); err != nil { return nil, err } return hdr, nil } // <API key> fills type bits which have been removed on Go 1.9 archive/tar func <API key>(mode int64, fi os.FileInfo) int64 { fm := fi.Mode() switch { case fm.IsRegular(): mode |= modeISREG case fi.IsDir(): mode |= modeISDIR case fm&os.ModeSymlink != 0: mode |= modeISLNK case fm&os.ModeDevice != 0: if fm&os.ModeCharDevice != 0 { mode |= modeISCHR } else { mode |= modeISBLK } case fm&os.ModeNamedPipe != 0: mode |= modeISFIFO case fm&os.ModeSocket != 0: mode |= modeISSOCK } return mode } // canonicalTarName provides a <API key> and consistent posix-style //path for files and directories to be archived regardless of the platform. func canonicalTarName(name string, isDir bool) (string, error) { name, err := <API key>(name) if err != nil { return "", err } // suffix with '/' for directories if isDir && !strings.HasSuffix(name, "/") { name += "/" } return name, nil }
+++ date = "2016-03-06T21:28:07-06:00" title = "Gareth Rushgrove" type = "talk" +++ ## Rate of Change, (Un)opinionated Platforms and Devops Coevolution There has been a recent explosion in new technologies for running software systems. Many architectures are now based on ever smaller (micro) services. The devops movement has crossed the chasm and become mainstream with operators and developers working more closely together than ever before. These three threads are the result of coevolution - where a change in one practice has a direct effect on others. Join us to gain insights on how the adoption of practices such as devops and microservices, and tools such as platform as a service, are interconnected. You'll also develop a better understanding of how devops emerged in widely different organisations. Last, but by no means least, we'll explore the power of coevolution which makes cause and effect bi-directional, making it possible to leverage what you do and how you do it to improve your organisation as a whole. <script async class="speakerdeck-embed" data-id="<API key>" data-ratio="1.77777777777778" src="//speakerdeck.com/assets/embed.js"></script> <iframe src="https://player.vimeo.com/video/165641911" width="640" height="360" frameborder="0" <API key> mozallowfullscreen allowfullscreen></iframe> <p><a href="https:
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: <API key>("")] [assembly: AssemblyCompany("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("<API key>")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")]
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Form Validation : CodeIgniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../nav/nav.js"></script> <script type="text/javascript" src="../nav/prototype.lite.js"></script> <script type="text/javascript" src="../nav/moo.fx.js"></script> <script type="text/javascript" src="../nav/user_guide_menu.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='ExpressionEngine Dev Team' /> <meta name='description' content='CodeIgniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>CodeIgniter User Guide Version 1.7.3</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; Form Validation </td> <td id="searchbox"><form method="get" action="http: </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <p class="important"> This library has been deprecated. Use of the form_validation library is encouraged. </p> <h1>Form Validation</h1> <p>Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario:</p> <ol> <li>A form is displayed.</li> <li>You fill it in and submit it.</li> <li>If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem.</li> <li>This process continues until you have submitted a valid form.</li> </ol> <p>On the receiving end, the script must:</p> <ol> <li>Check for required data.</li> <li>Verify that the data is of the correct type, and meets the correct criteria. (For example, if a username is submitted it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc.)</li> <li>Sanitize the data for security.</li> <li>Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)</li> <li>Prep the data for insertion in the database.</li> </ol> <p>Although there is nothing complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement.</p> <dfn>CodeIgniter provides a comprehensive validation framework that truly minimizes the amount of code you'll write. It also removes all control structures from your form HTML, permitting it to be clean and free of code.</dfn> <h2>Overview</h2> <p>In order to implement CodeIgniter's form validation you'll need three things:</p> <ol> <li>A <a href="../general/views.html">View</a> file containing the form.</li> <li>A View file containing a "success" message to be displayed upon successful submission.</li> <li>A <a href="../general/controllers.html">controller</a> function to receive and process the submitted data.</li> </ol> <p>Let's create those three things, using a member sign-up form as the example.</p> <h2>The Form</h2> <p>Using a text editor, create a form called <dfn>myform.php</dfn>. In it, place this code and save it to your <samp>applications/views/</samp> folder:</p> <textarea class="textarea" style="width:100%" cols="50" rows="30">&lt;html> &lt;head> &lt;title>My Form&lt;/title> &lt;/head> &lt;body> &lt;?php echo $this->validation->error_string; ?> &lt;?php echo form_open('form'); ?> &lt;h5>Username&lt;/h5> &lt;input type="text" name="username" value="" size="50" /> &lt;h5>Password&lt;/h5> &lt;input type="text" name="password" value="" size="50" /> &lt;h5>Password Confirm&lt;/h5> &lt;input type="text" name="passconf" value="" size="50" /> &lt;h5>Email Address&lt;/h5> &lt;input type="text" name="email" value="" size="50" /> &lt;div>&lt;input type="submit" value="Submit" />&lt;/div> &lt;/form> &lt;/body> &lt;/html> </textarea> <h2>The Success Page</h2> <p>Using a text editor, create a form called <dfn>formsuccess.php</dfn>. In it, place this code and save it to your <samp>applications/views/</samp> folder:</p> <textarea class="textarea" style="width:100%" cols="50" rows="14"> &lt;html> &lt;head> &lt;title>My Form&lt;/title> &lt;/head> &lt;body> &lt;h3>Your form was successfully submitted!&lt;/h3> &lt;p>&lt;?php echo anchor('form', 'Try it again!'); ?>&lt;/p> &lt;/body> &lt;/html> </textarea> <h2>The Controller</h2> <p>Using a text editor, create a controller called <dfn>form.php</dfn>. In it, place this code and save it to your <samp>applications/controllers/</samp> folder:</p> <textarea class="textarea" style="width:100%" cols="50" rows="21">&lt;?php class Form extends Controller { function index() { $this->load->helper(array('form', 'url')); $this->load->library('validation'); if ($this->validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } ?></textarea> <h2>Try it!</h2> <p>To try your form, visit your site using a URL similar to this one:</p> <code>example.com/index.php/<var>form</var>/</code> <p><strong>If you submit the form you should simply see the form reload. That's because you haven't set up any validation rules yet, which we'll get to in a moment.</strong></p> <h2>Explanation</h2> <p>You'll notice several things about the above pages:</p> <p>The <dfn>form</dfn> (myform.php) is a standard web form with a couple exceptions:</p> <ol> <li>It uses a <dfn>form helper</dfn> to create the form opening. Technically, this isn't necessary. You could create the form using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable and flexible in the event your URLs change.</li> <li>At the top of the form you'll notice the following variable: <code>&lt;?php echo $this->validation->error_string; ?&gt;</code> <p>This variable will display any error messages sent back by the validator. If there are no messages it returns nothing.</p> </li> </ol> <p>The <dfn>controller</dfn> (form.php) has one function: <dfn>index()</dfn>. This function initializes the validation class and loads the <var>form helper</var> and <var>URL helper</var> used by your view files. It also <samp>runs</samp> the validation routine. Based on whether the validation was successful it either presents the form or the success page.</p> <p><strong>Since you haven't told the validation class to validate anything yet, it returns "false" (boolean false) by default. The <samp>run()</samp> function only returns "true" if it has successfully applied your rules without any of them failing.</strong></p> <h2>Setting Validation Rules</h2> <p>CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. Let's see it in action, we'll explain it afterwards.</p> <p>In your <dfn>controller</dfn> (form.php), add this code just below the validation initialization function:</p> <code>$rules['username'] = "required";<br /> $rules['password'] = "required";<br /> $rules['passconf'] = "required";<br /> $rules['email'] = "required";<br /> <br /> $this->validation->set_rules($rules);</code> <p>Your controller should now look like this:</p> <textarea class="textarea" style="width:100%" cols="50" rows="28">&lt;?php class Form extends Controller { function index() { $this->load->helper(array('form', 'url')); $this->load->library('validation'); $rules['username'] = "required"; $rules['password'] = "required"; $rules['passconf'] = "required"; $rules['email'] = "required"; $this->validation->set_rules($rules); if ($this->validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } } ?></textarea> <p><dfn>Now submit the form with the fields blank and you should see the error message. If you submit the form with all the fields populated you'll see your success page.</dfn></p> <p class="important"><strong>Note:</strong> The form fields are not yet being re-populated with the data when there is an error. We'll get to that shortly, once we're through explaining the validation rules.</p> <h2>Changing the Error Delimiters</h2> <p>By default, the system adds a paragraph tag (&lt;p&gt;) around each error message shown. You can easily change these delimiters with this code, placed in your controller:</p> <code>$this->validation-><API key>('<kbd>&lt;div class="error"></kbd>', '<kbd>&lt;/div></kbd>');</code> <p>In this example, we've switched to using div tags.</p> <h2>Cascading Rules</h2> <p>CodeIgniter lets you pipe multiple rules together. Let's try it. Change your rules array like this:</p> <code>$rules['username'] = "required|min_length[5]|max_length[12]";<br /> $rules['password'] = "required|matches[passconf]";<br /> $rules['passconf'] = "required";<br /> $rules['email'] = "required|valid_email";</code> <p>The above code requires that:</p> <ol> <li>The username field be no shorter than 5 characters and no longer than 12.</li> <li>The password field must match the password confirmation field.</li> <li>The email field must contain a valid email address.</li> </ol> <p>Give it a try!</p> <p class="important"><strong>Note:</strong> There are numerous rules available which you can read about in the validation reference.</p> <h2>Prepping Data</h2> <p>In addition to the validation functions like the ones we used above, you can also prep your data in various ways. For example, you can set up rules like this:</p> <code>$rules['username'] = "<kbd>trim</kbd>|required|min_length[5]|max_length[12]|<kbd>xss_clean</kbd>";<br /> $rules['password'] = "<kbd>trim</kbd>|required|matches[passconf]|<kbd>md5</kbd>";<br /> $rules['passconf'] = "<kbd>trim</kbd>|required";<br /> $rules['email'] = "<kbd>trim</kbd>|required|valid_email";</code> <p>In the above example, we are "trimming" the fields, converting the password to MD5, and running the username through the "xss_clean" function, which removes malicious data.</p> <p class="important"><strong>Any native PHP function that accepts one parameter can be used as a rule, like <dfn>htmlspecialchars</dfn>, <dfn>trim</dfn>, <dfn>MD5</dfn>, etc.</strong></p> <p><strong>Note:</strong> You will generally want to use the prepping functions <strong>after</strong> the validation rules so if there is an error, the original data will be shown in the form.</p> <h2>Callbacks: Your own Validation Functions</h2> <p>The validation system supports callbacks to your own validation functions. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback function that does that. Let's create a simple example.</p> <p>In your controller, change the "username" rule to this:</p> <code>$rules['username'] = "<API key>"; </code> <p>Then add a new function called <dfn>username_check</dfn> to your controller. Here's how your controller should look:</p> <textarea class="textarea" style="width:100%" cols="50" rows="44">&lt;?php class Form extends Controller { function index() { $this->load->helper(array('form', 'url')); $this->load->library('validation'); $rules['username'] = "<API key>"; $rules['password'] = "required"; $rules['passconf'] = "required"; $rules['email'] = "required"; $this->validation->set_rules($rules); if ($this->validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } function username_check($str) { if ($str == 'test') { $this->validation->set_message('username_check', 'The %s field can not be the word "test"'); return FALSE; } else { return TRUE; } } } ?></textarea> <p>Reload your form and submit it with the word "test" as the username. You can see that the form field data was passed to your callback function for you to process.</p> <p><strong>To invoke a callback just put the function name in a rule, with "callback_" as the rule prefix.</strong></p> <p>The error message was set using the <dfn>$this->validation->set_message</dfn> function. Just remember that the message key (the first parameter) must match your function name.</p> <p class="important"><strong>Note:</strong> You can apply your own custom error messages to any rule, just by setting the message similarly. For example, to change the message for the "required" rule you will do this:</p> <code>$this->validation->set_message('required', 'Your custom message here');</code> <h2>Re-populating the form</h2> <p>Thus far we have only been dealing with errors. It's time to repopulate the form field with the submitted data. This is done similarly to your rules. Add the following code to your controller, just below your rules:</p> <code>$fields['username'] = 'Username';<br /> $fields['password'] = 'Password';<br /> $fields['passconf'] = 'Password Confirmation';<br /> $fields['email'] = 'Email Address';<br /> <br /> $this->validation->set_fields($fields);</code> <p>The array keys are the actual names of the form fields, the value represents the full name that you want shown in the error message.</p> <p>The index function of your controller should now look like this:</p> <textarea class="textarea" style="width:100%" cols="50" rows="30">function index() { $this->load->helper(array('form', 'url')); $this->load->library('validation'); $rules['username'] = "required"; $rules['password'] = "required"; $rules['passconf'] = "required"; $rules['email'] = "required"; $this->validation->set_rules($rules); $fields['username'] = 'Username'; $fields['password'] = 'Password'; $fields['passconf'] = 'Password Confirmation'; $fields['email'] = 'Email Address'; $this->validation->set_fields($fields); if ($this->validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } }</textarea> <p>Now open your <dfn>myform.php</dfn> view file and update the value in each field so that it has an attribute corresponding to its name:</p> <textarea class="textarea" style="width:100%" cols="50" rows="30"> &lt;html> &lt;head> &lt;title>My Form&lt;/title> &lt;/head> &lt;body> &lt;?php echo $this->validation->error_string; ?> &lt;?php echo form_open('form'); ?> &lt;h5>Username&lt;/h5> &lt;input type="text" name="username" value="&lt;?php echo $this->validation->username;?>" size="50" /> &lt;h5>Password&lt;/h5> &lt;input type="text" name="password" value="&lt;?php echo $this->validation->password;?>" size="50" /> &lt;h5>Password Confirm&lt;/h5> &lt;input type="text" name="passconf" value="&lt;?php echo $this->validation->passconf;?>" size="50" /> &lt;h5>Email Address&lt;/h5> &lt;input type="text" name="email" value="&lt;?php echo $this->validation->email;?>" size="50" /> &lt;div>&lt;input type="submit" value="Submit" />&lt;/div> &lt;/form> &lt;/body> &lt;/html> </textarea> <p>Now reload your page and submit the form so that it triggers an error. Your form fields should be populated and the error messages will contain a more relevant field name.</p> <h2>Showing Errors Individually</h2> <p>If you prefer to show an error message next to each form field, rather than as a list, you can change your form so that it looks like this:</p> <textarea class="textarea" style="width:100%" cols="50" rows="20"> &lt;h5>Username&lt;/h5> &lt;?php echo $this->validation->username_error; ?> &lt;input type="text" name="username" value="&lt;?php echo $this->validation->username;?>" size="50" /> &lt;h5>Password&lt;/h5> &lt;?php echo $this->validation->password_error; ?> &lt;input type="text" name="password" value="&lt;?php echo $this->validation->password;?>" size="50" /> &lt;h5>Password Confirm&lt;/h5> &lt;?php echo $this->validation->passconf_error; ?> &lt;input type="text" name="passconf" value="&lt;?php echo $this->validation->passconf;?>" size="50" /> &lt;h5>Email Address&lt;/h5> &lt;?php echo $this->validation->email_error; ?> &lt;input type="text" name="email" value="&lt;?php echo $this->validation->email;?>" size="50" /></textarea> <p>If there are no errors, nothing will be shown. If there is an error, the message will appear, wrapped in the delimiters you have set (&lt;p> tags by default).</p> <p class="important"><strong>Note: </strong>To display errors this way you must remember to set your fields using the <kbd>$this->validation->set_fields</kbd> function described earlier. The errors will be turned into variables that have "_error" after your field name. For example, your "username" error will be available at:<br /><dfn>$this->validation->username_error</dfn>.</p> <h2>Rule Reference</h2> <p>The following is a list of all the native rules that are available to use:</p> <table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder"> <tr> <th>Rule</th> <th>Parameter</th> <th>Description</th> <th>Example</th> </tr><tr> <td class="td"><strong>required</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element is empty.</td> <td class="td">&nbsp;</td> </tr><tr> <td class="td"><strong>matches</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element does not match the one in the parameter.</td> <td class="td">matches[form_item]</td> </tr><tr> <td class="td"><strong>min_length</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is shorter then the parameter value.</td> <td class="td">min_length[6]</td> </tr><tr> <td class="td"><strong>max_length</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is longer then the parameter value.</td> <td class="td">max_length[12]</td> </tr><tr> <td class="td"><strong>exact_length</strong></td> <td class="td">Yes</td> <td class="td">Returns FALSE if the form element is not exactly the parameter value.</td> <td class="td">exact_length[8]</td> </tr><tr> <td class="td"><strong>alpha</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than alphabetical characters.</td> <td class="td">&nbsp;</td> </tr><tr> <td class="td"><strong>alpha_numeric</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters.</td> <td class="td">&nbsp;</td> </tr><tr> <td class="td"><strong>alpha_dash</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>numeric</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than numeric characters.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>integer</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element contains anything other than an integer.</td> <td class="td">&nbsp;</td> </tr><tr> <td class="td"><strong>valid_email</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the form element does not contain a valid email address.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>valid_emails</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if any value provided in a comma separated list is not a valid email.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>valid_ip</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the supplied IP is not valid.</td> <td class="td">&nbsp;</td> </tr> <tr> <td class="td"><strong>valid_base64</strong></td> <td class="td">No</td> <td class="td">Returns FALSE if the supplied string contains anything other than valid Base64 characters.</td> <td class="td">&nbsp;</td> </tr> </table> <p><strong>Note:</strong> These rules can also be called as discrete functions. For example:</p> <code>$this->validation->required($string);</code> <p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter.</p> <h2>Prepping Reference</h2> <p>The following is a list of all the prepping functions that are available to use:</p> <table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder"> <tr> <th>Name</th> <th>Parameter</th> <th>Description</th> </tr><tr> <td class="td"><strong>xss_clean</strong></td> <td class="td">No</td> <td class="td">Runs the data through the XSS filtering function, described in the <a href="input.html">Input Class</a> page.</td> </tr><tr> <td class="td"><strong>prep_for_form</strong></td> <td class="td">No</td> <td class="td">Converts special characters so that HTML data can be shown in a form field without breaking it.</td> </tr><tr> <td class="td"><strong>prep_url</strong></td> <td class="td">No</td> <td class="td">Adds "http://" to URLs if missing.</td> </tr><tr> <td class="td"><strong>strip_image_tags</strong></td> <td class="td">No</td> <td class="td">Strips the HTML from image tags leaving the raw URL.</td> </tr><tr> <td class="td"><strong>encode_php_tags</strong></td> <td class="td">No</td> <td class="td">Converts PHP tags to entities.</td> </tr> </table> <p class="important"><strong>Note:</strong> You can also use any native PHP functions that permit one parameter, like <kbd>trim</kbd>, <kbd>htmlspecialchars</kbd>, <kbd>urldecode</kbd>, etc.</p> <h2>Setting Custom Error Messages</h2> <p>All of the native error messages are located in the following language file: <dfn>language/english/validation_lang.php</dfn></p> <p>To set your own custom message you can either edit that file, or use the following function:</p> <code>$this->validation->set_message('<var>rule</var>', '<var>Error Message</var>');</code> <p>Where <var>rule</var> corresponds to the name of a particular rule, and <var>Error Message</var> is the text you would like displayed.</p> <h2>Dealing with Select Menus, Radio Buttons, and Checkboxes</h2> <p>If you use select menus, radio buttons or checkboxes, you will want the state of these items to be retained in the event of an error. The Validation class has three functions that help you do this:</p> <h2>set_select()</h2> <p>Permits you to display the menu item that was selected. The first parameter must contain the name of the select menu, the second parameter must contain the value of each item. Example:</p> <code> &lt;select name="myselect"><br /> &lt;option value="one" <dfn>&lt;?php echo $this->validation->set_select('myselect', 'one'); ?></dfn> >One&lt;/option><br /> &lt;option value="two" <dfn>&lt;?php echo $this->validation->set_select('myselect', 'two'); ?></dfn> >Two&lt;/option><br /> &lt;option value="three" <dfn>&lt;?php echo $this->validation->set_select('myselect', 'three'); ?></dfn> >Three&lt;/option><br /> &lt;/select> </code> <h2>set_checkbox()</h2> <p>Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second parameter must contain its value. Example:</p> <code>&lt;input type="checkbox" name="mycheck" value="1" <dfn>&lt;?php echo $this->validation->set_checkbox('mycheck', '1'); ?></dfn> /></code> <h2>set_radio()</h2> <p>Permits you to display radio buttons in the state they were submitted. The first parameter must contain the name of the radio button, the second parameter must contain its value. Example:</p> <code>&lt;input type="radio" name="myradio" value="1" <dfn>&lt;?php echo $this->validation->set_radio('myradio', '1'); ?></dfn> /></code> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="user_agent.html">User Agent Class</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="xmlrpc.html">XML-RPC Class</a> </p> <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright & </div> </body> </html>
body { font-family: Source Sans Pro, Ubuntu, sans-serif; background-color: #fffdfa; color: #073642; font-size: 17px; } a.button { font-weight: bold; } .homeContainer { background-color: #073642; } .homeContainer, .projectTitle { color: #eee8d5; padding-top: 25px; padding-bottom: 25px; } .homeContainer a.button { background-color: #cb4b16; border-color: #cb4b16; color: #eee8d5; } .darkBackground { background-color: #073642; } .darkBackground a { color: #268bd2; } .lightBackground { color: #073642; background-color: #fffdfa; } .projectTitle { font-weight: 800; max-width: 800px; margin: auto; } .projectTitle small { line-height: 1.5em; } .imageAlignLeft .blockImage { max-width: 300px; } .imageAlignRight .blockImage { max-width: 300px; } .useCases .gridBlock { max-width: 920px; margin: auto; padding-top: 40px; padding-bottom: 40px; } .useCases .imageAlignLeft .blockImage { /* max-width: 200px; */ /* margin: auto; */ } .useCases .imageAlignRight .blockImage { /* max-width: 200px; */ /* margin: auto; */ } .useCases h2 { /* font-size: 20px; */ } .logos { max-width: 640px; margin: auto; } .<API key> { background-color: #f0f0f0; } .<API key> a h3 { color: #707482; text-decoration: none; border-bottom: 1px solid #2d7de4; } .navigationSlider .slidingNav ul li a { color: #707482; font-weight: 600; letter-spacing: 0.35px; font-size: 16px; border-bottom: 3px solid transparent; margin-left: 6px; margin-right: 10px; padding-left: 0; padding-right: 0; } .navigationSlider .slidingNav ul li.siteNavGroupActive a, .navigationSlider .slidingNav ul li.siteNavItemActive a, .navigationSlider .slidingNav ul li a:focus, .navigationSlider .slidingNav ul li a:hover { color: #707482 !important; border-bottom: 3px solid #2d7de4; background: none; } .nav-footer { background-color: #002b36; } .nav-footer .sitemap .nav-home { height: 34px; opacity: 0.8; padding: 10px; transition: opacity 0.15s ease-in-out; width: 200px; } .blog .wrapper { max-width: 1400px; } .blog .post { max-width: 780px; } .versionsContainer { max-width: 780px; } .card { display: inline-block; vertical-align: top; border: 2px solid #e6e6e6; margin-top: 1em; margin-bottom: 1em; margin-right: 1em; } .card p { padding: 1em; } .card header { background: #e6e6e6; display: block; text-align: center; font-weight: 600; line-height: 2em; } .card .buttonWrapper { text-align: center; margin: 10px; } @media only screen and (min-device-width: 360px) and (max-device-width: 736px) { .card { max-width: 350px; } } @media only screen and (min-width: 1024px) { .card { max-width: 510px; } } @media only screen and (max-width: 1023px) { .card { max-width: 510px; } } @media only screen and (min-width: 1400px) { .card { max-width: 510px; } } @media only screen and (min-width: 1500px) { .card { max-width: 650px; } }