code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace Drupal\admin_toolbar_tools\Controller; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\CronInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Drupal\Core\Menu\ContextualLinkManager; use Drupal\Core\Menu\LocalActionManager; use Drupal\Core\Menu\LocalTaskManager; use Drupal\Core\Menu\MenuLinkManager; /** * Class ToolbarController * @package Drupal\admin_toolbar_tools\Controller */ class ToolbarController extends ControllerBase { /** * The cron service. * * @var $cron \Drupal\Core\CronInterface */ protected $cron; protected $menuLinkManager; protected $contextualLinkManager; protected $localTaskLinkManager; protected $localActionLinkManager; protected $cacheRender; /** * Constructs a CronController object. * * @param \Drupal\Core\CronInterface $cron * The cron service. */ public function __construct(CronInterface $cron, MenuLinkManager $menuLinkManager, ContextualLinkManager $contextualLinkManager, LocalTaskManager $localTaskLinkManager, LocalActionManager $localActionLinkManager, CacheBackendInterface $cacheRender) { $this->cron = $cron; $this->menuLinkManager = $menuLinkManager; $this->contextualLinkManager = $contextualLinkManager; $this->localTaskLinkManager = $localTaskLinkManager; $this->localActionLinkManager = $localActionLinkManager; $this->cacheRender = $cacheRender; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('cron'), $container->get('plugin.manager.menu.link'), $container->get('plugin.manager.menu.contextual_link'), $container->get('plugin.manager.menu.local_task'), $container->get('plugin.manager.menu.local_action'), $container->get('cache.render') ); } // Reload the previous page. public function reload_page() { $request = \Drupal::request(); if($request->server->get('HTTP_REFERER')) { return $request->server->get('HTTP_REFERER'); } else{ return '/'; } } // Flushes all caches. public function flushAll() { drupal_flush_all_caches(); drupal_set_message($this->t('All caches cleared.')); return new RedirectResponse($this->reload_page()); } // Flushes css and javascript caches. public function flush_js_css() { \Drupal::state() ->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36)); drupal_set_message($this->t('CSS and JavaScript cache cleared.')); return new RedirectResponse($this->reload_page()); } // Flushes plugins caches. public function flush_plugins() { \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions(); drupal_set_message($this->t('Plugins cache cleared.')); return new RedirectResponse($this->reload_page()); } // Resets all static caches. public function flush_static() { drupal_static_reset(); drupal_set_message($this->t('Static cache cleared.')); return new RedirectResponse($this->reload_page()); } // Clears all cached menu data. public function flush_menu() { menu_cache_clear_all(); $this->menuLinkManager->rebuild(); $this->contextualLinkManager->clearCachedDefinitions(); $this->localTaskLinkManager->clearCachedDefinitions(); $this->localActionLinkManager->clearCachedDefinitions(); drupal_set_message($this->t('Routing and links cache cleared.')); return new RedirectResponse($this->reload_page()); } // Links to drupal.org home page. public function drupal_org() { $response = new RedirectResponse("https://www.drupal.org"); $response->send(); return $response; } // Displays the administration link Development. public function development() { return new RedirectResponse('/admin/structure/menu/'); } // Access to Drupal 8 changes (list changes of the different versions of drupal core). public function list_changes() { $response = new RedirectResponse("https://www.drupal.org/list-changes"); $response->send(); return $response; } // Adds a link to the Drupal 8 documentation. public function documentation() { $response = new RedirectResponse("https://api.drupal.org/api/drupal/8"); $response->send(); return $response; } public function runCron() { $this->cron->run(); drupal_set_message($this->t('CRON ran successfully.')); return new RedirectResponse($this->reload_page()); } public function cacheRender() { $this->cacheRender->invalidateAll(); drupal_set_message($this->t('Render cache cleared.')); return new RedirectResponse($this->reload_page()); } }
hook42/towel
modules/contrib/admin_toolbar/admin_toolbar_tools/src/Controller/ToolbarController.php
PHP
gpl-2.0
4,942
/** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OXID eShop Community Edition 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @package out * @copyright (C) OXID eSales AG 2003-2013 * @version OXID eShop CE * @version SVN: $Id: oxpromocategory.js 35529 2011-05-23 07:31:20Z vilma $ */ ( function( $ ) { oxCenterElementOnHover = { _create: function(){ var self = this; var el = self.element; el.hover(function(){ var targetObj = $(".viewAllHover", el); var targetObjWidth = targetObj.outerWidth() / 2; var parentObjWidth = el.width() / 2; targetObj.css("left", parentObjWidth - targetObjWidth + "px"); targetObj.show(); }, function(){ $(".viewAllHover", el).hide(); }); } } $.widget( "ui.oxCenterElementOnHover", oxCenterElementOnHover ); } )( jQuery );
apnfq/oxid_test
out/azure/src/js/widgets/oxcenterelementonhover.js
JavaScript
gpl-3.0
1,679
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OXID eShop Community Edition 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @package core * @copyright (C) OXID eSales AG 2003-2011 * @version OXID eShop CE * @version SVN: $Id: oxfb.php 25467 2010-02-01 14:14:26Z alfonsas $ */ try { include_once getShopBasePath() . "core/facebook/facebook.php"; } catch ( Exception $oEx ) { // skipping class includion if curl or json is not active oxConfig::getInstance()->setConfigParam( "bl_showFbConnect", false ); return; } error_reporting($iOldErrorReproting); /** * Facebook API * * @package core */ class oxFb extends Facebook { /** * oxUtils class instance. * * @var oxutils */ private static $_instance = null; /** * oxUtils class instance. * * @var oxutils */ protected $_blIsConnected = null; /** * Sets default application parameters - FB application ID, * secure key and cookie support. * * @return null */ public function __construct() { $oConfig = oxConfig::getInstance(); $aFbConfig["appId"] = $oConfig->getConfigParam( "sFbAppId" ); $aFbConfig["secret"] = $oConfig->getConfigParam( "sFbSecretKey" ); $aFbConfig["cookie"] = true; parent::__construct( $aFbConfig ); } /** * Returns object instance * * @return oxPictureHandler */ public static function getInstance() { // disable caching for test modules if ( defined( 'OXID_PHP_UNIT' ) ) { self::$_instance = modInstances::getMod( __CLASS__ ); } if ( !self::$_instance instanceof oxFb ) { self::$_instance = oxNew( 'oxFb' ); if ( defined( 'OXID_PHP_UNIT' ) ) { modInstances::addMod( __CLASS__, self::$_instance); } } return self::$_instance; } /** * Checks is user is connected using Facebook connect. * * @return bool */ public function isConnected() { $oConfig = oxConfig::getInstance(); if ( !$oConfig->getConfigParam( "bl_showFbConnect" ) ) { return false; } if ( $this->_blIsConnected !== null ) { return $this->_blIsConnected; } $this->_blIsConnected = false; $oSession = $this->getSession(); if ( $oSession ) { try { if ( $this->getUser() ) { $this->_blIsConnected = true; } } catch (FacebookApiException $e) { $this->_blIsConnected = false; } } return $this->_blIsConnected; } }
OXIDprojects/oxid-ce-hot-offer
core/oxfb.php
PHP
gpl-3.0
3,426
<?php /** * PHPExcel * * Copyright (c) 2006 - 2013 PHPExcel * * 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. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Shared * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version 1.7.9, 2013-06-02 */ /** * PHPExcel_Shared_Date * * @category PHPExcel * @package PHPExcel_Shared * @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Shared_Date { /** constants */ const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0 const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0 /* * Names of the months of the year, indexed by shortname * Planned usage for locale settings * * @public * @var string[] */ public static $_monthNames = array( 'Jan' => 'January', 'Feb' => 'February', 'Mar' => 'March', 'Apr' => 'April', 'May' => 'May', 'Jun' => 'June', 'Jul' => 'July', 'Aug' => 'August', 'Sep' => 'September', 'Oct' => 'October', 'Nov' => 'November', 'Dec' => 'December', ); /* * Names of the months of the year, indexed by shortname * Planned usage for locale settings * * @public * @var string[] */ public static $_numberSuffixes = array( 'st', 'nd', 'rd', 'th', ); /* * Base calendar year to use for calculations * * @private * @var int */ protected static $_excelBaseDate = self::CALENDAR_WINDOWS_1900; /** * Set the Excel calendar (Windows 1900 or Mac 1904) * * @param integer $baseDate Excel base date (1900 or 1904) * @return boolean Success or failure */ public static function setExcelCalendar($baseDate) { if (($baseDate == self::CALENDAR_WINDOWS_1900) || ($baseDate == self::CALENDAR_MAC_1904)) { self::$_excelBaseDate = $baseDate; return TRUE; } return FALSE; } // function setExcelCalendar() /** * Return the Excel calendar (Windows 1900 or Mac 1904) * * @return integer Excel base date (1900 or 1904) */ public static function getExcelCalendar() { return self::$_excelBaseDate; } // function getExcelCalendar() /** * Convert a date from Excel to PHP * * @param long $dateValue Excel date/time value * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as * a UST timestamp, or adjusted to UST * @param StringHelper $timezone The timezone for finding the adjustment from UST * @return long PHP serialized date/time */ public static function ExcelToPHP($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) { if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) { $my_excelBaseDate = 25569; // Adjust for the spurious 29-Feb-1900 (Day 60) if ($dateValue < 60) { --$my_excelBaseDate; } } else { $my_excelBaseDate = 24107; } // Perform conversion if ($dateValue >= 1) { $utcDays = $dateValue - $my_excelBaseDate; $returnValue = round($utcDays * 86400); if (($returnValue <= PHP_INT_MAX) && ($returnValue >= -PHP_INT_MAX)) { $returnValue = (integer) $returnValue; } } else { $hours = round($dateValue * 24); $mins = round($dateValue * 1440) - round($hours * 60); $secs = round($dateValue * 86400) - round($hours * 3600) - round($mins * 60); $returnValue = (integer) gmmktime($hours, $mins, $secs); } $timezoneAdjustment = ($adjustToTimezone) ? PHPExcel_Shared_TimeZone::getTimezoneAdjustment($timezone, $returnValue) : 0; // Return return $returnValue + $timezoneAdjustment; } // function ExcelToPHP() /** * Convert a date from Excel to a PHP Date/Time object * * @param integer $dateValue Excel date/time value * @return integer PHP date/time object */ public static function ExcelToPHPObject($dateValue = 0) { $dateTime = self::ExcelToPHP($dateValue); $days = floor($dateTime / 86400); $time = round((($dateTime / 86400) - $days) * 86400); $hours = round($time / 3600); $minutes = round($time / 60) - ($hours * 60); $seconds = round($time) - ($hours * 3600) - ($minutes * 60); $dateObj = date_create('1-Jan-1970+'.$days.' days'); $dateObj->setTime($hours,$minutes,$seconds); return $dateObj; } // function ExcelToPHPObject() /** * Convert a date from PHP to Excel * * @param mixed $dateValue PHP serialized date/time or date object * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as * a UST timestamp, or adjusted to UST * @param StringHelper $timezone The timezone for finding the adjustment from UST * @return mixed Excel date/time value * or boolean FALSE on failure */ public static function PHPToExcel($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) { $saveTimeZone = date_default_timezone_get(); date_default_timezone_set('UTC'); $retValue = FALSE; if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) { $retValue = self::FormattedPHPToExcel( $dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'), $dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s') ); } elseif (is_numeric($dateValue)) { $retValue = self::FormattedPHPToExcel( date('Y',$dateValue), date('m',$dateValue), date('d',$dateValue), date('H',$dateValue), date('i',$dateValue), date('s',$dateValue) ); } date_default_timezone_set($saveTimeZone); return $retValue; } // function PHPToExcel() /** * FormattedPHPToExcel * * @param long $year * @param long $month * @param long $day * @param long $hours * @param long $minutes * @param long $seconds * @return long Excel date/time value */ public static function FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) { if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) { // // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel // This affects every date following 28th February 1900 // $excel1900isLeapYear = TRUE; if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = FALSE; } $my_excelBaseDate = 2415020; } else { $my_excelBaseDate = 2416481; $excel1900isLeapYear = FALSE; } // Julian base date Adjustment if ($month > 2) { $month -= 3; } else { $month += 9; --$year; } // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) $century = substr($year,0,2); $decade = substr($year,2,2); $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $my_excelBaseDate + $excel1900isLeapYear; $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; return (float) $excelDate + $excelTime; } // function FormattedPHPToExcel() /** * Is a given cell a date/time? * * @param PHPExcel_Cell $pCell * @return boolean */ public static function isDateTime(PHPExcel_Cell $pCell) { return self::isDateTimeFormat( $pCell->getWorksheet()->getStyle( $pCell->getCoordinate() )->getNumberFormat() ); } // function isDateTime() /** * Is a given number format a date/time? * * @param PHPExcel_Style_NumberFormat $pFormat * @return boolean */ public static function isDateTimeFormat(PHPExcel_Style_NumberFormat $pFormat) { return self::isDateTimeFormatCode($pFormat->getFormatCode()); } // function isDateTimeFormat() private static $possibleDateFormatCharacters = 'eymdHs'; /** * Is a given number format code a date/time? * * @param string $pFormatCode * @return boolean */ public static function isDateTimeFormatCode($pFormatCode = '') { // Switch on formatcode switch ($pFormatCode) { // General contains an epoch letter 'e', so we trap for it explicitly here case PHPExcel_Style_NumberFormat::FORMAT_GENERAL: return FALSE; // Explicitly defined date formats case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD: case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS: case PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS: case PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7: case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8: case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17: case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22: return TRUE; } // Typically number, currency or accounting (or occasionally fraction) formats if ((substr($pFormatCode,0,1) == '_') || (substr($pFormatCode,0,2) == '0 ')) { return FALSE; } // Try checking for any of the date formatting characters that don't appear within square braces if (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$pFormatCode)) { // We might also have a format mask containing quoted strings... // we don't want to test for any of our characters within the quoted blocks if (strpos($pFormatCode,'"') !== FALSE) { $segMatcher = FALSE; foreach(explode('"',$pFormatCode) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) if (($segMatcher = !$segMatcher) && (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$subVal))) { return TRUE; } } return FALSE; } return TRUE; } // No date... return FALSE; } // function isDateTimeFormatCode() /** * Convert a date/time string to Excel time * * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10' * @return float|FALSE Excel date/time serial value */ public static function stringToExcel($dateValue = '') { if (strlen($dateValue) < 2) return FALSE; if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue)) return FALSE; $dateValueNew = PHPExcel_Calculation_DateTime::DATEVALUE($dateValue); if ($dateValueNew === PHPExcel_Calculation_Functions::VALUE()) { return FALSE; } else { if (strpos($dateValue, ':') !== FALSE) { $timeValue = PHPExcel_Calculation_DateTime::TIMEVALUE($dateValue); if ($timeValue === PHPExcel_Calculation_Functions::VALUE()) { return FALSE; } $dateValueNew += $timeValue; } return $dateValueNew; } } public static function monthStringToNumber($month) { $monthIndex = 1; foreach(self::$_monthNames as $shortMonthName => $longMonthName) { if (($month === $longMonthName) || ($month === $shortMonthName)) { return $monthIndex; } ++$monthIndex; } return $month; } public static function dayStringToNumber($day) { $strippedDayValue = (str_replace(self::$_numberSuffixes,'',$day)); if (is_numeric($strippedDayValue)) { return $strippedDayValue; } return $day; } }
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.2/groupoffice-6.2-setup-www/go/vendor/PHPExcel/PHPExcel/Shared/Date.php
PHP
gpl-3.0
12,755
// Generated by CoffeeScript 1.5.0 var auth, changeDashboard, createGraph, dashboard, dataPoll, default_graphite_url, default_period, description, generateDataURL, generateEventsURL, generateGraphiteTargets, getTargetColor, graphScaffold, graphite_url, graphs, init, metrics, period, refresh, refreshSummary, refreshTimer, scheme, toggleCss, _avg, _formatBase1024KMGTP, _last, _max, _min, _sum; graphite_url = graphite_url || 'demo'; default_graphite_url = graphite_url; default_period = 1440; if (scheme === void 0) { scheme = 'classic9'; } period = default_period; dashboard = dashboards[0]; metrics = dashboard['metrics']; description = dashboard['description']; refresh = dashboard['refresh']; refreshTimer = null; auth = auth != null ? auth : false; graphs = []; dataPoll = function() { var graph, _i, _len, _results; _results = []; for (_i = 0, _len = graphs.length; _i < _len; _i++) { graph = graphs[_i]; _results.push(graph.refreshGraph(period)); } return _results; }; _sum = function(series) { return _.reduce(series, (function(memo, val) { return memo + val; }), 0); }; _avg = function(series) { return _sum(series) / series.length; }; _max = function(series) { return _.reduce(series, (function(memo, val) { if (memo === null) { return val; } if (val > memo) { return val; } return memo; }), null); }; _min = function(series) { return _.reduce(series, (function(memo, val) { if (memo === null) { return val; } if (val < memo) { return val; } return memo; }), null); }; _last = function(series) { return _.reduce(series, (function(memo, val) { if (val !== null) { return val; } return memo; }), null); }; _formatBase1024KMGTP = function(y, formatter) { var abs_y; if (formatter == null) { formatter = d3.format(".2r"); } abs_y = Math.abs(y); if (abs_y >= 1125899906842624) { return formatter(y / 1125899906842624) + "P"; } else if (abs_y >= 1099511627776) { return formatter(y / 1099511627776) + "T"; } else if (abs_y >= 1073741824) { return formatter(y / 1073741824) + "G"; } else if (abs_y >= 1048576) { return formatter(y / 1048576) + "M"; } else if (abs_y >= 1024) { return formatter(y / 1024) + "K"; } else if (abs_y < 1 && y > 0) { return formatter(y); } else if (abs_y === 0) { return 0; } else { return formatter(y); } }; refreshSummary = function(graph) { var summary_func, y_data, _ref; if (!((_ref = graph.args) != null ? _ref.summary : void 0)) { return; } if (graph.args.summary === "sum") { summary_func = _sum; } if (graph.args.summary === "avg") { summary_func = _avg; } if (graph.args.summary === "min") { summary_func = _min; } if (graph.args.summary === "max") { summary_func = _max; } if (graph.args.summary === "last") { summary_func = _last; } if (typeof graph.args.summary === "function") { summary_func = graph.args.summary; } if (!summary_func) { console.log("unknown summary function " + graph.args.summary); } y_data = _.map(_.flatten(_.pluck(graph.graph.series, 'data')), function(d) { return d.y; }); return $("" + graph.args.anchor + " .graph-summary").html(graph.args.summary_formatter(summary_func(y_data))); }; graphScaffold = function() { var colspan, context, converter, graph_template, i, metric, offset, _i, _len; graph_template = "{{#dashboard_description}}\n <div class=\"well\">{{{dashboard_description}}}</div>\n{{/dashboard_description}}\n{{#metrics}}\n {{#start_row}}\n <div class=\"row-fluid\">\n {{/start_row}}\n <div class=\"{{span}}\" id=\"graph-{{graph_id}}\">\n <h2>{{metric_alias}} <span class=\"pull-right graph-summary\"><span></h2>\n <div class=\"chart\"></div>\n <div class=\"timeline\"></div>\n <p>{{metric_description}}</p>\n <div class=\"legend\"></div>\n </div>\n {{#end_row}}\n </div>\n {{/end_row}}\n{{/metrics}}"; $('#graphs').empty(); context = { metrics: [] }; converter = new Markdown.Converter(); if (description) { context['dashboard_description'] = converter.makeHtml(description); } offset = 0; for (i = _i = 0, _len = metrics.length; _i < _len; i = ++_i) { metric = metrics[i]; colspan = metric.colspan != null ? metric.colspan : 1; context['metrics'].push({ start_row: offset % 3 === 0, end_row: offset % 3 === 2, graph_id: i, span: 'span' + (4 * colspan), metric_alias: metric.alias, metric_description: metric.description }); offset += colspan; } return $('#graphs').append(Mustache.render(graph_template, context)); }; init = function() { var dash, i, metric, refreshInterval, _i, _j, _len, _len1; $('.dropdown-menu').empty(); for (_i = 0, _len = dashboards.length; _i < _len; _i++) { dash = dashboards[_i]; $('.dropdown-menu').append("<li><a href=\"#\">" + dash.name + "</a></li>"); } graphScaffold(); graphs = []; for (i = _j = 0, _len1 = metrics.length; _j < _len1; i = ++_j) { metric = metrics[i]; graphs.push(createGraph("#graph-" + i, metric)); } $('.page-header h1').empty().append(dashboard.name); refreshInterval = refresh || 10000; if (refreshTimer) { clearInterval(refreshTimer); } return refreshTimer = setInterval(dataPoll, refreshInterval); }; getTargetColor = function(targets, target) { var t, _i, _len; if (typeof targets !== 'object') { return; } for (_i = 0, _len = targets.length; _i < _len; _i++) { t = targets[_i]; if (!t.color) { continue; } if (t.target === target || t.alias === target) { return t.color; } } }; generateGraphiteTargets = function(targets) { var graphite_targets, target, _i, _len; if (typeof targets === "string") { return "&target=" + targets; } if (typeof targets === "function") { return "&target=" + (targets()); } graphite_targets = ""; for (_i = 0, _len = targets.length; _i < _len; _i++) { target = targets[_i]; if (typeof target === "string") { graphite_targets += "&target=" + target; } if (typeof target === "function") { graphite_targets += "&target=" + (target()); } if (typeof target === "object") { graphite_targets += "&target=" + ((target != null ? target.target : void 0) || ''); } } return graphite_targets; }; generateDataURL = function(targets, annotator_target, max_data_points) { var data_targets; annotator_target = annotator_target ? "&target=" + annotator_target : ""; data_targets = generateGraphiteTargets(targets); return "" + graphite_url + "/render?from=-" + period + "minutes&" + data_targets + annotator_target + "&maxDataPoints=" + max_data_points + "&format=json&jsonp=?"; }; generateEventsURL = function(event_tags) { var jsonp, tags; tags = event_tags === '*' ? '' : "&tags=" + event_tags; jsonp = window.json_fallback ? '' : "&jsonp=?"; return "" + graphite_url + "/events/get_data?from=-" + period + "minutes" + tags + jsonp; }; createGraph = function(anchor, metric) { var graph, graph_provider, _ref, _ref1; if (graphite_url === 'demo') { graph_provider = Rickshaw.Graph.Demo; } else { graph_provider = Rickshaw.Graph.JSONP.Graphite; } return graph = new graph_provider({ anchor: anchor, targets: metric.target || metric.targets, summary: metric.summary, summary_formatter: metric.summary_formatter || _formatBase1024KMGTP, scheme: metric.scheme || dashboard.scheme || scheme || 'classic9', annotator_target: ((_ref = metric.annotator) != null ? _ref.target : void 0) || metric.annotator, annotator_description: ((_ref1 = metric.annotator) != null ? _ref1.description : void 0) || 'deployment', events: metric.events, element: $("" + anchor + " .chart")[0], width: $("" + anchor + " .chart").width(), height: metric.height || 300, min: metric.min || 0, max: metric.max, null_as: metric.null_as === void 0 ? null : metric.null_as, renderer: metric.renderer || 'area', interpolation: metric.interpolation || 'step-before', unstack: metric.unstack, stroke: metric.stroke === false ? false : true, strokeWidth: metric.stroke_width, dataURL: generateDataURL(metric.target || metric.targets), onRefresh: function(transport) { return refreshSummary(transport); }, onComplete: function(transport) { var detail, hover_formatter, shelving, xAxis, yAxis; graph = transport.graph; xAxis = new Rickshaw.Graph.Axis.Time({ graph: graph }); xAxis.render(); yAxis = new Rickshaw.Graph.Axis.Y({ graph: graph, tickFormat: function(y) { return _formatBase1024KMGTP(y); }, ticksTreatment: 'glow' }); yAxis.render(); hover_formatter = metric.hover_formatter || _formatBase1024KMGTP; detail = new Rickshaw.Graph.HoverDetail({ graph: graph, yFormatter: function(y) { return hover_formatter(y); } }); $("" + anchor + " .legend").empty(); this.legend = new Rickshaw.Graph.Legend({ graph: graph, element: $("" + anchor + " .legend")[0] }); shelving = new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: this.legend }); if (metric.annotator || metric.events) { this.annotator = new GiraffeAnnotate({ graph: graph, element: $("" + anchor + " .timeline")[0] }); } return refreshSummary(this); } }); }; Rickshaw.Graph.JSONP.Graphite = Rickshaw.Class.create(Rickshaw.Graph.JSONP, { request: function() { return this.refreshGraph(period); }, refreshGraph: function(period) { var deferred, _this = this; deferred = this.getAjaxData(period); return deferred.done(function(result) { var annotations, el, i, result_data, series, _i, _len; if (result.length <= 0) { return; } result_data = _.filter(result, function(el) { var _ref; return el.target !== ((_ref = _this.args.annotator_target) != null ? _ref.replace(/["']/g, '') : void 0); }); result_data = _this.preProcess(result_data); if (!_this.graph) { _this.success(_this.parseGraphiteData(result_data, _this.args.null_as)); } series = _this.parseGraphiteData(result_data, _this.args.null_as); if (_this.args.annotator_target) { annotations = _this.parseGraphiteData(_.filter(result, function(el) { return el.target === _this.args.annotator_target.replace(/["']/g, ''); }), _this.args.null_as); } for (i = _i = 0, _len = series.length; _i < _len; i = ++_i) { el = series[i]; _this.graph.series[i].data = el.data; _this.addTotals(i); } _this.graph.renderer.unstack = _this.args.unstack; _this.graph.render(); if (_this.args.events) { deferred = _this.getEvents(period); deferred.done(function(result) { return _this.addEventAnnotations(result); }); } _this.addAnnotations(annotations, _this.args.annotator_description); return _this.args.onRefresh(_this); }); }, addTotals: function(i) { var avg, label, max, min, series_data, sum; label = $(this.legend.lines[i].element).find('span.label').text(); $(this.legend.lines[i].element).find('span.totals').remove(); series_data = _.map(this.legend.lines[i].series.data, function(d) { return d.y; }); sum = _formatBase1024KMGTP(_sum(series_data)); max = _formatBase1024KMGTP(_max(series_data)); min = _formatBase1024KMGTP(_min(series_data)); avg = _formatBase1024KMGTP(_avg(series_data)); return $(this.legend.lines[i].element).append("<span class='totals pull-right'> &Sigma;: " + sum + " <i class='icon-caret-down'></i>: " + min + " <i class='icon-caret-up'></i>: " + max + " <i class='icon-sort'></i>: " + avg + "</span>"); }, preProcess: function(result) { var item, _i, _len; for (_i = 0, _len = result.length; _i < _len; _i++) { item = result[_i]; if (item.datapoints.length === 1) { item.datapoints[0][1] = 0; if (this.args.unstack) { item.datapoints.push([0, 1]); } else { item.datapoints.push([item.datapoints[0][0], 1]); } } } return result; }, parseGraphiteData: function(d, null_as) { var palette, rev_xy, targets; if (null_as == null) { null_as = null; } rev_xy = function(datapoints) { return _.map(datapoints, function(point) { return { 'x': point[1], 'y': point[0] !== null ? point[0] : null_as }; }); }; palette = new Rickshaw.Color.Palette({ scheme: this.args.scheme }); targets = this.args.target || this.args.targets; d = _.map(d, function(el) { var color, _ref; if ((_ref = typeof targets) === "string" || _ref === "function") { color = palette.color(); } else { color = getTargetColor(targets, el.target) || palette.color(); } return { "color": color, "name": el.target, "data": rev_xy(el.datapoints) }; }); Rickshaw.Series.zeroFill(d); return d; }, addEventAnnotations: function(events_json) { var active_annotation, event, _i, _len, _ref, _ref1; if (!events_json) { return; } this.annotator || (this.annotator = new GiraffeAnnotate({ graph: this.graph, element: $("" + this.args.anchor + " .timeline")[0] })); this.annotator.data = {}; $(this.annotator.elements.timeline).empty(); active_annotation = $(this.annotator.elements.timeline).parent().find('.annotation_line.active').size() > 0; if ((_ref = $(this.annotator.elements.timeline).parent()) != null) { _ref.find('.annotation_line').remove(); } for (_i = 0, _len = events_json.length; _i < _len; _i++) { event = events_json[_i]; this.annotator.add(event.when, "" + event.what + " " + (event.data || '')); } this.annotator.update(); if (active_annotation) { return (_ref1 = $(this.annotator.elements.timeline).parent()) != null ? _ref1.find('.annotation_line').addClass('active') : void 0; } }, addAnnotations: function(annotations, description) { var annotation_timestamps, _ref; if (!annotations) { return; } annotation_timestamps = _((_ref = annotations[0]) != null ? _ref.data : void 0).filter(function(el) { return el.y !== 0 && el.y !== null; }); return this.addEventAnnotations(_.map(annotation_timestamps, function(a) { return { when: a.x, what: description }; })); }, getEvents: function(period) { var deferred, _this = this; this.period = period; return deferred = $.ajax({ dataType: 'json', url: generateEventsURL(this.args.events), error: function(xhr, textStatus, errorThrown) { if (textStatus === 'parsererror' && /was not called/.test(errorThrown.message)) { window.json_fallback = true; return _this.refreshGraph(period); } else { return console.log("error loading eventsURL: " + generateEventsURL(_this.args.events)); } } }); }, getAjaxData: function(period) { var deferred; this.period = period; return deferred = $.ajax({ dataType: 'json', url: generateDataURL(this.args.targets, this.args.annotator_target, this.args.width), error: this.error.bind(this) }); } }); Rickshaw.Graph.Demo = Rickshaw.Class.create(Rickshaw.Graph.JSONP.Graphite, { success: function(data) { var i, palette, _i; palette = new Rickshaw.Color.Palette({ scheme: this.args.scheme }); this.seriesData = [[], [], [], [], [], [], [], [], []]; this.random = new Rickshaw.Fixtures.RandomData(period / 60 + 10); for (i = _i = 0; _i <= 60; i = ++_i) { this.random.addData(this.seriesData); } this.graph = new Rickshaw.Graph({ element: this.args.element, width: this.args.width, height: this.args.height, min: this.args.min, max: this.args.max, renderer: this.args.renderer, interpolation: this.args.interpolation, stroke: this.args.stroke, strokeWidth: this.args.strokeWidth, series: [ { color: palette.color(), data: this.seriesData[0], name: 'Moscow' }, { color: palette.color(), data: this.seriesData[1], name: 'Shanghai' }, { color: palette.color(), data: this.seriesData[2], name: 'Amsterdam' }, { color: palette.color(), data: this.seriesData[3], name: 'Paris' }, { color: palette.color(), data: this.seriesData[4], name: 'Tokyo' }, { color: palette.color(), data: this.seriesData[5], name: 'London' }, { color: palette.color(), data: this.seriesData[6], name: 'New York' } ] }); this.graph.renderer.unstack = this.args.unstack; this.graph.render(); return this.onComplete(this); }, refreshGraph: function(period) { var i, _i, _ref, _results; if (!this.graph) { return this.success(); } else { this.random.addData(this.seriesData); this.random.addData(this.seriesData); _.each(this.seriesData, function(d) { return d.shift(); }); this.args.onRefresh(this); this.graph.render(); _results = []; for (i = _i = 0, _ref = this.graph.series.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(this.addTotals(i)); } return _results; } } }); /* # Events and interaction */ $('.dropdown-menu').on('click', 'a', function() { changeDashboard($(this).text()); $('.dropdown').removeClass('open'); return false; }); changeDashboard = function(dash_name) { dashboard = _.where(dashboards, { name: dash_name })[0] || dashboards[0]; graphite_url = dashboard['graphite_url'] || default_graphite_url; description = dashboard['description']; metrics = dashboard['metrics']; refresh = dashboard['refresh']; period || (period = default_period); init(); return $.bbq.pushState({ dashboard: dashboard.name }); }; $('.timepanel').on('click', 'a.range', function() { var dash, timeFrame, _ref; if (graphite_url === 'demo') { changeDashboard(dashboard.name); } period = $(this).attr('data-timeframe') || default_period; dataPoll(); timeFrame = $(this).attr('href').replace(/^#/, ''); dash = (_ref = $.bbq.getState()) != null ? _ref.dashboard : void 0; $.bbq.pushState({ timeFrame: timeFrame, dashboard: dash || dashboard.name }); $(this).parent('.btn-group').find('a').removeClass('active'); $(this).addClass('active'); return false; }); toggleCss = function(css_selector) { if ($.rule(css_selector).text().match('display: ?none')) { return $.rule(css_selector, 'style').remove(); } else { return $.rule("" + css_selector + " {display:none;}").appendTo('style'); } }; $('#legend-toggle').on('click', function() { $(this).toggleClass('active'); $('.legend').toggle(); return false; }); $('#axis-toggle').on('click', function() { $(this).toggleClass('active'); toggleCss('.y_grid'); toggleCss('.y_ticks'); toggleCss('.x_tick'); return false; }); $('#x-label-toggle').on('click', function() { toggleCss('.rickshaw_graph .detail .x_label'); $(this).toggleClass('active'); return false; }); $('#x-item-toggle').on('click', function() { toggleCss('.rickshaw_graph .detail .item.active'); $(this).toggleClass('active'); return false; }); $(window).bind('hashchange', function(e) { var dash, timeFrame, _ref, _ref1; timeFrame = ((_ref = e.getState()) != null ? _ref.timeFrame : void 0) || $(".timepanel a.range[data-timeframe='" + default_period + "']")[0].text || "1d"; dash = (_ref1 = e.getState()) != null ? _ref1.dashboard : void 0; if (dash !== dashboard.name) { changeDashboard(dash); } return $('.timepanel a.range[href="#' + timeFrame + '"]').click(); }); $(function() { $(window).trigger('hashchange'); return init(); });
Stub-O-Matic-BA/stubo-app
stubo/static/giraffe/js/giraffe.js
JavaScript
gpl-3.0
20,491
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #include "plServerReplyMsg.h" #include "hsStream.h" #include "hsBitVector.h" void plServerReplyMsg::Read(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgRead(stream, mgr); stream->ReadLE(&fType); } void plServerReplyMsg::Write(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgWrite(stream, mgr); stream->WriteLE(fType); } enum ServerReplyFlags { kServerReplyType, }; void plServerReplyMsg::ReadVersion(hsStream* s, hsResMgr* mgr) { plMessage::IMsgReadVersion(s, mgr); hsBitVector contentFlags; contentFlags.Read(s); if (contentFlags.IsBitSet(kServerReplyType)) s->ReadLE(&fType); } void plServerReplyMsg::WriteVersion(hsStream* s, hsResMgr* mgr) { plMessage::IMsgWriteVersion(s, mgr); hsBitVector contentFlags; contentFlags.SetBit(kServerReplyType); contentFlags.Write(s); // kServerReplyType s->WriteLE(fType); }
cwalther/Plasma-nobink-test
Sources/Plasma/NucleusLib/pnMessage/plServerReplyMsg.cpp
C++
gpl-3.0
2,654
package org.whispersystems.signalservice.api.storage; import org.whispersystems.libsignal.util.guava.Preconditions; import org.whispersystems.signalservice.internal.storage.protos.ManifestRecord; import java.util.Arrays; import java.util.Objects; public class StorageId { private final int type; private final byte[] raw; public static StorageId forContact(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.CONTACT_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forGroupV1(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.GROUPV1_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forGroupV2(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.GROUPV2_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forAccount(byte[] raw) { return new StorageId(ManifestRecord.Identifier.Type.ACCOUNT_VALUE, Preconditions.checkNotNull(raw)); } public static StorageId forType(byte[] raw, int type) { return new StorageId(type, raw); } public boolean isUnknown() { return !isKnownType(type); } private StorageId(int type, byte[] raw) { this.type = type; this.raw = raw; } public int getType() { return type; } public byte[] getRaw() { return raw; } public StorageId withNewBytes(byte[] key) { return new StorageId(type, key); } public static boolean isKnownType(int val) { for (ManifestRecord.Identifier.Type type : ManifestRecord.Identifier.Type.values()) { if (type != ManifestRecord.Identifier.Type.UNRECOGNIZED && type.getNumber() == val) { return true; } } return false; } public static int largestKnownType() { int max = 0; for (ManifestRecord.Identifier.Type type : ManifestRecord.Identifier.Type.values()) { if (type != ManifestRecord.Identifier.Type.UNRECOGNIZED) { max = Math.max(type.getNumber(), max); } } return max; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StorageId storageId = (StorageId) o; return type == storageId.type && Arrays.equals(raw, storageId.raw); } @Override public int hashCode() { int result = Objects.hash(type); result = 31 * result + Arrays.hashCode(raw); return result; } }
Turasa/libsignal-service-java
service/src/main/java/org/whispersystems/signalservice/api/storage/StorageId.java
Java
gpl-3.0
2,421
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2020 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package kernel import ( "fmt" "path/filepath" "strings" "github.com/snapcore/snapd/osutil" ) func validateAssetsContent(kernelRoot string, info *Info) error { // bare structure content is checked to exist during layout // make sure that filesystem content source paths exist as well for name, as := range info.Assets { for _, assetContent := range as.Content { c := assetContent // a single trailing / is allowed and indicates a directory isDir := strings.HasSuffix(c, "/") if isDir { c = strings.TrimSuffix(c, "/") } if filepath.Clean(c) != c || strings.Contains(c, "..") || c == "/" { return fmt.Errorf("asset %q: invalid content %q", name, assetContent) } realSource := filepath.Join(kernelRoot, c) if !osutil.FileExists(realSource) { return fmt.Errorf("asset %q: content %q source path does not exist", name, assetContent) } if isDir { // expecting a directory if !osutil.IsDirectory(realSource + "/") { return fmt.Errorf("asset %q: content %q is not a directory", name, assetContent) } } } } return nil } // Validate checks whether the given directory contains valid kernel snap // metadata and a matching content. func Validate(kernelRoot string) error { info, err := ReadInfo(kernelRoot) if err != nil { return fmt.Errorf("invalid kernel metadata: %v", err) } if err := validateAssetsContent(kernelRoot, info); err != nil { return err } return nil }
mvo5/snappy
kernel/validate.go
GO
gpl-3.0
2,124
<?php /* * @copyright 2015 Mautic Contributors. All rights reserved * @author Mautic * * @link http://mautic.org * * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ $isPrototype = ($form->vars['name'] == '__name__'); $filterType = $form['field']->vars['value']; $inGroup = $form->vars['data']['glue'] === 'and'; $object = (isset($form->vars['data']['object'])) ? $form->vars['data']['object'] : 'lead'; $class = (isset($form->vars['data']['object']) && $form->vars['data']['object'] == 'company') ? 'fa-building' : 'fa-user'; ?> <div class="panel<?php echo ($inGroup && $first === false) ? ' in-group' : ''; ?>"> <div class="panel-heading <?php if (!$isPrototype && $form->vars['name'] === '0') { echo ' hide'; } ?>"> <div class="panel-glue col-sm-2 pl-0 "> <?php echo $view['form']->widget($form['glue']); ?> </div> </div> <div class="panel-body"> <div class="col-xs-6 col-sm-3 field-name"> <i class="object-icon fa <?php echo $class; ?>" aria-hidden="true"></i> <span><?php echo ($isPrototype) ? '__label__' : $fields[$object][$filterType]['label']; ?></span> </div> <div class="col-xs-6 col-sm-3 padding-none"> <?php echo $view['form']->widget($form['operator']); ?> </div> <?php $hasErrors = count($form['filter']->vars['errors']) || count($form['display']->vars['errors']); ?> <div class="col-xs-10 col-sm-5 padding-none<?php if ($hasErrors) { echo ' has-error'; } ?>"> <?php echo $view['form']->widget($form['filter']); ?> <?php echo $view['form']->errors($form['filter']); ?> <?php echo $view['form']->widget($form['display']); ?> <?php echo $view['form']->errors($form['display']); ?> </div> <div class="col-xs-2 col-sm-1"> <a href="javascript: void(0);" class="remove-selected btn btn-default text-danger pull-right"><i class="fa fa-trash-o"></i></a> </div> <?php echo $view['form']->widget($form['field']); ?> <?php echo $view['form']->widget($form['type']); ?> <?php echo $view['form']->widget($form['object']); ?> </div> </div>
PatchRanger/mautic
app/bundles/LeadBundle/Views/FormTheme/Filter/_leadlist_filters_entry_widget.html.php
PHP
gpl-3.0
2,233
package org.limewire.collection; import java.util.Iterator; /** * A convenience class to aid in developing iterators that cannot be modified. */ public abstract class UnmodifiableIterator<E> implements Iterator<E> { /** Throws UnsupportedOperationException */ public final void remove() { throw new UnsupportedOperationException(); } }
alejandroarturom/frostwire-desktop
src/org/limewire/collection/UnmodifiableIterator.java
Java
gpl-3.0
355
//===-- XCoreISelDAGToDAG.cpp - A dag to dag inst selector for XCore ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the XCore target. // //===----------------------------------------------------------------------===// #include "XCore.h" #include "XCoreTargetMachine.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetLowering.h" using namespace llvm; /// XCoreDAGToDAGISel - XCore specific code to select XCore machine /// instructions for SelectionDAG operations. /// namespace { class XCoreDAGToDAGISel : public SelectionDAGISel { public: XCoreDAGToDAGISel(XCoreTargetMachine &TM, CodeGenOpt::Level OptLevel) : SelectionDAGISel(TM, OptLevel) {} SDNode *Select(SDNode *N) override; SDNode *SelectBRIND(SDNode *N); /// getI32Imm - Return a target constant with the specified value, of type /// i32. inline SDValue getI32Imm(unsigned Imm, SDLoc dl) { return CurDAG->getTargetConstant(Imm, dl, MVT::i32); } inline bool immMskBitp(SDNode *inN) const { ConstantSDNode *N = cast<ConstantSDNode>(inN); uint32_t value = (uint32_t)N->getZExtValue(); if (!isMask_32(value)) { return false; } int msksize = 32 - countLeadingZeros(value); return (msksize >= 1 && msksize <= 8) || msksize == 16 || msksize == 24 || msksize == 32; } // Complex Pattern Selectors. bool SelectADDRspii(SDValue Addr, SDValue &Base, SDValue &Offset); bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) override; const char *getPassName() const override { return "XCore DAG->DAG Pattern Instruction Selection"; } // Include the pieces autogenerated from the target description. #include "XCoreGenDAGISel.inc" }; } // end anonymous namespace /// createXCoreISelDag - This pass converts a legalized DAG into a /// XCore-specific DAG, ready for instruction scheduling. /// FunctionPass *llvm::createXCoreISelDag(XCoreTargetMachine &TM, CodeGenOpt::Level OptLevel) { return new XCoreDAGToDAGISel(TM, OptLevel); } bool XCoreDAGToDAGISel::SelectADDRspii(SDValue Addr, SDValue &Base, SDValue &Offset) { FrameIndexSDNode *FIN = nullptr; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr))) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32); return true; } if (Addr.getOpcode() == ISD::ADD) { ConstantSDNode *CN = nullptr; if ((FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) && (CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) && (CN->getSExtValue() % 4 == 0 && CN->getSExtValue() >= 0)) { // Constant positive word offset from frame index Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(CN->getSExtValue(), SDLoc(Addr), MVT::i32); return true; } } return false; } bool XCoreDAGToDAGISel:: SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) { SDValue Reg; switch (ConstraintID) { default: return true; case InlineAsm::Constraint_m: // Memory. switch (Op.getOpcode()) { default: return true; case XCoreISD::CPRelativeWrapper: Reg = CurDAG->getRegister(XCore::CP, MVT::i32); break; case XCoreISD::DPRelativeWrapper: Reg = CurDAG->getRegister(XCore::DP, MVT::i32); break; } } OutOps.push_back(Reg); OutOps.push_back(Op.getOperand(0)); return false; } SDNode *XCoreDAGToDAGISel::Select(SDNode *N) { SDLoc dl(N); switch (N->getOpcode()) { default: break; case ISD::Constant: { uint64_t Val = cast<ConstantSDNode>(N)->getZExtValue(); if (immMskBitp(N)) { // Transformation function: get the size of a mask // Look for the first non-zero bit SDValue MskSize = getI32Imm(32 - countLeadingZeros((uint32_t)Val), dl); return CurDAG->getMachineNode(XCore::MKMSK_rus, dl, MVT::i32, MskSize); } else if (!isUInt<16>(Val)) { SDValue CPIdx = CurDAG->getTargetConstantPool( ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val), getTargetLowering()->getPointerTy(CurDAG->getDataLayout())); SDNode *node = CurDAG->getMachineNode(XCore::LDWCP_lru6, dl, MVT::i32, MVT::Other, CPIdx, CurDAG->getEntryNode()); MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1); MemOp[0] = MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), MachineMemOperand::MOLoad, 4, 4); cast<MachineSDNode>(node)->setMemRefs(MemOp, MemOp + 1); return node; } break; } case XCoreISD::LADD: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) }; return CurDAG->getMachineNode(XCore::LADD_l5r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::LSUB: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) }; return CurDAG->getMachineNode(XCore::LSUB_l5r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::MACCU: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3) }; return CurDAG->getMachineNode(XCore::MACCU_l4r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::MACCS: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3) }; return CurDAG->getMachineNode(XCore::MACCS_l4r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::LMUL: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3) }; return CurDAG->getMachineNode(XCore::LMUL_l6r, dl, MVT::i32, MVT::i32, Ops); } case XCoreISD::CRC8: { SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) }; return CurDAG->getMachineNode(XCore::CRC8_l4r, dl, MVT::i32, MVT::i32, Ops); } case ISD::BRIND: if (SDNode *ResNode = SelectBRIND(N)) return ResNode; break; // Other cases are autogenerated. } return SelectCode(N); } /// Given a chain return a new chain where any appearance of Old is replaced /// by New. There must be at most one instruction between Old and Chain and /// this instruction must be a TokenFactor. Returns an empty SDValue if /// these conditions don't hold. static SDValue replaceInChain(SelectionDAG *CurDAG, SDValue Chain, SDValue Old, SDValue New) { if (Chain == Old) return New; if (Chain->getOpcode() != ISD::TokenFactor) return SDValue(); SmallVector<SDValue, 8> Ops; bool found = false; for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) { if (Chain->getOperand(i) == Old) { Ops.push_back(New); found = true; } else { Ops.push_back(Chain->getOperand(i)); } } if (!found) return SDValue(); return CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, Ops); } SDNode *XCoreDAGToDAGISel::SelectBRIND(SDNode *N) { SDLoc dl(N); // (brind (int_xcore_checkevent (addr))) SDValue Chain = N->getOperand(0); SDValue Addr = N->getOperand(1); if (Addr->getOpcode() != ISD::INTRINSIC_W_CHAIN) return nullptr; unsigned IntNo = cast<ConstantSDNode>(Addr->getOperand(1))->getZExtValue(); if (IntNo != Intrinsic::xcore_checkevent) return nullptr; SDValue nextAddr = Addr->getOperand(2); SDValue CheckEventChainOut(Addr.getNode(), 1); if (!CheckEventChainOut.use_empty()) { // If the chain out of the checkevent intrinsic is an operand of the // indirect branch or used in a TokenFactor which is the operand of the // indirect branch then build a new chain which uses the chain coming into // the checkevent intrinsic instead. SDValue CheckEventChainIn = Addr->getOperand(0); SDValue NewChain = replaceInChain(CurDAG, Chain, CheckEventChainOut, CheckEventChainIn); if (!NewChain.getNode()) return nullptr; Chain = NewChain; } // Enable events on the thread using setsr 1 and then disable them immediately // after with clrsr 1. If any resources owned by the thread are ready an event // will be taken. If no resource is ready we branch to the address which was // the operand to the checkevent intrinsic. SDValue constOne = getI32Imm(1, dl); SDValue Glue = SDValue(CurDAG->getMachineNode(XCore::SETSR_branch_u6, dl, MVT::Glue, constOne, Chain), 0); Glue = SDValue(CurDAG->getMachineNode(XCore::CLRSR_branch_u6, dl, MVT::Glue, constOne, Glue), 0); if (nextAddr->getOpcode() == XCoreISD::PCRelativeWrapper && nextAddr->getOperand(0)->getOpcode() == ISD::TargetBlockAddress) { return CurDAG->SelectNodeTo(N, XCore::BRFU_lu6, MVT::Other, nextAddr->getOperand(0), Glue); } return CurDAG->SelectNodeTo(N, XCore::BAU_1r, MVT::Other, nextAddr, Glue); }
vinutah/apps
tools/llvm/llvm_39/opt/lib/Target/XCore/XCoreISelDAGToDAG.cpp
C++
gpl-3.0
10,390
/* Copyright (C) 2010,2011,2012,2013,2014 The ESPResSo project Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010 Max-Planck-Institute for Polymer Research, Theory Group, This file is part of ESPResSo. ESPResSo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ESPResSo 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file lb-boundaries.cpp * * Boundary conditions for Lattice Boltzmann fluid dynamics. * Header file for \ref lb-boundaries.hpp. * */ #include "utils.hpp" #include "constraint.hpp" #include "lb-boundaries.hpp" #include "lbgpu.hpp" #include "lb.hpp" #include "electrokinetics.hpp" #include "electrokinetics_pdb_parse.hpp" #include "interaction_data.hpp" #include "communication.hpp" #if defined (LB_BOUNDARIES) || defined (LB_BOUNDARIES_GPU) int n_lb_boundaries = 0; LB_Boundary *lb_boundaries = NULL; void lbboundary_mindist_position(double pos[3], double* mindist, double distvec[3], int* no) { double vec[3] = {1e100, 1e100, 1e100}; double dist=1e100; *mindist = 1e100; int n; Particle* p1=0; for(n=0;n<n_lb_boundaries;n++) { switch(lb_boundaries[n].type) { case LB_BOUNDARY_WAL: calculate_wall_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.wal, &dist, vec); break; case LB_BOUNDARY_SPH: calculate_sphere_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.sph, &dist, vec); break; case LB_BOUNDARY_CYL: calculate_cylinder_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.cyl, &dist, vec); break; case LB_BOUNDARY_RHOMBOID: calculate_rhomboid_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.rhomboid, &dist, vec); break; case LB_BOUNDARY_POR: calculate_pore_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.pore, &dist, vec); break; case LB_BOUNDARY_STOMATOCYTE: calculate_stomatocyte_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.stomatocyte, &dist, vec); break; case LB_BOUNDARY_HOLLOW_CONE: calculate_hollow_cone_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.hollow_cone, &dist, vec); break; case CONSTRAINT_SPHEROCYLINDER: calculate_spherocylinder_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.spherocyl, &dist, vec); break; case LB_BOUNDARY_VOXEL: // needed for fluid calculation ??? calculate_voxel_dist(p1, pos, (Particle*) NULL, &lb_boundaries[n].c.voxel, &dist, vec); break; } if (dist<*mindist || n == 0) { *no=n; *mindist=dist; distvec[0] = vec[0]; distvec[1] = vec[1]; distvec[2] = vec[2]; } } } /** Initialize boundary conditions for all constraints in the system. */ void lb_init_boundaries() { int n, x, y, z; //char *errtxt; double pos[3], dist, dist_tmp=0.0, dist_vec[3]; if (lattice_switch & LATTICE_LB_GPU) { #if defined (LB_GPU) && defined (LB_BOUNDARIES_GPU) int number_of_boundnodes = 0; int *host_boundary_node_list= (int*)Utils::malloc(sizeof(int)); int *host_boundary_index_list= (int*)Utils::malloc(sizeof(int)); size_t size_of_index; int boundary_number = -1; // the number the boundary will actually belong to. #ifdef EK_BOUNDARIES ekfloat *host_wallcharge_species_density = NULL; float node_wallcharge = 0.0f; int wallcharge_species = -1, charged_boundaries = 0; int node_charged = 0; for(n = 0; n < int(n_lb_boundaries); n++) lb_boundaries[n].net_charge = 0.0; if (ek_initialized) { host_wallcharge_species_density = (ekfloat*) Utils::malloc(ek_parameters.number_of_nodes * sizeof(ekfloat)); for(n = 0; n < int(n_lb_boundaries); n++) { if(lb_boundaries[n].charge_density != 0.0) { charged_boundaries = 1; break; } } if (pdb_charge_lattice) { charged_boundaries = 1; } for(n = 0; n < int(ek_parameters.number_of_species); n++) if(ek_parameters.valency[n] != 0.0) { wallcharge_species = n; break; } if(wallcharge_species == -1 && charged_boundaries) { ostringstream msg; msg <<"no charged species available to create wall charge\n"; runtimeError(msg); } } #endif for(z=0; z<int(lbpar_gpu.dim_z); z++) { for(y=0; y<int(lbpar_gpu.dim_y); y++) { for (x=0; x<int(lbpar_gpu.dim_x); x++) { pos[0] = (x+0.5)*lbpar_gpu.agrid; pos[1] = (y+0.5)*lbpar_gpu.agrid; pos[2] = (z+0.5)*lbpar_gpu.agrid; dist = 1e99; #ifdef EK_BOUNDARIES if (ek_initialized) { host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = 0.0f; node_charged = 0; node_wallcharge = 0.0f; } #endif for (n=0; n < n_lb_boundaries; n++) { switch (lb_boundaries[n].type) { case LB_BOUNDARY_WAL: calculate_wall_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.wal, &dist_tmp, dist_vec); break; case LB_BOUNDARY_SPH: calculate_sphere_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.sph, &dist_tmp, dist_vec); break; case LB_BOUNDARY_CYL: calculate_cylinder_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.cyl, &dist_tmp, dist_vec); break; case LB_BOUNDARY_RHOMBOID: calculate_rhomboid_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.rhomboid, &dist_tmp, dist_vec); break; case LB_BOUNDARY_POR: calculate_pore_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.pore, &dist_tmp, dist_vec); break; case LB_BOUNDARY_STOMATOCYTE: calculate_stomatocyte_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.stomatocyte, &dist_tmp, dist_vec); break; case LB_BOUNDARY_HOLLOW_CONE: calculate_hollow_cone_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.hollow_cone, &dist_tmp, dist_vec); break; case LB_BOUNDARY_SPHEROCYLINDER: calculate_spherocylinder_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.spherocyl, &dist_tmp, dist_vec); break; case LB_BOUNDARY_VOXEL: // voxel data do not need dist //calculate_voxel_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.voxel, &dist_tmp, dist_vec); dist_tmp=1e99; break; default: ostringstream msg; msg <<"lbboundary type "<< lb_boundaries[n].type << " not implemented in lb_init_boundaries()\n"; runtimeError(msg); } if (dist > dist_tmp || n == 0) { dist = dist_tmp; boundary_number = n; } #ifdef EK_BOUNDARIES if (ek_initialized) { if(dist_tmp <= 0 && lb_boundaries[n].charge_density != 0.0f) { node_charged = 1; node_wallcharge += lb_boundaries[n].charge_density * ek_parameters.agrid*ek_parameters.agrid*ek_parameters.agrid; lb_boundaries[n].net_charge += lb_boundaries[n].charge_density * ek_parameters.agrid*ek_parameters.agrid*ek_parameters.agrid; } } #endif } #ifdef EK_BOUNDARIES if(pdb_boundary_lattice && pdb_boundary_lattice[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x]) { dist = -1; boundary_number = n_lb_boundaries; // Makes sure that boundary_number is not used by a constraint } #endif if (dist <= 0 && boundary_number >= 0 && (n_lb_boundaries > 0 || pdb_boundary_lattice)) { size_of_index = (number_of_boundnodes+1)*sizeof(int); host_boundary_node_list = (int *) Utils::realloc(host_boundary_node_list, size_of_index); host_boundary_index_list = (int *) Utils::realloc(host_boundary_index_list, size_of_index); host_boundary_node_list[number_of_boundnodes] = x + lbpar_gpu.dim_x*y + lbpar_gpu.dim_x*lbpar_gpu.dim_y*z; host_boundary_index_list[number_of_boundnodes] = boundary_number + 1; number_of_boundnodes++; //printf("boundindex %i: \n", number_of_boundnodes); } #ifdef EK_BOUNDARIES if (ek_initialized) { ek_parameters.number_of_boundary_nodes = number_of_boundnodes; if(wallcharge_species != -1) { if(pdb_charge_lattice && pdb_charge_lattice[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] != 0.0f) { node_charged = 1; node_wallcharge += pdb_charge_lattice[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x]; } if(node_charged) host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = node_wallcharge / ek_parameters.valency[wallcharge_species]; else if(dist <= 0) host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = 0.0f; else host_wallcharge_species_density[ek_parameters.dim_y*ek_parameters.dim_x*z + ek_parameters.dim_x*y + x] = ek_parameters.density[wallcharge_species] * ek_parameters.agrid*ek_parameters.agrid*ek_parameters.agrid; } } #endif } } } /**call of cuda fkt*/ float* boundary_velocity = (float *) Utils::malloc(3*(n_lb_boundaries+1)*sizeof(float)); for (n=0; n<n_lb_boundaries; n++) { boundary_velocity[3*n+0]=lb_boundaries[n].velocity[0]; boundary_velocity[3*n+1]=lb_boundaries[n].velocity[1]; boundary_velocity[3*n+2]=lb_boundaries[n].velocity[2]; } boundary_velocity[3*n_lb_boundaries+0] = 0.0f; boundary_velocity[3*n_lb_boundaries+1] = 0.0f; boundary_velocity[3*n_lb_boundaries+2] = 0.0f; if (n_lb_boundaries || pdb_boundary_lattice) lb_init_boundaries_GPU(n_lb_boundaries, number_of_boundnodes, host_boundary_node_list, host_boundary_index_list, boundary_velocity); free(boundary_velocity); free(host_boundary_node_list); free(host_boundary_index_list); #ifdef EK_BOUNDARIES if (ek_initialized) { ek_init_species_density_wallcharge(host_wallcharge_species_density, wallcharge_species); free(host_wallcharge_species_density); } #endif #endif /* defined (LB_GPU) && defined (LB_BOUNDARIES_GPU) */ } else { #if defined (LB) && defined (LB_BOUNDARIES) int node_domain_position[3], offset[3]; int the_boundary=-1; map_node_array(this_node, node_domain_position); offset[0] = node_domain_position[0]*lblattice.grid[0]; offset[1] = node_domain_position[1]*lblattice.grid[1]; offset[2] = node_domain_position[2]*lblattice.grid[2]; for (n=0;n<lblattice.halo_grid_volume;n++) { lbfields[n].boundary = 0; } if (lblattice.halo_grid_volume==0) return; for (z=0; z<lblattice.grid[2]+2; z++) { for (y=0; y<lblattice.grid[1]+2; y++) { for (x=0; x<lblattice.grid[0]+2; x++) { pos[0] = (offset[0]+(x-0.5))*lblattice.agrid[0]; pos[1] = (offset[1]+(y-0.5))*lblattice.agrid[1]; pos[2] = (offset[2]+(z-0.5))*lblattice.agrid[2]; dist = 1e99; for (n=0;n<n_lb_boundaries;n++) { switch (lb_boundaries[n].type) { case LB_BOUNDARY_WAL: calculate_wall_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.wal, &dist_tmp, dist_vec); break; case LB_BOUNDARY_SPH: calculate_sphere_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.sph, &dist_tmp, dist_vec); break; case LB_BOUNDARY_CYL: calculate_cylinder_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.cyl, &dist_tmp, dist_vec); break; case LB_BOUNDARY_RHOMBOID: calculate_rhomboid_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.rhomboid, &dist_tmp, dist_vec); break; case LB_BOUNDARY_POR: calculate_pore_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.pore, &dist_tmp, dist_vec); break; case LB_BOUNDARY_STOMATOCYTE: calculate_stomatocyte_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.stomatocyte, &dist_tmp, dist_vec); break; case LB_BOUNDARY_HOLLOW_CONE: calculate_hollow_cone_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.hollow_cone, &dist_tmp, dist_vec); break; case LB_BOUNDARY_VOXEL: // voxel data do not need dist dist_tmp=1e99; //calculate_voxel_dist((Particle*) NULL, pos, (Particle*) NULL, &lb_boundaries[n].c.voxel, &dist_tmp, dist_vec); break; default: ostringstream msg; msg <<"lbboundary type " << lb_boundaries[n].type << " not implemented in lb_init_boundaries()\n"; runtimeError(msg); } if (dist_tmp<dist || n == 0) { dist = dist_tmp; the_boundary = n; } } if (dist <= 0 && the_boundary >= 0 && n_lb_boundaries > 0) { lbfields[get_linear_index(x,y,z,lblattice.halo_grid)].boundary = the_boundary+1; //printf("boundindex %i: \n", get_linear_index(x,y,z,lblattice.halo_grid)); } else { lbfields[get_linear_index(x,y,z,lblattice.halo_grid)].boundary = 0; } } } } //printf("init voxels\n\n"); // SET VOXEL BOUNDARIES DIRECTLY int xxx,yyy,zzz=0; char line[80]; for (n=0;n<n_lb_boundaries;n++) { switch (lb_boundaries[n].type) { case LB_BOUNDARY_VOXEL: //lbfields[get_linear_index(lb_boundaries[n].c.voxel.pos[0],lb_boundaries[n].c.voxel.pos[1],lb_boundaries[n].c.voxel.pos[2],lblattice.halo_grid)].boundary = n+1; FILE *fp; //fp=fopen("/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/NSvsLBM/geometry_files/bottleneck_fine_voxel_data_d20_converted_noMirror.csv", "r"); //fp=fopen("/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/NSvsLBM/geometry_files/bottleneck_fine_voxel_data_d80_converted_noMirror.csv", "r"); //fp=fopen("/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/NSvsLBM/geometry_files/bottleneck_fine_voxel_data_d80_converted.csv", "r"); fp=fopen(lb_boundaries[n].c.voxel.filename, "r"); while(fgets(line, 80, fp) != NULL) { /* get a line, up to 80 chars from fp, done if NULL */ sscanf (line, "%d %d %d", &xxx,&yyy,&zzz); //printf("%d %d %d\n", xxx,yyy,zzz); //lbfields[get_linear_index(xxx,yyy+30,zzz,lblattice.halo_grid)].boundary = n+1; lbfields[get_linear_index(xxx,yyy,zzz,lblattice.halo_grid)].boundary = n+1; } fclose(fp); break; default: break; } } // CHECK FOR BOUNDARY NEIGHBOURS AND SET FLUID NORMAL VECTOR //int neighbours = {0,0,0,0,0,0}; //int x=0,y=0,z=0; //double nn[]={0.0,0.0,0.0,0.0,0.0,0.0}; //for (n=0;n<n_lb_boundaries;n++) { //switch (lb_boundaries[n].type) { //case LB_BOUNDARY_VOXEL: //x=lb_boundaries[n].c.voxel.pos[0]; //y=lb_boundaries[n].c.voxel.pos[1]; //z=lb_boundaries[n].c.voxel.pos[2]; //if(((x-1) >= 0) && (lbfields[get_linear_index(x-1,y,z,lblattice.halo_grid)].boundary == 0)) nn[0] = -1.0;//neighbours[0] = -1; //if(((x+1) <= lblattice.grid[0]) && (lbfields[get_linear_index(x+1,y,z,lblattice.halo_grid)].boundary == 0)) nn[1] = 1.0;//neighbours[1] = 1; ////printf("%.0lf %.0lf ",nn[0],nn[1]); //lb_boundaries[n].c.voxel.n[0] = nn[0]+nn[1]; ////nn=0.0; //if(((y-1) >= 0) && (lbfields[get_linear_index(x,y-1,z,lblattice.halo_grid)].boundary == 0)) nn[2] = -1.0;//neighbours[2] = -1; //if(((y+1) <= lblattice.grid[1]) && (lbfields[get_linear_index(x,y+1,z,lblattice.halo_grid)].boundary == 0)) nn[3] = 1.0;//neighbours[3] = 1; ////printf("%.0lf %.0lf ",nn[2],nn[3]); //lb_boundaries[n].c.voxel.n[1] = nn[2]+nn[3]; ////nn=0.0; //if(((z-1) >= 0) && (lbfields[get_linear_index(x,y,z-1,lblattice.halo_grid)].boundary == 0)) nn[4] = -1.0;//neighbours[4] = -1; //if(((z+1) <= lblattice.grid[2]) && (lbfields[get_linear_index(x,y,z+1,lblattice.halo_grid)].boundary == 0)) nn[5] = 1.0;//neighbours[5]= 1; ////printf("%.0lf %.0lf ",nn[4],nn[5]); //lb_boundaries[n].c.voxel.n[2] = nn[4]+nn[5]; //nn[0]=0.0,nn[1]=0.0,nn[2]=0.0,nn[3]=0.0,nn[4]=0.0,nn[5]=0.0; ////printf("t %d pos: %.0lf %.0lf %.0lf, fluid normal %.0lf %.0lf %.0lf\n",n, x,y,z,lb_boundaries[n].c.voxel.normal[0],lb_boundaries[n].c.voxel.normal[1],lb_boundaries[n].c.voxel.normal[2]); ////printf("boundaries: %d %d %d %d %d %d\n",lbfields[get_linear_index(x-1,y,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x+1,y,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y-1,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y+1,z,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y,z-1,lblattice.halo_grid)].boundary,lbfields[get_linear_index(x,y,z+1,lblattice.halo_grid)].boundary); //break; //default: //break; //} //} //// DO THE SAME FOR THE CONSTRAINTS: CONSTRAINTS MUST BE SET AND THE SAME AS LB_BOUNDARY !!! //for(n=0;n<n_constraints;n++) { //switch(constraints[n].type) { //case CONSTRAINT_VOXEL: //x=constraints[n].c.voxel.pos[0]; //y=constraints[n].c.voxel.pos[1]; //z=constraints[n].c.voxel.pos[2]; //if(((x-1) >= 0) && (lbfields[get_linear_index(x-1,y,z,lblattice.halo_grid)].boundary == 0)) nn[0] = -1.0;//neighbours[0] = -1; //if(((x+1) <= lblattice.grid[0]) && (lbfields[get_linear_index(x+1,y,z,lblattice.halo_grid)].boundary == 0)) nn[1] = 1.0;//neighbours[1] = 1; ////printf("%.0lf %.0lf ",nn[0],nn[1]); //constraints[n].c.voxel.n[0] = nn[0]+nn[1]; ////nn=0.0; //if(((y-1) >= 0) && (lbfields[get_linear_index(x,y-1,z,lblattice.halo_grid)].boundary == 0)) nn[2] = -1.0;//neighbours[2] = -1; //if(((y+1) <= lblattice.grid[1]) && (lbfields[get_linear_index(x,y+1,z,lblattice.halo_grid)].boundary == 0)) nn[3] = 1.0;//neighbours[3] = 1; ////printf("%.0lf %.0lf ",nn[2],nn[3]); //constraints[n].c.voxel.n[1] = nn[2]+nn[3]; ////nn=0.0; //if(((z-1) >= 0) && (lbfields[get_linear_index(x,y,z-1,lblattice.halo_grid)].boundary == 0)) nn[4] = -1.0;//neighbours[4] = -1; //if(((z+1) <= lblattice.grid[2]) && (lbfields[get_linear_index(x,y,z+1,lblattice.halo_grid)].boundary == 0)) nn[5] = 1.0;//neighbours[5]= 1; ////printf("%.0lf %.0lf ",nn[4],nn[5]); //constraints[n].c.voxel.n[2] = nn[4]+nn[5]; //nn[0]=0.0,nn[1]=0.0,nn[2]=0.0,nn[3]=0.0,nn[4]=0.0,nn[5]=0.0; //break; //default: //break; //} //} //#ifdef VOXEL_BOUNDARIES /* for (z=0; z<lblattice.grid[2]+2; z++) { for (y=0; y<lblattice.grid[1]+2; y++) { for (x=0; x<lblattice.grid[0]+2; x++) { lbfields[get_linear_index(x,y,z,lblattice.halo_grid)].boundary = 1; } } } static const char filename[] = "/home/mgusenbauer/Daten/Copy/DUK/GentlePump/Optimierer/voxels/stl/data_final.csv"; FILE *file = fopen ( filename, "r" ); int coords[3]; printf("start new\n"); if ( file != NULL ){ char line [ 128 ]; // or other suitable maximum line size while ( fgets ( line, sizeof line, file ) != NULL ) {// read a line //fputs ( line, stdout ); // write the line //coords = line.Split(' ').Select(n => Convert.ToInt32(n)).ToArray(); //printf("readline: %s\n",line); int i; sscanf(line, "%d %d %d", &coords[0],&coords[1],&coords[2]); //printf("%d %d %d\n", coords[0],coords[1],coords[2]); lbfields[get_linear_index(coords[0]+5,coords[1]+5,coords[2]+5,lblattice.halo_grid)].boundary = 0; } fclose ( file ); } printf("end new\n"); */ #endif } } int lbboundary_get_force(int no, double* f) { #if defined (LB_BOUNDARIES) || defined (LB_BOUNDARIES_GPU) double* forces = (double *) Utils::malloc(3*n_lb_boundaries*sizeof(double)); if (lattice_switch & LATTICE_LB_GPU) { #if defined (LB_BOUNDARIES_GPU) && defined (LB_GPU) lb_gpu_get_boundary_forces(forces); f[0]=-forces[3*no+0]; f[1]=-forces[3*no+1]; f[2]=-forces[3*no+2]; #else return ES_ERROR; #endif } else { #if defined (LB_BOUNDARIES) && defined (LB) mpi_gather_stats(8, forces, NULL, NULL, NULL); f[0]=forces[3*no+0]*lbpar.agrid/lbpar.tau/lbpar.tau; f[1]=forces[3*no+1]*lbpar.agrid/lbpar.tau/lbpar.tau; f[2]=forces[3*no+2]*lbpar.agrid/lbpar.tau/lbpar.tau; #else return ES_ERROR; #endif } free(forces); #endif return 0; } #endif /* LB_BOUNDARIES or LB_BOUNDARIES_GPU */ #ifdef LB_BOUNDARIES void lb_bounce_back() { #ifdef D3Q19 #ifndef PULL int k,i,l; int yperiod = lblattice.halo_grid[0]; int zperiod = lblattice.halo_grid[0]*lblattice.halo_grid[1]; int next[19]; int x,y,z; double population_shift; double modes[19]; next[0] = 0; // ( 0, 0, 0) = next[1] = 1; // ( 1, 0, 0) + next[2] = - 1; // (-1, 0, 0) next[3] = yperiod; // ( 0, 1, 0) + next[4] = - yperiod; // ( 0,-1, 0) next[5] = zperiod; // ( 0, 0, 1) + next[6] = - zperiod; // ( 0, 0,-1) next[7] = (1+yperiod); // ( 1, 1, 0) + next[8] = - (1+yperiod); // (-1,-1, 0) next[9] = (1-yperiod); // ( 1,-1, 0) next[10] = - (1-yperiod); // (-1, 1, 0) + next[11] = (1+zperiod); // ( 1, 0, 1) + next[12] = - (1+zperiod); // (-1, 0,-1) next[13] = (1-zperiod); // ( 1, 0,-1) next[14] = - (1-zperiod); // (-1, 0, 1) + next[15] = (yperiod+zperiod); // ( 0, 1, 1) + next[16] = - (yperiod+zperiod); // ( 0,-1,-1) next[17] = (yperiod-zperiod); // ( 0, 1,-1) next[18] = - (yperiod-zperiod); // ( 0,-1, 1) + int reverse[] = { 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15, 18, 17 }; /* bottom-up sweep */ // for (k=lblattice.halo_offset;k<lblattice.halo_grid_volume;k++) { for (z=0; z<lblattice.grid[2]+2; z++) { for (y=0; y<lblattice.grid[1]+2; y++) { for (x=0; x<lblattice.grid[0]+2; x++) { k= get_linear_index(x,y,z,lblattice.halo_grid); if (lbfields[k].boundary) { lb_calc_modes(k, modes); for (i=0; i<19; i++) { population_shift=0; for (l=0; l<3; l++) { population_shift-=lbpar.agrid*lbpar.agrid*lbpar.agrid*lbpar.agrid*lbpar.agrid*lbpar.rho[0]*2*lbmodel.c[i][l]*lbmodel.w[i]*lb_boundaries[lbfields[k].boundary-1].velocity[l]/lbmodel.c_sound_sq; } if ( x-lbmodel.c[i][0] > 0 && x -lbmodel.c[i][0] < lblattice.grid[0]+1 && y-lbmodel.c[i][1] > 0 && y -lbmodel.c[i][1] < lblattice.grid[1]+1 && z-lbmodel.c[i][2] > 0 && z -lbmodel.c[i][2] < lblattice.grid[2]+1) { if ( !lbfields[k-next[i]].boundary ) { for (l=0; l<3; l++) { lb_boundaries[lbfields[k].boundary-1].force[l]+=(2*lbfluid[1][i][k]+population_shift)*lbmodel.c[i][l]; } lbfluid[1][reverse[i]][k-next[i]] = lbfluid[1][i][k]+ population_shift; } else { lbfluid[1][reverse[i]][k-next[i]] = lbfluid[1][i][k] = 0.0; } } } } } } } #else #error Bounce back boundary conditions are only implemented for PUSH scheme! #endif #else #error Bounce back boundary conditions are only implemented for D3Q19! #endif } #endif
Smiljanic/Esspresso-Code
src/core/lb-boundaries.cpp
C++
gpl-3.0
25,248
/* -*- c++ -*- */ /* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <atsc_rs_decoder.h> #include <gr_io_signature.h> #include <atsc_consts.h> atsc_rs_decoder_sptr atsc_make_rs_decoder() { return atsc_rs_decoder_sptr(new atsc_rs_decoder()); } atsc_rs_decoder::atsc_rs_decoder() : gr_sync_block("atsc_rs_decoder", gr_make_io_signature(1, 1, sizeof(atsc_mpeg_packet_rs_encoded)), gr_make_io_signature(1, 1, sizeof(atsc_mpeg_packet_no_sync))) { reset(); } int atsc_rs_decoder::work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const atsc_mpeg_packet_rs_encoded *in = (const atsc_mpeg_packet_rs_encoded *) input_items[0]; atsc_mpeg_packet_no_sync *out = (atsc_mpeg_packet_no_sync *) output_items[0]; for (int i = 0; i < noutput_items; i++){ assert(in[i].pli.regular_seg_p()); out[i].pli = in[i].pli; // copy pipeline info... int nerrors_corrrected = d_rs_decoder.decode(out[i], in[i]); out[i].pli.set_transport_error(nerrors_corrrected == -1); } return noutput_items; }
GREO/GNU-Radio
gr-atsc/src/lib/atsc_rs_decoder.cc
C++
gpl-3.0
1,900
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * DML layer tests. * * @package core_dml * @category phpunit * @copyright 2008 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); class core_dml_testcase extends database_driver_testcase { protected function setUp() { parent::setUp(); $dbman = $this->tdb->get_manager(); // Loads DDL libs. } /** * Get a xmldb_table object for testing, deleting any existing table * of the same name, for example if one was left over from a previous test * run that crashed. * * @param string $suffix table name suffix, use if you need more test tables * @return xmldb_table the table object. */ private function get_test_table($suffix = '') { $tablename = "test_table"; if ($suffix !== '') { $tablename .= $suffix; } $table = new xmldb_table($tablename); $table->setComment("This is a test'n drop table. You can drop it safely"); return $table; } public function test_diagnose() { $DB = $this->tdb; $result = $DB->diagnose(); $this->assertNull($result, 'Database self diagnostics failed %s'); } public function test_get_server_info() { $DB = $this->tdb; $result = $DB->get_server_info(); $this->assertInternalType('array', $result); $this->assertArrayHasKey('description', $result); $this->assertArrayHasKey('version', $result); } public function test_get_in_or_equal() { $DB = $this->tdb; // SQL_PARAMS_QM - IN or =. // Correct usage of multiple values. $in_values = array('value1', 'value2', '3', 4, null, false, true); list($usql, $params) = $DB->get_in_or_equal($in_values); $this->assertSame('IN ('.implode(',', array_fill(0, count($in_values), '?')).')', $usql); $this->assertEquals(count($in_values), count($params)); foreach ($params as $key => $value) { $this->assertSame($in_values[$key], $value); } // Correct usage of single value (in an array). $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values); $this->assertEquals("= ?", $usql); $this->assertCount(1, $params); $this->assertEquals($in_values[0], $params[0]); // Correct usage of single value. $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values); $this->assertEquals("= ?", $usql); $this->assertCount(1, $params); $this->assertEquals($in_value, $params[0]); // SQL_PARAMS_QM - NOT IN or <>. // Correct usage of multiple values. $in_values = array('value1', 'value2', 'value3', 'value4'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false); $this->assertEquals("NOT IN (?,?,?,?)", $usql); $this->assertCount(4, $params); foreach ($params as $key => $value) { $this->assertEquals($in_values[$key], $value); } // Correct usage of single value (in array(). $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false); $this->assertEquals("<> ?", $usql); $this->assertCount(1, $params); $this->assertEquals($in_values[0], $params[0]); // Correct usage of single value. $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false); $this->assertEquals("<> ?", $usql); $this->assertCount(1, $params); $this->assertEquals($in_value, $params[0]); // SQL_PARAMS_NAMED - IN or =. // Correct usage of multiple values. $in_values = array('value1', 'value2', 'value3', 'value4'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true); $this->assertCount(4, $params); reset($in_values); $ps = array(); foreach ($params as $key => $value) { $this->assertEquals(current($in_values), $value); next($in_values); $ps[] = ':'.$key; } $this->assertEquals("IN (".implode(',', $ps).")", $usql); // Correct usage of single values (in array). $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true); $this->assertCount(1, $params); $value = reset($params); $key = key($params); $this->assertEquals("= :$key", $usql); $this->assertEquals($in_value, $value); // Correct usage of single value. $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true); $this->assertCount(1, $params); $value = reset($params); $key = key($params); $this->assertEquals("= :$key", $usql); $this->assertEquals($in_value, $value); // SQL_PARAMS_NAMED - NOT IN or <>. // Correct usage of multiple values. $in_values = array('value1', 'value2', 'value3', 'value4'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->assertCount(4, $params); reset($in_values); $ps = array(); foreach ($params as $key => $value) { $this->assertEquals(current($in_values), $value); next($in_values); $ps[] = ':'.$key; } $this->assertEquals("NOT IN (".implode(',', $ps).")", $usql); // Correct usage of single values (in array). $in_values = array('value1'); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->assertCount(1, $params); $value = reset($params); $key = key($params); $this->assertEquals("<> :$key", $usql); $this->assertEquals($in_value, $value); // Correct usage of single value. $in_value = 'value1'; list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->assertCount(1, $params); $value = reset($params); $key = key($params); $this->assertEquals("<> :$key", $usql); $this->assertEquals($in_value, $value); // Make sure the param names are unique. list($usql1, $params1) = $DB->get_in_or_equal(array(1, 2, 3), SQL_PARAMS_NAMED, 'param'); list($usql2, $params2) = $DB->get_in_or_equal(array(1, 2, 3), SQL_PARAMS_NAMED, 'param'); $params1 = array_keys($params1); $params2 = array_keys($params2); $common = array_intersect($params1, $params2); $this->assertCount(0, $common); // Some incorrect tests. // Incorrect usage passing not-allowed params type. $in_values = array(1, 2, 3); try { list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_DOLLAR, 'param', false); $this->fail('An Exception is missing, expected due to not supported SQL_PARAMS_DOLLAR'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('typenotimplement', $e->errorcode); } // Incorrect usage passing empty array. $in_values = array(); try { list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false); $this->fail('An Exception is missing, expected due to empty array of items'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Test using $onemptyitems. // Correct usage passing empty array and $onemptyitems = null (equal = true, QM). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, null); $this->assertSame(' IS NULL', $usql); $this->assertSame(array(), $params); // Correct usage passing empty array and $onemptyitems = null (equal = false, NAMED). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, null); $this->assertSame(' IS NOT NULL', $usql); $this->assertSame(array(), $params); // Correct usage passing empty array and $onemptyitems = true (equal = true, QM). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, true); $this->assertSame('= ?', $usql); $this->assertSame(array(true), $params); // Correct usage passing empty array and $onemptyitems = true (equal = false, NAMED). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, true); $this->assertCount(1, $params); $value = reset($params); $key = key($params); $this->assertSame('<> :'.$key, $usql); $this->assertSame($value, true); // Correct usage passing empty array and $onemptyitems = -1 (equal = true, QM). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, -1); $this->assertSame('= ?', $usql); $this->assertSame(array(-1), $params); // Correct usage passing empty array and $onemptyitems = -1 (equal = false, NAMED). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, -1); $this->assertCount(1, $params); $value = reset($params); $key = key($params); $this->assertSame('<> :'.$key, $usql); $this->assertSame($value, -1); // Correct usage passing empty array and $onemptyitems = 'onevalue' (equal = true, QM). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, 'onevalue'); $this->assertSame('= ?', $usql); $this->assertSame(array('onevalue'), $params); // Correct usage passing empty array and $onemptyitems = 'onevalue' (equal = false, NAMED). $in_values = array(); list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, 'onevalue'); $this->assertCount(1, $params); $value = reset($params); $key = key($params); $this->assertSame('<> :'.$key, $usql); $this->assertSame($value, 'onevalue'); } public function test_fix_table_names() { $DB = new moodle_database_for_testing(); $prefix = $DB->get_prefix(); // Simple placeholder. $placeholder = "{user_123}"; $this->assertSame($prefix."user_123", $DB->public_fix_table_names($placeholder)); // Wrong table name. $placeholder = "{user-a}"; $this->assertSame($placeholder, $DB->public_fix_table_names($placeholder)); // Wrong table name. $placeholder = "{123user}"; $this->assertSame($placeholder, $DB->public_fix_table_names($placeholder)); // Full SQL. $sql = "SELECT * FROM {user}, {funny_table_name}, {mdl_stupid_table} WHERE {user}.id = {funny_table_name}.userid"; $expected = "SELECT * FROM {$prefix}user, {$prefix}funny_table_name, {$prefix}mdl_stupid_table WHERE {$prefix}user.id = {$prefix}funny_table_name.userid"; $this->assertSame($expected, $DB->public_fix_table_names($sql)); } public function test_fix_sql_params() { $DB = $this->tdb; $prefix = $DB->get_prefix(); $table = $this->get_test_table(); $tablename = $table->getName(); // Correct table placeholder substitution. $sql = "SELECT * FROM {{$tablename}}"; $sqlarray = $DB->fix_sql_params($sql); $this->assertEquals("SELECT * FROM {$prefix}".$tablename, $sqlarray[0]); // Conversions of all param types. $sql = array(); $sql[SQL_PARAMS_NAMED] = "SELECT * FROM {$prefix}testtable WHERE name = :param1, course = :param2"; $sql[SQL_PARAMS_QM] = "SELECT * FROM {$prefix}testtable WHERE name = ?, course = ?"; $sql[SQL_PARAMS_DOLLAR] = "SELECT * FROM {$prefix}testtable WHERE name = \$1, course = \$2"; $params = array(); $params[SQL_PARAMS_NAMED] = array('param1'=>'first record', 'param2'=>1); $params[SQL_PARAMS_QM] = array('first record', 1); $params[SQL_PARAMS_DOLLAR] = array('first record', 1); list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_NAMED], $params[SQL_PARAMS_NAMED]); $this->assertSame($rsql, $sql[$rtype]); $this->assertSame($rparams, $params[$rtype]); list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_QM], $params[SQL_PARAMS_QM]); $this->assertSame($rsql, $sql[$rtype]); $this->assertSame($rparams, $params[$rtype]); list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_DOLLAR], $params[SQL_PARAMS_DOLLAR]); $this->assertSame($rsql, $sql[$rtype]); $this->assertSame($rparams, $params[$rtype]); // Malformed table placeholder. $sql = "SELECT * FROM [testtable]"; $sqlarray = $DB->fix_sql_params($sql); $this->assertSame($sql, $sqlarray[0]); // Mixed param types (colon and dollar). $sql = "SELECT * FROM {{$tablename}} WHERE name = :param1, course = \$1"; $params = array('param1' => 'record1', 'param2' => 3); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Mixed param types (question and dollar). $sql = "SELECT * FROM {{$tablename}} WHERE name = ?, course = \$1"; $params = array('param1' => 'record2', 'param2' => 5); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Too few params in sql. $sql = "SELECT * FROM {{$tablename}} WHERE name = ?, course = ?, id = ?"; $params = array('record2', 3); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Too many params in array: no error, just use what is necessary. $params[] = 1; $params[] = time(); $sqlarray = $DB->fix_sql_params($sql, $params); $this->assertInternalType('array', $sqlarray); $this->assertCount(3, $sqlarray[1]); // Named params missing from array. $sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :course"; $params = array('wrongname' => 'record1', 'course' => 1); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Duplicate named param in query - this is a very important feature!! // it helps with debugging of sloppy code. $sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :name"; $params = array('name' => 'record2', 'course' => 3); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Extra named param is ignored. $sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :course"; $params = array('name' => 'record1', 'course' => 1, 'extrastuff'=>'haha'); $sqlarray = $DB->fix_sql_params($sql, $params); $this->assertInternalType('array', $sqlarray); $this->assertCount(2, $sqlarray[1]); // Params exceeding 30 chars length. $sql = "SELECT * FROM {{$tablename}} WHERE name = :long_placeholder_with_more_than_30"; $params = array('long_placeholder_with_more_than_30' => 'record1'); try { $DB->fix_sql_params($sql, $params); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Booleans in NAMED params are casting to 1/0 int. $sql = "SELECT * FROM {{$tablename}} WHERE course = ? OR course = ?"; $params = array(true, false); list($sql, $params) = $DB->fix_sql_params($sql, $params); $this->assertTrue(reset($params) === 1); $this->assertTrue(next($params) === 0); // Booleans in QM params are casting to 1/0 int. $sql = "SELECT * FROM {{$tablename}} WHERE course = :course1 OR course = :course2"; $params = array('course1' => true, 'course2' => false); list($sql, $params) = $DB->fix_sql_params($sql, $params); $this->assertTrue(reset($params) === 1); $this->assertTrue(next($params) === 0); // Booleans in DOLLAR params are casting to 1/0 int. $sql = "SELECT * FROM {{$tablename}} WHERE course = \$1 OR course = \$2"; $params = array(true, false); list($sql, $params) = $DB->fix_sql_params($sql, $params); $this->assertTrue(reset($params) === 1); $this->assertTrue(next($params) === 0); // No data types are touched except bool. $sql = "SELECT * FROM {{$tablename}} WHERE name IN (?,?,?,?,?,?)"; $inparams = array('abc', 'ABC', null, '1', 1, 1.4); list($sql, $params) = $DB->fix_sql_params($sql, $inparams); $this->assertSame(array_values($params), array_values($inparams)); } public function test_strtok() { // Strtok was previously used by bound emulation, make sure it is not used any more. $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, 'lala'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $str = 'a?b?c?d'; $this->assertSame(strtok($str, '?'), 'a'); $DB->get_records($tablename, array('id'=>1)); $this->assertSame(strtok('?'), 'b'); } public function test_tweak_param_names() { // Note the tweak_param_names() method is only available in the oracle driver, // hence we look for expected results indirectly, by testing various DML methods. // with some "extreme" conditions causing the tweak to happen. $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); // Add some columns with 28 chars in the name. $table->add_field('long_int_columnname_with_28c', XMLDB_TYPE_INTEGER, '10'); $table->add_field('long_dec_columnname_with_28c', XMLDB_TYPE_NUMBER, '10,2'); $table->add_field('long_str_columnname_with_28c', XMLDB_TYPE_CHAR, '100'); // Add some columns with 30 chars in the name. $table->add_field('long_int_columnname_with_30cxx', XMLDB_TYPE_INTEGER, '10'); $table->add_field('long_dec_columnname_with_30cxx', XMLDB_TYPE_NUMBER, '10,2'); $table->add_field('long_str_columnname_with_30cxx', XMLDB_TYPE_CHAR, '100'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertTrue($dbman->table_exists($tablename)); // Test insert record. $rec1 = new stdClass(); $rec1->long_int_columnname_with_28c = 28; $rec1->long_dec_columnname_with_28c = 28.28; $rec1->long_str_columnname_with_28c = '28'; $rec1->long_int_columnname_with_30cxx = 30; $rec1->long_dec_columnname_with_30cxx = 30.30; $rec1->long_str_columnname_with_30cxx = '30'; // Insert_record(). $rec1->id = $DB->insert_record($tablename, $rec1); $this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id))); // Update_record(). $DB->update_record($tablename, $rec1); $this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id))); // Set_field(). $rec1->long_int_columnname_with_28c = 280; $DB->set_field($tablename, 'long_int_columnname_with_28c', $rec1->long_int_columnname_with_28c, array('id' => $rec1->id, 'long_int_columnname_with_28c' => 28)); $rec1->long_dec_columnname_with_28c = 280.28; $DB->set_field($tablename, 'long_dec_columnname_with_28c', $rec1->long_dec_columnname_with_28c, array('id' => $rec1->id, 'long_dec_columnname_with_28c' => 28.28)); $rec1->long_str_columnname_with_28c = '280'; $DB->set_field($tablename, 'long_str_columnname_with_28c', $rec1->long_str_columnname_with_28c, array('id' => $rec1->id, 'long_str_columnname_with_28c' => '28')); $rec1->long_int_columnname_with_30cxx = 300; $DB->set_field($tablename, 'long_int_columnname_with_30cxx', $rec1->long_int_columnname_with_30cxx, array('id' => $rec1->id, 'long_int_columnname_with_30cxx' => 30)); $rec1->long_dec_columnname_with_30cxx = 300.30; $DB->set_field($tablename, 'long_dec_columnname_with_30cxx', $rec1->long_dec_columnname_with_30cxx, array('id' => $rec1->id, 'long_dec_columnname_with_30cxx' => 30.30)); $rec1->long_str_columnname_with_30cxx = '300'; $DB->set_field($tablename, 'long_str_columnname_with_30cxx', $rec1->long_str_columnname_with_30cxx, array('id' => $rec1->id, 'long_str_columnname_with_30cxx' => '30')); $this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id))); // Delete_records(). $rec2 = $DB->get_record($tablename, array('id' => $rec1->id)); $rec2->id = $DB->insert_record($tablename, $rec2); $this->assertEquals(2, $DB->count_records($tablename)); $DB->delete_records($tablename, (array) $rec2); $this->assertEquals(1, $DB->count_records($tablename)); // Get_recordset(). $rs = $DB->get_recordset($tablename, (array) $rec1); $iterations = 0; foreach ($rs as $rec2) { $iterations++; } $rs->close(); $this->assertEquals(1, $iterations); $this->assertEquals($rec1, $rec2); // Get_records(). $recs = $DB->get_records($tablename, (array) $rec1); $this->assertCount(1, $recs); $this->assertEquals($rec1, reset($recs)); // Get_fieldset_select(). $select = 'id = :id AND long_int_columnname_with_28c = :long_int_columnname_with_28c AND long_dec_columnname_with_28c = :long_dec_columnname_with_28c AND long_str_columnname_with_28c = :long_str_columnname_with_28c AND long_int_columnname_with_30cxx = :long_int_columnname_with_30cxx AND long_dec_columnname_with_30cxx = :long_dec_columnname_with_30cxx AND long_str_columnname_with_30cxx = :long_str_columnname_with_30cxx'; $fields = $DB->get_fieldset_select($tablename, 'long_int_columnname_with_28c', $select, (array)$rec1); $this->assertCount(1, $fields); $this->assertEquals($rec1->long_int_columnname_with_28c, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_dec_columnname_with_28c', $select, (array)$rec1); $this->assertEquals($rec1->long_dec_columnname_with_28c, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_str_columnname_with_28c', $select, (array)$rec1); $this->assertEquals($rec1->long_str_columnname_with_28c, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_int_columnname_with_30cxx', $select, (array)$rec1); $this->assertEquals($rec1->long_int_columnname_with_30cxx, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_dec_columnname_with_30cxx', $select, (array)$rec1); $this->assertEquals($rec1->long_dec_columnname_with_30cxx, reset($fields)); $fields = $DB->get_fieldset_select($tablename, 'long_str_columnname_with_30cxx', $select, (array)$rec1); $this->assertEquals($rec1->long_str_columnname_with_30cxx, reset($fields)); // Overlapping placeholders (progressive str_replace). $overlapselect = 'id = :p AND long_int_columnname_with_28c = :param1 AND long_dec_columnname_with_28c = :param2 AND long_str_columnname_with_28c = :param_with_29_characters_long AND long_int_columnname_with_30cxx = :param_with_30_characters_long_ AND long_dec_columnname_with_30cxx = :param_ AND long_str_columnname_with_30cxx = :param__'; $overlapparams = array( 'p' => $rec1->id, 'param1' => $rec1->long_int_columnname_with_28c, 'param2' => $rec1->long_dec_columnname_with_28c, 'param_with_29_characters_long' => $rec1->long_str_columnname_with_28c, 'param_with_30_characters_long_' => $rec1->long_int_columnname_with_30cxx, 'param_' => $rec1->long_dec_columnname_with_30cxx, 'param__' => $rec1->long_str_columnname_with_30cxx); $recs = $DB->get_records_select($tablename, $overlapselect, $overlapparams); $this->assertCount(1, $recs); $this->assertEquals($rec1, reset($recs)); // Execute(). $DB->execute("DELETE FROM {{$tablename}} WHERE $select", (array)$rec1); $this->assertEquals(0, $DB->count_records($tablename)); } public function test_get_tables() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); // Need to test with multiple DBs. $table = $this->get_test_table(); $tablename = $table->getName(); $original_count = count($DB->get_tables()); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertTrue(count($DB->get_tables()) == $original_count + 1); $dbman->drop_table($table); $this->assertTrue(count($DB->get_tables()) == $original_count); } public function test_get_indexes() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_index('course-id', XMLDB_INDEX_UNIQUE, array('course', 'id')); $dbman->create_table($table); $indices = $DB->get_indexes($tablename); $this->assertInternalType('array', $indices); $this->assertCount(2, $indices); // We do not care about index names for now. $first = array_shift($indices); $second = array_shift($indices); if (count($first['columns']) == 2) { $composed = $first; $single = $second; } else { $composed = $second; $single = $first; } $this->assertFalse($single['unique']); $this->assertTrue($composed['unique']); $this->assertCount(1, $single['columns']); $this->assertCount(2, $composed['columns']); $this->assertSame('course', $single['columns'][0]); $this->assertSame('course', $composed['columns'][0]); $this->assertSame('id', $composed['columns'][1]); } public function test_get_columns() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, 'lala'); $table->add_field('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table->add_field('enumfield', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'test2'); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onefloat', XMLDB_TYPE_FLOAT, '10,2', null, null, null, 300); $table->add_field('anotherfloat', XMLDB_TYPE_FLOAT, null, null, null, null, 400); $table->add_field('negativedfltint', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '-1'); $table->add_field('negativedfltnumber', XMLDB_TYPE_NUMBER, '10', null, XMLDB_NOTNULL, null, '-2'); $table->add_field('negativedfltfloat', XMLDB_TYPE_FLOAT, '10', null, XMLDB_NOTNULL, null, '-3'); $table->add_field('someint1', XMLDB_TYPE_INTEGER, '1', null, null, null, '0'); $table->add_field('someint2', XMLDB_TYPE_INTEGER, '2', null, null, null, '0'); $table->add_field('someint3', XMLDB_TYPE_INTEGER, '3', null, null, null, '0'); $table->add_field('someint4', XMLDB_TYPE_INTEGER, '4', null, null, null, '0'); $table->add_field('someint5', XMLDB_TYPE_INTEGER, '5', null, null, null, '0'); $table->add_field('someint6', XMLDB_TYPE_INTEGER, '6', null, null, null, '0'); $table->add_field('someint7', XMLDB_TYPE_INTEGER, '7', null, null, null, '0'); $table->add_field('someint8', XMLDB_TYPE_INTEGER, '8', null, null, null, '0'); $table->add_field('someint9', XMLDB_TYPE_INTEGER, '9', null, null, null, '0'); $table->add_field('someint10', XMLDB_TYPE_INTEGER, '10', null, null, null, '0'); $table->add_field('someint18', XMLDB_TYPE_INTEGER, '18', null, null, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $columns = $DB->get_columns($tablename); $this->assertInternalType('array', $columns); $fields = $table->getFields(); $this->assertCount(count($columns), $fields); $field = $columns['id']; $this->assertSame('R', $field->meta_type); $this->assertTrue($field->auto_increment); $this->assertTrue($field->unique); $field = $columns['course']; $this->assertSame('I', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertTrue($field->has_default); $this->assertEquals(0, $field->default_value); $this->assertTrue($field->not_null); for ($i=1; $i<=10; $i++) { $field = $columns['someint'.$i]; $this->assertSame('I', $field->meta_type); $this->assertGreaterThanOrEqual($i, $field->max_length); } $field = $columns['someint18']; $this->assertSame('I', $field->meta_type); $this->assertGreaterThanOrEqual(18, $field->max_length); $field = $columns['name']; $this->assertSame('C', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertEquals(255, $field->max_length); $this->assertTrue($field->has_default); $this->assertSame('lala', $field->default_value); $this->assertFalse($field->not_null); $field = $columns['description']; $this->assertSame('X', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertFalse($field->has_default); $this->assertNull($field->default_value); $this->assertFalse($field->not_null); $field = $columns['enumfield']; $this->assertSame('C', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertSame('test2', $field->default_value); $this->assertTrue($field->not_null); $field = $columns['onenum']; $this->assertSame('N', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertEquals(10, $field->max_length); $this->assertEquals(2, $field->scale); $this->assertTrue($field->has_default); $this->assertEquals(200.0, $field->default_value); $this->assertFalse($field->not_null); $field = $columns['onefloat']; $this->assertSame('N', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertTrue($field->has_default); $this->assertEquals(300.0, $field->default_value); $this->assertFalse($field->not_null); $field = $columns['anotherfloat']; $this->assertSame('N', $field->meta_type); $this->assertFalse($field->auto_increment); $this->assertTrue($field->has_default); $this->assertEquals(400.0, $field->default_value); $this->assertFalse($field->not_null); // Test negative defaults in numerical columns. $field = $columns['negativedfltint']; $this->assertTrue($field->has_default); $this->assertEquals(-1, $field->default_value); $field = $columns['negativedfltnumber']; $this->assertTrue($field->has_default); $this->assertEquals(-2, $field->default_value); $field = $columns['negativedfltfloat']; $this->assertTrue($field->has_default); $this->assertEquals(-3, $field->default_value); for ($i = 0; $i < count($columns); $i++) { if ($i == 0) { $next_column = reset($columns); $next_field = reset($fields); } else { $next_column = next($columns); $next_field = next($fields); } $this->assertEquals($next_column->name, $next_field->getName()); } // Test get_columns for non-existing table returns empty array. MDL-30147. $columns = $DB->get_columns('xxxx'); $this->assertEquals(array(), $columns); // Create something similar to "context_temp" with id column without sequence. $dbman->drop_table($table); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $columns = $DB->get_columns($tablename); $this->assertFalse($columns['id']->auto_increment); } public function test_get_manager() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $this->assertInstanceOf('database_manager', $dbman); } public function test_setup_is_unicodedb() { $DB = $this->tdb; $this->assertTrue($DB->setup_is_unicodedb()); } public function test_set_debug() { // Tests get_debug() too. $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $sql = "SELECT * FROM {{$tablename}}"; $prevdebug = $DB->get_debug(); ob_start(); $DB->set_debug(true); $this->assertTrue($DB->get_debug()); $DB->execute($sql); $DB->set_debug(false); $this->assertFalse($DB->get_debug()); $debuginfo = ob_get_contents(); ob_end_clean(); $this->assertFalse($debuginfo === ''); ob_start(); $DB->execute($sql); $debuginfo = ob_get_contents(); ob_end_clean(); $this->assertTrue($debuginfo === ''); $DB->set_debug($prevdebug); } public function test_execute() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $table1 = $this->get_test_table('1'); $tablename1 = $table1->getName(); $table1->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table1->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table1->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0'); $table1->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table1->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table1); $table2 = $this->get_test_table('2'); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table2->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename1, array('course' => 3, 'name' => 'aaa')); $DB->insert_record($tablename1, array('course' => 1, 'name' => 'bbb')); $DB->insert_record($tablename1, array('course' => 7, 'name' => 'ccc')); $DB->insert_record($tablename1, array('course' => 3, 'name' => 'ddd')); // Select results are ignored. $sql = "SELECT * FROM {{$tablename1}} WHERE course = :course"; $this->assertTrue($DB->execute($sql, array('course'=>3))); // Throw exception on error. $sql = "XXUPDATE SET XSSD"; try { $DB->execute($sql); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Update records. $sql = "UPDATE {{$tablename1}} SET course = 6 WHERE course = ?"; $this->assertTrue($DB->execute($sql, array('3'))); $this->assertEquals(2, $DB->count_records($tablename1, array('course' => 6))); // Update records with subquery condition. // Confirm that the option not using table aliases is cross-db. $sql = "UPDATE {{$tablename1}} SET course = 0 WHERE NOT EXISTS ( SELECT course FROM {{$tablename2}} tbl2 WHERE tbl2.course = {{$tablename1}}.course AND 1 = 0)"; // Really we don't update anything, but verify the syntax is allowed. $this->assertTrue($DB->execute($sql)); // Insert from one into second table. $sql = "INSERT INTO {{$tablename2}} (course) SELECT course FROM {{$tablename1}}"; $this->assertTrue($DB->execute($sql)); $this->assertEquals(4, $DB->count_records($tablename2)); // Insert a TEXT with raw SQL, binding TEXT params. $course = 9999; $onetext = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $sql = "INSERT INTO {{$tablename2}} (course, onetext) VALUES (:course, :onetext)"; $DB->execute($sql, array('course' => $course, 'onetext' => $onetext)); $records = $DB->get_records($tablename2, array('course' => $course)); $this->assertCount(1, $records); $record = reset($records); $this->assertSame($onetext, $record->onetext); // Update a TEXT with raw SQL, binding TEXT params. $newcourse = 10000; $newonetext = file_get_contents(__DIR__ . '/fixtures/clob.txt') . '- updated'; $sql = "UPDATE {{$tablename2}} SET course = :newcourse, onetext = :newonetext WHERE course = :oldcourse"; $DB->execute($sql, array('oldcourse' => $course, 'newcourse' => $newcourse, 'newonetext' => $newonetext)); $records = $DB->get_records($tablename2, array('course' => $course)); $this->assertCount(0, $records); $records = $DB->get_records($tablename2, array('course' => $newcourse)); $this->assertCount(1, $records); $record = reset($records); $this->assertSame($newonetext, $record->onetext); } public function test_get_recordset() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $data = array(array('course' => 3, 'name' => 'record1', 'onetext'=>'abc'), array('course' => 3, 'name' => 'record2', 'onetext'=>'abcd'), array('course' => 5, 'name' => 'record3', 'onetext'=>'abcde')); foreach ($data as $key => $record) { $data[$key]['id'] = $DB->insert_record($tablename, $record); } // Standard recordset iteration. $rs = $DB->get_recordset($tablename); $this->assertInstanceOf('moodle_recordset', $rs); reset($data); foreach ($rs as $record) { $data_record = current($data); foreach ($record as $k => $v) { $this->assertEquals($data_record[$k], $v); } next($data); } $rs->close(); // Iterator style usage. $rs = $DB->get_recordset($tablename); $this->assertInstanceOf('moodle_recordset', $rs); reset($data); while ($rs->valid()) { $record = $rs->current(); $data_record = current($data); foreach ($record as $k => $v) { $this->assertEquals($data_record[$k], $v); } next($data); $rs->next(); } $rs->close(); // Make sure rewind is ignored. $rs = $DB->get_recordset($tablename); $this->assertInstanceOf('moodle_recordset', $rs); reset($data); $i = 0; foreach ($rs as $record) { $i++; $rs->rewind(); if ($i > 10) { $this->fail('revind not ignored in recordsets'); break; } $data_record = current($data); foreach ($record as $k => $v) { $this->assertEquals($data_record[$k], $v); } next($data); } $rs->close(); // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext' => '1'); try { $rs = $DB->get_recordset($tablename, $conditions); $this->fail('An Exception is missing, expected due to equating of text fields'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } // Test nested iteration. $rs1 = $DB->get_recordset($tablename); $i = 0; foreach ($rs1 as $record1) { $rs2 = $DB->get_recordset($tablename); $i++; $j = 0; foreach ($rs2 as $record2) { $j++; } $rs2->close(); $this->assertCount($j, $data); } $rs1->close(); $this->assertCount($i, $data); // Notes: // * limits are tested in test_get_recordset_sql() // * where_clause() is used internally and is tested in test_get_records() } public function test_get_recordset_static() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $rs = $DB->get_recordset($tablename, array(), 'id'); $DB->set_field($tablename, 'course', 666, array('course'=>1)); $DB->delete_records($tablename, array('course'=>2)); $i = 0; foreach ($rs as $record) { $i++; $this->assertEquals($i, $record->course); } $rs->close(); $this->assertEquals(4, $i); // Now repeat with limits because it may use different code. $DB->delete_records($tablename, array()); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $rs = $DB->get_recordset($tablename, array(), 'id', '*', 0, 3); $DB->set_field($tablename, 'course', 666, array('course'=>1)); $DB->delete_records($tablename, array('course'=>2)); $i = 0; foreach ($rs as $record) { $i++; $this->assertEquals($i, $record->course); } $rs->close(); $this->assertEquals(3, $i); } public function test_get_recordset_iterator_keys() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0'); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $data = array(array('course' => 3, 'name' => 'record1'), array('course' => 3, 'name' => 'record2'), array('course' => 5, 'name' => 'record3')); foreach ($data as $key => $record) { $data[$key]['id'] = $DB->insert_record($tablename, $record); } // Test repeated numeric keys are returned ok. $rs = $DB->get_recordset($tablename, null, null, 'course, name, id'); reset($data); $count = 0; foreach ($rs as $key => $record) { $data_record = current($data); $this->assertEquals($data_record['course'], $key); next($data); $count++; } $rs->close(); $this->assertEquals(3, $count); // Test string keys are returned ok. $rs = $DB->get_recordset($tablename, null, null, 'name, course, id'); reset($data); $count = 0; foreach ($rs as $key => $record) { $data_record = current($data); $this->assertEquals($data_record['name'], $key); next($data); $count++; } $rs->close(); $this->assertEquals(3, $count); // Test numeric not starting in 1 keys are returned ok. $rs = $DB->get_recordset($tablename, null, 'id DESC', 'id, course, name'); $data = array_reverse($data); reset($data); $count = 0; foreach ($rs as $key => $record) { $data_record = current($data); $this->assertEquals($data_record['id'], $key); next($data); $count++; } $rs->close(); $this->assertEquals(3, $count); } public function test_get_recordset_list() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, null, null, '0'); $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course')); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => null)); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 0)); $rs = $DB->get_recordset_list($tablename, 'course', array(3, 2)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(3, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(3)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(2, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(null)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(6, null)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(null, 5, 5, 5)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(2, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(true)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array(false)); $counter = 0; foreach ($rs as $record) { $counter++; } $this->assertEquals(1, $counter); $rs->close(); $rs = $DB->get_recordset_list($tablename, 'course', array()); // Must return 0 rows without conditions. MDL-17645. $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(0, $counter); // Notes: // * limits are tested in test_get_recordset_sql() // * where_clause() is used internally and is tested in test_get_records() } public function test_get_recordset_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $rs = $DB->get_recordset_select($tablename, ''); $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(4, $counter); $this->assertNotEmpty($rs = $DB->get_recordset_select($tablename, 'course = 3')); $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(2, $counter); // Notes: // * limits are tested in test_get_recordset_sql() } public function test_get_recordset_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $inskey1 = $DB->insert_record($tablename, array('course' => 3)); $inskey2 = $DB->insert_record($tablename, array('course' => 5)); $inskey3 = $DB->insert_record($tablename, array('course' => 4)); $inskey4 = $DB->insert_record($tablename, array('course' => 3)); $inskey5 = $DB->insert_record($tablename, array('course' => 2)); $inskey6 = $DB->insert_record($tablename, array('course' => 1)); $inskey7 = $DB->insert_record($tablename, array('course' => 0)); $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3)); $counter = 0; foreach ($rs as $record) { $counter++; } $rs->close(); $this->assertEquals(2, $counter); // Limits - only need to test this case, the rest have been tested by test_get_records_sql() // only limitfrom = skips that number of records. $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 2, 0); $records = array(); foreach ($rs as $key => $record) { $records[$key] = $record; } $rs->close(); $this->assertCount(5, $records); $this->assertEquals($inskey3, reset($records)->id); $this->assertEquals($inskey7, end($records)->id); // Note: fetching nulls, empties, LOBs already tested by test_insert_record() no needed here. } public function test_export_table_recordset() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $ids = array(); $ids[] = $DB->insert_record($tablename, array('course' => 3)); $ids[] = $DB->insert_record($tablename, array('course' => 5)); $ids[] = $DB->insert_record($tablename, array('course' => 4)); $ids[] = $DB->insert_record($tablename, array('course' => 3)); $ids[] = $DB->insert_record($tablename, array('course' => 2)); $ids[] = $DB->insert_record($tablename, array('course' => 1)); $ids[] = $DB->insert_record($tablename, array('course' => 0)); $rs = $DB->export_table_recordset($tablename); $rids = array(); foreach ($rs as $record) { $rids[] = $record->id; } $rs->close(); $this->assertEquals($ids, $rids, '', 0, 0, true); } public function test_get_records() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); // All records. $records = $DB->get_records($tablename); $this->assertCount(4, $records); $this->assertEquals(3, $records[1]->course); $this->assertEquals(3, $records[2]->course); $this->assertEquals(5, $records[3]->course); $this->assertEquals(2, $records[4]->course); // Records matching certain conditions. $records = $DB->get_records($tablename, array('course' => 3)); $this->assertCount(2, $records); $this->assertEquals(3, $records[1]->course); $this->assertEquals(3, $records[2]->course); // All records sorted by course. $records = $DB->get_records($tablename, null, 'course'); $this->assertCount(4, $records); $current_record = reset($records); $this->assertEquals(4, $current_record->id); $current_record = next($records); $this->assertEquals(1, $current_record->id); $current_record = next($records); $this->assertEquals(2, $current_record->id); $current_record = next($records); $this->assertEquals(3, $current_record->id); // All records, but get only one field. $records = $DB->get_records($tablename, null, '', 'id'); $this->assertFalse(isset($records[1]->course)); $this->assertTrue(isset($records[1]->id)); $this->assertCount(4, $records); // Booleans into params. $records = $DB->get_records($tablename, array('course' => true)); $this->assertCount(0, $records); $records = $DB->get_records($tablename, array('course' => false)); $this->assertCount(0, $records); // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext' => '1'); try { $records = $DB->get_records($tablename, $conditions); if (debugging()) { // Only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } // Test get_records passing non-existing table. // with params. try { $records = $DB->get_records('xxxx', array('id' => 0)); $this->fail('An Exception is missing, expected due to query against non-existing table'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); if (debugging()) { // Information for developers only, normal users get general error message. $this->assertSame('ddltablenotexist', $e->errorcode); } } // And without params. try { $records = $DB->get_records('xxxx', array()); $this->fail('An Exception is missing, expected due to query against non-existing table'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); if (debugging()) { // Information for developers only, normal users get general error message. $this->assertSame('ddltablenotexist', $e->errorcode); } } // Test get_records passing non-existing column. try { $records = $DB->get_records($tablename, array('xxxx' => 0)); $this->fail('An Exception is missing, expected due to query against non-existing column'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); if (debugging()) { // Information for developers only, normal users get general error message. $this->assertSame('ddlfieldnotexist', $e->errorcode); } } // Note: delegate limits testing to test_get_records_sql(). } public function test_get_records_list() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $records = $DB->get_records_list($tablename, 'course', array(3, 2)); $this->assertInternalType('array', $records); $this->assertCount(3, $records); $this->assertEquals(1, reset($records)->id); $this->assertEquals(2, next($records)->id); $this->assertEquals(4, next($records)->id); $this->assertSame(array(), $records = $DB->get_records_list($tablename, 'course', array())); // Must return 0 rows without conditions. MDL-17645. $this->assertCount(0, $records); // Note: delegate limits testing to test_get_records_sql(). } public function test_get_records_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $inskey1 = $DB->insert_record($tablename, array('course' => 3)); $inskey2 = $DB->insert_record($tablename, array('course' => 5)); $inskey3 = $DB->insert_record($tablename, array('course' => 4)); $inskey4 = $DB->insert_record($tablename, array('course' => 3)); $inskey5 = $DB->insert_record($tablename, array('course' => 2)); $inskey6 = $DB->insert_record($tablename, array('course' => 1)); $inskey7 = $DB->insert_record($tablename, array('course' => 0)); $table2 = $this->get_test_table("2"); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table2->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename2, array('course'=>3, 'nametext'=>'badabing')); $DB->insert_record($tablename2, array('course'=>4, 'nametext'=>'badabang')); $DB->insert_record($tablename2, array('course'=>5, 'nametext'=>'badabung')); $DB->insert_record($tablename2, array('course'=>6, 'nametext'=>'badabong')); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3)); $this->assertCount(2, $records); $this->assertEquals($inskey1, reset($records)->id); $this->assertEquals($inskey4, next($records)->id); // Awful test, requires debug enabled and sent to browser. Let's do that and restore after test. $records = $DB->get_records_sql("SELECT course AS id, course AS course FROM {{$tablename}}", null); $this->assertDebuggingCalled(); $this->assertCount(6, $records); set_debugging(DEBUG_MINIMAL); $records = $DB->get_records_sql("SELECT course AS id, course AS course FROM {{$tablename}}", null); $this->assertDebuggingNotCalled(); $this->assertCount(6, $records); set_debugging(DEBUG_DEVELOPER); // Negative limits = no limits. $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, -1, -1); $this->assertCount(7, $records); // Zero limits = no limits. $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 0, 0); $this->assertCount(7, $records); // Only limitfrom = skips that number of records. $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 2, 0); $this->assertCount(5, $records); $this->assertEquals($inskey3, reset($records)->id); $this->assertEquals($inskey7, end($records)->id); // Only limitnum = fetches that number of records. $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 0, 3); $this->assertCount(3, $records); $this->assertEquals($inskey1, reset($records)->id); $this->assertEquals($inskey3, end($records)->id); // Both limitfrom and limitnum = skips limitfrom records and fetches limitnum ones. $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 3, 2); $this->assertCount(2, $records); $this->assertEquals($inskey4, reset($records)->id); $this->assertEquals($inskey5, end($records)->id); // Both limitfrom and limitnum in query having subqueris. // Note the subquery skips records with course = 0 and 3. $sql = "SELECT * FROM {{$tablename}} WHERE course NOT IN ( SELECT course FROM {{$tablename}} WHERE course IN (0, 3)) ORDER BY course"; $records = $DB->get_records_sql($sql, null, 0, 2); // Skip 0, get 2. $this->assertCount(2, $records); $this->assertEquals($inskey6, reset($records)->id); $this->assertEquals($inskey5, end($records)->id); $records = $DB->get_records_sql($sql, null, 2, 2); // Skip 2, get 2. $this->assertCount(2, $records); $this->assertEquals($inskey3, reset($records)->id); $this->assertEquals($inskey2, end($records)->id); // Test 2 tables with aliases and limits with order bys. $sql = "SELECT t1.id, t1.course AS cid, t2.nametext FROM {{$tablename}} t1, {{$tablename2}} t2 WHERE t2.course=t1.course ORDER BY t1.course, ". $DB->sql_compare_text('t2.nametext'); $records = $DB->get_records_sql($sql, null, 2, 2); // Skip courses 3 and 6, get 4 and 5. $this->assertCount(2, $records); $this->assertSame('5', end($records)->cid); $this->assertSame('4', reset($records)->cid); // Test 2 tables with aliases and limits with the highest INT limit works. $records = $DB->get_records_sql($sql, null, 2, PHP_INT_MAX); // Skip course {3,6}, get {4,5}. $this->assertCount(2, $records); $this->assertSame('5', end($records)->cid); $this->assertSame('4', reset($records)->cid); // Test 2 tables with aliases and limits with order bys (limit which is highest INT number). $records = $DB->get_records_sql($sql, null, PHP_INT_MAX, 2); // Skip all courses. $this->assertCount(0, $records); // Test 2 tables with aliases and limits with order bys (limit which s highest INT number). $records = $DB->get_records_sql($sql, null, PHP_INT_MAX, PHP_INT_MAX); // Skip all courses. $this->assertCount(0, $records); // TODO: Test limits in queries having DISTINCT clauses. // Note: fetching nulls, empties, LOBs already tested by test_update_record() no needed here. } public function test_get_records_menu() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 2)); $records = $DB->get_records_menu($tablename, array('course' => 3)); $this->assertInternalType('array', $records); $this->assertCount(2, $records); $this->assertNotEmpty($records[1]); $this->assertNotEmpty($records[2]); $this->assertEquals(3, $records[1]); $this->assertEquals(3, $records[2]); // Note: delegate limits testing to test_get_records_sql(). } public function test_get_records_select_menu() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $records = $DB->get_records_select_menu($tablename, "course > ?", array(2)); $this->assertInternalType('array', $records); $this->assertCount(3, $records); $this->assertArrayHasKey(1, $records); $this->assertArrayNotHasKey(2, $records); $this->assertArrayHasKey(3, $records); $this->assertArrayHasKey(4, $records); $this->assertSame('3', $records[1]); $this->assertSame('3', $records[3]); $this->assertSame('5', $records[4]); // Note: delegate limits testing to test_get_records_sql(). } public function test_get_records_sql_menu() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $records = $DB->get_records_sql_menu("SELECT * FROM {{$tablename}} WHERE course > ?", array(2)); $this->assertInternalType('array', $records); $this->assertCount(3, $records); $this->assertArrayHasKey(1, $records); $this->assertArrayNotHasKey(2, $records); $this->assertArrayHasKey(3, $records); $this->assertArrayHasKey(4, $records); $this->assertSame('3', $records[1]); $this->assertSame('3', $records[3]); $this->assertSame('5', $records[4]); // Note: delegate limits testing to test_get_records_sql(). } public function test_get_record() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $record = $DB->get_record($tablename, array('id' => 2)); $this->assertInstanceOf('stdClass', $record); $this->assertEquals(2, $record->course); $this->assertEquals(2, $record->id); } public function test_get_record_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $record = $DB->get_record_select($tablename, "id = ?", array(2)); $this->assertInstanceOf('stdClass', $record); $this->assertEquals(2, $record->course); // Note: delegates limit testing to test_get_records_sql(). } public function test_get_record_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); // Standard use. $record = $DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(2)); $this->assertInstanceOf('stdClass', $record); $this->assertEquals(2, $record->course); $this->assertEquals(2, $record->id); // Backwards compatibility with $ignoremultiple. $this->assertFalse((bool)IGNORE_MISSING); $this->assertTrue((bool)IGNORE_MULTIPLE); // Record not found - ignore. $this->assertFalse($DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), IGNORE_MISSING)); $this->assertFalse($DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), IGNORE_MULTIPLE)); // Record not found error. try { $DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), MUST_EXIST); $this->fail("Exception expected"); } catch (dml_missing_record_exception $e) { $this->assertTrue(true); } $this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MISSING)); $this->assertDebuggingCalled(); set_debugging(DEBUG_MINIMAL); $this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MISSING)); $this->assertDebuggingNotCalled(); set_debugging(DEBUG_DEVELOPER); // Multiple matches ignored. $this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MULTIPLE)); // Multiple found error. try { $DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), MUST_EXIST); $this->fail("Exception expected"); } catch (dml_multiple_records_exception $e) { $this->assertTrue(true); } } public function test_get_field() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $id1 = $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 5)); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('course' => 3))); $this->assertFalse($DB->get_field($tablename, 'course', array('course' => 11), IGNORE_MISSING)); try { $DB->get_field($tablename, 'course', array('course' => 4), MUST_EXIST); $this->fail('Exception expected due to missing record'); } catch (dml_exception $ex) { $this->assertTrue(true); } $this->assertEquals(5, $DB->get_field($tablename, 'course', array('course' => 5), IGNORE_MULTIPLE)); $this->assertDebuggingNotCalled(); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('course' => 5), IGNORE_MISSING)); $this->assertDebuggingCalled(); // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext' => '1'); try { $DB->get_field($tablename, 'course', $conditions); if (debugging()) { // Only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } } public function test_get_field_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $this->assertEquals(3, $DB->get_field_select($tablename, 'course', "id = ?", array(1))); } public function test_get_field_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $this->assertEquals(3, $DB->get_field_sql("SELECT course FROM {{$tablename}} WHERE id = ?", array(1))); } public function test_get_fieldset_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 6)); $fieldset = $DB->get_fieldset_select($tablename, 'course', "course > ?", array(1)); $this->assertInternalType('array', $fieldset); $this->assertCount(3, $fieldset); $this->assertEquals(3, $fieldset[0]); $this->assertEquals(2, $fieldset[1]); $this->assertEquals(6, $fieldset[2]); } public function test_get_fieldset_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 6)); $fieldset = $DB->get_fieldset_sql("SELECT * FROM {{$tablename}} WHERE course > ?", array(1)); $this->assertInternalType('array', $fieldset); $this->assertCount(3, $fieldset); $this->assertEquals(2, $fieldset[0]); $this->assertEquals(3, $fieldset[1]); $this->assertEquals(4, $fieldset[2]); } public function test_insert_record_raw() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $record = (object)array('course' => 1, 'onechar' => 'xx'); $before = clone($record); $result = $DB->insert_record_raw($tablename, $record); $this->assertSame(1, $result); $this->assertEquals($record, $before); $record = $DB->get_record($tablename, array('course' => 1)); $this->assertInstanceOf('stdClass', $record); $this->assertSame('xx', $record->onechar); $result = $DB->insert_record_raw($tablename, array('course' => 2, 'onechar' => 'yy'), false); $this->assertTrue($result); // Note: bulk not implemented yet. $DB->insert_record_raw($tablename, array('course' => 3, 'onechar' => 'zz'), true, true); $record = $DB->get_record($tablename, array('course' => 3)); $this->assertInstanceOf('stdClass', $record); $this->assertSame('zz', $record->onechar); // Custom sequence (id) - returnid is ignored. $result = $DB->insert_record_raw($tablename, array('id' => 10, 'course' => 3, 'onechar' => 'bb'), true, false, true); $this->assertTrue($result); $record = $DB->get_record($tablename, array('id' => 10)); $this->assertInstanceOf('stdClass', $record); $this->assertSame('bb', $record->onechar); // Custom sequence - missing id error. try { $DB->insert_record_raw($tablename, array('course' => 3, 'onechar' => 'bb'), true, false, true); $this->fail('Exception expected due to missing record'); } catch (coding_exception $ex) { $this->assertTrue(true); } // Wrong column error. try { $DB->insert_record_raw($tablename, array('xxxxx' => 3, 'onechar' => 'bb')); $this->fail('Exception expected due to invalid column'); } catch (dml_exception $ex) { $this->assertTrue(true); } // Create something similar to "context_temp" with id column without sequence. $dbman->drop_table($table); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $record = (object)array('id'=>5, 'course' => 1); $DB->insert_record_raw($tablename, $record, false, false, true); $record = $DB->get_record($tablename, array()); $this->assertEquals(5, $record->id); } public function test_insert_record() { // All the information in this test is fetched from DB by get_recordset() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(1, $DB->insert_record($tablename, array('course' => 1), true)); $record = $DB->get_record($tablename, array('course' => 1)); $this->assertEquals(1, $record->id); $this->assertEquals(100, $record->oneint); // Just check column defaults have been applied. $this->assertEquals(200, $record->onenum); $this->assertSame('onestring', $record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Without returning id, bulk not implemented. $result = $this->assertTrue($DB->insert_record($tablename, array('course' => 99), false, true)); $record = $DB->get_record($tablename, array('course' => 99)); $this->assertEquals(2, $record->id); $this->assertEquals(99, $record->course); // Check nulls are set properly for all types. $record = new stdClass(); $record->oneint = null; $record->onenum = null; $record->onechar = null; $record->onetext = null; $record->onebinary = null; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(0, $record->course); $this->assertNull($record->oneint); $this->assertNull($record->onenum); $this->assertNull($record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check zeros are set properly for all types. $record = new stdClass(); $record->oneint = 0; $record->onenum = 0; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); // Check booleans are set properly for all types. $record = new stdClass(); $record->oneint = true; // Trues. $record->onenum = true; $record->onechar = true; $record->onetext = true; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(1, $record->oneint); $this->assertEquals(1, $record->onenum); $this->assertEquals(1, $record->onechar); $this->assertEquals(1, $record->onetext); $record = new stdClass(); $record->oneint = false; // Falses. $record->onenum = false; $record->onechar = false; $record->onetext = false; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); $this->assertEquals(0, $record->onechar); $this->assertEquals(0, $record->onetext); // Check string data causes exception in numeric types. $record = new stdClass(); $record->oneint = 'onestring'; $record->onenum = 0; try { $DB->insert_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } $record = new stdClass(); $record->oneint = 0; $record->onenum = 'onestring'; try { $DB->insert_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Check empty string data is stored as 0 in numeric datatypes. $record = new stdClass(); $record->oneint = ''; // Empty string. $record->onenum = 0; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertTrue(is_numeric($record->oneint) && $record->oneint == 0); $record = new stdClass(); $record->oneint = 0; $record->onenum = ''; // Empty string. $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertTrue(is_numeric($record->onenum) && $record->onenum == 0); // Check empty strings are set properly in string types. $record = new stdClass(); $record->oneint = 0; $record->onenum = 0; $record->onechar = ''; $record->onetext = ''; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertTrue($record->onechar === ''); $this->assertTrue($record->onetext === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types. $record = new stdClass(); $record->oneint = ((210.10 + 39.92) - 150.02); $record->onenum = ((210.10 + 39.92) - 150.02); $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals(100, $record->oneint); $this->assertEquals(100, $record->onenum); // Check various quotes/backslashes combinations in string types. $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $record = new stdClass(); $record->onechar = $teststring; $record->onetext = $teststring; $recid = $DB->insert_record($tablename, $record); $record = $DB->get_record($tablename, array('id' => $recid)); $this->assertEquals($teststring, $record->onechar); $this->assertEquals($teststring, $record->onetext); } // Check LOBs in text/binary columns. $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $record = new stdClass(); $record->onetext = $clob; $record->onebinary = $blob; $recid = $DB->insert_record($tablename, $record); $rs = $DB->get_recordset($tablename, array('id' => $recid)); $record = $rs->current(); $rs->close(); $this->assertEquals($clob, $record->onetext, 'Test CLOB insert (full contents output disabled)'); $this->assertEquals($blob, $record->onebinary, 'Test BLOB insert (full contents output disabled)'); // And "small" LOBs too, just in case. $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $record = new stdClass(); $record->onetext = $newclob; $record->onebinary = $newblob; $recid = $DB->insert_record($tablename, $record); $rs = $DB->get_recordset($tablename, array('id' => $recid)); $record = $rs->current(); $rs->close(); $this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB insert (full contents output disabled)'); $this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB insert (full contents output disabled)'); $this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing. // And "diagnostic" LOBs too, just in case. $newclob = '\'"\\;/ěščřžýáíé'; $newblob = '\'"\\;/ěščřžýáíé'; $record = new stdClass(); $record->onetext = $newclob; $record->onebinary = $newblob; $recid = $DB->insert_record($tablename, $record); $rs = $DB->get_recordset($tablename, array('id' => $recid)); $record = $rs->current(); $rs->close(); $this->assertSame($newclob, $record->onetext); $this->assertSame($newblob, $record->onebinary); $this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing. // Test data is not modified. $record = new stdClass(); $record->id = -1; // Has to be ignored. $record->course = 3; $record->lalala = 'lalal'; // Unused. $before = clone($record); $DB->insert_record($tablename, $record); $this->assertEquals($record, $before); // Make sure the id is always increasing and never reuses the same id. $id1 = $DB->insert_record($tablename, array('course' => 3)); $id2 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($id1 < $id2); $DB->delete_records($tablename, array('id'=>$id2)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($id2 < $id3); $DB->delete_records($tablename, array()); $id4 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($id3 < $id4); // Test saving a float in a CHAR column, and reading it back. $id = $DB->insert_record($tablename, array('onechar' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id))); $id = $DB->insert_record($tablename, array('onechar' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id))); // Test saving a float in a TEXT column, and reading it back. $id = $DB->insert_record($tablename, array('onetext' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id))); $id = $DB->insert_record($tablename, array('onetext' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id))); // Test that inserting data violating one unique key leads to error. // Empty the table completely. $this->assertTrue($DB->delete_records($tablename)); // Add one unique constraint (index). $key = new xmldb_key('testuk', XMLDB_KEY_UNIQUE, array('course', 'oneint')); $dbman->add_key($table, $key); // Let's insert one record violating the constraint multiple times. $record = (object)array('course' => 1, 'oneint' => 1); $this->assertTrue($DB->insert_record($tablename, $record, false)); // Insert 1st. No problem expected. // Re-insert same record, not returning id. dml_exception expected. try { $DB->insert_record($tablename, $record, false); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Re-insert same record, returning id. dml_exception expected. try { $DB->insert_record($tablename, $record, true); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Try to insert a record into a non-existent table. dml_exception expected. try { $DB->insert_record('nonexistenttable', $record, true); $this->fail("Expecting an exception, none occurred"); } catch (exception $e) { $this->assertTrue($e instanceof dml_exception); } } public function test_insert_records() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertCount(0, $DB->get_records($tablename)); $record = new stdClass(); $record->id = '1'; $record->course = '1'; $record->oneint = null; $record->onenum = '1.00'; $record->onechar = 'a'; $record->onetext = 'aaa'; $expected = array(); $records = array(); for ($i = 1; $i <= 2000; $i++) { // This may take a while, it should be higher than defaults in DML drivers. $rec = clone($record); $rec->id = (string)$i; $rec->oneint = (string)$i; $expected[$i] = $rec; $rec = clone($rec); unset($rec->id); $records[$i] = $rec; } $DB->insert_records($tablename, $records); $stored = $DB->get_records($tablename, array(), 'id ASC'); $this->assertEquals($expected, $stored); // Test there can be some extra properties including id. $count = $DB->count_records($tablename); $rec1 = (array)$record; $rec1['xxx'] = 1; $rec2 = (array)$record; $rec2['xxx'] = 2; $records = array($rec1, $rec2); $DB->insert_records($tablename, $records); $this->assertEquals($count + 2, $DB->count_records($tablename)); // Test not all properties are necessary. $rec1 = (array)$record; unset($rec1['course']); $rec2 = (array)$record; unset($rec2['course']); $records = array($rec1, $rec2); $DB->insert_records($tablename, $records); // Make sure no changes in data object structure are tolerated. $rec1 = (array)$record; unset($rec1['id']); $rec2 = (array)$record; unset($rec2['id']); $records = array($rec1, $rec2); $DB->insert_records($tablename, $records); $rec2['xx'] = '1'; $records = array($rec1, $rec2); try { $DB->insert_records($tablename, $records); $this->fail('coding_exception expected when insert_records receives different object data structures'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } unset($rec2['xx']); unset($rec2['course']); $rec2['course'] = '1'; $records = array($rec1, $rec2); try { $DB->insert_records($tablename, $records); $this->fail('coding_exception expected when insert_records receives different object data structures'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } $records = 1; try { $DB->insert_records($tablename, $records); $this->fail('coding_exception expected when insert_records receives non-traversable data'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } $records = array(1); try { $DB->insert_records($tablename, $records); $this->fail('coding_exception expected when insert_records receives non-objet record'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_import_record() { // All the information in this test is fetched from DB by get_recordset() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(1, $DB->insert_record($tablename, array('course' => 1), true)); $record = $DB->get_record($tablename, array('course' => 1)); $this->assertEquals(1, $record->id); $this->assertEquals(100, $record->oneint); // Just check column defaults have been applied. $this->assertEquals(200, $record->onenum); $this->assertSame('onestring', $record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Ignore extra columns. $record = (object)array('id'=>13, 'course'=>2, 'xxxx'=>788778); $before = clone($record); $this->assertTrue($DB->import_record($tablename, $record)); $this->assertEquals($record, $before); $records = $DB->get_records($tablename); $this->assertEquals(2, $records[13]->course); // Check nulls are set properly for all types. $record = new stdClass(); $record->id = 20; $record->oneint = null; $record->onenum = null; $record->onechar = null; $record->onetext = null; $record->onebinary = null; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 20)); $this->assertEquals(0, $record->course); $this->assertNull($record->oneint); $this->assertNull($record->onenum); $this->assertNull($record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check zeros are set properly for all types. $record = new stdClass(); $record->id = 23; $record->oneint = 0; $record->onenum = 0; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 23)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); // Check string data causes exception in numeric types. $record = new stdClass(); $record->id = 32; $record->oneint = 'onestring'; $record->onenum = 0; try { $DB->import_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } $record = new stdClass(); $record->id = 35; $record->oneint = 0; $record->onenum = 'onestring'; try { $DB->import_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Check empty strings are set properly in string types. $record = new stdClass(); $record->id = 44; $record->oneint = 0; $record->onenum = 0; $record->onechar = ''; $record->onetext = ''; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 44)); $this->assertTrue($record->onechar === ''); $this->assertTrue($record->onetext === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types. $record = new stdClass(); $record->id = 47; $record->oneint = ((210.10 + 39.92) - 150.02); $record->onenum = ((210.10 + 39.92) - 150.02); $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => 47)); $this->assertEquals(100, $record->oneint); $this->assertEquals(100, $record->onenum); // Check various quotes/backslashes combinations in string types. $i = 50; $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $record = new stdClass(); $record->id = $i; $record->onechar = $teststring; $record->onetext = $teststring; $this->assertTrue($DB->import_record($tablename, $record)); $record = $DB->get_record($tablename, array('id' => $i)); $this->assertEquals($teststring, $record->onechar); $this->assertEquals($teststring, $record->onetext); $i = $i + 3; } // Check LOBs in text/binary columns. $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $record = new stdClass(); $record->id = 70; $record->onetext = $clob; $record->onebinary = ''; $this->assertTrue($DB->import_record($tablename, $record)); $rs = $DB->get_recordset($tablename, array('id' => 70)); $record = $rs->current(); $rs->close(); $this->assertEquals($clob, $record->onetext, 'Test CLOB insert (full contents output disabled)'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $record = new stdClass(); $record->id = 71; $record->onetext = ''; $record->onebinary = $blob; $this->assertTrue($DB->import_record($tablename, $record)); $rs = $DB->get_recordset($tablename, array('id' => 71)); $record = $rs->current(); $rs->close(); $this->assertEquals($blob, $record->onebinary, 'Test BLOB insert (full contents output disabled)'); // And "small" LOBs too, just in case. $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $record = new stdClass(); $record->id = 73; $record->onetext = $newclob; $record->onebinary = $newblob; $this->assertTrue($DB->import_record($tablename, $record)); $rs = $DB->get_recordset($tablename, array('id' => 73)); $record = $rs->current(); $rs->close(); $this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB insert (full contents output disabled)'); $this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB insert (full contents output disabled)'); $this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing. } public function test_update_record_raw() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 3)); $record = $DB->get_record($tablename, array('course' => 1)); $record->course = 2; $this->assertTrue($DB->update_record_raw($tablename, $record)); $this->assertEquals(0, $DB->count_records($tablename, array('course' => 1))); $this->assertEquals(1, $DB->count_records($tablename, array('course' => 2))); $this->assertEquals(1, $DB->count_records($tablename, array('course' => 3))); $record = $DB->get_record($tablename, array('course' => 3)); $record->xxxxx = 2; try { $DB->update_record_raw($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('moodle_exception', $e); } $record = $DB->get_record($tablename, array('course' => 3)); unset($record->id); try { $DB->update_record_raw($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_update_record() { // All the information in this test is fetched from DB by get_record() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $record = $DB->get_record($tablename, array('course' => 1)); $record->course = 2; $this->assertTrue($DB->update_record($tablename, $record)); $this->assertFalse($record = $DB->get_record($tablename, array('course' => 1))); $this->assertNotEmpty($record = $DB->get_record($tablename, array('course' => 2))); $this->assertEquals(100, $record->oneint); // Just check column defaults have been applied. $this->assertEquals(200, $record->onenum); $this->assertSame('onestring', $record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check nulls are set properly for all types. $record->oneint = null; $record->onenum = null; $record->onechar = null; $record->onetext = null; $record->onebinary = null; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertNull($record->oneint); $this->assertNull($record->onenum); $this->assertNull($record->onechar); $this->assertNull($record->onetext); $this->assertNull($record->onebinary); // Check zeros are set properly for all types. $record->oneint = 0; $record->onenum = 0; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); // Check booleans are set properly for all types. $record->oneint = true; // Trues. $record->onenum = true; $record->onechar = true; $record->onetext = true; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(1, $record->oneint); $this->assertEquals(1, $record->onenum); $this->assertEquals(1, $record->onechar); $this->assertEquals(1, $record->onetext); $record->oneint = false; // Falses. $record->onenum = false; $record->onechar = false; $record->onetext = false; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(0, $record->oneint); $this->assertEquals(0, $record->onenum); $this->assertEquals(0, $record->onechar); $this->assertEquals(0, $record->onetext); // Check string data causes exception in numeric types. $record->oneint = 'onestring'; $record->onenum = 0; try { $DB->update_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } $record->oneint = 0; $record->onenum = 'onestring'; try { $DB->update_record($tablename, $record); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Check empty string data is stored as 0 in numeric datatypes. $record->oneint = ''; // Empty string. $record->onenum = 0; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertTrue(is_numeric($record->oneint) && $record->oneint == 0); $record->oneint = 0; $record->onenum = ''; // Empty string. $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertTrue(is_numeric($record->onenum) && $record->onenum == 0); // Check empty strings are set properly in string types. $record->oneint = 0; $record->onenum = 0; $record->onechar = ''; $record->onetext = ''; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertTrue($record->onechar === ''); $this->assertTrue($record->onetext === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types. $record->oneint = ((210.10 + 39.92) - 150.02); $record->onenum = ((210.10 + 39.92) - 150.02); $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals(100, $record->oneint); $this->assertEquals(100, $record->onenum); // Check various quotes/backslashes combinations in string types. $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $record->onechar = $teststring; $record->onetext = $teststring; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals($teststring, $record->onechar); $this->assertEquals($teststring, $record->onetext); } // Check LOBs in text/binary columns. $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $record->onetext = $clob; $record->onebinary = $blob; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals($clob, $record->onetext, 'Test CLOB update (full contents output disabled)'); $this->assertEquals($blob, $record->onebinary, 'Test BLOB update (full contents output disabled)'); // And "small" LOBs too, just in case. $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $record->onetext = $newclob; $record->onebinary = $newblob; $DB->update_record($tablename, $record); $record = $DB->get_record($tablename, array('course' => 2)); $this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB update (full contents output disabled)'); $this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB update (full contents output disabled)'); // Test saving a float in a CHAR column, and reading it back. $id = $DB->insert_record($tablename, array('onechar' => 'X')); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onechar' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id))); // Test saving a float in a TEXT column, and reading it back. $id = $DB->insert_record($tablename, array('onetext' => 'X')); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1.0)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e20)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-4)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-5)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-300)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->update_record($tablename, array('id' => $id, 'onetext' => 1e300)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id))); } public function test_set_field() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // Simple set_field. $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->set_field($tablename, 'course', 2, array('id' => $id1))); $this->assertEquals(2, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3))); $DB->delete_records($tablename, array()); // Multiple fields affected. $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $DB->set_field($tablename, 'course', '5', array('course' => 1)); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3))); $DB->delete_records($tablename, array()); // No field affected. $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $DB->set_field($tablename, 'course', '5', array('course' => 0)); $this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3))); $DB->delete_records($tablename, array()); // All fields - no condition. $id1 = $DB->insert_record($tablename, array('course' => 1)); $id2 = $DB->insert_record($tablename, array('course' => 1)); $id3 = $DB->insert_record($tablename, array('course' => 3)); $DB->set_field($tablename, 'course', 5, array()); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id1))); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id2))); $this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id3))); // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext' => '1'); try { $DB->set_field($tablename, 'onechar', 'frog', $conditions); if (debugging()) { // Only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } // Test saving a float in a CHAR column, and reading it back. $id = $DB->insert_record($tablename, array('onechar' => 'X')); $DB->set_field($tablename, 'onechar', 1.0, array('id' => $id)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e20, array('id' => $id)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e-4, array('id' => $id)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e-5, array('id' => $id)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e-300, array('id' => $id)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id))); $DB->set_field($tablename, 'onechar', 1e300, array('id' => $id)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id))); // Test saving a float in a TEXT column, and reading it back. $id = $DB->insert_record($tablename, array('onetext' => 'X')); $DB->set_field($tablename, 'onetext', 1.0, array('id' => $id)); $this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e20, array('id' => $id)); $this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e-4, array('id' => $id)); $this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e-5, array('id' => $id)); $this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e-300, array('id' => $id)); $this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id))); $DB->set_field($tablename, 'onetext', 1e300, array('id' => $id)); $this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id))); // Note: All the nulls, booleans, empties, quoted and backslashes tests // go to set_field_select() because set_field() is just one wrapper over it. } public function test_set_field_select() { // All the information in this test is fetched from DB by get_field() so we // have such method properly tested against nulls, empties and friends... $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null); $table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $this->assertTrue($DB->set_field_select($tablename, 'course', 2, 'id = ?', array(1))); $this->assertEquals(2, $DB->get_field($tablename, 'course', array('id' => 1))); // Check nulls are set properly for all types. $DB->set_field_select($tablename, 'oneint', null, 'id = ?', array(1)); // Trues. $DB->set_field_select($tablename, 'onenum', null, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onechar', null, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', null, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onebinary', null, 'id = ?', array(1)); $this->assertNull($DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onenum', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onetext', array('id' => 1))); $this->assertNull($DB->get_field($tablename, 'onebinary', array('id' => 1))); // Check zeros are set properly for all types. $DB->set_field_select($tablename, 'oneint', 0, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onenum', 0, 'id = ?', array(1)); $this->assertEquals(0, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onenum', array('id' => 1))); // Check booleans are set properly for all types. $DB->set_field_select($tablename, 'oneint', true, 'id = ?', array(1)); // Trues. $DB->set_field_select($tablename, 'onenum', true, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onechar', true, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', true, 'id = ?', array(1)); $this->assertEquals(1, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(1, $DB->get_field($tablename, 'onenum', array('id' => 1))); $this->assertEquals(1, $DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertEquals(1, $DB->get_field($tablename, 'onetext', array('id' => 1))); $DB->set_field_select($tablename, 'oneint', false, 'id = ?', array(1)); // Falses. $DB->set_field_select($tablename, 'onenum', false, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onechar', false, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', false, 'id = ?', array(1)); $this->assertEquals(0, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onenum', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertEquals(0, $DB->get_field($tablename, 'onetext', array('id' => 1))); // Check string data causes exception in numeric types. try { $DB->set_field_select($tablename, 'oneint', 'onestring', 'id = ?', array(1)); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } try { $DB->set_field_select($tablename, 'onenum', 'onestring', 'id = ?', array(1)); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); } // Check empty string data is stored as 0 in numeric datatypes. $DB->set_field_select($tablename, 'oneint', '', 'id = ?', array(1)); $field = $DB->get_field($tablename, 'oneint', array('id' => 1)); $this->assertTrue(is_numeric($field) && $field == 0); $DB->set_field_select($tablename, 'onenum', '', 'id = ?', array(1)); $field = $DB->get_field($tablename, 'onenum', array('id' => 1)); $this->assertTrue(is_numeric($field) && $field == 0); // Check empty strings are set properly in string types. $DB->set_field_select($tablename, 'onechar', '', 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', '', 'id = ?', array(1)); $this->assertTrue($DB->get_field($tablename, 'onechar', array('id' => 1)) === ''); $this->assertTrue($DB->get_field($tablename, 'onetext', array('id' => 1)) === ''); // Check operation ((210.10 + 39.92) - 150.02) against numeric types. $DB->set_field_select($tablename, 'oneint', ((210.10 + 39.92) - 150.02), 'id = ?', array(1)); $DB->set_field_select($tablename, 'onenum', ((210.10 + 39.92) - 150.02), 'id = ?', array(1)); $this->assertEquals(100, $DB->get_field($tablename, 'oneint', array('id' => 1))); $this->assertEquals(100, $DB->get_field($tablename, 'onenum', array('id' => 1))); // Check various quotes/backslashes combinations in string types. $teststrings = array( 'backslashes and quotes alone (even): "" \'\' \\\\', 'backslashes and quotes alone (odd): """ \'\'\' \\\\\\', 'backslashes and quotes sequences (even): \\"\\" \\\'\\\'', 'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\''); foreach ($teststrings as $teststring) { $DB->set_field_select($tablename, 'onechar', $teststring, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onetext', $teststring, 'id = ?', array(1)); $this->assertEquals($teststring, $DB->get_field($tablename, 'onechar', array('id' => 1))); $this->assertEquals($teststring, $DB->get_field($tablename, 'onetext', array('id' => 1))); } // Check LOBs in text/binary columns. $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $blob = file_get_contents(__DIR__ . '/fixtures/randombinary'); $DB->set_field_select($tablename, 'onetext', $clob, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onebinary', $blob, 'id = ?', array(1)); $this->assertEquals($clob, $DB->get_field($tablename, 'onetext', array('id' => 1)), 'Test CLOB set_field (full contents output disabled)'); $this->assertEquals($blob, $DB->get_field($tablename, 'onebinary', array('id' => 1)), 'Test BLOB set_field (full contents output disabled)'); // And "small" LOBs too, just in case. $newclob = substr($clob, 0, 500); $newblob = substr($blob, 0, 250); $DB->set_field_select($tablename, 'onetext', $newclob, 'id = ?', array(1)); $DB->set_field_select($tablename, 'onebinary', $newblob, 'id = ?', array(1)); $this->assertEquals($newclob, $DB->get_field($tablename, 'onetext', array('id' => 1)), 'Test "small" CLOB set_field (full contents output disabled)'); $this->assertEquals($newblob, $DB->get_field($tablename, 'onebinary', array('id' => 1)), 'Test "small" BLOB set_field (full contents output disabled)'); // This is the failure from MDL-24863. This was giving an error on MSSQL, // which converts the '1' to an integer, which cannot then be compared with // onetext cast to a varchar. This should be fixed and working now. $newchar = 'frog'; // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $params = array('onetext' => '1'); try { $DB->set_field_select($tablename, 'onechar', $newchar, $DB->sql_compare_text('onetext') . ' = ?', $params); $this->assertTrue(true, 'No exceptions thrown with numerical text param comparison for text field.'); } catch (dml_exception $e) { $this->assertFalse(true, 'We have an unexpected exception.'); throw $e; } } public function test_count_records() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(0, $DB->count_records($tablename)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $this->assertSame(3, $DB->count_records($tablename)); // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext' => '1'); try { $DB->count_records($tablename, $conditions); if (debugging()) { // Only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } } public function test_count_records_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(0, $DB->count_records($tablename)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $this->assertSame(2, $DB->count_records_select($tablename, 'course > ?', array(3))); } public function test_count_records_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertSame(0, $DB->count_records($tablename)); $DB->insert_record($tablename, array('course' => 3, 'onechar' => 'a')); $DB->insert_record($tablename, array('course' => 4, 'onechar' => 'b')); $DB->insert_record($tablename, array('course' => 5, 'onechar' => 'c')); $this->assertSame(2, $DB->count_records_sql("SELECT COUNT(*) FROM {{$tablename}} WHERE course > ?", array(3))); // Test invalid use. try { $DB->count_records_sql("SELECT onechar FROM {{$tablename}} WHERE course = ?", array(3)); $this->fail('Exception expected when non-number field used in count_records_sql'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $DB->count_records_sql("SELECT course FROM {{$tablename}} WHERE 1 = 2"); $this->fail('Exception expected when non-number field used in count_records_sql'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_record_exists() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertEquals(0, $DB->count_records($tablename)); $this->assertFalse($DB->record_exists($tablename, array('course' => 3))); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->record_exists($tablename, array('course' => 3))); // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext' => '1'); try { $DB->record_exists($tablename, $conditions); if (debugging()) { // Only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } } public function test_record_exists_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertEquals(0, $DB->count_records($tablename)); $this->assertFalse($DB->record_exists_select($tablename, "course = ?", array(3))); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->record_exists_select($tablename, "course = ?", array(3))); } public function test_record_exists_sql() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertEquals(0, $DB->count_records($tablename)); $this->assertFalse($DB->record_exists_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3))); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->record_exists_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3))); } public function test_recordset_locks_delete() { $DB = $this->tdb; $dbman = $DB->get_manager(); // Setup. $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 6)); // Test against db write locking while on an open recordset. $rs = $DB->get_recordset($tablename, array(), null, 'course', 2, 2); // Get courses = {3,4}. foreach ($rs as $record) { $cid = $record->course; $DB->delete_records($tablename, array('course' => $cid)); $this->assertFalse($DB->record_exists($tablename, array('course' => $cid))); } $rs->close(); $this->assertEquals(4, $DB->count_records($tablename, array())); } public function test_recordset_locks_update() { $DB = $this->tdb; $dbman = $DB->get_manager(); // Setup. $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 4)); $DB->insert_record($tablename, array('course' => 5)); $DB->insert_record($tablename, array('course' => 6)); // Test against db write locking while on an open recordset. $rs = $DB->get_recordset($tablename, array(), null, 'course', 2, 2); // Get courses = {3,4}. foreach ($rs as $record) { $cid = $record->course; $DB->set_field($tablename, 'course', 10, array('course' => $cid)); $this->assertFalse($DB->record_exists($tablename, array('course' => $cid))); } $rs->close(); $this->assertEquals(2, $DB->count_records($tablename, array('course' => 10))); } public function test_delete_records() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 2)); // Delete all records. $this->assertTrue($DB->delete_records($tablename)); $this->assertEquals(0, $DB->count_records($tablename)); // Delete subset of records. $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 2)); $this->assertTrue($DB->delete_records($tablename, array('course' => 2))); $this->assertEquals(1, $DB->count_records($tablename)); // Delete all. $this->assertTrue($DB->delete_records($tablename, array())); $this->assertEquals(0, $DB->count_records($tablename)); // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext'=>'1'); try { $DB->delete_records($tablename, $conditions); if (debugging()) { // Only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } // Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int). $conditions = array('onetext' => 1); try { $DB->delete_records($tablename, $conditions); if (debugging()) { // Only in debug mode - hopefully all devs test code in debug mode... $this->fail('An Exception is missing, expected due to equating of text fields'); } } catch (moodle_exception $e) { $this->assertInstanceOf('dml_exception', $e); $this->assertSame('textconditionsnotallowed', $e->errorcode); } } public function test_delete_records_select() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 2)); $this->assertTrue($DB->delete_records_select($tablename, 'course = ?', array(2))); $this->assertEquals(1, $DB->count_records($tablename)); } public function test_delete_records_list() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 1)); $DB->insert_record($tablename, array('course' => 2)); $DB->insert_record($tablename, array('course' => 3)); $this->assertTrue($DB->delete_records_list($tablename, 'course', array(2, 3))); $this->assertEquals(1, $DB->count_records($tablename)); $this->assertTrue($DB->delete_records_list($tablename, 'course', array())); // Must delete 0 rows without conditions. MDL-17645. $this->assertEquals(1, $DB->count_records($tablename)); } public function test_object_params() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $o = new stdClass(); // Objects without __toString - never worked. try { $DB->fix_sql_params("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Objects with __toString() forbidden everywhere since 2.3. $o = new dml_test_object_one(); try { $DB->fix_sql_params("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $DB->execute("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $DB->get_recordset_sql("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $DB->get_records_sql("SELECT {{$tablename}} WHERE course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $record = new stdClass(); $record->course = $o; $DB->insert_record_raw($tablename, $record); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $record = new stdClass(); $record->course = $o; $DB->insert_record($tablename, $record); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $record = new stdClass(); $record->course = $o; $DB->import_record($tablename, $record); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $record = new stdClass(); $record->id = 1; $record->course = $o; $DB->update_record_raw($tablename, $record); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $record = new stdClass(); $record->id = 1; $record->course = $o; $DB->update_record($tablename, $record); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $DB->set_field_select($tablename, 'course', 1, "course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { $DB->delete_records_select($tablename, "course = ? ", array($o)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } } public function test_sql_null_from_clause() { $DB = $this->tdb; $sql = "SELECT 1 AS id ".$DB->sql_null_from_clause(); $this->assertEquals(1, $DB->get_field_sql($sql)); } public function test_sql_bitand() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('col1', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('col2', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('col1' => 3, 'col2' => 10)); $sql = "SELECT ".$DB->sql_bitand(10, 3)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals(2, $DB->get_field_sql($sql)); $sql = "SELECT id, ".$DB->sql_bitand('col1', 'col2')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql); $this->assertCount(1, $result); $this->assertEquals(2, reset($result)->res); $sql = "SELECT id, ".$DB->sql_bitand('col1', '?')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql, array(10)); $this->assertCount(1, $result); $this->assertEquals(2, reset($result)->res); } public function test_sql_bitnot() { $DB = $this->tdb; $not = $DB->sql_bitnot(2); $notlimited = $DB->sql_bitand($not, 7); // Might be positive or negative number which can not fit into PHP INT! $sql = "SELECT $notlimited AS res ".$DB->sql_null_from_clause(); $this->assertEquals(5, $DB->get_field_sql($sql)); } public function test_sql_bitor() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('col1', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('col2', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('col1' => 3, 'col2' => 10)); $sql = "SELECT ".$DB->sql_bitor(10, 3)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals(11, $DB->get_field_sql($sql)); $sql = "SELECT id, ".$DB->sql_bitor('col1', 'col2')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql); $this->assertCount(1, $result); $this->assertEquals(11, reset($result)->res); $sql = "SELECT id, ".$DB->sql_bitor('col1', '?')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql, array(10)); $this->assertCount(1, $result); $this->assertEquals(11, reset($result)->res); } public function test_sql_bitxor() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('col1', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('col2', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('col1' => 3, 'col2' => 10)); $sql = "SELECT ".$DB->sql_bitxor(10, 3)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals(9, $DB->get_field_sql($sql)); $sql = "SELECT id, ".$DB->sql_bitxor('col1', 'col2')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql); $this->assertCount(1, $result); $this->assertEquals(9, reset($result)->res); $sql = "SELECT id, ".$DB->sql_bitxor('col1', '?')." AS res FROM {{$tablename}}"; $result = $DB->get_records_sql($sql, array(10)); $this->assertCount(1, $result); $this->assertEquals(9, reset($result)->res); } public function test_sql_modulo() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_modulo(10, 7)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals(3, $DB->get_field_sql($sql)); } public function test_sql_ceil() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_ceil(665.666)." AS res ".$DB->sql_null_from_clause(); $this->assertEquals(666, $DB->get_field_sql($sql)); } public function test_cast_char2int() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table1 = $this->get_test_table("1"); $tablename1 = $table1->getName(); $table1->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table1->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table1->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table1->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table1); $DB->insert_record($tablename1, array('name'=>'0100', 'nametext'=>'0200')); $DB->insert_record($tablename1, array('name'=>'10', 'nametext'=>'20')); $table2 = $this->get_test_table("2"); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('res', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table2->add_field('restext', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename2, array('res'=>100, 'restext'=>200)); // Casting varchar field. $sql = "SELECT * FROM {".$tablename1."} t1 JOIN {".$tablename2."} t2 ON ".$DB->sql_cast_char2int("t1.name")." = t2.res "; $records = $DB->get_records_sql($sql); $this->assertCount(1, $records); // Also test them in order clauses. $sql = "SELECT * FROM {{$tablename1}} ORDER BY ".$DB->sql_cast_char2int('name'); $records = $DB->get_records_sql($sql); $this->assertCount(2, $records); $this->assertSame('10', reset($records)->name); $this->assertSame('0100', next($records)->name); // Casting text field. $sql = "SELECT * FROM {".$tablename1."} t1 JOIN {".$tablename2."} t2 ON ".$DB->sql_cast_char2int("t1.nametext", true)." = t2.restext "; $records = $DB->get_records_sql($sql); $this->assertCount(1, $records); // Also test them in order clauses. $sql = "SELECT * FROM {{$tablename1}} ORDER BY ".$DB->sql_cast_char2int('nametext', true); $records = $DB->get_records_sql($sql); $this->assertCount(2, $records); $this->assertSame('20', reset($records)->nametext); $this->assertSame('0200', next($records)->nametext); } public function test_cast_char2real() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null); $table->add_field('res', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'10.10', 'nametext'=>'10.10', 'res'=>5.1)); $DB->insert_record($tablename, array('name'=>'91.10', 'nametext'=>'91.10', 'res'=>666)); $DB->insert_record($tablename, array('name'=>'011.10', 'nametext'=>'011.10', 'res'=>10.1)); // Casting varchar field. $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_cast_char2real('name')." > res"; $records = $DB->get_records_sql($sql); $this->assertCount(2, $records); // Also test them in order clauses. $sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_cast_char2real('name'); $records = $DB->get_records_sql($sql); $this->assertCount(3, $records); $this->assertSame('10.10', reset($records)->name); $this->assertSame('011.10', next($records)->name); $this->assertSame('91.10', next($records)->name); // Casting text field. $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_cast_char2real('nametext', true)." > res"; $records = $DB->get_records_sql($sql); $this->assertCount(2, $records); // Also test them in order clauses. $sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_cast_char2real('nametext', true); $records = $DB->get_records_sql($sql); $this->assertCount(3, $records); $this->assertSame('10.10', reset($records)->nametext); $this->assertSame('011.10', next($records)->nametext); $this->assertSame('91.10', next($records)->nametext); } public function test_sql_compare_text() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'abcd', 'description'=>'abcd')); $DB->insert_record($tablename, array('name'=>'abcdef', 'description'=>'bbcdef')); $DB->insert_record($tablename, array('name'=>'aaaa', 'description'=>'aaaacccccccccccccccccc')); $DB->insert_record($tablename, array('name'=>'xxxx', 'description'=>'123456789a123456789b123456789c123456789d')); // Only some supported databases truncate TEXT fields for comparisons, currently MSSQL and Oracle. $dbtruncatestextfields = ($DB->get_dbfamily() == 'mssql' || $DB->get_dbfamily() == 'oracle'); if ($dbtruncatestextfields) { // Ensure truncation behaves as expected. $sql = "SELECT " . $DB->sql_compare_text('description') . " AS field FROM {{$tablename}} WHERE name = ?"; $description = $DB->get_field_sql($sql, array('xxxx')); // Should truncate to 32 chars (the default). $this->assertEquals('123456789a123456789b123456789c12', $description); $sql = "SELECT " . $DB->sql_compare_text('description', 35) . " AS field FROM {{$tablename}} WHERE name = ?"; $description = $DB->get_field_sql($sql, array('xxxx')); // Should truncate to the specified number of chars. $this->assertEquals('123456789a123456789b123456789c12345', $description); } // Ensure text field comparison is successful. $sql = "SELECT * FROM {{$tablename}} WHERE name = ".$DB->sql_compare_text('description'); $records = $DB->get_records_sql($sql); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE name = ".$DB->sql_compare_text('description', 4); $records = $DB->get_records_sql($sql); if ($dbtruncatestextfields) { // Should truncate description to 4 characters before comparing. $this->assertCount(2, $records); } else { // Should leave untruncated, so one less match. $this->assertCount(1, $records); } // Now test the function with really big content and params. $clob = file_get_contents(__DIR__ . '/fixtures/clob.txt'); $DB->insert_record($tablename, array('name' => 'zzzz', 'description' => $clob)); $sql = "SELECT * FROM {{$tablename}} WHERE " . $DB->sql_compare_text('description') . " = " . $DB->sql_compare_text(':clob'); $records = $DB->get_records_sql($sql, array('clob' => $clob)); $this->assertCount(1, $records); $record = reset($records); $this->assertSame($clob, $record->description); } public function test_unique_index_collation_trouble() { // Note: this is a work in progress, we should probably move this to ddl test. $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('name', XMLDB_INDEX_UNIQUE, array('name')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'aaa')); try { $DB->insert_record($tablename, array('name'=>'AAA')); } catch (moodle_exception $e) { // TODO: ignore case insensitive uniqueness problems for now. // $this->fail("Unique index is case sensitive - this may cause problems in some tables"); } try { $DB->insert_record($tablename, array('name'=>'aäa')); $DB->insert_record($tablename, array('name'=>'aáa')); $this->assertTrue(true); } catch (moodle_exception $e) { $family = $DB->get_dbfamily(); if ($family === 'mysql' or $family === 'mssql') { $this->fail("Unique index is accent insensitive, this may cause problems for non-ascii languages. This is usually caused by accent insensitive default collation."); } else { // This should not happen, PostgreSQL and Oracle do not support accent insensitive uniqueness. $this->fail("Unique index is accent insensitive, this may cause problems for non-ascii languages."); } throw($e); } } public function test_sql_binary_equal() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'aaa')); $DB->insert_record($tablename, array('name'=>'aáa')); $DB->insert_record($tablename, array('name'=>'aäa')); $DB->insert_record($tablename, array('name'=>'bbb')); $DB->insert_record($tablename, array('name'=>'BBB')); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('bbb')); $this->assertEquals(1, count($records), 'SQL operator "=" is expected to be case sensitive'); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('aaa')); $this->assertEquals(1, count($records), 'SQL operator "=" is expected to be accent sensitive'); } public function test_sql_like() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'SuperDuperRecord')); $DB->insert_record($tablename, array('name'=>'Nodupor')); $DB->insert_record($tablename, array('name'=>'ouch')); $DB->insert_record($tablename, array('name'=>'ouc_')); $DB->insert_record($tablename, array('name'=>'ouc%')); $DB->insert_record($tablename, array('name'=>'aui')); $DB->insert_record($tablename, array('name'=>'aüi')); $DB->insert_record($tablename, array('name'=>'aÜi')); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false); $records = $DB->get_records_sql($sql, array("%dup_r%")); $this->assertCount(2, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true); $records = $DB->get_records_sql($sql, array("%dup%")); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?'); // Defaults. $records = $DB->get_records_sql($sql, array("%dup%")); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true); $records = $DB->get_records_sql($sql, array("ouc\\_")); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '|'); $records = $DB->get_records_sql($sql, array($DB->sql_like_escape("ouc%", '|'))); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true); $records = $DB->get_records_sql($sql, array('aui')); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, true); // NOT LIKE. $records = $DB->get_records_sql($sql, array("%o%")); $this->assertCount(3, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false, true, true); // NOT ILIKE. $records = $DB->get_records_sql($sql, array("%D%")); $this->assertCount(6, $records); // Verify usual escaping characters work fine. $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '\\'); $records = $DB->get_records_sql($sql, array("ouc\\_")); $this->assertCount(1, $records); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '|'); $records = $DB->get_records_sql($sql, array("ouc|%")); $this->assertCount(1, $records); // TODO: we do not require accent insensitivness yet, just make sure it does not throw errors. $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, false); $records = $DB->get_records_sql($sql, array('aui')); // $this->assertEquals(2, count($records), 'Accent insensitive LIKE searches may not be supported in all databases, this is not a problem.'); $sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false, false); $records = $DB->get_records_sql($sql, array('aui')); // $this->assertEquals(3, count($records), 'Accent insensitive LIKE searches may not be supported in all databases, this is not a problem.'); } public function test_coalesce() { $DB = $this->tdb; // Testing not-null occurrences, return 1st. $sql = "SELECT COALESCE('returnthis', 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(:paramvalue, 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); // Testing null occurrences, return 2nd. $sql = "SELECT COALESCE(null, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(:paramvalue, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => null))); $sql = "SELECT COALESCE(null, :paramvalue, 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); // Testing null occurrences, return 3rd. $sql = "SELECT COALESCE(null, null, 'returnthis') AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(null, :paramvalue, 'returnthis') AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => null))); $sql = "SELECT COALESCE(null, null, :paramvalue) AS test" . $DB->sql_null_from_clause(); $this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); // Testing all null occurrences, return null. // Note: under mssql, if all elements are nulls, at least one must be a "typed" null, hence // we cannot test this in a cross-db way easily, so next 2 tests are using // different queries depending of the DB family. $customnull = $DB->get_dbfamily() == 'mssql' ? 'CAST(null AS varchar)' : 'null'; $sql = "SELECT COALESCE(null, null, " . $customnull . ") AS test" . $DB->sql_null_from_clause(); $this->assertNull($DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(null, :paramvalue, " . $customnull . ") AS test" . $DB->sql_null_from_clause(); $this->assertNull($DB->get_field_sql($sql, array('paramvalue' => null))); // Check there are not problems with whitespace strings. $sql = "SELECT COALESCE(null, :paramvalue, null) AS test" . $DB->sql_null_from_clause(); $this->assertSame('', $DB->get_field_sql($sql, array('paramvalue' => ''))); } public function test_sql_concat() { $DB = $this->tdb; $dbman = $DB->get_manager(); // Testing all sort of values. $sql = "SELECT ".$DB->sql_concat("?", "?", "?")." AS fullname ". $DB->sql_null_from_clause(); // String, some unicode chars. $params = array('name', 'áéíóú', 'name3'); $this->assertSame('nameáéíóúname3', $DB->get_field_sql($sql, $params)); // String, spaces and numbers. $params = array('name', ' ', 12345); $this->assertSame('name 12345', $DB->get_field_sql($sql, $params)); // Float, empty and strings. $params = array(123.45, '', 'test'); $this->assertSame('123.45test', $DB->get_field_sql($sql, $params)); // Only integers. $params = array(12, 34, 56); $this->assertSame('123456', $DB->get_field_sql($sql, $params)); // Float, null and strings. $params = array(123.45, null, 'test'); $this->assertNull($DB->get_field_sql($sql, $params)); // Concatenate null with anything result = null. // Testing fieldnames + values and also integer fieldnames. $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('description'=>'áéíóú')); $DB->insert_record($tablename, array('description'=>'dxxx')); $DB->insert_record($tablename, array('description'=>'bcde')); // Fieldnames and values mixed. $sql = 'SELECT id, ' . $DB->sql_concat('description', "'harcoded'", '?', '?') . ' AS result FROM {' . $tablename . '}'; $records = $DB->get_records_sql($sql, array(123.45, 'test')); $this->assertCount(3, $records); $this->assertSame('áéíóúharcoded123.45test', $records[1]->result); // Integer fieldnames and values. $sql = 'SELECT id, ' . $DB->sql_concat('id', "'harcoded'", '?', '?') . ' AS result FROM {' . $tablename . '}'; $records = $DB->get_records_sql($sql, array(123.45, 'test')); $this->assertCount(3, $records); $this->assertSame('1harcoded123.45test', $records[1]->result); // All integer fieldnames. $sql = 'SELECT id, ' . $DB->sql_concat('id', 'id', 'id') . ' AS result FROM {' . $tablename . '}'; $records = $DB->get_records_sql($sql, array()); $this->assertCount(3, $records); $this->assertSame('111', $records[1]->result); } public function test_concat_join() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_concat_join("' '", array("?", "?", "?"))." AS fullname ".$DB->sql_null_from_clause(); $params = array("name", "name2", "name3"); $result = $DB->get_field_sql($sql, $params); $this->assertEquals("name name2 name3", $result); } public function test_sql_fullname() { $DB = $this->tdb; $sql = "SELECT ".$DB->sql_fullname(':first', ':last')." AS fullname ".$DB->sql_null_from_clause(); $params = array('first'=>'Firstname', 'last'=>'Surname'); $this->assertEquals("Firstname Surname", $DB->get_field_sql($sql, $params)); } public function test_sql_order_by_text() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('description'=>'abcd')); $DB->insert_record($tablename, array('description'=>'dxxx')); $DB->insert_record($tablename, array('description'=>'bcde')); $sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_order_by_text('description'); $records = $DB->get_records_sql($sql); $first = array_shift($records); $this->assertEquals(1, $first->id); $second = array_shift($records); $this->assertEquals(3, $second->id); $last = array_shift($records); $this->assertEquals(2, $last->id); } public function test_sql_substring() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $string = 'abcdefghij'; $DB->insert_record($tablename, array('name'=>$string)); $sql = "SELECT id, ".$DB->sql_substr("name", 5)." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql); $this->assertEquals(substr($string, 5-1), $record->name); $sql = "SELECT id, ".$DB->sql_substr("name", 5, 2)." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql); $this->assertEquals(substr($string, 5-1, 2), $record->name); try { // Silence php warning. @$DB->sql_substr("name"); $this->fail("Expecting an exception, none occurred"); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } // Cover the function using placeholders in all positions. $start = 4; $length = 2; // 1st param (target). $sql = "SELECT id, ".$DB->sql_substr(":param1", $start)." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql, array('param1' => $string)); $this->assertEquals(substr($string, $start - 1), $record->name); // PHP's substr is 0-based. // 2nd param (start). $sql = "SELECT id, ".$DB->sql_substr("name", ":param1")." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql, array('param1' => $start)); $this->assertEquals(substr($string, $start - 1), $record->name); // PHP's substr is 0-based. // 3rd param (length). $sql = "SELECT id, ".$DB->sql_substr("name", $start, ":param1")." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql, array('param1' => $length)); $this->assertEquals(substr($string, $start - 1, $length), $record->name); // PHP's substr is 0-based. // All together. $sql = "SELECT id, ".$DB->sql_substr(":param1", ":param2", ":param3")." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql, array('param1' => $string, 'param2' => $start, 'param3' => $length)); $this->assertEquals(substr($string, $start - 1, $length), $record->name); // PHP's substr is 0-based. // Try also with some expression passed. $sql = "SELECT id, ".$DB->sql_substr("name", "(:param1 + 1) - 1")." AS name FROM {{$tablename}}"; $record = $DB->get_record_sql($sql, array('param1' => $start)); $this->assertEquals(substr($string, $start - 1), $record->name); // PHP's substr is 0-based. } public function test_sql_length() { $DB = $this->tdb; $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_length("'aeiou'").$DB->sql_null_from_clause()), 5); $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_length("'áéíóú'").$DB->sql_null_from_clause()), 5); } public function test_sql_position() { $DB = $this->tdb; $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_position("'ood'", "'Moodle'").$DB->sql_null_from_clause()), 2); $this->assertEquals($DB->get_field_sql( "SELECT ".$DB->sql_position("'Oracle'", "'Moodle'").$DB->sql_null_from_clause()), 0); } public function test_sql_empty() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $this->assertSame('', $DB->sql_empty()); // Since 2.5 the hack is applied automatically to all bound params. $this->assertDebuggingCalled(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('namenotnull', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'default value'); $table->add_field('namenotnullnodeflt', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'', 'namenotnull'=>'')); $DB->insert_record($tablename, array('name'=>null)); $DB->insert_record($tablename, array('name'=>'lalala')); $DB->insert_record($tablename, array('name'=>0)); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('')); $this->assertCount(1, $records); $record = reset($records); $this->assertSame('', $record->name); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE namenotnull = ?", array('')); $this->assertCount(1, $records); $record = reset($records); $this->assertSame('', $record->namenotnull); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE namenotnullnodeflt = ?", array('')); $this->assertCount(4, $records); $record = reset($records); $this->assertSame('', $record->namenotnullnodeflt); } public function test_sql_isempty() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); $table->add_field('namenull', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null); $table->add_field('descriptionnull', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'', 'namenull'=>'', 'description'=>'', 'descriptionnull'=>'')); $DB->insert_record($tablename, array('name'=>'??', 'namenull'=>null, 'description'=>'??', 'descriptionnull'=>null)); $DB->insert_record($tablename, array('name'=>'la', 'namenull'=>'la', 'description'=>'la', 'descriptionnull'=>'lalala')); $DB->insert_record($tablename, array('name'=>0, 'namenull'=>0, 'description'=>0, 'descriptionnull'=>0)); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'name', false, false)); $this->assertCount(1, $records); $record = reset($records); $this->assertSame('', $record->name); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'namenull', true, false)); $this->assertCount(1, $records); $record = reset($records); $this->assertSame('', $record->namenull); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'description', false, true)); $this->assertCount(1, $records); $record = reset($records); $this->assertSame('', $record->description); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'descriptionnull', true, true)); $this->assertCount(1, $records); $record = reset($records); $this->assertSame('', $record->descriptionnull); } public function test_sql_isnotempty() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); $table->add_field('namenull', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null); $table->add_field('descriptionnull', XMLDB_TYPE_TEXT, 'big', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'', 'namenull'=>'', 'description'=>'', 'descriptionnull'=>'')); $DB->insert_record($tablename, array('name'=>'??', 'namenull'=>null, 'description'=>'??', 'descriptionnull'=>null)); $DB->insert_record($tablename, array('name'=>'la', 'namenull'=>'la', 'description'=>'la', 'descriptionnull'=>'lalala')); $DB->insert_record($tablename, array('name'=>0, 'namenull'=>0, 'description'=>0, 'descriptionnull'=>0)); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'name', false, false)); $this->assertCount(3, $records); $record = reset($records); $this->assertSame('??', $record->name); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'namenull', true, false)); $this->assertCount(2, $records); // Nulls aren't comparable (so they aren't "not empty"). SQL expected behaviour. $record = reset($records); $this->assertSame('la', $record->namenull); // So 'la' is the first non-empty 'namenull' record. $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'description', false, true)); $this->assertCount(3, $records); $record = reset($records); $this->assertSame('??', $record->description); $records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'descriptionnull', true, true)); $this->assertCount(2, $records); // Nulls aren't comparable (so they aren't "not empty"). SQL expected behaviour. $record = reset($records); $this->assertSame('lalala', $record->descriptionnull); // So 'lalala' is the first non-empty 'descriptionnull' record. } public function test_sql_regex() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('name'=>'lalala')); $DB->insert_record($tablename, array('name'=>'holaaa')); $DB->insert_record($tablename, array('name'=>'aouch')); $sql = "SELECT * FROM {{$tablename}} WHERE name ".$DB->sql_regex()." ?"; $params = array('a$'); if ($DB->sql_regex_supported()) { $records = $DB->get_records_sql($sql, $params); $this->assertCount(2, $records); } else { $this->assertTrue(true, 'Regexp operations not supported. Test skipped'); } $sql = "SELECT * FROM {{$tablename}} WHERE name ".$DB->sql_regex(false)." ?"; $params = array('.a'); if ($DB->sql_regex_supported()) { $records = $DB->get_records_sql($sql, $params); $this->assertCount(1, $records); } else { $this->assertTrue(true, 'Regexp operations not supported. Test skipped'); } } /** * Test some complicated variations of set_field_select. */ public function test_set_field_select_complicated() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3, 'content' => 'hello', 'name'=>'xyz')); $DB->insert_record($tablename, array('course' => 3, 'content' => 'world', 'name'=>'abc')); $DB->insert_record($tablename, array('course' => 5, 'content' => 'hello', 'name'=>'def')); $DB->insert_record($tablename, array('course' => 2, 'content' => 'universe', 'name'=>'abc')); // This SQL is a tricky case because we are selecting from the same table we are updating. $sql = 'id IN (SELECT outerq.id from (SELECT innerq.id from {' . $tablename . '} innerq WHERE course = 3) outerq)'; $DB->set_field_select($tablename, 'name', 'ghi', $sql); $this->assertSame(2, $DB->count_records_select($tablename, 'name = ?', array('ghi'))); } /** * Test some more complex SQL syntax which moodle uses and depends on to work * useful to determine if new database libraries can be supported. */ public function test_get_records_sql_complicated() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => 3, 'content' => 'hello', 'name'=>'xyz')); $DB->insert_record($tablename, array('course' => 3, 'content' => 'world', 'name'=>'abc')); $DB->insert_record($tablename, array('course' => 5, 'content' => 'hello', 'name'=>'def')); $DB->insert_record($tablename, array('course' => 2, 'content' => 'universe', 'name'=>'abc')); // Test grouping by expressions in the query. MDL-26819. Note that there are 4 ways: // - By column position (GROUP by 1) - Not supported by mssql & oracle // - By column name (GROUP by course) - Supported by all, but leading to wrong results // - By column alias (GROUP by casecol) - Not supported by mssql & oracle // - By complete expression (GROUP BY CASE ...) - 100% cross-db, this test checks it $sql = "SELECT (CASE WHEN course = 3 THEN 1 ELSE 0 END) AS casecol, COUNT(1) AS countrecs, MAX(name) AS maxname FROM {{$tablename}} GROUP BY CASE WHEN course = 3 THEN 1 ELSE 0 END ORDER BY casecol DESC"; $result = array( 1 => (object)array('casecol' => 1, 'countrecs' => 2, 'maxname' => 'xyz'), 0 => (object)array('casecol' => 0, 'countrecs' => 2, 'maxname' => 'def')); $records = $DB->get_records_sql($sql, null); $this->assertEquals($result, $records); // Another grouping by CASE expression just to ensure it works ok for multiple WHEN. $sql = "SELECT CASE name WHEN 'xyz' THEN 'last' WHEN 'def' THEN 'mid' WHEN 'abc' THEN 'first' END AS casecol, COUNT(1) AS countrecs, MAX(name) AS maxname FROM {{$tablename}} GROUP BY CASE name WHEN 'xyz' THEN 'last' WHEN 'def' THEN 'mid' WHEN 'abc' THEN 'first' END ORDER BY casecol DESC"; $result = array( 'mid' => (object)array('casecol' => 'mid', 'countrecs' => 1, 'maxname' => 'def'), 'last' => (object)array('casecol' => 'last', 'countrecs' => 1, 'maxname' => 'xyz'), 'first'=> (object)array('casecol' => 'first', 'countrecs' => 2, 'maxname' => 'abc')); $records = $DB->get_records_sql($sql, null); $this->assertEquals($result, $records); // Test CASE expressions in the ORDER BY clause - used by MDL-34657. $sql = "SELECT id, course, name FROM {{$tablename}} ORDER BY CASE WHEN (course = 5 OR name = 'xyz') THEN 0 ELSE 1 END, name, course"; // First, records matching the course = 5 OR name = 'xyz', then the rest. Each. // group ordered by name and course. $result = array( 3 => (object)array('id' => 3, 'course' => 5, 'name' => 'def'), 1 => (object)array('id' => 1, 'course' => 3, 'name' => 'xyz'), 4 => (object)array('id' => 4, 'course' => 2, 'name' => 'abc'), 2 => (object)array('id' => 2, 'course' => 3, 'name' => 'abc')); $records = $DB->get_records_sql($sql, null); $this->assertEquals($result, $records); // Verify also array keys, order is important in this test. $this->assertEquals(array_keys($result), array_keys($records)); // Test limits in queries with DISTINCT/ALL clauses and multiple whitespace. MDL-25268. $sql = "SELECT DISTINCT course FROM {{$tablename}} ORDER BY course"; // Only limitfrom. $records = $DB->get_records_sql($sql, null, 1); $this->assertCount(2, $records); $this->assertEquals(3, reset($records)->course); $this->assertEquals(5, next($records)->course); // Only limitnum. $records = $DB->get_records_sql($sql, null, 0, 2); $this->assertCount(2, $records); $this->assertEquals(2, reset($records)->course); $this->assertEquals(3, next($records)->course); // Both limitfrom and limitnum. $records = $DB->get_records_sql($sql, null, 2, 2); $this->assertCount(1, $records); $this->assertEquals(5, reset($records)->course); // We have sql like this in moodle, this syntax breaks on older versions of sqlite for example.. $sql = "SELECT a.id AS id, a.course AS course FROM {{$tablename}} a JOIN (SELECT * FROM {{$tablename}}) b ON a.id = b.id WHERE a.course = ?"; $records = $DB->get_records_sql($sql, array(3)); $this->assertCount(2, $records); $this->assertEquals(1, reset($records)->id); $this->assertEquals(2, next($records)->id); // Do NOT try embedding sql_xxxx() helper functions in conditions array of count_records(), they don't break params/binding! $count = $DB->count_records_select($tablename, "course = :course AND ".$DB->sql_compare_text('content')." = :content", array('course' => 3, 'content' => 'hello')); $this->assertEquals(1, $count); // Test int x string comparison. $sql = "SELECT * FROM {{$tablename}} c WHERE name = ?"; $this->assertCount(0, $DB->get_records_sql($sql, array(10))); $this->assertCount(0, $DB->get_records_sql($sql, array("10"))); $DB->insert_record($tablename, array('course' => 7, 'content' => 'xx', 'name'=>'1')); $DB->insert_record($tablename, array('course' => 7, 'content' => 'yy', 'name'=>'2')); $this->assertCount(1, $DB->get_records_sql($sql, array(1))); $this->assertCount(1, $DB->get_records_sql($sql, array("1"))); $this->assertCount(0, $DB->get_records_sql($sql, array(10))); $this->assertCount(0, $DB->get_records_sql($sql, array("10"))); $DB->insert_record($tablename, array('course' => 7, 'content' => 'xx', 'name'=>'1abc')); $this->assertCount(1, $DB->get_records_sql($sql, array(1))); $this->assertCount(1, $DB->get_records_sql($sql, array("1"))); // Test get_in_or_equal() with a big number of elements. Note that ideally // we should be detecting and warning about any use over, say, 200 elements // And recommend to change code to use subqueries and/or chunks instead. $currentcount = $DB->count_records($tablename); $numelements = 10000; // Verify that we can handle 10000 elements (crazy!) $values = range(1, $numelements); list($insql, $inparams) = $DB->get_in_or_equal($values, SQL_PARAMS_QM); // With QM params. $sql = "SELECT * FROM {{$tablename}} WHERE id $insql"; $results = $DB->get_records_sql($sql, $inparams); $this->assertCount($currentcount, $results); list($insql, $inparams) = $DB->get_in_or_equal($values, SQL_PARAMS_NAMED); // With NAMED params. $sql = "SELECT * FROM {{$tablename}} WHERE id $insql"; $results = $DB->get_records_sql($sql, $inparams); $this->assertCount($currentcount, $results); } public function test_replace_all_text() { $DB = $this->tdb; $dbman = $DB->get_manager(); if (!$DB->replace_all_text_supported()) { $this->markTestSkipped($DB->get_name().' does not support replacing of texts'); } $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '20', null, null); $table->add_field('intro', XMLDB_TYPE_TEXT, 'big', null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $id1 = (string)$DB->insert_record($tablename, array('name' => null, 'intro' => null)); $id2 = (string)$DB->insert_record($tablename, array('name' => '', 'intro' => '')); $id3 = (string)$DB->insert_record($tablename, array('name' => 'xxyy', 'intro' => 'vvzz')); $id4 = (string)$DB->insert_record($tablename, array('name' => 'aa bb aa bb', 'intro' => 'cc dd cc aa')); $id5 = (string)$DB->insert_record($tablename, array('name' => 'kkllll', 'intro' => 'kkllll')); $expected = $DB->get_records($tablename, array(), 'id ASC'); $columns = $DB->get_columns($tablename); $DB->replace_all_text($tablename, $columns['name'], 'aa', 'o'); $result = $DB->get_records($tablename, array(), 'id ASC'); $expected[$id4]->name = 'o bb o bb'; $this->assertEquals($expected, $result); $DB->replace_all_text($tablename, $columns['intro'], 'aa', 'o'); $result = $DB->get_records($tablename, array(), 'id ASC'); $expected[$id4]->intro = 'cc dd cc o'; $this->assertEquals($expected, $result); $DB->replace_all_text($tablename, $columns['name'], '_', '*'); $DB->replace_all_text($tablename, $columns['name'], '?', '*'); $DB->replace_all_text($tablename, $columns['name'], '%', '*'); $DB->replace_all_text($tablename, $columns['intro'], '_', '*'); $DB->replace_all_text($tablename, $columns['intro'], '?', '*'); $DB->replace_all_text($tablename, $columns['intro'], '%', '*'); $result = $DB->get_records($tablename, array(), 'id ASC'); $this->assertEquals($expected, $result); $long = '1234567890123456789'; $DB->replace_all_text($tablename, $columns['name'], 'kk', $long); $result = $DB->get_records($tablename, array(), 'id ASC'); $expected[$id5]->name = core_text::substr($long.'llll', 0, 20); $this->assertEquals($expected, $result); $DB->replace_all_text($tablename, $columns['intro'], 'kk', $long); $result = $DB->get_records($tablename, array(), 'id ASC'); $expected[$id5]->intro = $long.'llll'; $this->assertEquals($expected, $result); } public function test_onelevel_commit() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, $data); $this->assertEquals(1, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(1, $DB->count_records($tablename)); } public function test_transaction_ignore_error_trouble() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $table->add_index('course', XMLDB_INDEX_UNIQUE, array('course')); $dbman->create_table($table); // Test error on SQL_QUERY_INSERT. $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->insert_record($tablename, (object)array('course'=>1)); } catch (Exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // Test error on SQL_QUERY_SELECT. $DB->delete_records($tablename); $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->get_records_sql('s e l e c t'); } catch (moodle_exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // Test error on structure SQL_QUERY_UPDATE. $DB->delete_records($tablename); $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->execute('xxxx'); } catch (moodle_exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // Test error on structure SQL_QUERY_STRUCTURE. $DB->delete_records($tablename); $transaction = $DB->start_delegated_transaction(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, (object)array('course'=>1)); $this->assertEquals(1, $DB->count_records($tablename)); try { $DB->change_database_structure('xxxx'); } catch (moodle_exception $e) { // This must be ignored and it must not roll back the whole transaction. } $DB->insert_record($tablename, (object)array('course'=>2)); $this->assertEquals(2, $DB->count_records($tablename)); $transaction->allow_commit(); $this->assertEquals(2, $DB->count_records($tablename)); $this->assertFalse($DB->is_transaction_started()); // NOTE: SQL_QUERY_STRUCTURE is intentionally not tested here because it should never fail. } public function test_onelevel_rollback() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // This might in fact encourage ppl to migrate from myisam to innodb. $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, $data); $this->assertEquals(1, $DB->count_records($tablename)); try { $transaction->rollback(new Exception('test')); $this->fail('transaction rollback must rethrow exception'); } catch (Exception $e) { // Ignored. } $this->assertEquals(0, $DB->count_records($tablename)); } public function test_nested_transactions() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // Two level commit. $this->assertFalse($DB->is_transaction_started()); $transaction1 = $DB->start_delegated_transaction(); $this->assertTrue($DB->is_transaction_started()); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); $transaction2->allow_commit(); $this->assertTrue($DB->is_transaction_started()); $transaction1->allow_commit(); $this->assertFalse($DB->is_transaction_started()); $this->assertEquals(2, $DB->count_records($tablename)); $DB->delete_records($tablename); // Rollback from top level. $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); $transaction2->allow_commit(); try { $transaction1->rollback(new Exception('test')); $this->fail('transaction rollback must rethrow exception'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } $this->assertEquals(0, $DB->count_records($tablename)); $DB->delete_records($tablename); // Rollback from nested level. $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); try { $transaction2->rollback(new Exception('test')); $this->fail('transaction rollback must rethrow exception'); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } $this->assertEquals(2, $DB->count_records($tablename)); // Not rolled back yet. try { $transaction1->allow_commit(); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_transaction_exception', $e); } $this->assertEquals(2, $DB->count_records($tablename)); // Not rolled back yet. // The forced rollback is done from the default_exception handler and similar places, // let's do it manually here. $this->assertTrue($DB->is_transaction_started()); $DB->force_transaction_rollback(); $this->assertFalse($DB->is_transaction_started()); $this->assertEquals(0, $DB->count_records($tablename)); // Finally rolled back. $DB->delete_records($tablename); // Test interactions of recordset and transactions - this causes problems in SQL Server. $table2 = $this->get_test_table('2'); $tablename2 = $table2->getName(); $table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table2->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table2); $DB->insert_record($tablename, array('course'=>1)); $DB->insert_record($tablename, array('course'=>2)); $DB->insert_record($tablename, array('course'=>3)); $DB->insert_record($tablename2, array('course'=>5)); $DB->insert_record($tablename2, array('course'=>6)); $DB->insert_record($tablename2, array('course'=>7)); $DB->insert_record($tablename2, array('course'=>8)); $rs1 = $DB->get_recordset($tablename); $i = 0; foreach ($rs1 as $record1) { $i++; $rs2 = $DB->get_recordset($tablename2); $j = 0; foreach ($rs2 as $record2) { $t = $DB->start_delegated_transaction(); $DB->set_field($tablename, 'course', $record1->course+1, array('id'=>$record1->id)); $DB->set_field($tablename2, 'course', $record2->course+1, array('id'=>$record2->id)); $t->allow_commit(); $j++; } $rs2->close(); $this->assertEquals(4, $j); } $rs1->close(); $this->assertEquals(3, $i); // Test nested recordsets isolation without transaction. $DB->delete_records($tablename); $DB->insert_record($tablename, array('course'=>1)); $DB->insert_record($tablename, array('course'=>2)); $DB->insert_record($tablename, array('course'=>3)); $DB->delete_records($tablename2); $DB->insert_record($tablename2, array('course'=>5)); $DB->insert_record($tablename2, array('course'=>6)); $DB->insert_record($tablename2, array('course'=>7)); $DB->insert_record($tablename2, array('course'=>8)); $rs1 = $DB->get_recordset($tablename); $i = 0; foreach ($rs1 as $record1) { $i++; $rs2 = $DB->get_recordset($tablename2); $j = 0; foreach ($rs2 as $record2) { $DB->set_field($tablename, 'course', $record1->course+1, array('id'=>$record1->id)); $DB->set_field($tablename2, 'course', $record2->course+1, array('id'=>$record2->id)); $j++; } $rs2->close(); $this->assertEquals(4, $j); } $rs1->close(); $this->assertEquals(3, $i); } public function test_transactions_forbidden() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->transactions_forbidden(); $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>1); $DB->insert_record($tablename, $data); try { $DB->transactions_forbidden(); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_transaction_exception', $e); } // The previous test does not force rollback. $transaction->allow_commit(); $this->assertFalse($DB->is_transaction_started()); $this->assertEquals(1, $DB->count_records($tablename)); } public function test_wrong_transactions() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); // Wrong order of nested commits. $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); try { $transaction1->allow_commit(); $this->fail('wrong order of commits must throw exception'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_transaction_exception', $e); } try { $transaction2->allow_commit(); $this->fail('first wrong commit forces rollback'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_transaction_exception', $e); } // This is done in default exception handler usually. $this->assertTrue($DB->is_transaction_started()); $this->assertEquals(2, $DB->count_records($tablename)); // Not rolled back yet. $DB->force_transaction_rollback(); $this->assertEquals(0, $DB->count_records($tablename)); $DB->delete_records($tablename); // Wrong order of nested rollbacks. $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = $DB->start_delegated_transaction(); $data = (object)array('course'=>4); $DB->insert_record($tablename, $data); try { // This first rollback should prevent all other rollbacks. $transaction1->rollback(new Exception('test')); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } try { $transaction2->rollback(new Exception('test')); } catch (Exception $e) { $this->assertEquals(get_class($e), 'Exception'); } try { $transaction1->rollback(new Exception('test')); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_transaction_exception', $e); } // This is done in default exception handler usually. $this->assertTrue($DB->is_transaction_started()); $DB->force_transaction_rollback(); $DB->delete_records($tablename); // Unknown transaction object. $transaction1 = $DB->start_delegated_transaction(); $data = (object)array('course'=>3); $DB->insert_record($tablename, $data); $transaction2 = new moodle_transaction($DB); try { $transaction2->allow_commit(); $this->fail('foreign transaction must fail'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_transaction_exception', $e); } try { $transaction1->allow_commit(); $this->fail('first wrong commit forces rollback'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_transaction_exception', $e); } $DB->force_transaction_rollback(); $DB->delete_records($tablename); } public function test_concurent_transactions() { // Notes about this test: // 1- MySQL needs to use one engine with transactions support (InnoDB). // 2- MSSQL needs to have enabled versioning for read committed // transactions (ALTER DATABASE xxx SET READ_COMMITTED_SNAPSHOT ON) $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $transaction = $DB->start_delegated_transaction(); $data = (object)array('course'=>1); $this->assertEquals(0, $DB->count_records($tablename)); $DB->insert_record($tablename, $data); $this->assertEquals(1, $DB->count_records($tablename)); // Open second connection. $cfg = $DB->export_dbconfig(); if (!isset($cfg->dboptions)) { $cfg->dboptions = array(); } $DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary); $DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions); // Second instance should not see pending inserts. $this->assertEquals(0, $DB2->count_records($tablename)); $data = (object)array('course'=>2); $DB2->insert_record($tablename, $data); $this->assertEquals(1, $DB2->count_records($tablename)); // First should see the changes done from second. $this->assertEquals(2, $DB->count_records($tablename)); // Now commit and we should see it finally in second connections. $transaction->allow_commit(); $this->assertEquals(2, $DB2->count_records($tablename)); // Let's try delete all is also working on (this checks MDL-29198). // Initially both connections see all the records in the table (2). $this->assertEquals(2, $DB->count_records($tablename)); $this->assertEquals(2, $DB2->count_records($tablename)); $transaction = $DB->start_delegated_transaction(); // Delete all from within transaction. $DB->delete_records($tablename); // Transactional $DB, sees 0 records now. $this->assertEquals(0, $DB->count_records($tablename)); // Others ($DB2) get no changes yet. $this->assertEquals(2, $DB2->count_records($tablename)); // Now commit and we should see changes. $transaction->allow_commit(); $this->assertEquals(0, $DB2->count_records($tablename)); $DB2->dispose(); } public function test_session_locks() { $DB = $this->tdb; $dbman = $DB->get_manager(); // Open second connection. $cfg = $DB->export_dbconfig(); if (!isset($cfg->dboptions)) { $cfg->dboptions = array(); } $DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary); $DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions); // Testing that acquiring a lock effectively locks. // Get a session lock on connection1. $rowid = rand(100, 200); $timeout = 1; $DB->get_session_lock($rowid, $timeout); // Try to get the same session lock on connection2. try { $DB2->get_session_lock($rowid, $timeout); $DB2->release_session_lock($rowid); // Should not be executed, but here for safety. $this->fail('An Exception is missing, expected due to session lock acquired.'); } catch (moodle_exception $e) { $this->assertInstanceOf('dml_sessionwait_exception', $e); $DB->release_session_lock($rowid); // Release lock on connection1. } // Testing that releasing a lock effectively frees. // Get a session lock on connection1. $rowid = rand(100, 200); $timeout = 1; $DB->get_session_lock($rowid, $timeout); // Release the lock on connection1. $DB->release_session_lock($rowid); // Get the just released lock on connection2. $DB2->get_session_lock($rowid, $timeout); // Release the lock on connection2. $DB2->release_session_lock($rowid); $DB2->dispose(); } public function test_bound_param_types() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => '1', 'content'=>'xx'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 2, 'content'=>'yy'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'somestring', 'content'=>'zz'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'aa', 'content'=>'1'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'bb', 'content'=>2))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'cc', 'content'=>'sometext'))); // Conditions in CHAR columns. $this->assertTrue($DB->record_exists($tablename, array('name'=>1))); $this->assertTrue($DB->record_exists($tablename, array('name'=>'1'))); $this->assertFalse($DB->record_exists($tablename, array('name'=>111))); $this->assertNotEmpty($DB->get_record($tablename, array('name'=>1))); $this->assertNotEmpty($DB->get_record($tablename, array('name'=>'1'))); $this->assertEmpty($DB->get_record($tablename, array('name'=>111))); $sqlqm = "SELECT * FROM {{$tablename}} WHERE name = ?"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array(1))); $this->assertCount(1, $records); $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array('1'))); $this->assertCount(1, $records); $records = $DB->get_records_sql($sqlqm, array(222)); $this->assertCount(0, $records); $sqlnamed = "SELECT * FROM {{$tablename}} WHERE name = :name"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('name' => 2))); $this->assertCount(1, $records); $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('name' => '2'))); $this->assertCount(1, $records); // Conditions in TEXT columns always must be performed with the sql_compare_text // helper function on both sides of the condition. $sqlqm = "SELECT * FROM {{$tablename}} WHERE " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text('?'); $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array('1'))); $this->assertCount(1, $records); $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array(1))); $this->assertCount(1, $records); $sqlnamed = "SELECT * FROM {{$tablename}} WHERE " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':content'); $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('content' => 2))); $this->assertCount(1, $records); $this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('content' => '2'))); $this->assertCount(1, $records); } public function test_bound_param_reserved() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => '1')); // Make sure reserved words do not cause fatal problems in query parameters. $DB->execute("UPDATE {{$tablename}} SET course = 1 WHERE id = :select", array('select'=>1)); $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE course = :select", array('select'=>1)); $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} WHERE course = :select", array('select'=>1)); $rs->close(); $DB->get_fieldset_sql("SELECT id FROM {{$tablename}} WHERE course = :select", array('select'=>1)); $DB->set_field_select($tablename, 'course', '1', "id = :select", array('select'=>1)); $DB->delete_records_select($tablename, "id = :select", array('select'=>1)); // If we get here test passed ok. $this->assertTrue(true); } public function test_limits_and_offsets() { $DB = $this->tdb; $dbman = $DB->get_manager(); $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'a', 'content'=>'one'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'b', 'content'=>'two'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'c', 'content'=>'three'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'd', 'content'=>'four'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'e', 'content'=>'five'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'f', 'content'=>'six'))); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4)); $this->assertCount(2, $records); $this->assertSame('e', reset($records)->name); $this->assertSame('f', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertEmpty($records = $DB->get_records_sql($sqlqm, null, 8)); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 4)); $this->assertCount(4, $records); $this->assertSame('a', reset($records)->name); $this->assertSame('d', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 8)); $this->assertCount(6, $records); $this->assertSame('a', reset($records)->name); $this->assertSame('f', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 1, 4)); $this->assertCount(4, $records); $this->assertSame('b', reset($records)->name); $this->assertSame('e', end($records)->name); $sqlqm = "SELECT * FROM {{$tablename}}"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4)); $this->assertCount(2, $records); $this->assertSame('e', reset($records)->name); $this->assertSame('f', end($records)->name); $sqlqm = "SELECT t.*, t.name AS test FROM {{$tablename}} t ORDER BY t.id ASC"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4)); $this->assertCount(2, $records); $this->assertSame('e', reset($records)->name); $this->assertSame('f', end($records)->name); $sqlqm = "SELECT DISTINCT t.name, t.name AS test FROM {{$tablename}} t ORDER BY t.name DESC"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4)); $this->assertCount(2, $records); $this->assertSame('b', reset($records)->name); $this->assertSame('a', end($records)->name); $sqlqm = "SELECT 1 FROM {{$tablename}} t WHERE t.name = 'a'"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 1)); $this->assertCount(1, $records); $sqlqm = "SELECT 'constant' FROM {{$tablename}} t WHERE t.name = 'a'"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 8)); $this->assertCount(1, $records); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'a', 'content'=>'one'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'b', 'content'=>'two'))); $this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'c', 'content'=>'three'))); $sqlqm = "SELECT t.name, COUNT(DISTINCT t2.id) AS count, 'Test' AS teststring FROM {{$tablename}} t LEFT JOIN ( SELECT t.id, t.name FROM {{$tablename}} t ) t2 ON t2.name = t.name GROUP BY t.name ORDER BY t.name ASC"; $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm)); $this->assertCount(6, $records); // a,b,c,d,e,f. $this->assertEquals(2, reset($records)->count); // a has 2 records now. $this->assertEquals(1, end($records)->count); // f has 1 record still. $this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 2)); $this->assertCount(2, $records); $this->assertEquals(2, reset($records)->count); $this->assertEquals(2, end($records)->count); } /** * Test debugging messages about invalid limit number values. */ public function test_invalid_limits_debugging() { $DB = $this->tdb; $dbman = $DB->get_manager(); // Setup test data. $table = $this->get_test_table(); $tablename = $table->getName(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $DB->insert_record($tablename, array('course' => '1')); // Verify that get_records_sql throws debug notices with invalid limit params. $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 'invalid'); $this->assertDebuggingCalled("Non-numeric limitfrom parameter detected: 'invalid', did you pass the correct arguments?"); $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, 'invalid'); $this->assertDebuggingCalled("Non-numeric limitnum parameter detected: 'invalid', did you pass the correct arguments?"); // Verify that get_recordset_sql throws debug notices with invalid limit params. $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}}", null, 'invalid'); $this->assertDebuggingCalled("Non-numeric limitfrom parameter detected: 'invalid', did you pass the correct arguments?"); $rs->close(); $rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}}", null, 1, 'invalid'); $this->assertDebuggingCalled("Non-numeric limitnum parameter detected: 'invalid', did you pass the correct arguments?"); $rs->close(); // Verify that some edge cases do no create debugging messages. // String form of integer values. $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, '1'); $this->assertDebuggingNotCalled(); $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, '2'); $this->assertDebuggingNotCalled(); // Empty strings. $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, ''); $this->assertDebuggingNotCalled(); $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, ''); $this->assertDebuggingNotCalled(); // Null values. $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, null); $this->assertDebuggingNotCalled(); $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, null); $this->assertDebuggingNotCalled(); // Verify that empty arrays DO create debugging mesages. $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, array()); $this->assertDebuggingCalled("Non-numeric limitfrom parameter detected: array (\n), did you pass the correct arguments?"); $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, array()); $this->assertDebuggingCalled("Non-numeric limitnum parameter detected: array (\n), did you pass the correct arguments?"); // Verify Negative number handling: // -1 is explicitly treated as 0 for historical reasons. $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, -1); $this->assertDebuggingNotCalled(); $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, -1); $this->assertDebuggingNotCalled(); // Any other negative values should throw debugging messages. $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, -2); $this->assertDebuggingCalled("Negative limitfrom parameter detected: -2, did you pass the correct arguments?"); $DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, -2); $this->assertDebuggingCalled("Negative limitnum parameter detected: -2, did you pass the correct arguments?"); } public function test_queries_counter() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); // Test database. $table = $this->get_test_table(); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('fieldvalue', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $tablename = $table->getName(); // Initial counters values. $initreads = $DB->perf_get_reads(); $initwrites = $DB->perf_get_writes(); $previousqueriestime = $DB->perf_get_queries_time(); // Selects counts as reads. // The get_records_sql() method generates only 1 db query. $whatever = $DB->get_records_sql("SELECT * FROM {{$tablename}}"); $this->assertEquals($initreads + 1, $DB->perf_get_reads()); // The get_records() method generates 2 queries the first time is called // as it is fetching the table structure. $whatever = $DB->get_records($tablename); $this->assertEquals($initreads + 3, $DB->perf_get_reads()); $this->assertEquals($initwrites, $DB->perf_get_writes()); // The elapsed time is counted. $lastqueriestime = $DB->perf_get_queries_time(); $this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime); $previousqueriestime = $lastqueriestime; // Only 1 now, it already fetched the table columns. $whatever = $DB->get_records($tablename); $this->assertEquals($initreads + 4, $DB->perf_get_reads()); // And only 1 more from now. $whatever = $DB->get_records($tablename); $this->assertEquals($initreads + 5, $DB->perf_get_reads()); // Inserts counts as writes. $rec1 = new stdClass(); $rec1->fieldvalue = 11; $rec1->id = $DB->insert_record($tablename, $rec1); $this->assertEquals($initwrites + 1, $DB->perf_get_writes()); $this->assertEquals($initreads + 5, $DB->perf_get_reads()); // The elapsed time is counted. $lastqueriestime = $DB->perf_get_queries_time(); $this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime); $previousqueriestime = $lastqueriestime; $rec2 = new stdClass(); $rec2->fieldvalue = 22; $rec2->id = $DB->insert_record($tablename, $rec2); $this->assertEquals($initwrites + 2, $DB->perf_get_writes()); // Updates counts as writes. $rec1->fieldvalue = 111; $DB->update_record($tablename, $rec1); $this->assertEquals($initwrites + 3, $DB->perf_get_writes()); $this->assertEquals($initreads + 5, $DB->perf_get_reads()); // The elapsed time is counted. $lastqueriestime = $DB->perf_get_queries_time(); $this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime); $previousqueriestime = $lastqueriestime; // Sum of them. $totaldbqueries = $DB->perf_get_reads() + $DB->perf_get_writes(); $this->assertEquals($totaldbqueries, $DB->perf_get_queries()); } public function test_sql_intersect() { $DB = $this->tdb; $dbman = $this->tdb->get_manager(); $tables = array(); for ($i = 0; $i < 3; $i++) { $table = $this->get_test_table('i'.$i); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('ival', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); $dbman->create_table($table); $tables[$i] = $table; } $DB->insert_record($tables[0]->getName(), array('ival' => 1, 'name' => 'One'), false); $DB->insert_record($tables[0]->getName(), array('ival' => 2, 'name' => 'Two'), false); $DB->insert_record($tables[0]->getName(), array('ival' => 3, 'name' => 'Three'), false); $DB->insert_record($tables[0]->getName(), array('ival' => 4, 'name' => 'Four'), false); $DB->insert_record($tables[1]->getName(), array('ival' => 1, 'name' => 'One'), false); $DB->insert_record($tables[1]->getName(), array('ival' => 2, 'name' => 'Two'), false); $DB->insert_record($tables[1]->getName(), array('ival' => 3, 'name' => 'Three'), false); $DB->insert_record($tables[2]->getName(), array('ival' => 1, 'name' => 'One'), false); $DB->insert_record($tables[2]->getName(), array('ival' => 2, 'name' => 'Two'), false); $DB->insert_record($tables[2]->getName(), array('ival' => 5, 'name' => 'Five'), false); // Intersection on the int column. $params = array('excludename' => 'Two'); $sql1 = 'SELECT ival FROM {'.$tables[0]->getName().'}'; $sql2 = 'SELECT ival FROM {'.$tables[1]->getName().'} WHERE name <> :excludename'; $sql3 = 'SELECT ival FROM {'.$tables[2]->getName().'}'; $sql = $DB->sql_intersect(array($sql1), 'ival') . ' ORDER BY ival'; $this->assertEquals(array(1, 2, 3, 4), $DB->get_fieldset_sql($sql, $params)); $sql = $DB->sql_intersect(array($sql1, $sql2), 'ival') . ' ORDER BY ival'; $this->assertEquals(array(1, 3), $DB->get_fieldset_sql($sql, $params)); $sql = $DB->sql_intersect(array($sql1, $sql2, $sql3), 'ival') . ' ORDER BY ival'; $this->assertEquals(array(1), $DB->get_fieldset_sql($sql, $params)); // Intersection on the char column. $params = array('excludeival' => 2); $sql1 = 'SELECT name FROM {'.$tables[0]->getName().'}'; $sql2 = 'SELECT name FROM {'.$tables[1]->getName().'} WHERE ival <> :excludeival'; $sql3 = 'SELECT name FROM {'.$tables[2]->getName().'}'; $sql = $DB->sql_intersect(array($sql1), 'name') . ' ORDER BY name'; $this->assertEquals(array('Four', 'One', 'Three', 'Two'), $DB->get_fieldset_sql($sql, $params)); $sql = $DB->sql_intersect(array($sql1, $sql2), 'name') . ' ORDER BY name'; $this->assertEquals(array('One', 'Three'), $DB->get_fieldset_sql($sql, $params)); $sql = $DB->sql_intersect(array($sql1, $sql2, $sql3), 'name') . ' ORDER BY name'; $this->assertEquals(array('One'), $DB->get_fieldset_sql($sql, $params)); // Intersection on the several columns. $params = array('excludename' => 'Two'); $sql1 = 'SELECT ival, name FROM {'.$tables[0]->getName().'}'; $sql2 = 'SELECT ival, name FROM {'.$tables[1]->getName().'} WHERE name <> :excludename'; $sql3 = 'SELECT ival, name FROM {'.$tables[2]->getName().'}'; $sql = $DB->sql_intersect(array($sql1), 'ival, name') . ' ORDER BY ival'; $this->assertEquals(array(1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four'), $DB->get_records_sql_menu($sql, $params)); $sql = $DB->sql_intersect(array($sql1, $sql2), 'ival, name') . ' ORDER BY ival'; $this->assertEquals(array(1 => 'One', 3 => 'Three'), $DB->get_records_sql_menu($sql, $params)); $sql = $DB->sql_intersect(array($sql1, $sql2, $sql3), 'ival, name') . ' ORDER BY ival'; $this->assertEquals(array(1 => 'One'), $DB->get_records_sql_menu($sql, $params)); // Drop temporary tables. foreach ($tables as $table) { $dbman->drop_table($table); } } } /** * This class is not a proper subclass of moodle_database. It is * intended to be used only in unit tests, in order to gain access to the * protected methods of moodle_database, and unit test them. */ class moodle_database_for_testing extends moodle_database { protected $prefix = 'mdl_'; public function public_fix_table_names($sql) { return $this->fix_table_names($sql); } public function driver_installed() {} public function get_dbfamily() {} protected function get_dbtype() {} protected function get_dblibrary() {} public function get_name() {} public function get_configuration_help() {} public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {} public function get_server_info() {} protected function allowed_param_types() {} public function get_last_error() {} public function get_tables($usecache=true) {} public function get_indexes($table) {} public function get_columns($table, $usecache=true) {} protected function normalise_value($column, $value) {} public function set_debug($state) {} public function get_debug() {} public function change_database_structure($sql) {} public function execute($sql, array $params=null) {} public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {} public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {} public function get_fieldset_sql($sql, array $params=null) {} public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {} public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {} public function import_record($table, $dataobject) {} public function update_record_raw($table, $params, $bulk=false) {} public function update_record($table, $dataobject, $bulk=false) {} public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {} public function delete_records_select($table, $select, array $params=null) {} public function sql_concat() {} public function sql_concat_join($separator="' '", $elements=array()) {} public function sql_substr($expr, $start, $length=false) {} public function begin_transaction() {} public function commit_transaction() {} public function rollback_transaction() {} } /** * Dumb test class with toString() returning 1. */ class dml_test_object_one { public function __toString() { return 1; } }
nagyistoce/moodle
lib/dml/tests/dml_test.php
PHP
gpl-3.0
256,559
/* * Copyright (C) 2010-2015 JPEXS, All rights reserved. * * 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 3.0 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. * * You should have received a copy of the GNU Lesser General Public * License along with this library. */ package com.jpexs.decompiler.flash.exporters; import com.jpexs.decompiler.flash.AbortRetryIgnoreHandler; import com.jpexs.decompiler.flash.EventListener; import com.jpexs.decompiler.flash.RetryTask; import com.jpexs.decompiler.flash.SWF; import com.jpexs.decompiler.flash.exporters.commonshape.ExportRectangle; import com.jpexs.decompiler.flash.exporters.commonshape.SVGExporter; import com.jpexs.decompiler.flash.exporters.modes.MorphShapeExportMode; import com.jpexs.decompiler.flash.exporters.morphshape.CanvasMorphShapeExporter; import com.jpexs.decompiler.flash.exporters.settings.MorphShapeExportSettings; import com.jpexs.decompiler.flash.tags.DefineMorphShapeTag; import com.jpexs.decompiler.flash.tags.Tag; import com.jpexs.decompiler.flash.tags.base.CharacterTag; import com.jpexs.decompiler.flash.tags.base.MorphShapeTag; import com.jpexs.decompiler.flash.types.CXFORMWITHALPHA; import com.jpexs.helpers.Helper; import com.jpexs.helpers.Path; import com.jpexs.helpers.utf8.Utf8Helper; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author JPEXS */ public class MorphShapeExporter { //TODO: implement morphshape export. How to handle 65536 frames? public List<File> exportMorphShapes(AbortRetryIgnoreHandler handler, final String outdir, List<Tag> tags, final MorphShapeExportSettings settings, EventListener evl) throws IOException, InterruptedException { List<File> ret = new ArrayList<>(); if (tags.isEmpty()) { return ret; } File foutdir = new File(outdir); Path.createDirectorySafe(foutdir); int count = 0; for (Tag t : tags) { if (t instanceof MorphShapeTag) { count++; } } if (count == 0) { return ret; } int currentIndex = 1; for (final Tag t : tags) { if (t instanceof MorphShapeTag) { if (evl != null) { evl.handleExportingEvent("morphshape", currentIndex, count, t.getName()); } int characterID = 0; if (t instanceof CharacterTag) { characterID = ((CharacterTag) t).getCharacterId(); } String ext = settings.mode == MorphShapeExportMode.CANVAS ? "html" : "svg"; final File file = new File(outdir + File.separator + characterID + "." + ext); new RetryTask(() -> { MorphShapeTag mst = (MorphShapeTag) t; switch (settings.mode) { case SVG: try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { ExportRectangle rect = new ExportRectangle(mst.getRect()); rect.xMax *= settings.zoom; rect.yMax *= settings.zoom; rect.xMin *= settings.zoom; rect.yMin *= settings.zoom; SVGExporter exporter = new SVGExporter(rect); mst.toSVG(exporter, -2, new CXFORMWITHALPHA(), 0, settings.zoom); fos.write(Utf8Helper.getBytes(exporter.getSVG())); } break; case CANVAS: try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { int deltaX = -Math.min(mst.getStartBounds().Xmin, mst.getEndBounds().Xmin); int deltaY = -Math.min(mst.getStartBounds().Ymin, mst.getEndBounds().Ymin); CanvasMorphShapeExporter cse = new CanvasMorphShapeExporter(((Tag) mst).getSwf(), mst.getShapeAtRatio(0), mst.getShapeAtRatio(DefineMorphShapeTag.MAX_RATIO), new CXFORMWITHALPHA(), SWF.unitDivisor, deltaX, deltaY); cse.export(); Set<Integer> needed = new HashSet<>(); CharacterTag ct = ((CharacterTag) mst); needed.add(ct.getCharacterId()); ct.getNeededCharactersDeep(needed); ByteArrayOutputStream baos = new ByteArrayOutputStream(); SWF.writeLibrary(ct.getSwf(), needed, baos); fos.write(Utf8Helper.getBytes(cse.getHtml(new String(baos.toByteArray(), Utf8Helper.charset), SWF.getTypePrefix(mst) + mst.getCharacterId(), mst.getRect()))); } break; } }, handler).run(); ret.add(file); if (evl != null) { evl.handleExportedEvent("morphshape", currentIndex, count, t.getName()); } currentIndex++; } } if (settings.mode == MorphShapeExportMode.CANVAS) { File fcanvas = new File(foutdir + File.separator + "canvas.js"); Helper.saveStream(SWF.class.getClassLoader().getResourceAsStream("com/jpexs/helpers/resource/canvas.js"), fcanvas); ret.add(fcanvas); } return ret; } }
Jackkal/jpexs-decompiler
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/exporters/MorphShapeExporter.java
Java
gpl-3.0
6,261
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Short answer * * @package mod * @subpackage lesson * @copyright 2009 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later **/ defined('MOODLE_INTERNAL') || die(); /** Short answer question type */ define("LESSON_PAGE_SHORTANSWER", "1"); class lesson_page_type_shortanswer extends lesson_page { protected $type = lesson_page::TYPE_QUESTION; protected $typeidstring = 'shortanswer'; protected $typeid = LESSON_PAGE_SHORTANSWER; protected $string = null; public function get_typeid() { return $this->typeid; } public function get_typestring() { if ($this->string===null) { $this->string = get_string($this->typeidstring, 'lesson'); } return $this->string; } public function get_idstring() { return $this->typeidstring; } public function display($renderer, $attempt) { global $USER, $CFG, $PAGE; $mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents())); $data = new stdClass; $data->id = $PAGE->cm->id; $data->pageid = $this->properties->id; if (isset($USER->modattempts[$this->lesson->id])) { $data->answer = s($attempt->useranswer); } $mform->set_data($data); return $mform->display(); } public function check_answer() { global $CFG; $result = parent::check_answer(); $mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents())); $data = $mform->get_data(); require_sesskey(); $studentanswer = trim($data->answer); if ($studentanswer === '') { $result->noanswer = true; return $result; } $studentanswer = s($studentanswer); $i=0; $answers = $this->get_answers(); foreach ($answers as $answer) { $i++; $expectedanswer = $answer->answer; // for easier handling of $answer->answer $ismatch = false; $markit = false; $useregexp = ($this->qoption); if ($useregexp) { //we are using 'normal analysis', which ignores case $ignorecase = ''; if (substr($expectedanswer,0,-2) == '/i') { $expectedanswer = substr($expectedanswer,0,-2); $ignorecase = 'i'; } } else { $expectedanswer = str_replace('*', '#####', $expectedanswer); $expectedanswer = preg_quote($expectedanswer, '/'); $expectedanswer = str_replace('#####', '.*', $expectedanswer); } // see if user typed in any of the correct answers if ((!$this->lesson->custom && $this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) or ($this->lesson->custom && $answer->score > 0) ) { if (!$useregexp) { // we are using 'normal analysis', which ignores case if (preg_match('/^'.$expectedanswer.'$/i',$studentanswer)) { $ismatch = true; } } else { if (preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer)) { $ismatch = true; } } if ($ismatch == true) { $result->correctanswer = true; } } else { if (!$useregexp) { //we are using 'normal analysis' // see if user typed in any of the wrong answers; don't worry about case if (preg_match('/^'.$expectedanswer.'$/i',$studentanswer)) { $ismatch = true; } } else { // we are using regular expressions analysis $startcode = substr($expectedanswer,0,2); switch ($startcode){ //1- check for absence of required string in $studentanswer (coded by initial '--') case "--": $expectedanswer = substr($expectedanswer,2); if (!preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer)) { $ismatch = true; } break; //2- check for code for marking wrong strings (coded by initial '++') case "++": $expectedanswer=substr($expectedanswer,2); $markit = true; //check for one or several matches if (preg_match_all('/'.$expectedanswer.'/'.$ignorecase,$studentanswer, $matches)) { $ismatch = true; $nb = count($matches[0]); $original = array(); $marked = array(); $fontStart = '<span class="incorrect matches">'; $fontEnd = '</span>'; for ($i = 0; $i < $nb; $i++) { array_push($original,$matches[0][$i]); array_push($marked,$fontStart.$matches[0][$i].$fontEnd); } $studentanswer = str_replace($original, $marked, $studentanswer); } break; //3- check for wrong answers belonging neither to -- nor to ++ categories default: if (preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer, $matches)) { $ismatch = true; } break; } $result->correctanswer = false; } } if ($ismatch) { $result->newpageid = $answer->jumpto; if (trim(strip_tags($answer->response))) { $result->response = $answer->response; } $result->answerid = $answer->id; break; // quit answer analysis immediately after a match has been found } } $result->studentanswer = $result->userresponse = $studentanswer; return $result; } public function option_description_string() { if ($this->properties->qoption) { return " - ".get_string("casesensitive", "lesson"); } return parent::option_description_string(); } public function display_answers(html_table $table) { $answers = $this->get_answers(); $options = new stdClass; $options->noclean = true; $options->para = false; $i = 1; foreach ($answers as $answer) { $cells = array(); if ($this->lesson->custom && $answer->score > 0) { // if the score is > 0, then it is correct $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n"; } else if ($this->lesson->custom) { $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n"; } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) { // underline correct answers $cells[] = '<span class="correct">'.get_string("answer", "lesson")." $i</span>: \n"; } else { $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n"; } $cells[] = format_text($answer->answer, $answer->answerformat, $options); $table->data[] = new html_table_row($cells); $cells = array(); $cells[] = "<span class=\"label\">".get_string("response", "lesson")." $i</span>"; $cells[] = format_text($answer->response, $answer->responseformat, $options); $table->data[] = new html_table_row($cells); $cells = array(); $cells[] = "<span class=\"label\">".get_string("score", "lesson").'</span>'; $cells[] = $answer->score; $table->data[] = new html_table_row($cells); $cells = array(); $cells[] = "<span class=\"label\">".get_string("jump", "lesson").'</span>'; $cells[] = $this->get_jump_name($answer->jumpto); $table->data[] = new html_table_row($cells); if ($i === 1){ $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;'; } $i++; } return $table; } public function stats(array &$pagestats, $tries) { if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt $temp = $tries[$this->lesson->maxattempts - 1]; } else { // else, user attempted the question less than the max, so grab the last one $temp = end($tries); } if (isset($pagestats[$temp->pageid][$temp->useranswer])) { $pagestats[$temp->pageid][$temp->useranswer]++; } else { $pagestats[$temp->pageid][$temp->useranswer] = 1; } if (isset($pagestats[$temp->pageid]["total"])) { $pagestats[$temp->pageid]["total"]++; } else { $pagestats[$temp->pageid]["total"] = 1; } return true; } public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) { $answers = $this->get_answers(); $formattextdefoptions = new stdClass; $formattextdefoptions->para = false; //I'll use it widely in this page foreach ($answers as $answer) { if ($useranswer == null && $i == 0) { // I have the $i == 0 because it is easier to blast through it all at once. if (isset($pagestats[$this->properties->id])) { $stats = $pagestats[$this->properties->id]; $total = $stats["total"]; unset($stats["total"]); foreach ($stats as $valentered => $ntimes) { $data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($valentered).'" />'; $percent = $ntimes / $total * 100; $percent = round($percent, 2); $percent .= "% ".get_string("enteredthis", "lesson"); $answerdata->answers[] = array($data, $percent); } } else { $answerdata->answers[] = array(get_string("nooneansweredthisquestion", "lesson"), " "); } $i++; } else if ($useranswer != null && ($answer->id == $useranswer->answerid || ($answer == end($answers) && empty($answerdata)))) { // get in here when what the user entered is not one of the answers $data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($useranswer->useranswer).'">'; if (isset($pagestats[$this->properties->id][$useranswer->useranswer])) { $percent = $pagestats[$this->properties->id][$useranswer->useranswer] / $pagestats[$this->properties->id]["total"] * 100; $percent = round($percent, 2); $percent .= "% ".get_string("enteredthis", "lesson"); } else { $percent = get_string("nooneenteredthis", "lesson"); } $answerdata->answers[] = array($data, $percent); if ($answer->id == $useranswer->answerid) { if ($answer->response == NULL) { if ($useranswer->correct) { $answerdata->response = get_string("thatsthecorrectanswer", "lesson"); } else { $answerdata->response = get_string("thatsthewronganswer", "lesson"); } } else { $answerdata->response = $answer->response; } if ($this->lesson->custom) { $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score; } elseif ($useranswer->correct) { $answerdata->score = get_string("receivedcredit", "lesson"); } else { $answerdata->score = get_string("didnotreceivecredit", "lesson"); } } else { $answerdata->response = get_string("thatsthewronganswer", "lesson"); if ($this->lesson->custom) { $answerdata->score = get_string("pointsearned", "lesson").": 0"; } else { $answerdata->score = get_string("didnotreceivecredit", "lesson"); } } } $answerpage->answerdata = $answerdata; } return $answerpage; } } class lesson_add_page_form_shortanswer extends lesson_add_page_form_base { public $qtype = 'shortanswer'; public $qtypestring = 'shortanswer'; public function custom_definition() { $this->_form->addElement('checkbox', 'qoption', get_string('options', 'lesson'), get_string('casesensitive', 'lesson')); //oh my, this is a regex option! $this->_form->setDefault('qoption', 0); $this->_form->addHelpButton('qoption', 'casesensitive', 'lesson'); for ($i = 0; $i < $this->_customdata['lesson']->maxanswers; $i++) { $this->_form->addElement('header', 'answertitle'.$i, get_string('answer').' '.($i+1)); $this->add_answer($i); $this->add_response($i); $this->add_jumpto($i, NULL, ($i == 0 ? LESSON_NEXTPAGE : LESSON_THISPAGE)); $this->add_score($i, null, ($i===0)?1:0); } } } class lesson_display_answer_form_shortanswer extends moodleform { public function definition() { global $OUTPUT; $mform = $this->_form; $contents = $this->_customdata['contents']; $mform->addElement('header', 'pageheader', $OUTPUT->box($contents, 'contents')); $options = new stdClass; $options->para = false; $options->noclean = true; $mform->addElement('hidden', 'id'); $mform->setType('id', PARAM_INT); $mform->addElement('hidden', 'pageid'); $mform->setType('pageid', PARAM_INT); $mform->addElement('text', 'answer', get_string('youranswer', 'lesson'), array('size'=>'50', 'maxlength'=>'200')); $mform->setType('answer', PARAM_TEXT); $this->add_action_buttons(null, get_string("pleaseenteryouranswerinthebox", "lesson")); } }
vuchannguyen/web
mod/lesson/pagetypes/shortanswer.php
PHP
gpl-3.0
15,979
#include <AP_HAL/AP_HAL.h> #include "AC_PrecLand.h" #include "AC_PrecLand_Backend.h" #include "AC_PrecLand_Companion.h" #include "AC_PrecLand_IRLock.h" #include "AC_PrecLand_SITL_Gazebo.h" #include "AC_PrecLand_SITL.h" extern const AP_HAL::HAL& hal; const AP_Param::GroupInfo AC_PrecLand::var_info[] = { // @Param: ENABLED // @DisplayName: Precision Land enabled/disabled and behaviour // @Description: Precision Land enabled/disabled and behaviour // @Values: 0:Disabled, 1:Enabled Always Land, 2:Enabled Strict // @User: Advanced AP_GROUPINFO_FLAGS("ENABLED", 0, AC_PrecLand, _enabled, 0, AP_PARAM_FLAG_ENABLE), // @Param: TYPE // @DisplayName: Precision Land Type // @Description: Precision Land Type // @Values: 0:None, 1:CompanionComputer, 2:IRLock, 3:SITL_Gazebo, 4:SITL // @User: Advanced AP_GROUPINFO("TYPE", 1, AC_PrecLand, _type, 0), // @Param: YAW_ALIGN // @DisplayName: Sensor yaw alignment // @Description: Yaw angle from body x-axis to sensor x-axis. // @Range: 0 360 // @Increment: 1 // @User: Advanced // @Units: Centi-degrees AP_GROUPINFO("YAW_ALIGN", 2, AC_PrecLand, _yaw_align, 0), // @Param: LAND_OFS_X // @DisplayName: Land offset forward // @Description: Desired landing position of the camera forward of the target in vehicle body frame // @Range: -20 20 // @Increment: 1 // @User: Advanced // @Units: Centimeters AP_GROUPINFO("LAND_OFS_X", 3, AC_PrecLand, _land_ofs_cm_x, 0), // @Param: LAND_OFS_Y // @DisplayName: Land offset right // @Description: desired landing position of the camera right of the target in vehicle body frame // @Range: -20 20 // @Increment: 1 // @User: Advanced // @Units: Centimeters AP_GROUPINFO("LAND_OFS_Y", 4, AC_PrecLand, _land_ofs_cm_y, 0), // 5 RESERVED for EKF_TYPE // 6 RESERVED for ACC_NSE AP_GROUPEND }; // Default constructor. // Note that the Vector/Matrix constructors already implicitly zero // their values. // AC_PrecLand::AC_PrecLand(const AP_AHRS& ahrs, const AP_InertialNav& inav) : _ahrs(ahrs), _inav(inav), _last_update_ms(0), _last_backend_los_meas_ms(0), _backend(nullptr) { // set parameters to defaults AP_Param::setup_object_defaults(this, var_info); // other initialisation _backend_state.healthy = false; } // init - perform any required initialisation of backends void AC_PrecLand::init() { // exit immediately if init has already been run if (_backend != nullptr) { return; } // default health to false _backend = nullptr; _backend_state.healthy = false; // instantiate backend based on type parameter switch ((enum PrecLandType)(_type.get())) { // no type defined case PRECLAND_TYPE_NONE: default: return; // companion computer case PRECLAND_TYPE_COMPANION: _backend = new AC_PrecLand_Companion(*this, _backend_state); break; // IR Lock #if CONFIG_HAL_BOARD == HAL_BOARD_PX4 || CONFIG_HAL_BOARD == HAL_BOARD_VRBRAIN case PRECLAND_TYPE_IRLOCK: _backend = new AC_PrecLand_IRLock(*this, _backend_state); break; #endif #if CONFIG_HAL_BOARD == HAL_BOARD_SITL case PRECLAND_TYPE_SITL_GAZEBO: _backend = new AC_PrecLand_SITL_Gazebo(*this, _backend_state); break; case PRECLAND_TYPE_SITL: _backend = new AC_PrecLand_SITL(*this, _backend_state); break; #endif } // init backend if (_backend != nullptr) { _backend->init(); } } // update - give chance to driver to get updates from sensor void AC_PrecLand::update(float rangefinder_alt_cm, bool rangefinder_alt_valid) { _attitude_history.push_back(_ahrs.get_rotation_body_to_ned()); // run backend update if (_backend != nullptr && _enabled) { // read from sensor _backend->update(); Vector3f vehicleVelocityNED = _inav.get_velocity()*0.01f; vehicleVelocityNED.z = -vehicleVelocityNED.z; if (target_acquired()) { // EKF prediction step float dt; Vector3f targetDelVel; _ahrs.getCorrectedDeltaVelocityNED(targetDelVel, dt); targetDelVel = -targetDelVel; _ekf_x.predict(dt, targetDelVel.x, 0.5f*dt); _ekf_y.predict(dt, targetDelVel.y, 0.5f*dt); } if (_backend->have_los_meas() && _backend->los_meas_time_ms() != _last_backend_los_meas_ms) { // we have a new, unique los measurement _last_backend_los_meas_ms = _backend->los_meas_time_ms(); Vector3f target_vec_unit_body; _backend->get_los_body(target_vec_unit_body); // Apply sensor yaw alignment rotation float sin_yaw_align = sinf(radians(_yaw_align*0.01f)); float cos_yaw_align = cosf(radians(_yaw_align*0.01f)); Matrix3f Rz = Matrix3f( cos_yaw_align, -sin_yaw_align, 0, sin_yaw_align, cos_yaw_align, 0, 0, 0, 1 ); Vector3f target_vec_unit_ned = _attitude_history.front() * Rz * target_vec_unit_body; bool target_vec_valid = target_vec_unit_ned.z > 0.0f; bool alt_valid = (rangefinder_alt_valid && rangefinder_alt_cm > 0.0f) || (_backend->distance_to_target() > 0.0f); if (target_vec_valid && alt_valid) { float alt; if (_backend->distance_to_target() > 0.0f) { alt = _backend->distance_to_target(); } else { alt = MAX(rangefinder_alt_cm*0.01f, 0.0f); } float dist = alt/target_vec_unit_ned.z; Vector3f targetPosRelMeasNED = Vector3f(target_vec_unit_ned.x*dist, target_vec_unit_ned.y*dist, alt); float xy_pos_var = sq(targetPosRelMeasNED.z*(0.01f + 0.01f*_ahrs.get_gyro().length()) + 0.02f); if (!target_acquired()) { // reset filter state if (_inav.get_filter_status().flags.horiz_pos_rel) { _ekf_x.init(targetPosRelMeasNED.x, xy_pos_var, -vehicleVelocityNED.x, sq(2.0f)); _ekf_y.init(targetPosRelMeasNED.y, xy_pos_var, -vehicleVelocityNED.y, sq(2.0f)); } else { _ekf_x.init(targetPosRelMeasNED.x, xy_pos_var, 0.0f, sq(10.0f)); _ekf_y.init(targetPosRelMeasNED.y, xy_pos_var, 0.0f, sq(10.0f)); } _last_update_ms = AP_HAL::millis(); } else { float NIS_x = _ekf_x.getPosNIS(targetPosRelMeasNED.x, xy_pos_var); float NIS_y = _ekf_y.getPosNIS(targetPosRelMeasNED.y, xy_pos_var); if (MAX(NIS_x, NIS_y) < 3.0f || _outlier_reject_count >= 3) { _outlier_reject_count = 0; _ekf_x.fusePos(targetPosRelMeasNED.x, xy_pos_var); _ekf_y.fusePos(targetPosRelMeasNED.y, xy_pos_var); _last_update_ms = AP_HAL::millis(); } else { _outlier_reject_count++; } } } } } } bool AC_PrecLand::target_acquired() const { return (AP_HAL::millis()-_last_update_ms) < 2000; } bool AC_PrecLand::get_target_position_cm(Vector2f& ret) const { if (!target_acquired()) { return false; } Vector3f land_ofs_ned_cm = _ahrs.get_rotation_body_to_ned() * Vector3f(_land_ofs_cm_x,_land_ofs_cm_y,0); ret.x = _ekf_x.getPos()*100.0f + _inav.get_position().x + land_ofs_ned_cm.x; ret.y = _ekf_y.getPos()*100.0f + _inav.get_position().y + land_ofs_ned_cm.y; return true; } bool AC_PrecLand::get_target_position_relative_cm(Vector2f& ret) const { if (!target_acquired()) { return false; } Vector3f land_ofs_ned_cm = _ahrs.get_rotation_body_to_ned() * Vector3f(_land_ofs_cm_x,_land_ofs_cm_y,0); ret.x = _ekf_x.getPos()*100.0f + land_ofs_ned_cm.x; ret.y = _ekf_y.getPos()*100.0f + land_ofs_ned_cm.y; return true; } bool AC_PrecLand::get_target_velocity_relative_cms(Vector2f& ret) const { if (!target_acquired()) { return false; } ret.x = _ekf_x.getVel()*100.0f; ret.y = _ekf_y.getVel()*100.0f; return true; } // handle_msg - Process a LANDING_TARGET mavlink message void AC_PrecLand::handle_msg(mavlink_message_t* msg) { // run backend update if (_backend != nullptr) { _backend->handle_msg(msg); } }
farmer-martin/ardupilot
libraries/AC_PrecLand/AC_PrecLand.cpp
C++
gpl-3.0
8,721
--TEST-- IntlTimeZone::createEnumeration(): variant with country --SKIPIF-- <?php if (!extension_loaded('intl')) die('skip intl extension not enabled'); --FILE-- <?php ini_set("intl.error_level", E_WARNING); $tz = IntlTimeZone::createEnumeration('NL'); var_dump(get_class($tz)); $count = count(iterator_to_array($tz)); var_dump($count >= 1); $tz->rewind(); var_dump(in_array('Europe/Amsterdam', iterator_to_array($tz))); ?> ==DONE== --EXPECT-- string(12) "IntlIterator" bool(true) bool(true) ==DONE==
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/php-5.5.11/ext/intl/tests/timezone_createEnumeration_variation2.phpt
PHP
gpl-3.0
504
function rewriteTaskTitles(blockid) { forEach( getElementsByTagAndClassName('a', 'task-title', 'tasktable_' + blockid), function(element) { disconnectAll(element); connect(element, 'onclick', function(e) { e.stop(); var description = getFirstElementByTagAndClassName('div', 'task-desc', element.parentNode); toggleElementClass('hidden', description); }); } ); } function TaskPager(blockid) { var self = this; paginatorProxy.addObserver(self); connect(self, 'pagechanged', partial(rewriteTaskTitles, blockid)); } var taskPagers = []; function initNewPlansBlock(blockid) { if ($('plans_page_container_' + blockid)) { new Paginator('block' + blockid + '_pagination', 'tasktable_' + blockid, 'artefact/plans/viewtasks.json.php', null); taskPagers.push(new TaskPager(blockid)); } rewriteTaskTitles(blockid); }
eireford/mahara
htdocs/artefact/plans/blocktype/plans/js/plansblock.js
JavaScript
gpl-3.0
963
/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.lookup; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.compiler.util.HashtableOfObject; public class ClassScope extends Scope { public TypeDeclaration referenceContext; private TypeReference superTypeReference; private final static char[] IncompleteHierarchy = new char[] {'h', 'a', 's', ' ', 'i', 'n', 'c', 'o', 'n', 's', 'i', 's', 't', 'e', 'n', 't', ' ', 'h', 'i', 'e', 'r', 'a', 'r', 'c', 'h', 'y'}; public ClassScope(Scope parent, TypeDeclaration context) { super(CLASS_SCOPE, parent); this.referenceContext = context; } void buildAnonymousTypeBinding(SourceTypeBinding enclosingType, ReferenceBinding supertype) { LocalTypeBinding anonymousType = buildLocalType(enclosingType, enclosingType.fPackage); SourceTypeBinding sourceType = referenceContext.binding; if (supertype.isInterface()) { sourceType.superclass = getJavaLangObject(); sourceType.superInterfaces = new ReferenceBinding[] { supertype }; } else { sourceType.superclass = supertype; sourceType.superInterfaces = TypeConstants.NoSuperInterfaces; } connectMemberTypes(); buildFieldsAndMethods(); anonymousType.faultInTypesForFieldsAndMethods(); sourceType.verifyMethods(environment().methodVerifier()); } private void buildFields() { boolean hierarchyIsInconsistent = referenceContext.binding.isHierarchyInconsistent(); if (referenceContext.fields == null) { if (hierarchyIsInconsistent) { // 72468 referenceContext.binding.fields = new FieldBinding[1]; referenceContext.binding.fields[0] = new FieldBinding(IncompleteHierarchy, VoidBinding, AccPrivate, referenceContext.binding, null); } else { referenceContext.binding.fields = NoFields; } return; } // count the number of fields vs. initializers FieldDeclaration[] fields = referenceContext.fields; int size = fields.length; int count = 0; for (int i = 0; i < size; i++) if (fields[i].isField()) count++; if (hierarchyIsInconsistent) count++; // iterate the field declarations to create the bindings, lose all duplicates FieldBinding[] fieldBindings = new FieldBinding[count]; HashtableOfObject knownFieldNames = new HashtableOfObject(count); boolean duplicate = false; count = 0; for (int i = 0; i < size; i++) { FieldDeclaration field = fields[i]; if (!field.isField()) { if (referenceContext.binding.isInterface()) problemReporter().interfaceCannotHaveInitializers(referenceContext.binding, field); } else { FieldBinding fieldBinding = new FieldBinding(field, null, field.modifiers | AccUnresolved, referenceContext.binding); // field's type will be resolved when needed for top level types checkAndSetModifiersForField(fieldBinding, field); if (knownFieldNames.containsKey(field.name)) { duplicate = true; FieldBinding previousBinding = (FieldBinding) knownFieldNames.get(field.name); if (previousBinding != null) { for (int f = 0; f < i; f++) { FieldDeclaration previousField = fields[f]; if (previousField.binding == previousBinding) { problemReporter().duplicateFieldInType(referenceContext.binding, previousField); previousField.binding = null; break; } } } knownFieldNames.put(field.name, null); // ensure that the duplicate field is found & removed problemReporter().duplicateFieldInType(referenceContext.binding, field); field.binding = null; } else { knownFieldNames.put(field.name, fieldBinding); // remember that we have seen a field with this name if (fieldBinding != null) fieldBindings[count++] = fieldBinding; } } } // remove duplicate fields if (duplicate) { FieldBinding[] newFieldBindings = new FieldBinding[knownFieldNames.size() - 1]; // we know we'll be removing at least 1 duplicate name size = count; count = 0; for (int i = 0; i < size; i++) { FieldBinding fieldBinding = fieldBindings[i]; if (knownFieldNames.get(fieldBinding.name) != null) newFieldBindings[count++] = fieldBinding; } fieldBindings = newFieldBindings; } if (hierarchyIsInconsistent) fieldBindings[count++] = new FieldBinding(IncompleteHierarchy, VoidBinding, AccPrivate, referenceContext.binding, null); if (count != fieldBindings.length) System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count); for (int i = 0; i < count; i++) fieldBindings[i].id = i; referenceContext.binding.fields = fieldBindings; } void buildFieldsAndMethods() { buildFields(); buildMethods(); SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.isMemberType() && !sourceType.isLocalType()) ((MemberTypeBinding) sourceType).checkSyntheticArgsAndFields(); ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) ((SourceTypeBinding) memberTypes[i]).scope.buildFieldsAndMethods(); } private LocalTypeBinding buildLocalType( SourceTypeBinding enclosingType, PackageBinding packageBinding) { referenceContext.scope = this; referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true); referenceContext.initializerScope = new MethodScope(this, referenceContext, false); // build the binding or the local type LocalTypeBinding localType = new LocalTypeBinding(this, enclosingType, this.switchCase()); referenceContext.binding = localType; checkAndSetModifiers(); buildTypeVariables(); // Look at member types ReferenceBinding[] memberTypeBindings = NoMemberTypes; if (referenceContext.memberTypes != null) { int size = referenceContext.memberTypes.length; memberTypeBindings = new ReferenceBinding[size]; int count = 0; nextMember : for (int i = 0; i < size; i++) { TypeDeclaration memberContext = referenceContext.memberTypes[i]; if (memberContext.isInterface()) { problemReporter().nestedClassCannotDeclareInterface(memberContext); continue nextMember; } ReferenceBinding type = localType; // check that the member does not conflict with an enclosing type do { if (CharOperation.equals(type.sourceName, memberContext.name)) { problemReporter().hidingEnclosingType(memberContext); continue nextMember; } type = type.enclosingType(); } while (type != null); // check the member type does not conflict with another sibling member type for (int j = 0; j < i; j++) { if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) { problemReporter().duplicateNestedType(memberContext); continue nextMember; } } ClassScope memberScope = new ClassScope(this, referenceContext.memberTypes[i]); LocalTypeBinding memberBinding = memberScope.buildLocalType(localType, packageBinding); memberBinding.setAsMemberType(); memberTypeBindings[count++] = memberBinding; } if (count != size) System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count); } localType.memberTypes = memberTypeBindings; return localType; } void buildLocalTypeBinding(SourceTypeBinding enclosingType) { LocalTypeBinding localType = buildLocalType(enclosingType, enclosingType.fPackage); connectTypeHierarchy(); buildFieldsAndMethods(); localType.faultInTypesForFieldsAndMethods(); referenceContext.binding.verifyMethods(environment().methodVerifier()); } private void buildMemberTypes() { SourceTypeBinding sourceType = referenceContext.binding; ReferenceBinding[] memberTypeBindings = NoMemberTypes; if (referenceContext.memberTypes != null) { int length = referenceContext.memberTypes.length; memberTypeBindings = new ReferenceBinding[length]; int count = 0; nextMember : for (int i = 0; i < length; i++) { TypeDeclaration memberContext = referenceContext.memberTypes[i]; if (memberContext.isInterface() && sourceType.isNestedType() && sourceType.isClass() && !sourceType.isStatic()) { problemReporter().nestedClassCannotDeclareInterface(memberContext); continue nextMember; } ReferenceBinding type = sourceType; // check that the member does not conflict with an enclosing type do { if (CharOperation.equals(type.sourceName, memberContext.name)) { problemReporter().hidingEnclosingType(memberContext); continue nextMember; } type = type.enclosingType(); } while (type != null); // check that the member type does not conflict with another sibling member type for (int j = 0; j < i; j++) { if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) { problemReporter().duplicateNestedType(memberContext); continue nextMember; } } ClassScope memberScope = new ClassScope(this, memberContext); memberTypeBindings[count++] = memberScope.buildType(sourceType, sourceType.fPackage); } if (count != length) System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count); } sourceType.memberTypes = memberTypeBindings; } private void buildMethods() { if (referenceContext.methods == null) { referenceContext.binding.methods = NoMethods; return; } // iterate the method declarations to create the bindings AbstractMethodDeclaration[] methods = referenceContext.methods; int size = methods.length; int clinitIndex = -1; for (int i = 0; i < size; i++) { if (methods[i] instanceof Clinit) { clinitIndex = i; break; } } MethodBinding[] methodBindings = new MethodBinding[clinitIndex == -1 ? size : size - 1]; int count = 0; for (int i = 0; i < size; i++) { if (i != clinitIndex) { MethodScope scope = new MethodScope(this, methods[i], false); MethodBinding methodBinding = scope.createMethod(methods[i]); if (methodBinding != null) // is null if binding could not be created methodBindings[count++] = methodBinding; } } if (count != methodBindings.length) System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count); referenceContext.binding.methods = methodBindings; referenceContext.binding.modifiers |= AccUnresolved; // until methods() is sent } SourceTypeBinding buildType(SourceTypeBinding enclosingType, PackageBinding packageBinding) { // provide the typeDeclaration with needed scopes referenceContext.scope = this; referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true); referenceContext.initializerScope = new MethodScope(this, referenceContext, false); if (enclosingType == null) { char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, referenceContext.name); referenceContext.binding = new SourceTypeBinding(className, packageBinding, this); } else { char[][] className = CharOperation.deepCopy(enclosingType.compoundName); className[className.length - 1] = CharOperation.concat(className[className.length - 1], referenceContext.name, '$'); referenceContext.binding = new MemberTypeBinding(className, this, enclosingType); } SourceTypeBinding sourceType = referenceContext.binding; sourceType.fPackage.addType(sourceType); checkAndSetModifiers(); buildTypeVariables(); buildMemberTypes(); return sourceType; } private void buildTypeVariables() { SourceTypeBinding sourceType = referenceContext.binding; TypeParameter[] typeParameters = referenceContext.typeParameters; // do not construct type variables if source < 1.5 if (typeParameters == null || environment().options.sourceLevel < ClassFileConstants.JDK1_5) { sourceType.typeVariables = NoTypeVariables; return; } sourceType.typeVariables = NoTypeVariables; // safety if (sourceType.id == T_Object) { // handle the case of redefining java.lang.Object up front problemReporter().objectCannotBeGeneric(referenceContext); return; } sourceType.typeVariables = createTypeVariables(typeParameters, sourceType); sourceType.modifiers |= AccGenericSignature; } private void checkAndSetModifiers() { SourceTypeBinding sourceType = referenceContext.binding; int modifiers = sourceType.modifiers; if ((modifiers & AccAlternateModifierProblem) != 0) problemReporter().duplicateModifierForType(sourceType); ReferenceBinding enclosingType = sourceType.enclosingType(); boolean isMemberType = sourceType.isMemberType(); if (isMemberType) { // checks for member types before local types to catch local members if (enclosingType.isStrictfp()) modifiers |= AccStrictfp; if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; if (enclosingType.isInterface()) modifiers |= AccPublic; } else if (sourceType.isLocalType()) { if (sourceType.isAnonymousType()) modifiers |= AccFinal; Scope scope = this; do { switch (scope.kind) { case METHOD_SCOPE : MethodScope methodScope = (MethodScope) scope; if (methodScope.isInsideInitializer()) { SourceTypeBinding type = ((TypeDeclaration) methodScope.referenceContext).binding; // inside field declaration ? check field modifier to see if deprecated if (methodScope.initializedField != null) { // currently inside this field initialization if (methodScope.initializedField.isViewedAsDeprecated() && !sourceType.isDeprecated()){ modifiers |= AccDeprecatedImplicitly; } } else { if (type.isStrictfp()) modifiers |= AccStrictfp; if (type.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; } } else { MethodBinding method = ((AbstractMethodDeclaration) methodScope.referenceContext).binding; if (method != null){ if (method.isStrictfp()) modifiers |= AccStrictfp; if (method.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; } } break; case CLASS_SCOPE : // local member if (enclosingType.isStrictfp()) modifiers |= AccStrictfp; if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; break; } scope = scope.parent; } while (scope != null); } // after this point, tests on the 16 bits reserved. int realModifiers = modifiers & AccJustFlag; if ((realModifiers & AccInterface) != 0) { // detect abnormal cases for interfaces if (isMemberType) { int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccInterface | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForMemberInterface(sourceType); /* } else if (sourceType.isLocalType()) { //interfaces cannot be defined inside a method int unexpectedModifiers = ~(AccAbstract | AccInterface | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForLocalInterface(sourceType); */ } else { int unexpectedModifiers = ~(AccPublic | AccAbstract | AccInterface | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForInterface(sourceType); } modifiers |= AccAbstract; } else { // detect abnormal cases for types if (isMemberType) { // includes member types defined inside local types int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccFinal | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForMemberClass(sourceType); } else if (sourceType.isLocalType()) { int unexpectedModifiers = ~(AccAbstract | AccFinal | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForLocalClass(sourceType); } else { int unexpectedModifiers = ~(AccPublic | AccAbstract | AccFinal | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForClass(sourceType); } // check that Final and Abstract are not set together if ((realModifiers & (AccFinal | AccAbstract)) == (AccFinal | AccAbstract)) problemReporter().illegalModifierCombinationFinalAbstractForClass(sourceType); } if (isMemberType) { // test visibility modifiers inconsistency, isolate the accessors bits if (enclosingType.isInterface()) { if ((realModifiers & (AccProtected | AccPrivate)) != 0) { problemReporter().illegalVisibilityModifierForInterfaceMemberType(sourceType); // need to keep the less restrictive if ((realModifiers & AccProtected) != 0) modifiers ^= AccProtected; if ((realModifiers & AccPrivate) != 0) modifiers ^= AccPrivate; } } else { int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) > 1) { problemReporter().illegalVisibilityModifierCombinationForMemberType(sourceType); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { if ((accessorBits & AccProtected) != 0) modifiers ^= AccProtected; if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } if ((accessorBits & AccProtected) != 0) if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } } // static modifier test if ((realModifiers & AccStatic) == 0) { if (enclosingType.isInterface()) modifiers |= AccStatic; } else { if (!enclosingType.isStatic()) // error the enclosing type of a static field must be static or a top-level type problemReporter().illegalStaticModifierForMemberType(sourceType); } } sourceType.modifiers = modifiers; } /* This method checks the modifiers of a field. * * 9.3 & 8.3 * Need to integrate the check for the final modifiers for nested types * * Note : A scope is accessible by : fieldBinding.declaringClass.scope */ private void checkAndSetModifiersForField(FieldBinding fieldBinding, FieldDeclaration fieldDecl) { int modifiers = fieldBinding.modifiers; if ((modifiers & AccAlternateModifierProblem) != 0) problemReporter().duplicateModifierForField(fieldBinding.declaringClass, fieldDecl); if (fieldBinding.declaringClass.isInterface()) { int expectedValue = AccPublic | AccStatic | AccFinal; // set the modifiers modifiers |= expectedValue; // and then check that they are the only ones if ((modifiers & AccJustFlag) != expectedValue) problemReporter().illegalModifierForInterfaceField(fieldBinding.declaringClass, fieldDecl); fieldBinding.modifiers = modifiers; return; } // after this point, tests on the 16 bits reserved. int realModifiers = modifiers & AccJustFlag; int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected | AccFinal | AccStatic | AccTransient | AccVolatile); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForField(fieldBinding.declaringClass, fieldDecl); int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) > 1) { problemReporter().illegalVisibilityModifierCombinationForField( fieldBinding.declaringClass, fieldDecl); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { if ((accessorBits & AccProtected) != 0) modifiers ^= AccProtected; if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } if ((accessorBits & AccProtected) != 0) if ((accessorBits & AccPrivate) != 0) modifiers ^= AccPrivate; } if ((realModifiers & (AccFinal | AccVolatile)) == (AccFinal | AccVolatile)) problemReporter().illegalModifierCombinationFinalVolatileForField( fieldBinding.declaringClass, fieldDecl); if (fieldDecl.initialization == null && (modifiers & AccFinal) != 0) { modifiers |= AccBlankFinal; } fieldBinding.modifiers = modifiers; } private void checkForInheritedMemberTypes(SourceTypeBinding sourceType) { // search up the hierarchy of the sourceType to see if any superType defines a member type // when no member types are defined, tag the sourceType & each superType with the HasNoMemberTypes bit // assumes super types have already been checked & tagged ReferenceBinding currentType = sourceType; ReferenceBinding[][] interfacesToVisit = null; int lastPosition = -1; do { if (currentType.hasMemberTypes()) // avoid resolving member types eagerly return; ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (interfacesToVisit == null) interfacesToVisit = new ReferenceBinding[5][]; if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } while ((currentType = currentType.superclass()) != null && (currentType.tagBits & HasNoMemberTypes) == 0); if (interfacesToVisit != null) { // contains the interfaces between the sourceType and any superclass, which was tagged as having no member types boolean needToTag = false; for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) { ReferenceBinding anInterface = interfaces[j]; if ((anInterface.tagBits & HasNoMemberTypes) == 0) { // skip interface if it already knows it has no member types if (anInterface.hasMemberTypes()) // avoid resolving member types eagerly return; needToTag = true; ReferenceBinding[] itsInterfaces = anInterface.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } } } if (needToTag) { for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) interfaces[j].tagBits |= HasNoMemberTypes; } } } // tag the sourceType and all of its superclasses, unless they have already been tagged currentType = sourceType; do { currentType.tagBits |= HasNoMemberTypes; } while ((currentType = currentType.superclass()) != null && (currentType.tagBits & HasNoMemberTypes) == 0); } // Perform deferred bound checks for parameterized type references (only done after hierarchy is connected) private void checkParameterizedTypeBounds() { TypeReference superclass = referenceContext.superclass; if (superclass != null) { superclass.checkBounds(this); } TypeReference[] superinterfaces = referenceContext.superInterfaces; if (superinterfaces != null) { for (int i = 0, length = superinterfaces.length; i < length; i++) { superinterfaces[i].checkBounds(this); } } TypeParameter[] typeParameters = referenceContext.typeParameters; if (typeParameters != null) { for (int i = 0, paramLength = typeParameters.length; i < paramLength; i++) { TypeParameter typeParameter = typeParameters[i]; TypeReference typeRef = typeParameter.type; if (typeRef != null) { typeRef.checkBounds(this); TypeReference[] boundRefs = typeParameter.bounds; if (boundRefs != null) for (int j = 0, k = boundRefs.length; j < k; j++) boundRefs[j].checkBounds(this); } } } } private void connectMemberTypes() { SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.memberTypes != NoMemberTypes) for (int i = 0, size = sourceType.memberTypes.length; i < size; i++) ((SourceTypeBinding) sourceType.memberTypes[i]).scope.connectTypeHierarchy(); } /* Our current belief based on available JCK tests is: inherited member types are visible as a potential superclass. inherited interfaces are not visible when defining a superinterface. Error recovery story: ensure the superclass is set to java.lang.Object if a problem is detected resolving the superclass. Answer false if an error was reported against the sourceType. */ private boolean connectSuperclass() { SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.id == T_Object) { // handle the case of redefining java.lang.Object up front sourceType.superclass = null; sourceType.superInterfaces = NoSuperInterfaces; if (referenceContext.superclass != null || referenceContext.superInterfaces != null) problemReporter().objectCannotHaveSuperTypes(sourceType); return true; // do not propagate Object's hierarchy problems down to every subtype } if (referenceContext.superclass == null) { sourceType.superclass = getJavaLangObject(); return !detectCycle(sourceType, sourceType.superclass, null); } TypeReference superclassRef = referenceContext.superclass; ReferenceBinding superclass = findSupertype(superclassRef); if (superclass != null) { // is null if a cycle was detected cycle or a problem if (superclass.isInterface()) { problemReporter().superclassMustBeAClass(sourceType, superclassRef, superclass); } else if (superclass.isFinal()) { problemReporter().classExtendFinalClass(sourceType, superclassRef, superclass); } else if ((superclass.tagBits & TagBits.HasWildcard) != 0) { problemReporter().superTypeCannotUseWildcard(sourceType, superclassRef, superclass); } else { // only want to reach here when no errors are reported sourceType.superclass = superclass; return true; } } sourceType.tagBits |= HierarchyHasProblems; sourceType.superclass = getJavaLangObject(); if ((sourceType.superclass.tagBits & BeginHierarchyCheck) == 0) detectCycle(sourceType, sourceType.superclass, null); return false; // reported some error against the source type } /* Our current belief based on available JCK 1.3 tests is: inherited member types are visible as a potential superclass. inherited interfaces are visible when defining a superinterface. Error recovery story: ensure the superinterfaces contain only valid visible interfaces. Answer false if an error was reported against the sourceType. */ private boolean connectSuperInterfaces() { SourceTypeBinding sourceType = referenceContext.binding; sourceType.superInterfaces = NoSuperInterfaces; if (referenceContext.superInterfaces == null) return true; if (sourceType.id == T_Object) // already handled the case of redefining java.lang.Object return true; boolean noProblems = true; int length = referenceContext.superInterfaces.length; ReferenceBinding[] interfaceBindings = new ReferenceBinding[length]; int count = 0; nextInterface : for (int i = 0; i < length; i++) { TypeReference superInterfaceRef = referenceContext.superInterfaces[i]; ReferenceBinding superInterface = findSupertype(superInterfaceRef); if (superInterface == null) { // detected cycle sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } superInterfaceRef.resolvedType = superInterface; // hold onto the problem type // Check for a duplicate interface once the name is resolved, otherwise we may be confused (ie : a.b.I and c.d.I) for (int k = 0; k < count; k++) { if (interfaceBindings[k] == superInterface) { // should this be treated as a warning? problemReporter().duplicateSuperinterface(sourceType, referenceContext, superInterface); continue nextInterface; } } if (superInterface.isClass()) { problemReporter().superinterfaceMustBeAnInterface(sourceType, superInterfaceRef, superInterface); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } if ((superInterface.tagBits & TagBits.HasWildcard) != 0) { problemReporter().superTypeCannotUseWildcard(sourceType, superInterfaceRef, superInterface); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } ReferenceBinding invalid = findAmbiguousInterface(superInterface, sourceType); if (invalid != null) { ReferenceBinding generic = null; if (superInterface.isParameterizedType()) generic = ((ParameterizedTypeBinding) superInterface).type; else if (invalid.isParameterizedType()) generic = ((ParameterizedTypeBinding) invalid).type; problemReporter().superinterfacesCollide(generic, referenceContext, superInterface, invalid); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } // only want to reach here when no errors are reported interfaceBindings[count++] = superInterface; } // hold onto all correctly resolved superinterfaces if (count > 0) { if (count != length) System.arraycopy(interfaceBindings, 0, interfaceBindings = new ReferenceBinding[count], 0, count); sourceType.superInterfaces = interfaceBindings; } return noProblems; } void connectTypeHierarchy() { SourceTypeBinding sourceType = referenceContext.binding; if ((sourceType.tagBits & BeginHierarchyCheck) == 0) { sourceType.tagBits |= BeginHierarchyCheck; boolean noProblems = connectTypeVariables(referenceContext.typeParameters); noProblems &= connectSuperclass(); noProblems &= connectSuperInterfaces(); sourceType.tagBits |= EndHierarchyCheck; if (noProblems && sourceType.isHierarchyInconsistent()) problemReporter().hierarchyHasProblems(sourceType); } // Perform deferred bound checks for parameterized type references (only done after hierarchy is connected) checkParameterizedTypeBounds(); connectMemberTypes(); try { checkForInheritedMemberTypes(sourceType); } catch (AbortCompilation e) { e.updateContext(referenceContext, referenceCompilationUnit().compilationResult); throw e; } } private void connectTypeHierarchyWithoutMembers() { // must ensure the imports are resolved if (parent instanceof CompilationUnitScope) { if (((CompilationUnitScope) parent).imports == null) ((CompilationUnitScope) parent).checkAndSetImports(); } else if (parent instanceof ClassScope) { // ensure that the enclosing type has already been checked ((ClassScope) parent).connectTypeHierarchyWithoutMembers(); } // double check that the hierarchy search has not already begun... SourceTypeBinding sourceType = referenceContext.binding; if ((sourceType.tagBits & BeginHierarchyCheck) != 0) return; sourceType.tagBits |= BeginHierarchyCheck; boolean noProblems = connectTypeVariables(referenceContext.typeParameters); noProblems &= connectSuperclass(); noProblems &= connectSuperInterfaces(); sourceType.tagBits |= EndHierarchyCheck; if (noProblems && sourceType.isHierarchyInconsistent()) problemReporter().hierarchyHasProblems(sourceType); } public boolean detectCycle(TypeBinding superType, TypeReference reference, TypeBinding[] argTypes) { if (!(superType instanceof ReferenceBinding)) return false; if (argTypes != null) { for (int i = 0, l = argTypes.length; i < l; i++) { TypeBinding argType = argTypes[i].leafComponentType(); if ((argType.tagBits & BeginHierarchyCheck) == 0 && argType instanceof SourceTypeBinding) // ensure if this is a source argument type that it has already been checked ((SourceTypeBinding) argType).scope.connectTypeHierarchyWithoutMembers(); } } if (reference == this.superTypeReference) { // see findSuperType() if (superType.isTypeVariable()) return false; // error case caught in resolveSuperType() // abstract class X<K,V> implements java.util.Map<K,V> // static abstract class M<K,V> implements Entry<K,V> if (superType.isParameterizedType()) superType = ((ParameterizedTypeBinding) superType).type; compilationUnitScope().recordSuperTypeReference(superType); // to record supertypes return detectCycle(referenceContext.binding, (ReferenceBinding) superType, reference); } if ((superType.tagBits & BeginHierarchyCheck) == 0 && superType instanceof SourceTypeBinding) // ensure if this is a source superclass that it has already been checked ((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers(); return false; } // Answer whether a cycle was found between the sourceType & the superType private boolean detectCycle(SourceTypeBinding sourceType, ReferenceBinding superType, TypeReference reference) { if (superType.isRawType()) superType = ((RawTypeBinding) superType).type; // by this point the superType must be a binary or source type if (sourceType == superType) { problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; return true; } if (superType.isMemberType()) { ReferenceBinding current = superType.enclosingType(); do { if (current.isHierarchyBeingConnected()) { problemReporter().hierarchyCircularity(sourceType, current, reference); sourceType.tagBits |= HierarchyHasProblems; current.tagBits |= HierarchyHasProblems; return true; } } while ((current = current.enclosingType()) != null); } if (superType.isBinaryBinding()) { // force its superclass & superinterfaces to be found... 2 possibilities exist - the source type is included in the hierarchy of: // - a binary type... this case MUST be caught & reported here // - another source type... this case is reported against the other source type boolean hasCycle = false; if (superType.superclass() != null) { if (sourceType == superType.superclass()) { problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } ReferenceBinding parentType = superType.superclass(); if (parentType.isParameterizedType()) parentType = ((ParameterizedTypeBinding) parentType).type; hasCycle |= detectCycle(sourceType, parentType, reference); if ((parentType.tagBits & HierarchyHasProblems) != 0) { sourceType.tagBits |= HierarchyHasProblems; parentType.tagBits |= HierarchyHasProblems; // propagate down the hierarchy } } ReferenceBinding[] itsInterfaces = superType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { for (int i = 0, length = itsInterfaces.length; i < length; i++) { ReferenceBinding anInterface = itsInterfaces[i]; if (sourceType == anInterface) { problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } if (anInterface.isParameterizedType()) anInterface = ((ParameterizedTypeBinding) anInterface).type; hasCycle |= detectCycle(sourceType, anInterface, reference); if ((anInterface.tagBits & HierarchyHasProblems) != 0) { sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; } } } return hasCycle; } if (superType.isHierarchyBeingConnected()) { if (((SourceTypeBinding) superType).scope.superTypeReference != null) { // if null then its connecting its type variables problemReporter().hierarchyCircularity(sourceType, superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } } if ((superType.tagBits & BeginHierarchyCheck) == 0) // ensure if this is a source superclass that it has already been checked ((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers(); if ((superType.tagBits & HierarchyHasProblems) != 0) sourceType.tagBits |= HierarchyHasProblems; return false; } private ReferenceBinding findAmbiguousInterface(ReferenceBinding newInterface, ReferenceBinding currentType) { TypeBinding newErasure = newInterface.erasure(); if (newInterface == newErasure) return null; ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; int lastPosition = -1; do { ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } while ((currentType = currentType.superclass()) != null); for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) { currentType = interfaces[j]; if (currentType.erasure() == newErasure) if (currentType != newInterface) return currentType; ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } } return null; } private ReferenceBinding findSupertype(TypeReference typeReference) { try { typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes compilationUnitScope().recordQualifiedReference(typeReference.getTypeName()); this.superTypeReference = typeReference; ReferenceBinding superType = (ReferenceBinding) typeReference.resolveSuperType(this); this.superTypeReference = null; return superType; } catch (AbortCompilation e) { e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; } } /* Answer the problem reporter to use for raising new problems. * * Note that as a side-effect, this updates the current reference context * (unit, type or method) in case the problem handler decides it is necessary * to abort. */ public ProblemReporter problemReporter() { MethodScope outerMethodScope; if ((outerMethodScope = outerMostMethodScope()) == null) { ProblemReporter problemReporter = referenceCompilationUnit().problemReporter; problemReporter.referenceContext = referenceContext; return problemReporter; } return outerMethodScope.problemReporter(); } /* Answer the reference type of this scope. * It is the nearest enclosing type of this scope. */ public TypeDeclaration referenceType() { return referenceContext; } public String toString() { if (referenceContext != null) return "--- Class Scope ---\n\n" //$NON-NLS-1$ + referenceContext.binding.toString(); return "--- Class Scope ---\n\n Binding not initialized" ; //$NON-NLS-1$ } }
Niky4000/UsefulUtils
projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/Compiler/src/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
Java
gpl-3.0
40,473
# Copyright (C) 2007, One Laptop Per Child # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
AbrahmAB/sugar
src/jarabe/journal/__init__.py
Python
gpl-3.0
679
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <jni.h> #include <vector> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "content/browser/android/content_view_statics.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/common/android/address_parser.h" #include "content/common/view_messages.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host_observer.h" #include "jni/ContentViewStatics_jni.h" using base::android::ConvertJavaStringToUTF16; using base::android::ConvertUTF16ToJavaString; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; namespace { // TODO(pliard): http://crbug.com/235909. Move WebKit shared timer toggling // functionality out of ContentViewStatistics and not be build on top of // blink::Platform::SuspendSharedTimer. // TODO(pliard): http://crbug.com/235912. Add unit tests for WebKit shared timer // toggling. // This tracks the renderer processes that received a suspend request. It's // important on resume to only resume the renderer processes that were actually // suspended as opposed to all the current renderer processes because the // suspend calls are refcounted within BlinkPlatformImpl and it expects a // perfectly matched number of resume calls. // Note that this class is only accessed from the UI thread. class SuspendedProcessWatcher : public content::RenderProcessHostObserver { public: // If the process crashes, stop watching the corresponding RenderProcessHost // and ensure it doesn't get over-resumed. void RenderProcessExited(content::RenderProcessHost* host, base::TerminationStatus status, int exit_code) override { StopWatching(host); } void RenderProcessHostDestroyed(content::RenderProcessHost* host) override { StopWatching(host); } // Suspends timers in all current render processes. void SuspendWebKitSharedTimers() { DCHECK(suspended_processes_.empty()); for (content::RenderProcessHost::iterator i( content::RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { content::RenderProcessHost* host = i.GetCurrentValue(); host->AddObserver(this); host->GetRendererInterface()->SetWebKitSharedTimersSuspended(true); suspended_processes_.push_back(host->GetID()); } } // Resumes timers in processes that were previously stopped. void ResumeWebkitSharedTimers() { for (std::vector<int>::const_iterator it = suspended_processes_.begin(); it != suspended_processes_.end(); ++it) { content::RenderProcessHost* host = content::RenderProcessHost::FromID(*it); DCHECK(host); host->RemoveObserver(this); host->GetRendererInterface()->SetWebKitSharedTimersSuspended(false); } suspended_processes_.clear(); } private: void StopWatching(content::RenderProcessHost* host) { std::vector<int>::iterator pos = std::find(suspended_processes_.begin(), suspended_processes_.end(), host->GetID()); DCHECK(pos != suspended_processes_.end()); host->RemoveObserver(this); suspended_processes_.erase(pos); } std::vector<int /* RenderProcessHost id */> suspended_processes_; }; base::LazyInstance<SuspendedProcessWatcher> g_suspended_processes_watcher = LAZY_INSTANCE_INITIALIZER; } // namespace // Returns the first substring consisting of the address of a physical location. static ScopedJavaLocalRef<jstring> FindAddress( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& addr) { base::string16 content_16 = ConvertJavaStringToUTF16(env, addr); base::string16 result_16; if (content::address_parser::FindAddress(content_16, &result_16)) return ConvertUTF16ToJavaString(env, result_16); return ScopedJavaLocalRef<jstring>(); } static void SetWebKitSharedTimersSuspended(JNIEnv* env, const JavaParamRef<jclass>& obj, jboolean suspend) { if (suspend) { g_suspended_processes_watcher.Pointer()->SuspendWebKitSharedTimers(); } else { g_suspended_processes_watcher.Pointer()->ResumeWebkitSharedTimers(); } } namespace content { bool RegisterWebViewStatics(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace content
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/content/browser/android/content_view_statics.cc
C++
gpl-3.0
4,753
#!/usr/bin/python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Certificate chain with 1 intermediate and a non-self-signed trust anchor. Verification should succeed, it doesn't matter that the root was not self-signed if it is designated as the trust anchor.""" import common uber_root = common.create_self_signed_root_certificate('UberRoot') # Non-self-signed root certificate (used as trust anchor) root = common.create_intermediate_certificate('Root', uber_root) # Intermediate certificate. intermediate = common.create_intermediate_certificate('Intermediate', root) # Target certificate. target = common.create_end_entity_certificate('Target', intermediate) chain = [target, intermediate] trusted = common.TrustAnchor(root, constrained=False) time = common.DEFAULT_TIME verify_result = True errors = None common.write_test_file(__doc__, chain, trusted, time, verify_result, errors)
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/net/data/verify_certificate_chain_unittest/generate-unconstrained-non-self-signed-root.py
Python
gpl-3.0
1,019
var searchData= [ ['matrix_5fbase',['MATRIX_BASE',['../memorymap_8h.html#a096dcc80deb3676aeb5d5b8db13cfeba',1,'memorymap.h']]] ];
Aghosh993/TARS_codebase
libopencm3/doc/sam3x/html/search/defines_7.js
JavaScript
gpl-3.0
132
namespace MissionPlanner { partial class GridUI { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GridUI)); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.lbl_turnrad = new System.Windows.Forms.Label(); this.label36 = new System.Windows.Forms.Label(); this.lbl_photoevery = new System.Windows.Forms.Label(); this.label35 = new System.Windows.Forms.Label(); this.lbl_flighttime = new System.Windows.Forms.Label(); this.label31 = new System.Windows.Forms.Label(); this.lbl_distbetweenlines = new System.Windows.Forms.Label(); this.label25 = new System.Windows.Forms.Label(); this.lbl_footprint = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.lbl_strips = new System.Windows.Forms.Label(); this.lbl_pictures = new System.Windows.Forms.Label(); this.label33 = new System.Windows.Forms.Label(); this.label34 = new System.Windows.Forms.Label(); this.lbl_grndres = new System.Windows.Forms.Label(); this.label29 = new System.Windows.Forms.Label(); this.lbl_spacing = new System.Windows.Forms.Label(); this.label27 = new System.Windows.Forms.Label(); this.lbl_distance = new System.Windows.Forms.Label(); this.lbl_area = new System.Windows.Forms.Label(); this.label23 = new System.Windows.Forms.Label(); this.label22 = new System.Windows.Forms.Label(); this.tabCamera = new System.Windows.Forms.TabPage(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.label18 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.NUM_repttime = new System.Windows.Forms.NumericUpDown(); this.num_reptpwm = new System.Windows.Forms.NumericUpDown(); this.NUM_reptservo = new System.Windows.Forms.NumericUpDown(); this.rad_digicam = new System.Windows.Forms.RadioButton(); this.rad_repeatservo = new System.Windows.Forms.RadioButton(); this.rad_trigdist = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.BUT_samplephoto = new MissionPlanner.Controls.MyButton(); this.label21 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.TXT_fovV = new System.Windows.Forms.TextBox(); this.TXT_fovH = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.TXT_cmpixel = new System.Windows.Forms.TextBox(); this.TXT_sensheight = new System.Windows.Forms.TextBox(); this.TXT_senswidth = new System.Windows.Forms.TextBox(); this.TXT_imgheight = new System.Windows.Forms.TextBox(); this.TXT_imgwidth = new System.Windows.Forms.TextBox(); this.NUM_focallength = new System.Windows.Forms.NumericUpDown(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.BUT_save = new MissionPlanner.Controls.MyButton(); this.tabGrid = new System.Windows.Forms.TabPage(); this.groupBox7 = new System.Windows.Forms.GroupBox(); this.LBL_Alternating_lanes = new System.Windows.Forms.Label(); this.LBL_Lane_Dist = new System.Windows.Forms.Label(); this.NUM_Lane_Dist = new System.Windows.Forms.NumericUpDown(); this.label28 = new System.Windows.Forms.Label(); this.groupBox_copter = new System.Windows.Forms.GroupBox(); this.TXT_headinghold = new System.Windows.Forms.TextBox(); this.BUT_headingholdminus = new System.Windows.Forms.Button(); this.BUT_headingholdplus = new System.Windows.Forms.Button(); this.CHK_copter_headingholdlock = new System.Windows.Forms.CheckBox(); this.CHK_copter_headinghold = new System.Windows.Forms.CheckBox(); this.LBL_copter_delay = new System.Windows.Forms.Label(); this.NUM_copter_delay = new System.Windows.Forms.NumericUpDown(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label32 = new System.Windows.Forms.Label(); this.NUM_leadin = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.NUM_spacing = new System.Windows.Forms.NumericUpDown(); this.label7 = new System.Windows.Forms.Label(); this.NUM_overshoot2 = new System.Windows.Forms.NumericUpDown(); this.label8 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.CMB_startfrom = new System.Windows.Forms.ComboBox(); this.num_overlap = new System.Windows.Forms.NumericUpDown(); this.num_sidelap = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.NUM_overshoot = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.NUM_Distance = new System.Windows.Forms.NumericUpDown(); this.tabSimple = new System.Windows.Forms.TabPage(); this.groupBox6 = new System.Windows.Forms.GroupBox(); this.label37 = new System.Windows.Forms.Label(); this.NUM_split = new System.Windows.Forms.NumericUpDown(); this.CHK_usespeed = new System.Windows.Forms.CheckBox(); this.CHK_toandland_RTL = new System.Windows.Forms.CheckBox(); this.CHK_toandland = new System.Windows.Forms.CheckBox(); this.label24 = new System.Windows.Forms.Label(); this.NUM_UpDownFlySpeed = new System.Windows.Forms.NumericUpDown(); this.label26 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.NUM_angle = new System.Windows.Forms.NumericUpDown(); this.CMB_camera = new System.Windows.Forms.ComboBox(); this.CHK_camdirection = new System.Windows.Forms.CheckBox(); this.NUM_altitude = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.CHK_advanced = new System.Windows.Forms.CheckBox(); this.CHK_footprints = new System.Windows.Forms.CheckBox(); this.CHK_internals = new System.Windows.Forms.CheckBox(); this.CHK_grid = new System.Windows.Forms.CheckBox(); this.CHK_markers = new System.Windows.Forms.CheckBox(); this.CHK_boundary = new System.Windows.Forms.CheckBox(); this.BUT_Accept = new MissionPlanner.Controls.MyButton(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.map = new MissionPlanner.Controls.myGMAP(); this.TRK_zoom = new MissionPlanner.Controls.MyTrackBar(); this.groupBox5.SuspendLayout(); this.tabCamera.SuspendLayout(); this.groupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_repttime)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.num_reptpwm)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_reptservo)).BeginInit(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_focallength)).BeginInit(); this.tabGrid.SuspendLayout(); this.groupBox7.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Lane_Dist)).BeginInit(); this.groupBox_copter.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_copter_delay)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_leadin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_spacing)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.num_overlap)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.num_sidelap)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Distance)).BeginInit(); this.tabSimple.SuspendLayout(); this.groupBox6.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_split)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_UpDownFlySpeed)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_angle)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_altitude)).BeginInit(); this.groupBox4.SuspendLayout(); this.tabControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.TRK_zoom)).BeginInit(); this.SuspendLayout(); // // groupBox5 // this.groupBox5.Controls.Add(this.lbl_turnrad); this.groupBox5.Controls.Add(this.label36); this.groupBox5.Controls.Add(this.lbl_photoevery); this.groupBox5.Controls.Add(this.label35); this.groupBox5.Controls.Add(this.lbl_flighttime); this.groupBox5.Controls.Add(this.label31); this.groupBox5.Controls.Add(this.lbl_distbetweenlines); this.groupBox5.Controls.Add(this.label25); this.groupBox5.Controls.Add(this.lbl_footprint); this.groupBox5.Controls.Add(this.label30); this.groupBox5.Controls.Add(this.lbl_strips); this.groupBox5.Controls.Add(this.lbl_pictures); this.groupBox5.Controls.Add(this.label33); this.groupBox5.Controls.Add(this.label34); this.groupBox5.Controls.Add(this.lbl_grndres); this.groupBox5.Controls.Add(this.label29); this.groupBox5.Controls.Add(this.lbl_spacing); this.groupBox5.Controls.Add(this.label27); this.groupBox5.Controls.Add(this.lbl_distance); this.groupBox5.Controls.Add(this.lbl_area); this.groupBox5.Controls.Add(this.label23); this.groupBox5.Controls.Add(this.label22); resources.ApplyResources(this.groupBox5, "groupBox5"); this.groupBox5.Name = "groupBox5"; this.groupBox5.TabStop = false; // // lbl_turnrad // resources.ApplyResources(this.lbl_turnrad, "lbl_turnrad"); this.lbl_turnrad.Name = "lbl_turnrad"; // // label36 // resources.ApplyResources(this.label36, "label36"); this.label36.Name = "label36"; // // lbl_photoevery // resources.ApplyResources(this.lbl_photoevery, "lbl_photoevery"); this.lbl_photoevery.Name = "lbl_photoevery"; // // label35 // resources.ApplyResources(this.label35, "label35"); this.label35.Name = "label35"; // // lbl_flighttime // resources.ApplyResources(this.lbl_flighttime, "lbl_flighttime"); this.lbl_flighttime.Name = "lbl_flighttime"; // // label31 // resources.ApplyResources(this.label31, "label31"); this.label31.Name = "label31"; // // lbl_distbetweenlines // resources.ApplyResources(this.lbl_distbetweenlines, "lbl_distbetweenlines"); this.lbl_distbetweenlines.Name = "lbl_distbetweenlines"; // // label25 // resources.ApplyResources(this.label25, "label25"); this.label25.Name = "label25"; // // lbl_footprint // resources.ApplyResources(this.lbl_footprint, "lbl_footprint"); this.lbl_footprint.Name = "lbl_footprint"; // // label30 // resources.ApplyResources(this.label30, "label30"); this.label30.Name = "label30"; // // lbl_strips // resources.ApplyResources(this.lbl_strips, "lbl_strips"); this.lbl_strips.Name = "lbl_strips"; // // lbl_pictures // resources.ApplyResources(this.lbl_pictures, "lbl_pictures"); this.lbl_pictures.Name = "lbl_pictures"; // // label33 // resources.ApplyResources(this.label33, "label33"); this.label33.Name = "label33"; // // label34 // resources.ApplyResources(this.label34, "label34"); this.label34.Name = "label34"; // // lbl_grndres // resources.ApplyResources(this.lbl_grndres, "lbl_grndres"); this.lbl_grndres.Name = "lbl_grndres"; // // label29 // resources.ApplyResources(this.label29, "label29"); this.label29.Name = "label29"; // // lbl_spacing // resources.ApplyResources(this.lbl_spacing, "lbl_spacing"); this.lbl_spacing.Name = "lbl_spacing"; // // label27 // resources.ApplyResources(this.label27, "label27"); this.label27.Name = "label27"; // // lbl_distance // resources.ApplyResources(this.lbl_distance, "lbl_distance"); this.lbl_distance.Name = "lbl_distance"; // // lbl_area // resources.ApplyResources(this.lbl_area, "lbl_area"); this.lbl_area.Name = "lbl_area"; // // label23 // resources.ApplyResources(this.label23, "label23"); this.label23.Name = "label23"; // // label22 // resources.ApplyResources(this.label22, "label22"); this.label22.Name = "label22"; // // tabCamera // this.tabCamera.Controls.Add(this.groupBox3); this.tabCamera.Controls.Add(this.groupBox2); resources.ApplyResources(this.tabCamera, "tabCamera"); this.tabCamera.Name = "tabCamera"; this.tabCamera.UseVisualStyleBackColor = true; // // groupBox3 // this.groupBox3.Controls.Add(this.label18); this.groupBox3.Controls.Add(this.label17); this.groupBox3.Controls.Add(this.label16); this.groupBox3.Controls.Add(this.NUM_repttime); this.groupBox3.Controls.Add(this.num_reptpwm); this.groupBox3.Controls.Add(this.NUM_reptservo); this.groupBox3.Controls.Add(this.rad_digicam); this.groupBox3.Controls.Add(this.rad_repeatservo); this.groupBox3.Controls.Add(this.rad_trigdist); resources.ApplyResources(this.groupBox3, "groupBox3"); this.groupBox3.Name = "groupBox3"; this.groupBox3.TabStop = false; // // label18 // resources.ApplyResources(this.label18, "label18"); this.label18.Name = "label18"; // // label17 // resources.ApplyResources(this.label17, "label17"); this.label17.Name = "label17"; // // label16 // resources.ApplyResources(this.label16, "label16"); this.label16.Name = "label16"; // // NUM_repttime // resources.ApplyResources(this.NUM_repttime, "NUM_repttime"); this.NUM_repttime.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this.NUM_repttime.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_repttime.Name = "NUM_repttime"; this.NUM_repttime.Value = new decimal(new int[] { 2, 0, 0, 0}); // // num_reptpwm // resources.ApplyResources(this.num_reptpwm, "num_reptpwm"); this.num_reptpwm.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this.num_reptpwm.Name = "num_reptpwm"; this.num_reptpwm.Value = new decimal(new int[] { 1100, 0, 0, 0}); // // NUM_reptservo // resources.ApplyResources(this.NUM_reptservo, "NUM_reptservo"); this.NUM_reptservo.Maximum = new decimal(new int[] { 12, 0, 0, 0}); this.NUM_reptservo.Minimum = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_reptservo.Name = "NUM_reptservo"; this.NUM_reptservo.Value = new decimal(new int[] { 5, 0, 0, 0}); // // rad_digicam // resources.ApplyResources(this.rad_digicam, "rad_digicam"); this.rad_digicam.Name = "rad_digicam"; this.rad_digicam.Tag = ""; this.rad_digicam.UseVisualStyleBackColor = true; // // rad_repeatservo // resources.ApplyResources(this.rad_repeatservo, "rad_repeatservo"); this.rad_repeatservo.Name = "rad_repeatservo"; this.rad_repeatservo.Tag = ""; this.rad_repeatservo.UseVisualStyleBackColor = true; // // rad_trigdist // resources.ApplyResources(this.rad_trigdist, "rad_trigdist"); this.rad_trigdist.Checked = true; this.rad_trigdist.Name = "rad_trigdist"; this.rad_trigdist.TabStop = true; this.rad_trigdist.Tag = ""; this.rad_trigdist.UseVisualStyleBackColor = true; // // groupBox2 // resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.Controls.Add(this.BUT_samplephoto); this.groupBox2.Controls.Add(this.label21); this.groupBox2.Controls.Add(this.label19); this.groupBox2.Controls.Add(this.label20); this.groupBox2.Controls.Add(this.TXT_fovV); this.groupBox2.Controls.Add(this.TXT_fovH); this.groupBox2.Controls.Add(this.label12); this.groupBox2.Controls.Add(this.TXT_cmpixel); this.groupBox2.Controls.Add(this.TXT_sensheight); this.groupBox2.Controls.Add(this.TXT_senswidth); this.groupBox2.Controls.Add(this.TXT_imgheight); this.groupBox2.Controls.Add(this.TXT_imgwidth); this.groupBox2.Controls.Add(this.NUM_focallength); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.label14); this.groupBox2.Controls.Add(this.label13); this.groupBox2.Controls.Add(this.label11); this.groupBox2.Controls.Add(this.BUT_save); this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // BUT_samplephoto // resources.ApplyResources(this.BUT_samplephoto, "BUT_samplephoto"); this.BUT_samplephoto.Name = "BUT_samplephoto"; this.BUT_samplephoto.UseVisualStyleBackColor = true; this.BUT_samplephoto.Click += new System.EventHandler(this.BUT_samplephoto_Click); // // label21 // resources.ApplyResources(this.label21, "label21"); this.label21.Name = "label21"; // // label19 // resources.ApplyResources(this.label19, "label19"); this.label19.Name = "label19"; // // label20 // resources.ApplyResources(this.label20, "label20"); this.label20.Name = "label20"; // // TXT_fovV // resources.ApplyResources(this.TXT_fovV, "TXT_fovV"); this.TXT_fovV.Name = "TXT_fovV"; // // TXT_fovH // resources.ApplyResources(this.TXT_fovH, "TXT_fovH"); this.TXT_fovH.Name = "TXT_fovH"; // // label12 // resources.ApplyResources(this.label12, "label12"); this.label12.Name = "label12"; // // TXT_cmpixel // resources.ApplyResources(this.TXT_cmpixel, "TXT_cmpixel"); this.TXT_cmpixel.Name = "TXT_cmpixel"; // // TXT_sensheight // resources.ApplyResources(this.TXT_sensheight, "TXT_sensheight"); this.TXT_sensheight.Name = "TXT_sensheight"; this.TXT_sensheight.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // TXT_senswidth // resources.ApplyResources(this.TXT_senswidth, "TXT_senswidth"); this.TXT_senswidth.Name = "TXT_senswidth"; this.TXT_senswidth.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // TXT_imgheight // resources.ApplyResources(this.TXT_imgheight, "TXT_imgheight"); this.TXT_imgheight.Name = "TXT_imgheight"; this.TXT_imgheight.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // TXT_imgwidth // resources.ApplyResources(this.TXT_imgwidth, "TXT_imgwidth"); this.TXT_imgwidth.Name = "TXT_imgwidth"; this.TXT_imgwidth.TextChanged += new System.EventHandler(this.TXT_TextChanged); // // NUM_focallength // this.NUM_focallength.DecimalPlaces = 1; this.NUM_focallength.Increment = new decimal(new int[] { 1, 0, 0, 65536}); resources.ApplyResources(this.NUM_focallength, "NUM_focallength"); this.NUM_focallength.Maximum = new decimal(new int[] { 180, 0, 0, 0}); this.NUM_focallength.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_focallength.Name = "NUM_focallength"; this.NUM_focallength.Value = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_focallength.ValueChanged += new System.EventHandler(this.NUM_ValueChanged); // // label9 // resources.ApplyResources(this.label9, "label9"); this.label9.Name = "label9"; // // label10 // resources.ApplyResources(this.label10, "label10"); this.label10.Name = "label10"; // // label14 // resources.ApplyResources(this.label14, "label14"); this.label14.Name = "label14"; // // label13 // resources.ApplyResources(this.label13, "label13"); this.label13.Name = "label13"; // // label11 // resources.ApplyResources(this.label11, "label11"); this.label11.Name = "label11"; // // BUT_save // resources.ApplyResources(this.BUT_save, "BUT_save"); this.BUT_save.Name = "BUT_save"; this.BUT_save.UseVisualStyleBackColor = true; this.BUT_save.Click += new System.EventHandler(this.BUT_save_Click); // // tabGrid // this.tabGrid.Controls.Add(this.groupBox7); this.tabGrid.Controls.Add(this.groupBox_copter); this.tabGrid.Controls.Add(this.groupBox1); resources.ApplyResources(this.tabGrid, "tabGrid"); this.tabGrid.Name = "tabGrid"; this.tabGrid.UseVisualStyleBackColor = true; // // groupBox7 // resources.ApplyResources(this.groupBox7, "groupBox7"); this.groupBox7.Controls.Add(this.LBL_Alternating_lanes); this.groupBox7.Controls.Add(this.LBL_Lane_Dist); this.groupBox7.Controls.Add(this.NUM_Lane_Dist); this.groupBox7.Controls.Add(this.label28); this.groupBox7.Name = "groupBox7"; this.groupBox7.TabStop = false; // // LBL_Alternating_lanes // resources.ApplyResources(this.LBL_Alternating_lanes, "LBL_Alternating_lanes"); this.LBL_Alternating_lanes.Name = "LBL_Alternating_lanes"; // // LBL_Lane_Dist // resources.ApplyResources(this.LBL_Lane_Dist, "LBL_Lane_Dist"); this.LBL_Lane_Dist.Name = "LBL_Lane_Dist"; // // NUM_Lane_Dist // resources.ApplyResources(this.NUM_Lane_Dist, "NUM_Lane_Dist"); this.NUM_Lane_Dist.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_Lane_Dist.Name = "NUM_Lane_Dist"; this.NUM_Lane_Dist.ValueChanged += new System.EventHandler(this.NUM_Lane_Dist_ValueChanged); // // label28 // resources.ApplyResources(this.label28, "label28"); this.label28.Name = "label28"; // // groupBox_copter // resources.ApplyResources(this.groupBox_copter, "groupBox_copter"); this.groupBox_copter.Controls.Add(this.TXT_headinghold); this.groupBox_copter.Controls.Add(this.BUT_headingholdminus); this.groupBox_copter.Controls.Add(this.BUT_headingholdplus); this.groupBox_copter.Controls.Add(this.CHK_copter_headingholdlock); this.groupBox_copter.Controls.Add(this.CHK_copter_headinghold); this.groupBox_copter.Controls.Add(this.LBL_copter_delay); this.groupBox_copter.Controls.Add(this.NUM_copter_delay); this.groupBox_copter.Name = "groupBox_copter"; this.groupBox_copter.TabStop = false; // // TXT_headinghold // resources.ApplyResources(this.TXT_headinghold, "TXT_headinghold"); this.TXT_headinghold.Name = "TXT_headinghold"; this.TXT_headinghold.ReadOnly = true; // // BUT_headingholdminus // resources.ApplyResources(this.BUT_headingholdminus, "BUT_headingholdminus"); this.BUT_headingholdminus.Name = "BUT_headingholdminus"; this.BUT_headingholdminus.UseVisualStyleBackColor = true; this.BUT_headingholdminus.Click += new System.EventHandler(this.BUT_headingholdminus_Click); // // BUT_headingholdplus // resources.ApplyResources(this.BUT_headingholdplus, "BUT_headingholdplus"); this.BUT_headingholdplus.Name = "BUT_headingholdplus"; this.BUT_headingholdplus.UseVisualStyleBackColor = true; this.BUT_headingholdplus.Click += new System.EventHandler(this.BUT_headingholdplus_Click); // // CHK_copter_headingholdlock // resources.ApplyResources(this.CHK_copter_headingholdlock, "CHK_copter_headingholdlock"); this.CHK_copter_headingholdlock.Name = "CHK_copter_headingholdlock"; this.CHK_copter_headingholdlock.UseVisualStyleBackColor = true; this.CHK_copter_headingholdlock.CheckedChanged += new System.EventHandler(this.CHK_copter_headingholdlock_CheckedChanged); // // CHK_copter_headinghold // resources.ApplyResources(this.CHK_copter_headinghold, "CHK_copter_headinghold"); this.CHK_copter_headinghold.Name = "CHK_copter_headinghold"; this.CHK_copter_headinghold.UseVisualStyleBackColor = true; this.CHK_copter_headinghold.CheckedChanged += new System.EventHandler(this.CHK_copter_headinghold_CheckedChanged); // // LBL_copter_delay // resources.ApplyResources(this.LBL_copter_delay, "LBL_copter_delay"); this.LBL_copter_delay.Name = "LBL_copter_delay"; // // NUM_copter_delay // this.NUM_copter_delay.DecimalPlaces = 1; this.NUM_copter_delay.Increment = new decimal(new int[] { 1, 0, 0, 65536}); resources.ApplyResources(this.NUM_copter_delay, "NUM_copter_delay"); this.NUM_copter_delay.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_copter_delay.Name = "NUM_copter_delay"; // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.label32); this.groupBox1.Controls.Add(this.NUM_leadin); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.NUM_spacing); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.NUM_overshoot2); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.label15); this.groupBox1.Controls.Add(this.CMB_startfrom); this.groupBox1.Controls.Add(this.num_overlap); this.groupBox1.Controls.Add(this.num_sidelap); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.NUM_overshoot); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.NUM_Distance); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // label32 // resources.ApplyResources(this.label32, "label32"); this.label32.Name = "label32"; // // NUM_leadin // resources.ApplyResources(this.NUM_leadin, "NUM_leadin"); this.NUM_leadin.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_leadin.Name = "NUM_leadin"; this.NUM_leadin.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // NUM_spacing // resources.ApplyResources(this.NUM_spacing, "NUM_spacing"); this.NUM_spacing.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this.NUM_spacing.Name = "NUM_spacing"; this.NUM_spacing.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // NUM_overshoot2 // resources.ApplyResources(this.NUM_overshoot2, "NUM_overshoot2"); this.NUM_overshoot2.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_overshoot2.Name = "NUM_overshoot2"; this.NUM_overshoot2.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // label15 // resources.ApplyResources(this.label15, "label15"); this.label15.Name = "label15"; // // CMB_startfrom // this.CMB_startfrom.FormattingEnabled = true; resources.ApplyResources(this.CMB_startfrom, "CMB_startfrom"); this.CMB_startfrom.Name = "CMB_startfrom"; this.CMB_startfrom.SelectedIndexChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // num_overlap // this.num_overlap.DecimalPlaces = 1; resources.ApplyResources(this.num_overlap, "num_overlap"); this.num_overlap.Name = "num_overlap"; this.num_overlap.Value = new decimal(new int[] { 50, 0, 0, 0}); this.num_overlap.ValueChanged += new System.EventHandler(this.NUM_ValueChanged); // // num_sidelap // this.num_sidelap.DecimalPlaces = 1; resources.ApplyResources(this.num_sidelap, "num_sidelap"); this.num_sidelap.Name = "num_sidelap"; this.num_sidelap.Value = new decimal(new int[] { 60, 0, 0, 0}); this.num_sidelap.ValueChanged += new System.EventHandler(this.NUM_ValueChanged); // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // NUM_overshoot // resources.ApplyResources(this.NUM_overshoot, "NUM_overshoot"); this.NUM_overshoot.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_overshoot.Name = "NUM_overshoot"; this.NUM_overshoot.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // NUM_Distance // this.NUM_Distance.DecimalPlaces = 2; resources.ApplyResources(this.NUM_Distance, "NUM_Distance"); this.NUM_Distance.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_Distance.Minimum = new decimal(new int[] { 3, 0, 0, 65536}); this.NUM_Distance.Name = "NUM_Distance"; this.NUM_Distance.Value = new decimal(new int[] { 50, 0, 0, 0}); this.NUM_Distance.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // tabSimple // this.tabSimple.Controls.Add(this.groupBox6); this.tabSimple.Controls.Add(this.groupBox4); this.tabSimple.Controls.Add(this.BUT_Accept); resources.ApplyResources(this.tabSimple, "tabSimple"); this.tabSimple.Name = "tabSimple"; this.tabSimple.UseVisualStyleBackColor = true; // // groupBox6 // this.groupBox6.Controls.Add(this.label37); this.groupBox6.Controls.Add(this.NUM_split); this.groupBox6.Controls.Add(this.CHK_usespeed); this.groupBox6.Controls.Add(this.CHK_toandland_RTL); this.groupBox6.Controls.Add(this.CHK_toandland); this.groupBox6.Controls.Add(this.label24); this.groupBox6.Controls.Add(this.NUM_UpDownFlySpeed); this.groupBox6.Controls.Add(this.label26); this.groupBox6.Controls.Add(this.label4); this.groupBox6.Controls.Add(this.NUM_angle); this.groupBox6.Controls.Add(this.CMB_camera); this.groupBox6.Controls.Add(this.CHK_camdirection); this.groupBox6.Controls.Add(this.NUM_altitude); this.groupBox6.Controls.Add(this.label1); resources.ApplyResources(this.groupBox6, "groupBox6"); this.groupBox6.Name = "groupBox6"; this.groupBox6.TabStop = false; // // label37 // resources.ApplyResources(this.label37, "label37"); this.label37.Name = "label37"; // // NUM_split // resources.ApplyResources(this.NUM_split, "NUM_split"); this.NUM_split.Maximum = new decimal(new int[] { 300, 0, 0, 0}); this.NUM_split.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_split.Name = "NUM_split"; this.NUM_split.Value = new decimal(new int[] { 1, 0, 0, 0}); this.NUM_split.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_usespeed // resources.ApplyResources(this.CHK_usespeed, "CHK_usespeed"); this.CHK_usespeed.Name = "CHK_usespeed"; this.CHK_usespeed.UseVisualStyleBackColor = true; // // CHK_toandland_RTL // resources.ApplyResources(this.CHK_toandland_RTL, "CHK_toandland_RTL"); this.CHK_toandland_RTL.Checked = true; this.CHK_toandland_RTL.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_toandland_RTL.Name = "CHK_toandland_RTL"; this.CHK_toandland_RTL.UseVisualStyleBackColor = true; // // CHK_toandland // resources.ApplyResources(this.CHK_toandland, "CHK_toandland"); this.CHK_toandland.Checked = true; this.CHK_toandland.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_toandland.Name = "CHK_toandland"; this.CHK_toandland.UseVisualStyleBackColor = true; // // label24 // resources.ApplyResources(this.label24, "label24"); this.label24.Name = "label24"; // // NUM_UpDownFlySpeed // resources.ApplyResources(this.NUM_UpDownFlySpeed, "NUM_UpDownFlySpeed"); this.NUM_UpDownFlySpeed.Maximum = new decimal(new int[] { 360, 0, 0, 0}); this.NUM_UpDownFlySpeed.Name = "NUM_UpDownFlySpeed"; this.NUM_UpDownFlySpeed.Value = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_UpDownFlySpeed.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label26 // resources.ApplyResources(this.label26, "label26"); this.label26.Name = "label26"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // NUM_angle // resources.ApplyResources(this.NUM_angle, "NUM_angle"); this.NUM_angle.Maximum = new decimal(new int[] { 360, 0, 0, 0}); this.NUM_angle.Name = "NUM_angle"; this.NUM_angle.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CMB_camera // this.CMB_camera.FormattingEnabled = true; resources.ApplyResources(this.CMB_camera, "CMB_camera"); this.CMB_camera.Name = "CMB_camera"; this.CMB_camera.SelectedIndexChanged += new System.EventHandler(this.CMB_camera_SelectedIndexChanged); // // CHK_camdirection // resources.ApplyResources(this.CHK_camdirection, "CHK_camdirection"); this.CHK_camdirection.Checked = true; this.CHK_camdirection.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_camdirection.Name = "CHK_camdirection"; this.CHK_camdirection.UseVisualStyleBackColor = true; this.CHK_camdirection.CheckedChanged += new System.EventHandler(this.CHK_camdirection_CheckedChanged); // // NUM_altitude // this.NUM_altitude.Increment = new decimal(new int[] { 10, 0, 0, 0}); resources.ApplyResources(this.NUM_altitude, "NUM_altitude"); this.NUM_altitude.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.NUM_altitude.Minimum = new decimal(new int[] { 5, 0, 0, 0}); this.NUM_altitude.Name = "NUM_altitude"; this.NUM_altitude.Value = new decimal(new int[] { 100, 0, 0, 0}); this.NUM_altitude.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // groupBox4 // this.groupBox4.Controls.Add(this.CHK_advanced); this.groupBox4.Controls.Add(this.CHK_footprints); this.groupBox4.Controls.Add(this.CHK_internals); this.groupBox4.Controls.Add(this.CHK_grid); this.groupBox4.Controls.Add(this.CHK_markers); this.groupBox4.Controls.Add(this.CHK_boundary); resources.ApplyResources(this.groupBox4, "groupBox4"); this.groupBox4.Name = "groupBox4"; this.groupBox4.TabStop = false; // // CHK_advanced // resources.ApplyResources(this.CHK_advanced, "CHK_advanced"); this.CHK_advanced.Name = "CHK_advanced"; this.CHK_advanced.UseVisualStyleBackColor = true; this.CHK_advanced.CheckedChanged += new System.EventHandler(this.CHK_advanced_CheckedChanged); // // CHK_footprints // resources.ApplyResources(this.CHK_footprints, "CHK_footprints"); this.CHK_footprints.Name = "CHK_footprints"; this.CHK_footprints.UseVisualStyleBackColor = true; this.CHK_footprints.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_internals // resources.ApplyResources(this.CHK_internals, "CHK_internals"); this.CHK_internals.Name = "CHK_internals"; this.CHK_internals.UseVisualStyleBackColor = true; this.CHK_internals.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_grid // resources.ApplyResources(this.CHK_grid, "CHK_grid"); this.CHK_grid.Checked = true; this.CHK_grid.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_grid.Name = "CHK_grid"; this.CHK_grid.UseVisualStyleBackColor = true; this.CHK_grid.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_markers // resources.ApplyResources(this.CHK_markers, "CHK_markers"); this.CHK_markers.Checked = true; this.CHK_markers.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_markers.Name = "CHK_markers"; this.CHK_markers.UseVisualStyleBackColor = true; this.CHK_markers.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // CHK_boundary // resources.ApplyResources(this.CHK_boundary, "CHK_boundary"); this.CHK_boundary.Checked = true; this.CHK_boundary.CheckState = System.Windows.Forms.CheckState.Checked; this.CHK_boundary.Name = "CHK_boundary"; this.CHK_boundary.UseVisualStyleBackColor = true; this.CHK_boundary.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged); // // BUT_Accept // resources.ApplyResources(this.BUT_Accept, "BUT_Accept"); this.BUT_Accept.Name = "BUT_Accept"; this.BUT_Accept.UseVisualStyleBackColor = true; this.BUT_Accept.Click += new System.EventHandler(this.BUT_Accept_Click); // // tabControl1 // this.tabControl1.Controls.Add(this.tabSimple); this.tabControl1.Controls.Add(this.tabGrid); this.tabControl1.Controls.Add(this.tabCamera); resources.ApplyResources(this.tabControl1, "tabControl1"); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; // // map // resources.ApplyResources(this.map, "map"); this.map.Bearing = 0F; this.map.CanDragMap = true; this.map.EmptyTileColor = System.Drawing.Color.Gray; this.map.GrayScaleMode = false; this.map.HelperLineOption = GMap.NET.WindowsForms.HelperLineOptions.DontShow; this.map.LevelsKeepInMemmory = 5; this.map.MarkersEnabled = true; this.map.MaxZoom = 19; this.map.MinZoom = 2; this.map.MouseWheelZoomType = GMap.NET.MouseWheelZoomType.MousePositionAndCenter; this.map.Name = "map"; this.map.NegativeMode = false; this.map.PolygonsEnabled = true; this.map.RetryLoadTile = 0; this.map.RoutesEnabled = true; this.map.ScaleMode = GMap.NET.WindowsForms.ScaleModes.Fractional; this.map.SelectedAreaFillColor = System.Drawing.Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(65)))), ((int)(((byte)(105)))), ((int)(((byte)(225))))); this.map.ShowTileGridLines = false; this.map.Zoom = 3D; this.map.MouseDown += new System.Windows.Forms.MouseEventHandler(this.map_MouseDown); this.map.MouseMove += new System.Windows.Forms.MouseEventHandler(this.map_MouseMove); // // TRK_zoom // resources.ApplyResources(this.TRK_zoom, "TRK_zoom"); this.TRK_zoom.LargeChange = 0.005F; this.TRK_zoom.Maximum = 19F; this.TRK_zoom.Minimum = 2F; this.TRK_zoom.Name = "TRK_zoom"; this.TRK_zoom.SmallChange = 0.001F; this.TRK_zoom.TickFrequency = 1F; this.TRK_zoom.TickStyle = System.Windows.Forms.TickStyle.TopLeft; this.TRK_zoom.Value = 2F; this.TRK_zoom.Scroll += new System.EventHandler(this.trackBar1_Scroll); // // GridUI // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; resources.ApplyResources(this, "$this"); this.Controls.Add(this.TRK_zoom); this.Controls.Add(this.map); this.Controls.Add(this.groupBox5); this.Controls.Add(this.tabControl1); this.Name = "GridUI"; this.Load += new System.EventHandler(this.GridUI_Load); this.Resize += new System.EventHandler(this.GridUI_Resize); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.tabCamera.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_repttime)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.num_reptpwm)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_reptservo)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_focallength)).EndInit(); this.tabGrid.ResumeLayout(false); this.groupBox7.ResumeLayout(false); this.groupBox7.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Lane_Dist)).EndInit(); this.groupBox_copter.ResumeLayout(false); this.groupBox_copter.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_copter_delay)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_leadin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_spacing)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.num_overlap)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.num_sidelap)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_Distance)).EndInit(); this.tabSimple.ResumeLayout(false); this.groupBox6.ResumeLayout(false); this.groupBox6.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.NUM_split)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_UpDownFlySpeed)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_angle)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NUM_altitude)).EndInit(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.tabControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.TRK_zoom)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Controls.myGMAP map; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.Label label22; private System.Windows.Forms.Label label23; private System.Windows.Forms.Label lbl_distance; private System.Windows.Forms.Label lbl_area; private System.Windows.Forms.Label lbl_spacing; private System.Windows.Forms.Label label27; private System.Windows.Forms.Label lbl_grndres; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label lbl_distbetweenlines; private System.Windows.Forms.Label label25; private System.Windows.Forms.Label lbl_footprint; private System.Windows.Forms.Label label30; private System.Windows.Forms.Label lbl_strips; private System.Windows.Forms.Label lbl_pictures; private System.Windows.Forms.Label label33; private System.Windows.Forms.Label label34; private System.Windows.Forms.Label lbl_flighttime; private System.Windows.Forms.Label label31; private System.Windows.Forms.Label lbl_photoevery; private System.Windows.Forms.Label label35; private System.Windows.Forms.TabPage tabCamera; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label17; private System.Windows.Forms.Label label16; private System.Windows.Forms.NumericUpDown NUM_repttime; private System.Windows.Forms.NumericUpDown num_reptpwm; private System.Windows.Forms.NumericUpDown NUM_reptservo; private System.Windows.Forms.RadioButton rad_digicam; private System.Windows.Forms.RadioButton rad_repeatservo; private System.Windows.Forms.RadioButton rad_trigdist; private System.Windows.Forms.GroupBox groupBox2; private Controls.MyButton BUT_samplephoto; private System.Windows.Forms.Label label21; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label20; private System.Windows.Forms.TextBox TXT_fovV; private System.Windows.Forms.TextBox TXT_fovH; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox TXT_cmpixel; private System.Windows.Forms.TextBox TXT_sensheight; private System.Windows.Forms.TextBox TXT_senswidth; private System.Windows.Forms.TextBox TXT_imgheight; private System.Windows.Forms.TextBox TXT_imgwidth; private System.Windows.Forms.NumericUpDown NUM_focallength; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label11; private Controls.MyButton BUT_save; private System.Windows.Forms.TabPage tabGrid; private System.Windows.Forms.GroupBox groupBox_copter; private System.Windows.Forms.CheckBox CHK_copter_headinghold; private System.Windows.Forms.Label LBL_copter_delay; private System.Windows.Forms.NumericUpDown NUM_copter_delay; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown NUM_spacing; private System.Windows.Forms.Label label7; private System.Windows.Forms.NumericUpDown NUM_overshoot2; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label15; private System.Windows.Forms.ComboBox CMB_startfrom; private System.Windows.Forms.NumericUpDown num_overlap; private System.Windows.Forms.NumericUpDown num_sidelap; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown NUM_overshoot; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown NUM_Distance; private System.Windows.Forms.TabPage tabSimple; private System.Windows.Forms.GroupBox groupBox6; private System.Windows.Forms.CheckBox CHK_usespeed; private System.Windows.Forms.CheckBox CHK_toandland_RTL; private System.Windows.Forms.CheckBox CHK_toandland; private System.Windows.Forms.Label label24; private System.Windows.Forms.NumericUpDown NUM_UpDownFlySpeed; private System.Windows.Forms.Label label26; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown NUM_angle; private System.Windows.Forms.ComboBox CMB_camera; private System.Windows.Forms.CheckBox CHK_camdirection; private System.Windows.Forms.NumericUpDown NUM_altitude; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.CheckBox CHK_advanced; private System.Windows.Forms.CheckBox CHK_footprints; private System.Windows.Forms.CheckBox CHK_internals; private System.Windows.Forms.CheckBox CHK_grid; private System.Windows.Forms.CheckBox CHK_markers; private System.Windows.Forms.CheckBox CHK_boundary; private Controls.MyButton BUT_Accept; private System.Windows.Forms.TabControl tabControl1; private Controls.MyTrackBar TRK_zoom; private System.Windows.Forms.CheckBox CHK_copter_headingholdlock; private System.Windows.Forms.TextBox TXT_headinghold; private System.Windows.Forms.Button BUT_headingholdminus; private System.Windows.Forms.Button BUT_headingholdplus; private System.Windows.Forms.GroupBox groupBox7; private System.Windows.Forms.Label label28; private System.Windows.Forms.Label LBL_Lane_Dist; private System.Windows.Forms.NumericUpDown NUM_Lane_Dist; private System.Windows.Forms.Label LBL_Alternating_lanes; private System.Windows.Forms.Label lbl_turnrad; private System.Windows.Forms.Label label36; private System.Windows.Forms.Label label32; private System.Windows.Forms.NumericUpDown NUM_leadin; private System.Windows.Forms.Label label37; private System.Windows.Forms.NumericUpDown NUM_split; } }
marcoarruda/MissionPlanner
ExtLibs/Grid/GridUI.Designer.cs
C#
gpl-3.0
60,645
/* eslint-disable jest/no-export, jest/no-disabled-tests */ /** * Internal dependencies */ const { shopper, merchant, createVariableProduct, } = require( '@woocommerce/e2e-utils' ); let variablePostIdValue; const cartDialogMessage = 'Please select some product options before adding this product to your cart.'; const runVariableProductUpdateTest = () => { describe('Shopper > Update variable product',() => { beforeAll(async () => { await merchant.login(); variablePostIdValue = await createVariableProduct(); await merchant.logout(); }); it('shopper can change variable attributes to the same value', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val1'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '9.99' }); }); it('shopper can change attributes to combination with dimensions and weight', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val2'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '20.00' }); await expect(page).toMatchElement('.woocommerce-variation-availability', { text: 'Out of stock' }); await expect(page).toMatchElement('.woocommerce-product-attributes-item--weight', { text: '200 kg' }); await expect(page).toMatchElement('.woocommerce-product-attributes-item--dimensions', { text: '10 × 20 × 15 cm' }); }); it('shopper can change variable product attributes to variation with a different price', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val1'); await expect(page).toSelect('#attr-3', 'val2'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '11.99' }); }); it('shopper can reset variations', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val2'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toClick('.reset_variations'); // Verify the reset by attempting to add the product to the cart const couponDialog = await expect(page).toDisplayDialog(async () => { await expect(page).toClick('.single_add_to_cart_button'); }); expect(couponDialog.message()).toMatch(cartDialogMessage); // Accept the dialog await couponDialog.accept(); }); }); }; module.exports = runVariableProductUpdateTest;
Ninos/woocommerce
tests/e2e/core-tests/specs/shopper/front-end-variable-product-updates.test.js
JavaScript
gpl-3.0
2,776
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_DataFusion_DataAccessOptions extends Google_Model { public $logMode; public function setLogMode($logMode) { $this->logMode = $logMode; } public function getLogMode() { return $this->logMode; } }
Merrick28/delain
web/vendor/google/apiclient-services/src/Google/Service/DataFusion/DataAccessOptions.php
PHP
gpl-3.0
837
package module // no syscall.Stat_t on windows, return 0 for inodes func inode(path string) (uint64, error) { return 0, nil }
grange74/terraform
config/module/inode_windows.go
GO
mpl-2.0
128
package profitbricks import ( "encoding/json" "errors" "fmt" "strconv" "strings" "time" "github.com/hashicorp/packer/packer" "github.com/mitchellh/multistep" "github.com/profitbricks/profitbricks-sdk-go" ) type stepCreateServer struct{} func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) c := state.Get("config").(*Config) profitbricks.SetAuth(c.PBUsername, c.PBPassword) profitbricks.SetDepth("5") if sshkey, ok := state.GetOk("publicKey"); ok { c.SSHKey = sshkey.(string) } ui.Say("Creating Virtual Data Center...") img := s.getImageId(c.Image, c) datacenter := profitbricks.Datacenter{ Properties: profitbricks.DatacenterProperties{ Name: c.SnapshotName, Location: c.Region, }, Entities: profitbricks.DatacenterEntities{ Servers: &profitbricks.Servers{ Items: []profitbricks.Server{ { Properties: profitbricks.ServerProperties{ Name: c.SnapshotName, Ram: c.Ram, Cores: c.Cores, }, Entities: &profitbricks.ServerEntities{ Volumes: &profitbricks.Volumes{ Items: []profitbricks.Volume{ { Properties: profitbricks.VolumeProperties{ Type: c.DiskType, Size: c.DiskSize, Name: c.SnapshotName, Image: img, }, }, }, }, }, }, }, }, }, } if c.SSHKey != "" { datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Properties.SshKeys = []string{c.SSHKey} } if c.Comm.SSHPassword != "" { datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Properties.ImagePassword = c.Comm.SSHPassword } datacenter = profitbricks.CompositeCreateDatacenter(datacenter) if datacenter.StatusCode > 299 { if datacenter.StatusCode > 299 { var restError RestError err := json.Unmarshal([]byte(datacenter.Response), &restError) if err != nil { ui.Error(fmt.Sprintf("Error decoding json response: %s", err.Error())) return multistep.ActionHalt } if len(restError.Messages) > 0 { ui.Error(restError.Messages[0].Message) } else { ui.Error(datacenter.Response) } return multistep.ActionHalt } } err := s.waitTillProvisioned(datacenter.Headers.Get("Location"), *c) if err != nil { ui.Error(fmt.Sprintf("Error occurred while creating a datacenter %s", err.Error())) return multistep.ActionHalt } state.Put("datacenter_id", datacenter.Id) lan := profitbricks.CreateLan(datacenter.Id, profitbricks.Lan{ Properties: profitbricks.LanProperties{ Public: true, Name: c.SnapshotName, }, }) if lan.StatusCode > 299 { ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(lan.Response))) return multistep.ActionHalt } err = s.waitTillProvisioned(lan.Headers.Get("Location"), *c) if err != nil { ui.Error(fmt.Sprintf("Error occurred while creating a LAN %s", err.Error())) return multistep.ActionHalt } lanId, _ := strconv.Atoi(lan.Id) nic := profitbricks.CreateNic(datacenter.Id, datacenter.Entities.Servers.Items[0].Id, profitbricks.Nic{ Properties: profitbricks.NicProperties{ Name: c.SnapshotName, Lan: lanId, Dhcp: true, }, }) if lan.StatusCode > 299 { ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(nic.Response))) return multistep.ActionHalt } err = s.waitTillProvisioned(nic.Headers.Get("Location"), *c) if err != nil { ui.Error(fmt.Sprintf("Error occurred while creating a NIC %s", err.Error())) return multistep.ActionHalt } state.Put("volume_id", datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Id) server := profitbricks.GetServer(datacenter.Id, datacenter.Entities.Servers.Items[0].Id) state.Put("server_ip", server.Entities.Nics.Items[0].Properties.Ips[0]) return multistep.ActionContinue } func (s *stepCreateServer) Cleanup(state multistep.StateBag) { c := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) ui.Say("Removing Virtual Data Center...") profitbricks.SetAuth(c.PBUsername, c.PBPassword) if dcId, ok := state.GetOk("datacenter_id"); ok { resp := profitbricks.DeleteDatacenter(dcId.(string)) if err := s.checkForErrors(resp); err != nil { ui.Error(fmt.Sprintf( "Error deleting Virtual Data Center. Please destroy it manually: %s", err)) } if err := s.waitTillProvisioned(resp.Headers.Get("Location"), *c); err != nil { ui.Error(fmt.Sprintf( "Error deleting Virtual Data Center. Please destroy it manually: %s", err)) } } } func (d *stepCreateServer) waitTillProvisioned(path string, config Config) error { d.setPB(config.PBUsername, config.PBPassword, config.PBUrl) waitCount := 120 if config.Retries > 0 { waitCount = config.Retries } for i := 0; i < waitCount; i++ { request := profitbricks.GetRequestStatus(path) if request.Metadata.Status == "DONE" { return nil } if request.Metadata.Status == "FAILED" { return errors.New(request.Metadata.Message) } time.Sleep(1 * time.Second) i++ } return nil } func (d *stepCreateServer) setPB(username string, password string, url string) { profitbricks.SetAuth(username, password) profitbricks.SetEndpoint(url) } func (d *stepCreateServer) checkForErrors(instance profitbricks.Resp) error { if instance.StatusCode > 299 { return errors.New(fmt.Sprintf("Error occurred %s", string(instance.Body))) } return nil } type RestError struct { HttpStatus int `json:"httpStatus,omitempty"` Messages []Message `json:"messages,omitempty"` } type Message struct { ErrorCode string `json:"errorCode,omitempty"` Message string `json:"message,omitempty"` } func (d *stepCreateServer) getImageId(imageName string, c *Config) string { d.setPB(c.PBUsername, c.PBPassword, c.PBUrl) images := profitbricks.ListImages() for i := 0; i < len(images.Items); i++ { imgName := "" if images.Items[i].Properties.Name != "" { imgName = images.Items[i].Properties.Name } diskType := c.DiskType if c.DiskType == "SSD" { diskType = "HDD" } if imgName != "" && strings.Contains(strings.ToLower(imgName), strings.ToLower(imageName)) && images.Items[i].Properties.ImageType == diskType && images.Items[i].Properties.Location == c.Region && images.Items[i].Properties.Public == true { return images.Items[i].Id } } return "" } func parseErrorMessage(raw string) (toreturn string) { var tmp map[string]interface{} json.Unmarshal([]byte(raw), &tmp) for _, v := range tmp["messages"].([]interface{}) { for index, i := range v.(map[string]interface{}) { if index == "message" { toreturn = toreturn + i.(string) + "\n" } } } return toreturn }
dayglojesus/packer
builder/profitbricks/step_create_server.go
GO
mpl-2.0
6,663
/** * <p> * The scrollview module does not add any new classes. It simply plugs the ScrollViewScrollbars plugin into the * base ScrollView class implementation provided by the scrollview-base module, so that all scrollview instances * have scrollbars enabled. * </p> * * <ul> * <li><a href="../classes/ScrollView.html">ScrollView API documentation</a></li> * <li><a href="scrollview-base.html">scrollview-base Module documentation</a></li> * </ul> * * @module scrollview */ Y.Base.plug(Y.ScrollView, Y.Plugin.ScrollViewScrollbars);
co-ment/comt
src/cm/media/js/lib/yui/yui3-3.15.0/src/scrollview/js/scrollview.js
JavaScript
agpl-3.0
556
<?php /* * Spring Signage Ltd - http://www.springsignage.com * Copyright (C) 2015 Spring Signage Ltd * (CommandFactory.php) */ namespace Xibo\Factory; use Xibo\Entity\Command; use Xibo\Entity\User; use Xibo\Exception\NotFoundException; use Xibo\Service\LogServiceInterface; use Xibo\Service\SanitizerServiceInterface; use Xibo\Storage\StorageServiceInterface; /** * Class CommandFactory * @package Xibo\Factory */ class CommandFactory extends BaseFactory { /** * @var DisplayProfileFactory */ private $displayProfileFactory; /** * Construct a factory * @param StorageServiceInterface $store * @param LogServiceInterface $log * @param SanitizerServiceInterface $sanitizerService * @param User $user * @param UserFactory $userFactory */ public function __construct($store, $log, $sanitizerService, $user, $userFactory) { $this->setCommonDependencies($store, $log, $sanitizerService); $this->setAclDependencies($user, $userFactory); } /** * Create Command * @return Command */ public function create() { return new Command($this->getStore(), $this->getLog()); } /** * Get by Id * @param $commandId * @return Command * @throws NotFoundException */ public function getById($commandId) { $commands = $this->query(null, ['commandId' => $commandId]); if (count($commands) <= 0) throw new NotFoundException(); return $commands[0]; } /** * Get by Display Profile Id * @param $displayProfileId * @return array[Command] */ public function getByDisplayProfileId($displayProfileId) { return $this->query(null, ['displayProfileId' => $displayProfileId]); } /** * @param array $sortOrder * @param array $filterBy * @return array */ public function query($sortOrder = null, $filterBy = null) { $entries = array(); if ($sortOrder == null) $sortOrder = ['command']; $params = array(); $select = 'SELECT `command`.commandId, `command`.command, `command`.code, `command`.description, `command`.userId '; if ($this->getSanitizer()->getInt('displayProfileId', $filterBy) !== null) { $select .= ', commandString, validationString '; } $body = ' FROM `command` '; if ($this->getSanitizer()->getInt('displayProfileId', $filterBy) !== null) { $body .= ' INNER JOIN `lkcommanddisplayprofile` ON `lkcommanddisplayprofile`.commandId = `command`.commandId AND `lkcommanddisplayprofile`.displayProfileId = :displayProfileId '; $params['displayProfileId'] = $this->getSanitizer()->getInt('displayProfileId', $filterBy); } $body .= ' WHERE 1 = 1 '; if ($this->getSanitizer()->getInt('commandId', $filterBy) !== null) { $body .= ' AND `command`.commandId = :commandId '; $params['commandId'] = $this->getSanitizer()->getInt('commandId', $filterBy); } if ($this->getSanitizer()->getString('command', $filterBy) != null) { $body .= ' AND `command`.command = :command '; $params['command'] = $this->getSanitizer()->getString('command', $filterBy); } if ($this->getSanitizer()->getString('code', $filterBy) != null) { $body .= ' AND `code`.code = :code '; $params['code'] = $this->getSanitizer()->getString('code', $filterBy); } // Sorting? $order = ''; if (is_array($sortOrder)) $order .= 'ORDER BY ' . implode(',', $sortOrder); $limit = ''; // Paging if ($filterBy !== null && $this->getSanitizer()->getInt('start', $filterBy) !== null && $this->getSanitizer()->getInt('length', $filterBy) !== null) { $limit = ' LIMIT ' . intval($this->getSanitizer()->getInt('start', $filterBy), 0) . ', ' . $this->getSanitizer()->getInt('length', 10, $filterBy); } $sql = $select . $body . $order . $limit; foreach ($this->getStore()->select($sql, $params) as $row) { $entries[] = (new Command($this->getStore(), $this->getLog(), $this->displayProfileFactory))->hydrate($row); } // Paging if ($limit != '' && count($entries) > 0) { $results = $this->getStore()->select('SELECT COUNT(*) AS total ' . $body, $params); $this->_countLast = intval($results[0]['total']); } return $entries; } }
alexhuang888/xibo-cms
lib/Factory/CommandFactory.php
PHP
agpl-3.0
4,638
/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* Copyright (C) 2009 Red Hat, Inc. 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. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "common.h" #include "red_channel.h" #include "red_client.h" #include "application.h" #include "debug.h" #include "utils.h" #include "openssl/rsa.h" #include "openssl/evp.h" #include "openssl/x509.h" void MigrationDisconnectSrcEvent::response(AbstractProcessLoop& events_loop) { static_cast<RedChannel*>(events_loop.get_owner())->do_migration_disconnect_src(); } void MigrationConnectTargetEvent::response(AbstractProcessLoop& events_loop) { static_cast<RedChannel*>(events_loop.get_owner())->do_migration_connect_target(); } RedChannelBase::RedChannelBase(uint8_t type, uint8_t id, const ChannelCaps& common_caps, const ChannelCaps& caps) : RedPeer() , _type (type) , _id (id) , _common_caps (common_caps) , _caps (caps) { } RedChannelBase::~RedChannelBase() { } static const char *spice_link_error_string(int err) { switch (err) { case SPICE_LINK_ERR_OK: return "no error"; case SPICE_LINK_ERR_ERROR: return "general error"; case SPICE_LINK_ERR_INVALID_MAGIC: return "invalid magic"; case SPICE_LINK_ERR_INVALID_DATA: return "invalid data"; case SPICE_LINK_ERR_VERSION_MISMATCH: return "version mismatch"; case SPICE_LINK_ERR_NEED_SECURED: return "need secured connection"; case SPICE_LINK_ERR_NEED_UNSECURED: return "need unsecured connection"; case SPICE_LINK_ERR_PERMISSION_DENIED: return "permission denied"; case SPICE_LINK_ERR_BAD_CONNECTION_ID: return "bad connection id"; case SPICE_LINK_ERR_CHANNEL_NOT_AVAILABLE: return "channel not available"; } return ""; } void RedChannelBase::link(uint32_t connection_id, const std::string& password, int protocol) { SpiceLinkHeader header; SpiceLinkMess link_mess; SpiceLinkReply* reply; uint32_t link_res; uint32_t i; BIO *bioKey; uint8_t *buffer, *p; uint32_t expected_major; header.magic = SPICE_MAGIC; header.size = sizeof(link_mess); if (protocol == 1) { /* protocol 1 == major 1, old 0.4 protocol, last active minor */ expected_major = header.major_version = 1; header.minor_version = 3; } else if (protocol == 2) { /* protocol 2 == current */ expected_major = header.major_version = SPICE_VERSION_MAJOR; header.minor_version = SPICE_VERSION_MINOR; } else { THROW("unsupported protocol version specified"); } link_mess.connection_id = connection_id; link_mess.channel_type = _type; link_mess.channel_id = _id; link_mess.num_common_caps = get_common_caps().size(); link_mess.num_channel_caps = get_caps().size(); link_mess.caps_offset = sizeof(link_mess); header.size += (link_mess.num_common_caps + link_mess.num_channel_caps) * sizeof(uint32_t); buffer = new uint8_t[sizeof(header) + sizeof(link_mess) + _common_caps.size() * sizeof(uint32_t) + _caps.size() * sizeof(uint32_t)]; p = buffer; memcpy(p, (uint8_t*)&header, sizeof(header)); p += sizeof(header); memcpy(p, (uint8_t*)&link_mess, sizeof(link_mess)); p += sizeof(link_mess); for (i = 0; i < _common_caps.size(); i++) { *(uint32_t *)p = _common_caps[i]; p += sizeof(uint32_t); } for (i = 0; i < _caps.size(); i++) { *(uint32_t *)p = _caps[i]; p += sizeof(uint32_t); } send(buffer, p - buffer); delete [] buffer; receive((uint8_t*)&header, sizeof(header)); if (header.magic != SPICE_MAGIC) { THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "bad magic"); } if (header.major_version != expected_major) { THROW_ERR(SPICEC_ERROR_CODE_VERSION_MISMATCH, "version mismatch: expect %u got %u", expected_major, header.major_version); } _remote_major = header.major_version; _remote_minor = header.minor_version; AutoArray<uint8_t> reply_buf(new uint8_t[header.size]); receive(reply_buf.get(), header.size); reply = (SpiceLinkReply *)reply_buf.get(); if (reply->error != SPICE_LINK_ERR_OK) { THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "connect error %u - %s", reply->error, spice_link_error_string(reply->error)); } uint32_t num_caps = reply->num_channel_caps + reply->num_common_caps; if ((uint8_t *)(reply + 1) > reply_buf.get() + header.size || (uint8_t *)reply + reply->caps_offset + num_caps * sizeof(uint32_t) > reply_buf.get() + header.size) { THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "access violation"); } uint32_t *caps = (uint32_t *)((uint8_t *)reply + reply->caps_offset); _remote_common_caps.clear(); for (i = 0; i < reply->num_common_caps; i++, caps++) { _remote_common_caps.resize(i + 1); _remote_common_caps[i] = *caps; } _remote_caps.clear(); for (i = 0; i < reply->num_channel_caps; i++, caps++) { _remote_caps.resize(i + 1); _remote_caps[i] = *caps; } bioKey = BIO_new(BIO_s_mem()); if (bioKey != NULL) { EVP_PKEY *pubkey; int nRSASize; RSA *rsa; BIO_write(bioKey, reply->pub_key, SPICE_TICKET_PUBKEY_BYTES); pubkey = d2i_PUBKEY_bio(bioKey, NULL); rsa = pubkey->pkey.rsa; nRSASize = RSA_size(rsa); AutoArray<unsigned char> bufEncrypted(new unsigned char[nRSASize]); /* The use of RSA encryption limit the potential maximum password length. for RSA_PKCS1_OAEP_PADDING it is RSA_size(rsa) - 41. */ if (RSA_public_encrypt(password.length() + 1, (unsigned char *)password.c_str(), (uint8_t *)bufEncrypted.get(), rsa, RSA_PKCS1_OAEP_PADDING) > 0) { send((uint8_t*)bufEncrypted.get(), nRSASize); } else { EVP_PKEY_free(pubkey); BIO_free(bioKey); THROW("could not encrypt password"); } memset(bufEncrypted.get(), 0, nRSASize); EVP_PKEY_free(pubkey); } else { THROW("Could not initiate BIO"); } BIO_free(bioKey); receive((uint8_t*)&link_res, sizeof(link_res)); if (link_res != SPICE_LINK_ERR_OK) { int error_code = (link_res == SPICE_LINK_ERR_PERMISSION_DENIED) ? SPICEC_ERROR_CODE_CONNECT_FAILED : SPICEC_ERROR_CODE_CONNECT_FAILED; THROW_ERR(error_code, "connect failed %u", link_res); } } void RedChannelBase::connect(const ConnectionOptions& options, uint32_t connection_id, const char* host, std::string password) { int protocol = options.protocol; if (protocol == 0) { /* AUTO, try major 2 first */ protocol = 2; } retry: try { if (options.allow_unsecure()) { try { RedPeer::connect_unsecure(host, options.unsecure_port); link(connection_id, password, protocol); return; } catch (Exception& e) { // On protocol version mismatch, don't connect_secure with the same version if (e.get_error_code() == SPICEC_ERROR_CODE_VERSION_MISMATCH || !options.allow_secure()) { throw; } RedPeer::close(); } } ASSERT(options.allow_secure()); RedPeer::connect_secure(options, host); link(connection_id, password, protocol); } catch (Exception& e) { // On protocol version mismatch, retry with older version if (e.get_error_code() == SPICEC_ERROR_CODE_VERSION_MISMATCH && protocol == 2 && options.protocol == 0) { RedPeer::cleanup(); protocol = 1; goto retry; } throw; } } void RedChannelBase::set_capability(ChannelCaps& caps, uint32_t cap) { uint32_t word_index = cap / 32; if (caps.size() < word_index + 1) { caps.resize(word_index + 1); } caps[word_index] |= 1 << (cap % 32); } void RedChannelBase::set_common_capability(uint32_t cap) { set_capability(_common_caps, cap); } void RedChannelBase::set_capability(uint32_t cap) { set_capability(_caps, cap); } bool RedChannelBase::test_capability(const ChannelCaps& caps, uint32_t cap) { uint32_t word_index = cap / 32; if (caps.size() < word_index + 1) { return false; } return (caps[word_index] & (1 << (cap % 32))) != 0; } bool RedChannelBase::test_common_capability(uint32_t cap) { return test_capability(_remote_common_caps, cap); } bool RedChannelBase::test_capability(uint32_t cap) { return test_capability(_remote_caps, cap); } void RedChannelBase::swap(RedChannelBase* other) { int tmp_ver; RedPeer::swap(other); tmp_ver = _remote_major; _remote_major = other->_remote_major; other->_remote_major = tmp_ver; tmp_ver = _remote_minor; _remote_minor = other->_remote_minor; other->_remote_minor = tmp_ver; } SendTrigger::SendTrigger(RedChannel& channel) : _channel (channel) { } void SendTrigger::on_event() { _channel.on_send_trigger(); } SPICE_GNUC_NORETURN void AbortTrigger::on_event() { THROW("abort"); } RedChannel::RedChannel(RedClient& client, uint8_t type, uint8_t id, RedChannel::MessageHandler* handler, Platform::ThreadPriority worker_priority) : RedChannelBase(type, id, ChannelCaps(), ChannelCaps()) , _marshallers (NULL) , _client (client) , _state (PASSIVE_STATE) , _action (WAIT_ACTION) , _error (SPICEC_ERROR_CODE_SUCCESS) , _wait_for_threads (true) , _socket_in_loop (false) , _worker (NULL) , _worker_priority (worker_priority) , _message_handler (handler) , _outgoing_message (NULL) , _incomming_header_pos (0) , _incomming_message (NULL) , _message_ack_count (0) , _message_ack_window (0) , _loop (this) , _send_trigger (*this) , _disconnect_stamp (0) , _disconnect_reason (SPICE_LINK_ERR_OK) { _loop.add_trigger(_send_trigger); _loop.add_trigger(_abort_trigger); } RedChannel::~RedChannel() { ASSERT(_state == TERMINATED_STATE || _state == PASSIVE_STATE); delete _worker; } void* RedChannel::worker_main(void *data) { try { RedChannel* channel = static_cast<RedChannel*>(data); channel->set_state(DISCONNECTED_STATE); Platform::set_thread_priority(NULL, channel->get_worker_priority()); channel->run(); } catch (Exception& e) { LOG_ERROR("unhandled exception: %s", e.what()); } catch (std::exception& e) { LOG_ERROR("unhandled exception: %s", e.what()); } catch (...) { LOG_ERROR("unhandled exception"); } return NULL; } void RedChannel::post_message(RedChannel::OutMessage* message) { Lock lock(_outgoing_lock); _outgoing_messages.push_back(message); lock.unlock(); _send_trigger.trigger(); } RedPeer::CompoundInMessage *RedChannel::receive() { CompoundInMessage *message = RedChannelBase::receive(); on_message_received(); return message; } RedChannel::OutMessage* RedChannel::get_outgoing_message() { if (_state != CONNECTED_STATE || _outgoing_messages.empty()) { return NULL; } RedChannel::OutMessage* message = _outgoing_messages.front(); _outgoing_messages.pop_front(); return message; } class AutoMessage { public: AutoMessage(RedChannel::OutMessage* message) : _message (message) {} ~AutoMessage() {if (_message) _message->release();} void set(RedChannel::OutMessage* message) { _message = message;} RedChannel::OutMessage* get() { return _message;} RedChannel::OutMessage* release(); private: RedChannel::OutMessage* _message; }; RedChannel::OutMessage* AutoMessage::release() { RedChannel::OutMessage* ret = _message; _message = NULL; return ret; } void RedChannel::start() { ASSERT(!_worker); _worker = new Thread(RedChannel::worker_main, this); Lock lock(_state_lock); while (_state == PASSIVE_STATE) { _state_cond.wait(lock); } } void RedChannel::set_state(int state) { Lock lock(_state_lock); _state = state; _state_cond.notify_all(); } void RedChannel::connect() { Lock lock(_action_lock); if (_state != DISCONNECTED_STATE && _state != PASSIVE_STATE) { return; } _action = CONNECT_ACTION; _action_cond.notify_one(); } void RedChannel::disconnect() { clear_outgoing_messages(); Lock lock(_action_lock); if (_state != CONNECTING_STATE && _state != CONNECTED_STATE) { return; } _action = DISCONNECT_ACTION; RedPeer::disconnect(); _action_cond.notify_one(); } void RedChannel::disconnect_migration_src() { clear_outgoing_messages(); Lock lock(_action_lock); if (_state == CONNECTING_STATE || _state == CONNECTED_STATE) { AutoRef<MigrationDisconnectSrcEvent> migrate_event(new MigrationDisconnectSrcEvent()); _loop.push_event(*migrate_event); } } void RedChannel::connect_migration_target() { LOG_INFO(""); AutoRef<MigrationConnectTargetEvent> migrate_event(new MigrationConnectTargetEvent()); _loop.push_event(*migrate_event); } void RedChannel::do_migration_disconnect_src() { if (_socket_in_loop) { _socket_in_loop = false; _loop.remove_socket(*this); } clear_outgoing_messages(); if (_outgoing_message) { _outgoing_message->release(); _outgoing_message = NULL; } _incomming_header_pos = 0; if (_incomming_message) { _incomming_message->unref(); _incomming_message = NULL; } on_disconnect_mig_src(); get_client().migrate_channel(*this); get_client().on_channel_disconnect_mig_src_completed(*this); } void RedChannel::do_migration_connect_target() { LOG_INFO(""); ASSERT(get_client().get_protocol() != 0); if (get_client().get_protocol() == 1) { _marshallers = spice_message_marshallers_get1(); } else { _marshallers = spice_message_marshallers_get(); } _loop.add_socket(*this); _socket_in_loop = true; on_connect_mig_target(); set_state(CONNECTED_STATE); on_event(); } void RedChannel::clear_outgoing_messages() { Lock lock(_outgoing_lock); while (!_outgoing_messages.empty()) { RedChannel::OutMessage* message = _outgoing_messages.front(); _outgoing_messages.pop_front(); message->release(); } } void RedChannel::run() { for (;;) { Lock lock(_action_lock); if (_action == WAIT_ACTION) { _action_cond.wait(lock); } int action = _action; _action = WAIT_ACTION; lock.unlock(); switch (action) { case CONNECT_ACTION: try { get_client().get_sync_info(get_type(), get_id(), _sync_info); on_connecting(); set_state(CONNECTING_STATE); ConnectionOptions con_options(_client.get_connection_options(get_type()), _client.get_port(), _client.get_sport(), _client.get_protocol(), _client.get_host_auth_options(), _client.get_connection_ciphers()); RedChannelBase::connect(con_options, _client.get_connection_id(), _client.get_host().c_str(), _client.get_password().c_str()); /* If automatic protocol, remember the first connect protocol type */ if (_client.get_protocol() == 0) { if (get_peer_major() == 1) { _client.set_protocol(1); } else { /* Major is 2 or unstable high value, use 2 */ _client.set_protocol(2); } } /* Initialize when we know the remote major version */ if (_client.get_peer_major() == 1) { _marshallers = spice_message_marshallers_get1(); } else { _marshallers = spice_message_marshallers_get(); } on_connect(); set_state(CONNECTED_STATE); _loop.add_socket(*this); _socket_in_loop = true; on_event(); _loop.run(); } catch (RedPeer::DisconnectedException&) { _error = SPICEC_ERROR_CODE_SUCCESS; } catch (Exception& e) { LOG_WARN("%s", e.what()); _error = e.get_error_code(); } catch (std::exception& e) { LOG_WARN("%s", e.what()); _error = SPICEC_ERROR_CODE_ERROR; } if (_socket_in_loop) { _socket_in_loop = false; _loop.remove_socket(*this); } if (_outgoing_message) { _outgoing_message->release(); _outgoing_message = NULL; } _incomming_header_pos = 0; if (_incomming_message) { _incomming_message->unref(); _incomming_message = NULL; } case DISCONNECT_ACTION: close(); on_disconnect(); set_state(DISCONNECTED_STATE); _client.on_channel_disconnected(*this); continue; case QUIT_ACTION: set_state(TERMINATED_STATE); return; } } } bool RedChannel::abort() { clear_outgoing_messages(); Lock lock(_action_lock); if (_state == TERMINATED_STATE) { if (_wait_for_threads) { _wait_for_threads = false; _worker->join(); } return true; } _action = QUIT_ACTION; _action_cond.notify_one(); lock.unlock(); RedPeer::disconnect(); _abort_trigger.trigger(); for (;;) { Lock state_lock(_state_lock); if (_state == TERMINATED_STATE) { break; } uint64_t timout = 1000 * 1000 * 100; // 100ms if (!_state_cond.timed_wait(state_lock, timout)) { return false; } } if (_wait_for_threads) { _wait_for_threads = false; _worker->join(); } return true; } void RedChannel::send_messages() { if (_outgoing_message) { return; } for (;;) { Lock lock(_outgoing_lock); AutoMessage message(get_outgoing_message()); if (!message.get()) { return; } RedPeer::OutMessage& peer_message = message.get()->peer_message(); uint32_t n = send(peer_message); if (n != peer_message.message_size()) { _outgoing_message = message.release(); _outgoing_pos = n; return; } } } void RedChannel::on_send_trigger() { send_messages(); } void RedChannel::on_message_received() { if (_message_ack_count && !--_message_ack_count) { post_message(new Message(SPICE_MSGC_ACK)); _message_ack_count = _message_ack_window; } } void RedChannel::on_message_complition(uint64_t serial) { Lock lock(*_sync_info.lock); *_sync_info.message_serial = serial; _sync_info.condition->notify_all(); } void RedChannel::receive_messages() { for (;;) { uint32_t n = RedPeer::receive((uint8_t*)&_incomming_header, sizeof(SpiceDataHeader)); if (n != sizeof(SpiceDataHeader)) { _incomming_header_pos = n; return; } AutoRef<CompoundInMessage> message(new CompoundInMessage(_incomming_header.serial, _incomming_header.type, _incomming_header.size, _incomming_header.sub_list)); n = RedPeer::receive((*message)->data(), (*message)->compound_size()); if (n != (*message)->compound_size()) { _incomming_message = message.release(); _incomming_message_pos = n; return; } on_message_received(); _message_handler->handle_message(*(*message)); on_message_complition((*message)->serial()); } } void RedChannel::on_event() { if (_outgoing_message) { RedPeer::OutMessage& peer_message = _outgoing_message->peer_message(); _outgoing_pos += do_send(peer_message, _outgoing_pos); if (_outgoing_pos == peer_message.message_size()) { _outgoing_message->release(); _outgoing_message = NULL; } } send_messages(); if (_incomming_header_pos) { _incomming_header_pos += RedPeer::receive(((uint8_t*)&_incomming_header) + _incomming_header_pos, sizeof(SpiceDataHeader) - _incomming_header_pos); if (_incomming_header_pos != sizeof(SpiceDataHeader)) { return; } _incomming_header_pos = 0; _incomming_message = new CompoundInMessage(_incomming_header.serial, _incomming_header.type, _incomming_header.size, _incomming_header.sub_list); _incomming_message_pos = 0; } if (_incomming_message) { _incomming_message_pos += RedPeer::receive(_incomming_message->data() + _incomming_message_pos, _incomming_message->compound_size() - _incomming_message_pos); if (_incomming_message_pos != _incomming_message->compound_size()) { return; } AutoRef<CompoundInMessage> message(_incomming_message); _incomming_message = NULL; on_message_received(); _message_handler->handle_message(*(*message)); on_message_complition((*message)->serial()); } receive_messages(); } void RedChannel::send_migrate_flush_mark() { if (_outgoing_message) { RedPeer::OutMessage& peer_message = _outgoing_message->peer_message(); do_send(peer_message, _outgoing_pos); _outgoing_message->release(); _outgoing_message = NULL; } Lock lock(_outgoing_lock); for (;;) { AutoMessage message(get_outgoing_message()); if (!message.get()) { break; } send(message.get()->peer_message()); } lock.unlock(); std::auto_ptr<RedPeer::OutMessage> message(new RedPeer::OutMessage(SPICE_MSGC_MIGRATE_FLUSH_MARK)); send(*message); } void RedChannel::handle_migrate(RedPeer::InMessage* message) { DBG(0, "channel type %u id %u", get_type(), get_id()); _socket_in_loop = false; _loop.remove_socket(*this); SpiceMsgMigrate* migrate = (SpiceMsgMigrate*)message->data(); if (migrate->flags & SPICE_MIGRATE_NEED_FLUSH) { send_migrate_flush_mark(); } AutoRef<CompoundInMessage> data_message; if (migrate->flags & SPICE_MIGRATE_NEED_DATA_TRANSFER) { data_message.reset(receive()); } _client.migrate_channel(*this); if (migrate->flags & SPICE_MIGRATE_NEED_DATA_TRANSFER) { if ((*data_message)->type() != SPICE_MSG_MIGRATE_DATA) { THROW("expect SPICE_MSG_MIGRATE_DATA"); } std::auto_ptr<RedPeer::OutMessage> message(new RedPeer::OutMessage(SPICE_MSGC_MIGRATE_DATA)); spice_marshaller_add(message->marshaller(), (*data_message)->data(), (*data_message)->size()); send(*message); } _loop.add_socket(*this); _socket_in_loop = true; on_migrate(); set_state(CONNECTED_STATE); on_event(); } void RedChannel::handle_set_ack(RedPeer::InMessage* message) { SpiceMsgSetAck* ack = (SpiceMsgSetAck*)message->data(); _message_ack_window = _message_ack_count = ack->window; Message *response = new Message(SPICE_MSGC_ACK_SYNC); SpiceMsgcAckSync sync; sync.generation = ack->generation; _marshallers->msgc_ack_sync(response->marshaller(), &sync); post_message(response); } void RedChannel::handle_ping(RedPeer::InMessage* message) { SpiceMsgPing *ping = (SpiceMsgPing *)message->data(); Message *pong = new Message(SPICE_MSGC_PONG); _marshallers->msgc_pong(pong->marshaller(), ping); post_message(pong); } void RedChannel::handle_disconnect(RedPeer::InMessage* message) { SpiceMsgDisconnect *disconnect = (SpiceMsgDisconnect *)message->data(); _disconnect_stamp = disconnect->time_stamp; _disconnect_reason = disconnect->reason; } void RedChannel::handle_notify(RedPeer::InMessage* message) { SpiceMsgNotify *notify = (SpiceMsgNotify *)message->data(); const char *severity; const char *visibility; char *message_str = (char *)""; const char *message_prefix = ""; static const char* severity_strings[] = {"info", "warn", "error"}; static const char* visibility_strings[] = {"!", "!!", "!!!"}; if (notify->severity > SPICE_NOTIFY_SEVERITY_ERROR) { THROW("bad severity"); } severity = severity_strings[notify->severity]; if (notify->visibilty > SPICE_NOTIFY_VISIBILITY_HIGH) { THROW("bad visibility"); } visibility = visibility_strings[notify->visibilty]; if (notify->message_len) { if ((message->size() - sizeof(*notify) < notify->message_len)) { THROW("access violation"); } message_str = new char[notify->message_len + 1]; memcpy(message_str, notify->message, notify->message_len); message_str[notify->message_len] = 0; message_prefix = ": "; } LOG_INFO("remote channel %u:%u %s%s #%u%s%s", get_type(), get_id(), severity, visibility, notify->what, message_prefix, message_str); if (notify->message_len) { delete [] message_str; } } void RedChannel::handle_wait_for_channels(RedPeer::InMessage* message) { SpiceMsgWaitForChannels *wait = (SpiceMsgWaitForChannels *)message->data(); if (message->size() < sizeof(*wait) + wait->wait_count * sizeof(wait->wait_list[0])) { THROW("access violation"); } _client.wait_for_channels(wait->wait_count, wait->wait_list); }
Open365/spice-web-client
misc/spice-0.12.0/client/red_channel.cpp
C++
agpl-3.0
27,728
<?php namespace Safe; use Safe\Exceptions\SwooleException; /** * * * @param string $filename The filename being written. * @param string $content The content writing to the file. * @param int $offset The offset. * @param callable $callback * @throws SwooleException * */ function swoole_async_write(string $filename, string $content, int $offset = null, callable $callback = null): void { error_clear_last(); if ($callback !== null) { $result = \swoole_async_write($filename, $content, $offset, $callback); } elseif ($offset !== null) { $result = \swoole_async_write($filename, $content, $offset); } else { $result = \swoole_async_write($filename, $content); } if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param string $filename The filename being written. * @param string $content The content writing to the file. * @param callable $callback * @param int $flags * @throws SwooleException * */ function swoole_async_writefile(string $filename, string $content, callable $callback = null, int $flags = 0): void { error_clear_last(); if ($flags !== 0) { $result = \swoole_async_writefile($filename, $content, $callback, $flags); } elseif ($callback !== null) { $result = \swoole_async_writefile($filename, $content, $callback); } else { $result = \swoole_async_writefile($filename, $content); } if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param callable $callback * @throws SwooleException * */ function swoole_event_defer(callable $callback): void { error_clear_last(); $result = \swoole_event_defer($callback); if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param int $fd * @throws SwooleException * */ function swoole_event_del(int $fd): void { error_clear_last(); $result = \swoole_event_del($fd); if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param int $fd * @param string $data * @throws SwooleException * */ function swoole_event_write(int $fd, string $data): void { error_clear_last(); $result = \swoole_event_write($fd, $data); if ($result === false) { throw SwooleException::createFromPhpError(); } }
Irstea/collec
vendor/thecodingmachine/safe/generated/swoole.php
PHP
agpl-3.0
2,407
/* * BrainBrowser: Web-based Neurological Visualization Tools * (https://brainbrowser.cbrain.mcgill.ca) * * Copyright (C) 2011 * The Royal Institution for the Advancement of Learning * McGill University * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BrainBrowser v2.1.1 * * Author: Tarek Sherif <tsherif@gmail.com> (http://tareksherif.ca/) * Author: Nicolas Kassis * Author: Paul Mougel */ !function(){"use strict";function a(a){var b,c,d,e,f={};for(f.values=a.replace(/^\s+/,"").replace(/\s+$/,"").split(/\s+/).map(parseFloat),d=f.values[0],e=f.values[0],b=1,c=f.values.length;c>b;b++)d=Math.min(d,f.values[b]),e=Math.max(e,f.values[b]);return f.min=d,f.max=e,f}self.addEventListener("message",function(b){var c=b.data,d=c.data;self.postMessage(a(d))})}();
rdvincent/brainbrowser
build/brainbrowser-2.1.1/workers/mniobj.intensity.worker.js
JavaScript
agpl-3.0
1,377
/* * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center. * * 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. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang3.StringUtils; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.HashMap; import javax.servlet.*; import javax.servlet.http.*; /** * * @author Manda Wilson */ public class SessionServiceRequestWrapper extends HttpServletRequestWrapper { public static final String SESSION_ERROR = "session_error"; public static final String SESSION_ID_PARAM = "session_id"; private static Log LOG = LogFactory.getLog(SessionServiceRequestWrapper.class); private Map<String, String[]> storedParameters; private String sessionId; /** * If session_id is a request parameter, calls session-service API to retrieve * stored session. Stores SESSION_ERROR as a request attribute if the session is * not found, or the session service returns an error. Stored session parameters * override current request parameters. If session_id is not a request parameter, * request behaves as normal. * * @param request wrapped HttpServletRequest */ public SessionServiceRequestWrapper(final HttpServletRequest request) { super(request); LOG.debug("new SessionServiceRequestWrapper()"); sessionId = super.getParameter(SESSION_ID_PARAM); LOG.debug("new SessionServiceRequestWrapper(): request parameter '" + SESSION_ID_PARAM + "' = '" + sessionId + "'"); if (!StringUtils.isBlank(sessionId)) { LOG.debug("new SessionServiceRequestWrapper(): retrieved parameters = '" + storedParameters + "'"); try { storedParameters = SessionServiceUtil.getSession(sessionId); if (storedParameters == null || storedParameters.size() == 0) { request.setAttribute(SESSION_ERROR, "Session with id '" + sessionId + "' not found."); } } catch (Exception e) { request.setAttribute(SESSION_ERROR, "Session service error. Session with id '" + sessionId + "' not loaded. Try again later. If problem persists contact site administrator."); } } } @Override public String getParameter(final String name) { if (storedParameters != null && !SESSION_ID_PARAM.equals(name)) { LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): accessing parameters from stored session with id '" + sessionId + "'"); if (storedParameters.containsKey(name)) { String value = storedParameters.get(name)[0]; LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): returning '" + value + "'"); return value; } LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): returning null - parameter name not found"); return null; } LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): accessing current request parameters"); return super.getParameter(name); } @Override public Map<String, String[]> getParameterMap() { if (storedParameters != null) { LOG.debug("SessionServiceRequestWrapper.getParameterMap(): accessing parameters from stored session with id '" + sessionId + "'"); return Collections.unmodifiableMap(storedParameters); } LOG.debug("SessionServiceRequestWrapper.getParameterMap(): accessing current request parameters"); return super.getParameterMap(); } @Override public Enumeration<String> getParameterNames() { if (storedParameters != null) { LOG.debug("SessionServiceRequestWrapper.getParameterNames(): accessing parameters from stored session with id '" + sessionId + "'"); return Collections.enumeration(storedParameters.keySet()); } LOG.debug("SessionServiceRequestWrapper.getParameterNames(): accessing current request parameters"); return super.getParameterNames(); } @Override public String[] getParameterValues(final String name) { if (storedParameters != null) { LOG.debug("SessionServiceRequestWrapper.getParameterValues(): accessing parameters from stored session with id '" + sessionId + "'"); return storedParameters.get(name); } LOG.debug("SessionServiceRequestWrapper.getParameterValues(): accessing current request parameters"); return super.getParameterValues(name); } }
onursumer/cbioportal
core/src/main/java/org/mskcc/cbio/portal/util/SessionServiceRequestWrapper.java
Java
agpl-3.0
6,093
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.common.budget.framework.period; import org.kuali.coeus.common.budget.framework.core.Budget; public class GenerateBudgetPeriodEvent extends BudgetPeriodEventBase { public GenerateBudgetPeriodEvent(Budget budget, BudgetPeriod budgetPeriod) { super(budget, budgetPeriod); } }
sanjupolus/KC6.oLatest
coeus-impl/src/main/java/org/kuali/coeus/common/budget/framework/period/GenerateBudgetPeriodEvent.java
Java
agpl-3.0
1,109
odoo.define('website_slides/static/src/tests/activity_tests.js', function (require) { 'use strict'; const components = { Activity: require('mail/static/src/components/activity/activity.js'), }; const { afterEach, beforeEach, createRootComponent, start, } = require('mail/static/src/utils/test_utils.js'); QUnit.module('website_slides', {}, function () { QUnit.module('components', {}, function () { QUnit.module('activity', {}, function () { QUnit.module('activity_tests.js', { beforeEach() { beforeEach(this); this.createActivityComponent = async activity => { await createRootComponent(this, components.Activity, { props: { activityLocalId: activity.localId }, target: this.widget.el, }); }; this.start = async params => { const { env, widget } = await start(Object.assign({}, params, { data: this.data, })); this.env = env; this.widget = widget; }; }, afterEach() { afterEach(this); }, }); QUnit.test('grant course access', async function (assert) { assert.expect(8); await this.start({ async mockRPC(route, args) { if (args.method === 'action_grant_access') { assert.strictEqual(args.args.length, 1); assert.strictEqual(args.args[0].length, 1); assert.strictEqual(args.args[0][0], 100); assert.strictEqual(args.kwargs.partner_id, 5); assert.step('access_grant'); } return this._super(...arguments); }, }); const activity = this.env.models['mail.activity'].create({ id: 100, canWrite: true, thread: [['insert', { id: 100, model: 'slide.channel', }]], requestingPartner: [['insert', { id: 5, displayName: "Pauvre pomme", }]], type: [['insert', { id: 1, displayName: "Access Request", }]], }); await this.createActivityComponent(activity); assert.containsOnce(document.body, '.o_Activity', "should have activity component"); assert.containsOnce(document.body, '.o_Activity_grantAccessButton', "should have grant access button"); document.querySelector('.o_Activity_grantAccessButton').click(); assert.verifySteps(['access_grant'], "Grant button should trigger the right rpc call"); }); QUnit.test('refuse course access', async function (assert) { assert.expect(8); await this.start({ async mockRPC(route, args) { if (args.method === 'action_refuse_access') { assert.strictEqual(args.args.length, 1); assert.strictEqual(args.args[0].length, 1); assert.strictEqual(args.args[0][0], 100); assert.strictEqual(args.kwargs.partner_id, 5); assert.step('access_refuse'); } return this._super(...arguments); }, }); const activity = this.env.models['mail.activity'].create({ id: 100, canWrite: true, thread: [['insert', { id: 100, model: 'slide.channel', }]], requestingPartner: [['insert', { id: 5, displayName: "Pauvre pomme", }]], type: [['insert', { id: 1, displayName: "Access Request", }]], }); await this.createActivityComponent(activity); assert.containsOnce(document.body, '.o_Activity', "should have activity component"); assert.containsOnce(document.body, '.o_Activity_refuseAccessButton', "should have refuse access button"); document.querySelector('.o_Activity_refuseAccessButton').click(); assert.verifySteps(['access_refuse'], "refuse button should trigger the right rpc call"); }); }); }); }); });
rven/odoo
addons/website_slides/static/src/components/activity/activity_tests.js
JavaScript
agpl-3.0
3,940
""" WSGI config for OIPA project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "OIPA.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OIPA.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
schlos/OIPA-V2.1
OIPA/OIPA/wsgi.py
Python
agpl-3.0
1,413
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ namespace Shopware\Recovery\Install\Service; use Shopware\Recovery\Install\Struct\Shop; /** * @category Shopware * * @copyright Copyright (c) shopware AG (http://www.shopware.de) */ class ShopService { /** * @var \PDO */ private $connection; /** * @param \PDO $connection */ public function __construct(\PDO $connection) { $this->connection = $connection; } /** * @param Shop $shop * * @throws \RuntimeException */ public function updateShop(Shop $shop) { if (empty($shop->locale) || empty($shop->host) ) { throw new \RuntimeException('Please fill in all required fields. (shop configuration)'); } try { $fetchLanguageId = $this->getLocaleIdByLocale($shop->locale); // Update s_core_shops $sql = <<<'EOT' UPDATE s_core_shops SET `name` = ?, locale_id = ?, host = ?, base_path = ?, hosts = ? WHERE `default` = 1 EOT; $prepareStatement = $this->connection->prepare($sql); $prepareStatement->execute([ $shop->name, $fetchLanguageId, $shop->host, $shop->basePath, $shop->host, ]); } catch (\Exception $e) { throw new \RuntimeException($e->getMessage(), 0, $e); } } /** * @param Shop $shop * * @throws \RuntimeException */ public function updateConfig(Shop $shop) { // Do update on shop-configuration if (empty($shop->name) || empty($shop->email)) { throw new \RuntimeException('Please fill in all required fields. (shop configuration#2)'); } $this->updateMailAddress($shop); $this->updateShopName($shop); } /** * @param string $locale * * @return int */ protected function getLocaleIdByLocale($locale) { $fetchLanguageId = $this->connection->prepare( 'SELECT id FROM s_core_locales WHERE locale = ?' ); $fetchLanguageId->execute([$locale]); $fetchLanguageId = $fetchLanguageId->fetchColumn(); if (!$fetchLanguageId) { throw new \RuntimeException('Language with id ' . $locale . ' not found'); } return (int) $fetchLanguageId; } /** * @param Shop $shop */ private function updateMailAddress(Shop $shop) { $this->updateConfigValue('mail', $shop->email); } /** * @param Shop $shop */ private function updateShopName(Shop $shop) { $this->updateConfigValue('shopName', $shop->name); } /** * @param string $elementName * @param mixed $value */ private function updateConfigValue($elementName, $value) { $sql = <<<'EOT' DELETE FROM s_core_config_values WHERE element_id = (SELECT id FROM s_core_config_elements WHERE name=:elementName) AND shop_id = 1 EOT; $this->connection->prepare($sql)->execute([ 'elementName' => $elementName, ]); $sql = <<<'EOT' INSERT INTO `s_core_config_values` (`id`, `element_id`, `shop_id`, `value`) VALUES (NULL, (SELECT id FROM s_core_config_elements WHERE name=:elementName), 1, :value); EOT; $prepared = $this->connection->prepare($sql); $prepared->execute([ 'elementName' => $elementName, 'value' => serialize($value), ]); } }
egoistIT/shopware
recovery/install/src/Service/ShopService.php
PHP
agpl-3.0
4,461
/** * tapcfg - A cross-platform configuration utility for TAP driver * Copyright (C) 2008-2011 Juho Vähä-Herttua * * 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. */ using TAPNet; using System; using System.Net; using System.Threading; public class TAPNetTest { private static void Main(string[] args) { VirtualDevice dev = new VirtualDevice(); dev.LogCallback = new LogCallback(LogCallback); dev.Start("Device name", true); Console.WriteLine("Got device name: {0}", dev.DeviceName); Console.WriteLine("Got device hwaddr: {0}", BitConverter.ToString(dev.HWAddress)); dev.HWAddress = new byte[] { 0x00, 0x01, 0x23, 0x45, 0x67, 0x89 }; dev.MTU = 1280; dev.SetAddress(IPAddress.Parse("192.168.10.1"), 16); dev.Enabled = true; while (true) { Thread.Sleep(1000); } } private static void LogCallback(LogLevel level, string msg) { Console.WriteLine(level + ": " + msg); } }
juhovh/tapcfg
src/demos/TAPNetTest.cs
C#
lgpl-2.1
1,388
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * import os class Psi4(CMakePackage): """Psi4 is an open-source suite of ab initio quantum chemistry programs designed for efficient, high-accuracy simulations of a variety of molecular properties.""" homepage = "http://www.psicode.org/" url = "https://github.com/psi4/psi4/archive/0.5.tar.gz" version('0.5', '53041b8a9be3958384171d0d22f9fdd0') variant('build_type', default='Release', description='The build type to build', values=('Debug', 'Release')) # Required dependencies depends_on('blas') depends_on('lapack') depends_on('boost+chrono+filesystem+python+regex+serialization+system+timer+thread') depends_on('python') depends_on('cmake@3.3:', type='build') depends_on('py-numpy', type=('build', 'run')) # Optional dependencies # TODO: add packages for these # depends_on('perl') # depends_on('erd') # depends_on('pcm-solver') # depends_on('chemps2') def cmake_args(self): spec = self.spec return [ '-DBLAS_TYPE={0}'.format(spec['blas'].name.upper()), '-DBLAS_LIBRARIES={0}'.format(spec['blas'].libs.joined()), '-DLAPACK_TYPE={0}'.format(spec['lapack'].name.upper()), '-DLAPACK_LIBRARIES={0}'.format( spec['lapack'].libs.joined()), '-DBOOST_INCLUDEDIR={0}'.format(spec['boost'].prefix.include), '-DBOOST_LIBRARYDIR={0}'.format(spec['boost'].prefix.lib), '-DENABLE_CHEMPS2=OFF' ] @run_after('install') def filter_compilers(self, spec, prefix): """Run after install to tell the configuration files to use the compilers that Spack built the package with. If this isn't done, they'll have PLUGIN_CXX set to Spack's generic cxx. We want it to be bound to whatever compiler it was built with.""" kwargs = {'ignore_absent': True, 'backup': False, 'string': True} cc_files = ['bin/psi4-config'] cxx_files = ['bin/psi4-config', 'include/psi4/psiconfig.h'] template = 'share/psi4/plugin/Makefile.template' for filename in cc_files: filter_file(os.environ['CC'], self.compiler.cc, os.path.join(prefix, filename), **kwargs) for filename in cxx_files: filter_file(os.environ['CXX'], self.compiler.cxx, os.path.join(prefix, filename), **kwargs) # The binary still keeps track of the compiler used to install Psi4 # and uses it when creating a plugin template filter_file('@PLUGIN_CXX@', self.compiler.cxx, os.path.join(prefix, template), **kwargs) # The binary links to the build include directory instead of the # installation include directory: # https://github.com/psi4/psi4/issues/410 filter_file('@PLUGIN_INCLUDES@', '-I{0}'.format( ' -I'.join([ os.path.join(spec['psi4'].prefix.include, 'psi4'), os.path.join(spec['boost'].prefix.include, 'boost'), os.path.join(spec['python'].headers.directories[0]), spec['lapack'].prefix.include, spec['blas'].prefix.include, '/usr/include' ]) ), os.path.join(prefix, template), **kwargs)
EmreAtes/spack
var/spack/repos/builtin/packages/psi4/package.py
Python
lgpl-2.1
4,596
/*****************************************/ /* Written by andrew.wilkins@csiro.au */ /* Please contact me if you make changes */ /*****************************************/ #include "RichardsExcavFlow.h" #include "Function.h" #include "Material.h" template<> InputParameters validParams<RichardsExcavFlow>() { InputParameters params = validParams<SideIntegralVariablePostprocessor>(); params.addRequiredParam<FunctionName>("excav_geom_function", "The function describing the excavation geometry (type RichardsExcavGeom)"); params.addRequiredParam<UserObjectName>("richardsVarNames_UO", "The UserObject that holds the list of Richards variable names."); params.addClassDescription("Records total flow INTO an excavation (if quantity is positive then flow has occured from rock into excavation void)"); return params; } RichardsExcavFlow::RichardsExcavFlow(const std::string & name, InputParameters parameters) : SideIntegralVariablePostprocessor(name, parameters), _richards_name_UO(getUserObject<RichardsVarNames>("richardsVarNames_UO")), _pvar(_richards_name_UO.richards_var_num(_var.number())), _flux(getMaterialProperty<std::vector<RealVectorValue> >("flux")), _func(getFunction("excav_geom_function")) {} Real RichardsExcavFlow::computeQpIntegral() { return -_func.value(_t, _q_point[_qp])*_normals[_qp]*_flux[_qp][_pvar]*_dt; }
cpritam/moose
modules/richards/src/postprocessors/RichardsExcavFlow.C
C++
lgpl-2.1
1,375
/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "RichardsExcavFlow.h" #include "Function.h" #include "Material.h" template<> InputParameters validParams<RichardsExcavFlow>() { InputParameters params = validParams<SideIntegralVariablePostprocessor>(); params.addRequiredParam<FunctionName>("excav_geom_function", "The function describing the excavation geometry (type RichardsExcavGeom)"); params.addRequiredParam<UserObjectName>("richardsVarNames_UO", "The UserObject that holds the list of Richards variable names."); params.addClassDescription("Records total flow INTO an excavation (if quantity is positive then flow has occured from rock into excavation void)"); return params; } RichardsExcavFlow::RichardsExcavFlow(const std::string & name, InputParameters parameters) : SideIntegralVariablePostprocessor(name, parameters), _richards_name_UO(getUserObject<RichardsVarNames>("richardsVarNames_UO")), _pvar(_richards_name_UO.richards_var_num(_var.number())), _flux(getMaterialProperty<std::vector<RealVectorValue> >("flux")), _func(getFunction("excav_geom_function")) {} Real RichardsExcavFlow::computeQpIntegral() { return -_func.value(_t, _q_point[_qp])*_normals[_qp]*_flux[_qp][_pvar]*_dt; }
gleicher27/Tardigrade
moose/modules/richards/src/postprocessors/RichardsExcavFlow.C
C++
lgpl-2.1
1,602
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main.contactlist.contactsource; import java.util.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.service.contactsource.*; import net.java.sip.communicator.service.protocol.*; /** * The <tt>StringContactSourceServiceImpl</tt> is an implementation of the * <tt>ContactSourceService</tt> that returns the searched string as a result * contact. * * @author Yana Stamcheva */ public class StringContactSourceServiceImpl implements ContactSourceService { /** * The protocol provider to be used with this string contact source. */ private final ProtocolProviderService protocolProvider; /** * The operation set supported by this string contact source. */ private final Class<? extends OperationSet> opSetClass; /** * Can display disable adding display details for source contacts. */ private boolean disableDisplayDetails = true; /** * Creates an instance of <tt>StringContactSourceServiceImpl</tt>. * * @param protocolProvider the protocol provider to be used with this string * contact source * @param opSet the operation set supported by this string contact source */ public StringContactSourceServiceImpl( ProtocolProviderService protocolProvider, Class<? extends OperationSet> opSet) { this.protocolProvider = protocolProvider; this.opSetClass = opSet; } /** * Returns the type of this contact source. * * @return the type of this contact source */ public int getType() { return SEARCH_TYPE; } /** * Returns a user-friendly string that identifies this contact source. * * @return the display name of this contact source */ public String getDisplayName() { return GuiActivator.getResources().getI18NString( "service.gui.SEARCH_STRING_CONTACT_SOURCE"); } /** * Creates query for the given <tt>queryString</tt>. * * @param queryString the string to search for * @return the created query */ public ContactQuery createContactQuery(String queryString) { return createContactQuery(queryString, -1); } /** * Creates query for the given <tt>queryString</tt>. * * @param queryString the string to search for * @param contactCount the maximum count of result contacts * @return the created query */ public ContactQuery createContactQuery( String queryString, int contactCount) { return new StringQuery(queryString); } /** * Changes whether to add display details for contact sources. * @param disableDisplayDetails */ public void setDisableDisplayDetails(boolean disableDisplayDetails) { this.disableDisplayDetails = disableDisplayDetails; } /** * Returns the source contact corresponding to the query string. * * @return the source contact corresponding to the query string */ public SourceContact createSourceContact(String queryString) { ArrayList<ContactDetail> contactDetails = new ArrayList<ContactDetail>(); ContactDetail contactDetail = new ContactDetail(queryString); // Init supported operation sets. ArrayList<Class<? extends OperationSet>> supportedOpSets = new ArrayList<Class<? extends OperationSet>>(); supportedOpSets.add(opSetClass); contactDetail.setSupportedOpSets(supportedOpSets); // Init preferred protocol providers. Map<Class<? extends OperationSet>,ProtocolProviderService> providers = new HashMap<Class<? extends OperationSet>, ProtocolProviderService>(); providers.put(opSetClass, protocolProvider); contactDetail.setPreferredProviders(providers); contactDetails.add(contactDetail); GenericSourceContact sourceContact = new GenericSourceContact( StringContactSourceServiceImpl.this, queryString, contactDetails); if(disableDisplayDetails) { sourceContact.setDisplayDetails( GuiActivator.getResources().getI18NString( "service.gui.CALL_VIA") + " " + protocolProvider.getAccountID().getDisplayName()); } return sourceContact; } /** * The query implementation. */ private class StringQuery extends AbstractContactQuery<ContactSourceService> { /** * The query string. */ private String queryString; /** * The query result list. */ private final List<SourceContact> results; /** * Creates an instance of this query implementation. * * @param queryString the string to query */ public StringQuery(String queryString) { super(StringContactSourceServiceImpl.this); this.queryString = queryString; this.results = new ArrayList<SourceContact>(); } /** * Returns the query string. * * @return the query string */ public String getQueryString() { return queryString; } /** * Returns the list of query results. * * @return the list of query results */ public List<SourceContact> getQueryResults() { return results; } @Override public void start() { SourceContact contact = createSourceContact(queryString); results.add(contact); fireContactReceived(contact); if (getStatus() != QUERY_CANCELED) setStatus(QUERY_COMPLETED); } } /** * Returns the index of the contact source in the result list. * * @return the index of the contact source in the result list */ public int getIndex() { return 0; } }
marclaporte/jitsi
src/net/java/sip/communicator/impl/gui/main/contactlist/contactsource/StringContactSourceServiceImpl.java
Java
lgpl-2.1
6,347
/* Soot - a J*va Optimization Framework * Copyright (C) 2002 Florian Loitsch * * 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. * * 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. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ package soot.jimple.toolkits.scalar.pre; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.EquivalentValue; import soot.G; import soot.Local; import soot.Scene; import soot.SideEffectTester; import soot.Singletons; import soot.Unit; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.IdentityStmt; import soot.jimple.Jimple; import soot.jimple.NaiveSideEffectTester; import soot.jimple.toolkits.graph.CriticalEdgeRemover; import soot.jimple.toolkits.pointer.PASideEffectTester; import soot.jimple.toolkits.scalar.LocalCreation; import soot.options.BCMOptions; import soot.options.Options; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.UnitGraph; import soot.util.Chain; import soot.util.UnitMap; /** * Performs a partial redundancy elimination (= code motion). This is done, by * moving <b>every</b>computation as high as possible (it is easy to show, that * they are computationally optimal), and then replacing the original * computation by a reference to this new high computation. This implies, that * we introduce <b>many</b> new helper-variables (that can easily be eliminated * afterwards).<br> * In order to catch every redundant expression, this transformation must be * done on a graph without critical edges. Therefore the first thing we do, is * removing them. A subsequent pass can then easily remove the synthetic nodes * we have introduced.<br> * The term "busy" refers to the fact, that we <b>always</b> move computations * as high as possible. Even, if this is not necessary. * * @see soot.jimple.toolkits.graph.CriticalEdgeRemover */ public class BusyCodeMotion extends BodyTransformer { public BusyCodeMotion(Singletons.Global g) { } public static BusyCodeMotion v() { return G.v().soot_jimple_toolkits_scalar_pre_BusyCodeMotion(); } private static final String PREFIX = "$bcm"; /** * performs the busy code motion. */ protected void internalTransform(Body b, String phaseName, Map<String, String> opts) { BCMOptions options = new BCMOptions(opts); HashMap<EquivalentValue, Local> expToHelper = new HashMap<EquivalentValue, Local>(); Chain<Unit> unitChain = b.getUnits(); if (Options.v().verbose()) G.v().out.println("[" + b.getMethod().getName() + "] performing Busy Code Motion..."); CriticalEdgeRemover.v().transform(b, phaseName + ".cer"); UnitGraph graph = new BriefUnitGraph(b); /* map each unit to its RHS. only take binary expressions */ Map<Unit, EquivalentValue> unitToEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) { protected EquivalentValue mapTo(Unit unit) { Value tmp = SootFilter.noInvokeRhs(unit); Value tmp2 = SootFilter.binop(tmp); if (tmp2 == null) tmp2 = SootFilter.concreteRef(tmp); return SootFilter.equiVal(tmp2); } }; /* same as before, but without exception-throwing expressions */ Map<Unit, EquivalentValue> unitToNoExceptionEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) { protected EquivalentValue mapTo(Unit unit) { Value tmp = SootFilter.binopRhs(unit); tmp = SootFilter.noExceptionThrowing(tmp); return SootFilter.equiVal(tmp); } }; /* if a more precise sideeffect-tester comes out, please change it here! */ SideEffectTester sideEffect; if (Scene.v().hasCallGraph() && !options.naive_side_effect()) { sideEffect = new PASideEffectTester(); } else { sideEffect = new NaiveSideEffectTester(); } sideEffect.newMethod(b.getMethod()); UpSafetyAnalysis upSafe = new UpSafetyAnalysis(graph, unitToEquivRhs, sideEffect); DownSafetyAnalysis downSafe = new DownSafetyAnalysis(graph, unitToNoExceptionEquivRhs, sideEffect); EarliestnessComputation earliest = new EarliestnessComputation(graph, upSafe, downSafe, sideEffect); LocalCreation localCreation = new LocalCreation(b.getLocals(), PREFIX); Iterator<Unit> unitIt = unitChain.snapshotIterator(); { /* insert the computations at the earliest positions */ while (unitIt.hasNext()) { Unit currentUnit = unitIt.next(); for (EquivalentValue equiVal : earliest.getFlowBefore(currentUnit)) { // Value exp = equiVal.getValue(); /* get the unic helper-name for this expression */ Local helper = expToHelper.get(equiVal); // Make sure not to place any stuff inside the identity block at // the beginning of the method if (currentUnit instanceof IdentityStmt) currentUnit = getFirstNonIdentityStmt(b); if (helper == null) { helper = localCreation.newLocal(equiVal.getType()); expToHelper.put(equiVal, helper); } /* insert a new Assignment-stmt before the currentUnit */ Value insertValue = Jimple.cloneIfNecessary(equiVal.getValue()); Unit firstComp = Jimple.v().newAssignStmt(helper, insertValue); unitChain.insertBefore(firstComp, currentUnit); } } } { /* replace old computations by the helper-vars */ unitIt = unitChain.iterator(); while (unitIt.hasNext()) { Unit currentUnit = unitIt.next(); EquivalentValue rhs = unitToEquivRhs.get(currentUnit); if (rhs != null) { Local helper = expToHelper.get(rhs); if (helper != null) ((AssignStmt) currentUnit).setRightOp(helper); } } } if (Options.v().verbose()) G.v().out.println("[" + b.getMethod().getName() + "] Busy Code Motion done!"); } private Unit getFirstNonIdentityStmt(Body b) { for (Unit u : b.getUnits()) if (!(u instanceof IdentityStmt)) return u; return null; } }
cfallin/soot
src/soot/jimple/toolkits/scalar/pre/BusyCodeMotion.java
Java
lgpl-2.1
6,656
/* * #%L * Alfresco Repository * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco 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 3 of the License, or * (at your option) any later version. * * Alfresco 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. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.cache; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import org.alfresco.repo.cache.TransactionStats.OpType; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Simple non-persistent implementation of {@link CacheStatistics}. Statistics * are empty at repository startup. * * @since 5.0 * @author Matt Ward */ public class InMemoryCacheStatistics implements CacheStatistics, ApplicationContextAware { /** Read/Write locks by cache name */ private final ConcurrentMap<String, ReentrantReadWriteLock> locks = new ConcurrentHashMap<>(); private Map<String, Map<OpType, OperationStats>> cacheToStatsMap = new HashMap<>(); private ApplicationContext applicationContext; @Override public long count(String cacheName, OpType opType) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } OperationStats opStats = cacheStats.get(opType); return opStats.getCount(); } finally { readLock.unlock(); } } @Override public double meanTime(String cacheName, OpType opType) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } OperationStats opStats = cacheStats.get(opType); return opStats.meanTime(); } finally { readLock.unlock(); } } @Override public void add(String cacheName, TransactionStats txStats) { boolean registerCacheStats = false; WriteLock writeLock = getWriteLock(cacheName); writeLock.lock(); try { // Are we adding new stats for a previously unseen cache? registerCacheStats = !cacheToStatsMap.containsKey(cacheName); if (registerCacheStats) { // There are no statistics yet for this cache. cacheToStatsMap.put(cacheName, new HashMap<OpType, OperationStats>()); } Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); for (OpType opType : OpType.values()) { SummaryStatistics txOpSummary = txStats.getTimings(opType); long count = txOpSummary.getN(); double totalTime = txOpSummary.getSum(); OperationStats oldStats = cacheStats.get(opType); OperationStats newStats; if (oldStats == null) { newStats = new OperationStats(totalTime, count); } else { newStats = new OperationStats(oldStats, totalTime, count); } cacheStats.put(opType, newStats); } } finally { writeLock.unlock(); } if (registerCacheStats) { // We've added stats for a previously unseen cache, raise an event // so that an MBean for the cache may be registered, for example. applicationContext.publishEvent(new CacheStatisticsCreated(this, cacheName)); } } @Override public double hitMissRatio(String cacheName) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } long hits = cacheStats.get(OpType.GET_HIT).getCount(); long misses = cacheStats.get(OpType.GET_MISS).getCount(); return (double)hits / (hits+misses); } finally { readLock.unlock(); } } @Override public long numGets(String cacheName) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } long hits = cacheStats.get(OpType.GET_HIT).getCount(); long misses = cacheStats.get(OpType.GET_MISS).getCount(); return hits+misses; } finally { readLock.unlock(); } } @Override public Map<OpType, OperationStats> allStats(String cacheName) { ReadLock readLock = getReadLock(cacheName); readLock.lock(); try { Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName); if (cacheStats == null) { throw new NoStatsForCache(cacheName); } return new HashMap<>(cacheStats); } finally { readLock.unlock(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * Gets a {@link ReentrantReadWriteLock} for a specific cache, lazily * creating the lock if necessary. Locks may be created per cache * (rather than hashing to a smaller pool) since the number of * caches is not too large. * * @param cacheName Cache name to obtain lock for. * @return ReentrantReadWriteLock */ private ReentrantReadWriteLock getLock(String cacheName) { if (!locks.containsKey(cacheName)) { ReentrantReadWriteLock newLock = new ReentrantReadWriteLock(); if (locks.putIfAbsent(cacheName, newLock) == null) { // Lock was successfully added to map. return newLock; }; } return locks.get(cacheName); } private ReadLock getReadLock(String cacheName) { ReadLock readLock = getLock(cacheName).readLock(); return readLock; } private WriteLock getWriteLock(String cacheName) { WriteLock writeLock = getLock(cacheName).writeLock(); return writeLock; } }
Alfresco/alfresco-repository
src/main/java/org/alfresco/repo/cache/InMemoryCacheStatistics.java
Java
lgpl-3.0
8,474
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Runtime.CompilerServices; #if !FEATURE_CORE_DLR namespace Microsoft.Scripting.Ast { #else namespace System.Linq.Expressions { #endif /// <summary> /// Represents creating a new array and possibly initializing the elements of the new array. /// </summary> [DebuggerTypeProxy(typeof(Expression.NewArrayExpressionProxy))] public class NewArrayExpression : Expression { private readonly ReadOnlyCollection<Expression> _expressions; private readonly Type _type; internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions) { _expressions = expressions; _type = type; } internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions) { if (nodeType == ExpressionType.NewArrayInit) { return new NewArrayInitExpression(type, expressions); } else { return new NewArrayBoundsExpression(type, expressions); } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Gets the bounds of the array if the value of the <see cref="P:NodeType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="P:NodeType"/> property is NewArrayInit. /// </summary> public ReadOnlyCollection<Expression> Expressions { get { return _expressions; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitNewArray(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expressions">The <see cref="Expressions" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public NewArrayExpression Update(IEnumerable<Expression> expressions) { if (expressions == Expressions) { return this; } if (NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(Type.GetElementType(), expressions); } return Expression.NewArrayBounds(Type.GetElementType(), expressions); } } internal sealed class NewArrayInitExpression : NewArrayExpression { internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.NewArrayInit; } } } internal sealed class NewArrayBoundsExpression : NewArrayExpression { internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions) : base(type, expressions) { } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.NewArrayBounds; } } } public partial class Expression { #region NewArrayInit /// <summary> /// Creates a new array expression of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns> public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers) { return NewArrayInit(type, (IEnumerable<Expression>)initializers); } /// <summary> /// Creates a new array expression of the specified type from the provided initializers. /// </summary> /// <param name="type">A Type that represents the element type of the array.</param> /// <param name="initializers">The expressions used to create the array elements.</param> /// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns> public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(initializers, "initializers"); if (type.Equals(typeof(void))) { throw Error.ArgumentCannotBeOfTypeVoid(); } ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly(); Expression[] newList = null; for (int i = 0, n = initializerList.Count; i < n; i++) { Expression expr = initializerList[i]; RequiresCanRead(expr, "initializers"); if (!TypeUtils.AreReferenceAssignable(type, expr.Type)) { if (!TryQuote(type, ref expr)){ throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type); } if (newList == null) { newList = new Expression[initializerList.Count]; for (int j = 0; j < i; j++) { newList[j] = initializerList[j]; } } } if (newList != null) { newList[i] = expr; } } if (newList != null) { initializerList = new TrueReadOnlyCollection<Expression>(newList); } return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList); } #endregion #region NewArrayBounds /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param> /// <param name="bounds">An array that contains Expression objects to use to populate the Expressions collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds) { return NewArrayBounds(type, (IEnumerable<Expression>)bounds); } /// <summary> /// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank. /// </summary> /// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param> /// <param name="bounds">An IEnumerable{T} that contains Expression objects to use to populate the Expressions collection.</param> /// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns> public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(bounds, "bounds"); if (type.Equals(typeof(void))) { throw Error.ArgumentCannotBeOfTypeVoid(); } ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly(); int dimensions = boundsList.Count; if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne(); for (int i = 0; i < dimensions; i++) { Expression expr = boundsList[i]; RequiresCanRead(expr, "bounds"); if (!TypeUtils.IsInteger(expr.Type)) { throw Error.ArgumentMustBeInteger(); } } Type arrayType; if (dimensions == 1) { //To get a vector, need call Type.MakeArrayType(). //Type.MakeArrayType(1) gives a non-vector array, which will cause type check error. arrayType = type.MakeArrayType(); } else { arrayType = type.MakeArrayType(dimensions); } return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, bounds.ToReadOnly()); } #endregion } }
edwinspire/VSharp
class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs
C#
lgpl-3.0
10,491
/** * Created : Mar 26, 2012 * * @author pquiring */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ProgrammerPanel extends javax.swing.JPanel implements Display, ActionListener { /** * Creates new form MainPanel */ public ProgrammerPanel(Backend backend) { initComponents(); divide.setText("\u00f7"); this.backend = backend; Insets zero = new Insets(0, 0, 0, 0); JButton b; for(int a=0;a<getComponentCount();a++) { Component c = getComponent(a); if (c instanceof JButton) { b = (JButton)c; b.addActionListener(this); b.setMargin(zero); } } backend.setRadix(10); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); output = new javax.swing.JTextField(); n7 = new javax.swing.JButton(); n8 = new javax.swing.JButton(); n9 = new javax.swing.JButton(); n4 = new javax.swing.JButton(); n5 = new javax.swing.JButton(); n6 = new javax.swing.JButton(); n1 = new javax.swing.JButton(); n2 = new javax.swing.JButton(); n3 = new javax.swing.JButton(); n0 = new javax.swing.JButton(); divide = new javax.swing.JButton(); multiple = new javax.swing.JButton(); minus = new javax.swing.JButton(); plus = new javax.swing.JButton(); allClear = new javax.swing.JButton(); open = new javax.swing.JButton(); close = new javax.swing.JButton(); eq = new javax.swing.JButton(); open1 = new javax.swing.JButton(); open2 = new javax.swing.JButton(); open3 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); hex = new javax.swing.JRadioButton(); decimal = new javax.swing.JRadioButton(); oct = new javax.swing.JRadioButton(); bin = new javax.swing.JRadioButton(); n10 = new javax.swing.JButton(); n11 = new javax.swing.JButton(); n12 = new javax.swing.JButton(); n13 = new javax.swing.JButton(); n14 = new javax.swing.JButton(); n15 = new javax.swing.JButton(); open4 = new javax.swing.JButton(); open5 = new javax.swing.JButton(); dec1 = new javax.swing.JButton(); allClear1 = new javax.swing.JButton(); output.setEditable(false); output.setHorizontalAlignment(javax.swing.JTextField.RIGHT); n7.setText("7"); n8.setText("8"); n9.setText("9"); n4.setText("4"); n5.setText("5"); n6.setText("6"); n1.setText("1"); n2.setText("2"); n3.setText("3"); n0.setText("0"); divide.setText("/"); multiple.setText("x"); minus.setText("-"); plus.setText("+"); allClear.setText("AC"); allClear.setToolTipText("All Clear"); open.setText("("); close.setText(")"); eq.setText("="); open1.setText("XOR"); open2.setText("AND"); open3.setText("NOT"); buttonGroup1.add(hex); hex.setText("Hex"); hex.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hexActionPerformed(evt); } }); buttonGroup1.add(decimal); decimal.setSelected(true); decimal.setText("Dec"); decimal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decimalActionPerformed(evt); } }); buttonGroup1.add(oct); oct.setText("Oct"); oct.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { octActionPerformed(evt); } }); buttonGroup1.add(bin); bin.setText("Bin"); bin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { binActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(hex) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(decimal) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(oct) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bin) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(hex) .addComponent(decimal) .addComponent(oct) .addComponent(bin)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); n10.setText("A"); n11.setText("B"); n12.setText("C"); n13.setText("D"); n14.setText("E"); n15.setText("F"); open4.setText("MOD"); open5.setText("OR"); dec1.setText("+/-"); allClear1.setText("<"); allClear1.setToolTipText("All Clear"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(output, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(n10, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n0, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(n8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(allClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(dec1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(62, 62, 62) .addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(eq, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(56, 56, 56)) .addGroup(layout.createSequentialGroup() .addComponent(n5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(multiple, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(open, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(allClear1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(open5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(n11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n12, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n13, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n14, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n15, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(output, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n7) .addComponent(n8) .addComponent(n9) .addComponent(divide) .addComponent(allClear) .addComponent(open2) .addComponent(allClear1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n4) .addComponent(n5) .addComponent(n6) .addComponent(multiple) .addComponent(close) .addComponent(open5) .addComponent(open)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n1) .addComponent(n2) .addComponent(n3) .addComponent(minus) .addComponent(open1) .addComponent(open4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n0) .addComponent(plus) .addComponent(dec1) .addComponent(open3) .addComponent(eq)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n10) .addComponent(n11) .addComponent(n12) .addComponent(n13) .addComponent(n14) .addComponent(n15)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void hexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hexActionPerformed backend.setRadix(16); }//GEN-LAST:event_hexActionPerformed private void decimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decimalActionPerformed backend.setRadix(10); }//GEN-LAST:event_decimalActionPerformed private void octActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_octActionPerformed backend.setRadix(8); }//GEN-LAST:event_octActionPerformed private void binActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_binActionPerformed backend.setRadix(2); }//GEN-LAST:event_binActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton allClear; private javax.swing.JButton allClear1; private javax.swing.JRadioButton bin; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton close; private javax.swing.JButton dec1; private javax.swing.JRadioButton decimal; private javax.swing.JButton divide; private javax.swing.JButton eq; private javax.swing.JRadioButton hex; private javax.swing.JPanel jPanel1; private javax.swing.JButton minus; private javax.swing.JButton multiple; private javax.swing.JButton n0; private javax.swing.JButton n1; private javax.swing.JButton n10; private javax.swing.JButton n11; private javax.swing.JButton n12; private javax.swing.JButton n13; private javax.swing.JButton n14; private javax.swing.JButton n15; private javax.swing.JButton n2; private javax.swing.JButton n3; private javax.swing.JButton n4; private javax.swing.JButton n5; private javax.swing.JButton n6; private javax.swing.JButton n7; private javax.swing.JButton n8; private javax.swing.JButton n9; private javax.swing.JRadioButton oct; private javax.swing.JButton open; private javax.swing.JButton open1; private javax.swing.JButton open2; private javax.swing.JButton open3; private javax.swing.JButton open4; private javax.swing.JButton open5; private javax.swing.JTextField output; private javax.swing.JButton plus; // End of variables declaration//GEN-END:variables private Backend backend; public void setDisplay(String str) { int idx = str.indexOf(','); if (idx != -1) { output.setText(str.substring(0,idx)); //remove radix } else { output.setText(str); } } public void actionPerformed(ActionEvent ae) { JButton b = (JButton)ae.getSource(); String txt = b.getText(); if (txt.length() == 1) { char first = txt.charAt(0); if (((first >= '0') && (first <= '9')) || (first == '.') || ((first >= 'A') && (first <= 'F'))) { backend.addDigit(first); return; } } backend.addOperation(txt); } public void cut() { output.cut(); } public void copy() { output.copy(); } public void setRadix(int rx) { switch (rx) { case 16: hex.setSelected(true); break; case 10: decimal.setSelected(true); break; case 8: oct.setSelected(true); break; case 2: bin.setSelected(true); break; } backend.setRadix(rx); } }
ericomattos/javaforce
projects/jfcalc/src/ProgrammerPanel.java
Java
lgpl-3.0
20,790
/* Copyright 2011, AUTHORS.txt (http://ui.operamasks.org/about) Dual licensed under the MIT or LGPL Version 2 licenses. */ /** * @file Spell checker */ // Register a plugin named "wsc". OMEDITOR.plugins.add( 'wsc', { requires : [ 'dialog' ], init : function( editor ) { var commandName = 'checkspell'; var command = editor.addCommand( commandName, new OMEDITOR.dialogCommand( commandName ) ); // SpellChecker doesn't work in Opera and with custom domain command.modes = { wysiwyg : ( !OMEDITOR.env.opera && !OMEDITOR.env.air && document.domain == window.location.hostname ) }; editor.ui.addButton( 'SpellChecker', { label : editor.lang.spellCheck.toolbar, command : commandName }); OMEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' ); } }); OMEDITOR.config.wsc_customerId = OMEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk' ; OMEDITOR.config.wsc_customLoaderScript = OMEDITOR.config.wsc_customLoaderScript || null;
yonghuang/fastui
samplecenter/basic/timeTest/operamasks-ui-2.0/development-bundle/ui/editor/_source/plugins/wsc/plugin.js
JavaScript
lgpl-3.0
1,027
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export default [ [ [ 'நள்.', 'நண்.', 'அதி.', 'கா.', 'மதி.', 'பிற்.', 'மா.', 'அந்தி மா.', 'இர.' ], [ 'நள்ளிரவு', 'நண்பகல்', 'அதிகாலை', 'காலை', 'மதியம்', 'பிற்பகல்', 'மாலை', 'அந்தி மாலை', 'இரவு' ], ], [ [ 'நள்.', 'நண்.', 'அதி.', 'கா.', 'மதி.', 'பிற்.', 'மா.', 'அந்தி மா.', 'இ.' ], [ 'நள்ளிரவு', 'நண்பகல்', 'அதிகாலை', 'காலை', 'மதியம்', 'பிற்பகல்', 'மாலை', 'அந்தி மாலை', 'இரவு' ], ], [ '00:00', '12:00', ['03:00', '05:00'], ['05:00', '12:00'], ['12:00', '14:00'], ['14:00', '16:00'], ['16:00', '18:00'], ['18:00', '21:00'], ['21:00', '03:00'] ] ]; //# sourceMappingURL=ta-MY.js.map
rospilot/rospilot
share/web_assets/nodejs_deps/node_modules/@angular/common/locales/extra/ta-MY.js
JavaScript
apache-2.0
1,346
/* * Copyright (c) 2014 Wael Chatila / Icegreen Technologies. All Rights Reserved. * This software is released under the Apache license 2.0 * This file has been modified by the copyright holder. * Original file can be found at http://james.apache.org */ package com.icegreen.greenmail.imap; /** * @author Darrell DeBoer <darrell@apache.org> * @version $Revision: 109034 $ */ public class ProtocolException extends Exception { public ProtocolException(String s) { super(s); } public ProtocolException(String s, Throwable cause) { super(s,cause); } }
buildscientist/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/imap/ProtocolException.java
Java
apache-2.0
610
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("uicolor","et",{title:"Värvivalija kasutajaliides",preview:"Automaatne eelvaade",config:"Aseta see sõne oma config.js faili.",predefined:"Eelmääratud värvikomplektid"});
viticm/pfadmin
vendor/frozennode/administrator/public/js/ckeditor/plugins/uicolor/lang/et.js
JavaScript
apache-2.0
344
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.GeoPointFieldType; public class GeoPointFieldTypeTests extends FieldTypeTestCase { @Override protected MappedFieldType createDefaultFieldType() { return new GeoPointFieldType(); } }
wuranbo/elasticsearch
core/src/test/java/org/elasticsearch/index/mapper/GeoPointFieldTypeTests.java
Java
apache-2.0
1,095
/* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the Apache License. * See the accompanying LICENSE file for terms. */ package com.yahoo.dba.perf.myperf.common; import java.util.List; import java.util.Set; import java.util.TreeSet; public class MyDatabases implements java.io.Serializable{ private static final long serialVersionUID = -8586381924495834726L; private Set<String> myDbSet = new TreeSet<String>(); synchronized public Set<String> getMyDbList() { return java.util.Collections.unmodifiableSet(this.myDbSet); } synchronized public void addDb(String name) { if(!this.myDbSet.contains(name)) this.myDbSet.add(name); } synchronized public void addDbs(List<String> names) { for (String name:names) { if(!this.myDbSet.contains(name)) this.myDbSet.add(name); } } synchronized public void removeDb(String name) { if(this.myDbSet.contains(name)) this.myDbSet.remove(name); } synchronized public void replaceDb(String oldName, String newName) { if(!this.myDbSet.contains(oldName)) { this.myDbSet.remove(oldName); this.myDbSet.remove(newName); } } synchronized public int size() { return this.myDbSet.size(); } }
wgpshashank/mysql_perf_analyzer
myperf/src/main/java/com/yahoo/dba/perf/myperf/common/MyDatabases.java
Java
apache-2.0
1,264
/* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.guvnor.tools.actions; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.text.MessageFormat; import java.util.Properties; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.webdav.IResponse; import org.guvnor.tools.Activator; import org.guvnor.tools.GuvnorRepository; import org.guvnor.tools.Messages; import org.guvnor.tools.utils.GuvnorMetadataProps; import org.guvnor.tools.utils.GuvnorMetadataUtils; import org.guvnor.tools.utils.PlatformUtils; import org.guvnor.tools.utils.webdav.IWebDavClient; import org.guvnor.tools.utils.webdav.WebDavClientFactory; import org.guvnor.tools.utils.webdav.WebDavException; import org.guvnor.tools.utils.webdav.WebDavServerCache; import org.guvnor.tools.views.RepositoryView; import org.guvnor.tools.views.ResourceHistoryView; import org.guvnor.tools.views.model.TreeObject; import org.guvnor.tools.views.model.TreeParent; import org.guvnor.tools.wizards.EditRepLocationWizard; /** * Shows the revision history for a given resource. */ public class EditConnectionAction implements IObjectActionDelegate { private GuvnorRepository rep; public EditConnectionAction() { super(); } /* * (non-Javadoc) * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, org.eclipse.ui.IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { } /* * (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { EditRepLocationWizard editWizard = new EditRepLocationWizard(rep); editWizard.init(Activator.getDefault().getWorkbench(), null); WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), editWizard); dialog.create(); dialog.open(); } /* * (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IAction action, ISelection selection) { // Reset state to default action.setEnabled(false); if (!(selection instanceof IStructuredSelection)) { return; } IStructuredSelection sel = (IStructuredSelection)selection; if (sel.size() != 1) { return; } if (sel.getFirstElement() instanceof TreeObject) { if (((TreeObject)sel.getFirstElement()).getNodeType() == TreeObject.Type.REPOSITORY) { rep = ((TreeObject)sel.getFirstElement()).getGuvnorRepository(); action.setEnabled(true); } } } }
droolsjbpm/droolsjbpm-tools
drools-eclipse/org.guvnor.tools/src/org/guvnor/tools/actions/EditConnectionAction.java
Java
apache-2.0
3,786
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function # $example on$ from pyspark.ml.feature import IndexToString, StringIndexer # $example off$ from pyspark.sql import SparkSession if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("IndexToStringExample")\ .getOrCreate() # $example on$ df = spark.createDataFrame( [(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")], ["id", "category"]) stringIndexer = StringIndexer(inputCol="category", outputCol="categoryIndex") model = stringIndexer.fit(df) indexed = model.transform(df) converter = IndexToString(inputCol="categoryIndex", outputCol="originalCategory") converted = converter.transform(indexed) converted.select("id", "originalCategory").show() # $example off$ spark.stop()
mrchristine/spark-examples-dbc
src/main/python/ml/index_to_string_example.py
Python
apache-2.0
1,615
/******************************************************************************* * Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved. * * WSO2.Telco Inc. licences this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.wso2telco.dep.oneapivalidation.service.impl.smsmessaging.northbound; import org.json.JSONObject; import com.wso2telco.dep.oneapivalidation.exceptions.CustomException; import com.wso2telco.dep.oneapivalidation.service.IServiceValidate; import com.wso2telco.dep.oneapivalidation.util.UrlValidator; import com.wso2telco.dep.oneapivalidation.util.Validation; import com.wso2telco.dep.oneapivalidation.util.ValidationRule; /** * * @author WSO2telco */ public class ValidateNBDeliveryInfoNotification implements IServiceValidate { private final String[] validationRules = { "DeliveryInfoNotification" }; public void validate(String json) throws CustomException { String callbackData = null; String address = null; String operatorCode = null; String filterCriteria = null; String deliveryStatus = null; try { JSONObject objJSONObject = new JSONObject(json); JSONObject objDeliveryInfoNotification = (JSONObject) objJSONObject .get("deliveryInfoNotification"); if (!objDeliveryInfoNotification.isNull("callbackData")) { callbackData = nullOrTrimmed(objDeliveryInfoNotification .getString("callbackData")); } JSONObject objDeliveryInfo = (JSONObject) objDeliveryInfoNotification .get("deliveryInfo"); if (objDeliveryInfo.get("address") != null) { address = nullOrTrimmed(objDeliveryInfo.getString("address")); } if (objDeliveryInfo.get("operatorCode") != null) { operatorCode = nullOrTrimmed(objDeliveryInfo .getString("operatorCode")); } if (!objDeliveryInfo.isNull("filterCriteria")) { filterCriteria = nullOrTrimmed(objDeliveryInfo .getString("filterCriteria")); } if (objDeliveryInfo.get("deliveryStatus") != null) { deliveryStatus = nullOrTrimmed(objDeliveryInfo .getString("deliveryStatus")); } } catch (Exception e) { throw new CustomException("POL0299", "Unexpected Error", new String[] { "" }); } ValidationRule[] rules = null; rules = new ValidationRule[] { new ValidationRule(ValidationRule.VALIDATION_TYPE_OPTIONAL, "callbackData", callbackData), new ValidationRule( ValidationRule.VALIDATION_TYPE_MANDATORY_TEL, "address", address), new ValidationRule(ValidationRule.VALIDATION_TYPE_MANDATORY, "operatorCode", operatorCode), new ValidationRule(ValidationRule.VALIDATION_TYPE_OPTIONAL, "filterCriteria", filterCriteria), new ValidationRule(ValidationRule.VALIDATION_TYPE_MANDATORY, "deliveryStatus", deliveryStatus) }; Validation.checkRequestParams(rules); } public void validateUrl(String pathInfo) throws CustomException { String[] requestParts = null; if (pathInfo != null) { if (pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1); } requestParts = pathInfo.split("/"); } UrlValidator.validateRequest(requestParts, validationRules); } private static String nullOrTrimmed(String s) { String rv = null; if (s != null && s.trim().length() > 0) { rv = s.trim(); } return rv; } public void validate(String[] params) throws CustomException { throw new UnsupportedOperationException("Not supported yet."); } }
WSO2Telco/component-dep
components/oneapi-validation/src/main/java/com/wso2telco/dep/oneapivalidation/service/impl/smsmessaging/northbound/ValidateNBDeliveryInfoNotification.java
Java
apache-2.0
4,034
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ml.dataframe; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.xcontent.ConstructingObjectParser; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.xpack.core.ml.job.messages.Messages; import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper; import org.elasticsearch.xpack.core.ml.utils.QueryProvider; import org.elasticsearch.xpack.core.ml.utils.RuntimeMappingsValidator; import org.elasticsearch.xpack.core.ml.utils.XContentObjectTransformer; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class DataFrameAnalyticsSource implements Writeable, ToXContentObject { public static final ParseField INDEX = new ParseField("index"); public static final ParseField QUERY = new ParseField("query"); public static final ParseField _SOURCE = new ParseField("_source"); @SuppressWarnings({ "unchecked"}) public static ConstructingObjectParser<DataFrameAnalyticsSource, Void> createParser(boolean ignoreUnknownFields) { ConstructingObjectParser<DataFrameAnalyticsSource, Void> parser = new ConstructingObjectParser<>("data_frame_analytics_source", ignoreUnknownFields, a -> new DataFrameAnalyticsSource( ((List<String>) a[0]).toArray(new String[0]), (QueryProvider) a[1], (FetchSourceContext) a[2], (Map<String, Object>) a[3])); parser.declareStringArray(ConstructingObjectParser.constructorArg(), INDEX); parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> QueryProvider.fromXContent(p, ignoreUnknownFields, Messages.DATA_FRAME_ANALYTICS_BAD_QUERY_FORMAT), QUERY); parser.declareField(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> FetchSourceContext.fromXContent(p), _SOURCE, ObjectParser.ValueType.OBJECT_ARRAY_BOOLEAN_OR_STRING); parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.map(), SearchSourceBuilder.RUNTIME_MAPPINGS_FIELD); return parser; } private final String[] index; private final QueryProvider queryProvider; private final FetchSourceContext sourceFiltering; private final Map<String, Object> runtimeMappings; public DataFrameAnalyticsSource(String[] index, @Nullable QueryProvider queryProvider, @Nullable FetchSourceContext sourceFiltering, @Nullable Map<String, Object> runtimeMappings) { this.index = ExceptionsHelper.requireNonNull(index, INDEX); if (index.length == 0) { throw new IllegalArgumentException("source.index must specify at least one index"); } if (Arrays.stream(index).anyMatch(Strings::isNullOrEmpty)) { throw new IllegalArgumentException("source.index must contain non-null and non-empty strings"); } this.queryProvider = queryProvider == null ? QueryProvider.defaultQuery() : queryProvider; if (sourceFiltering != null && sourceFiltering.fetchSource() == false) { throw new IllegalArgumentException("source._source cannot be disabled"); } this.sourceFiltering = sourceFiltering; this.runtimeMappings = runtimeMappings == null ? Collections.emptyMap() : Collections.unmodifiableMap(runtimeMappings); RuntimeMappingsValidator.validate(this.runtimeMappings); } public DataFrameAnalyticsSource(StreamInput in) throws IOException { index = in.readStringArray(); queryProvider = QueryProvider.fromStream(in); sourceFiltering = in.readOptionalWriteable(FetchSourceContext::new); runtimeMappings = in.readMap(); } public DataFrameAnalyticsSource(DataFrameAnalyticsSource other) { this.index = Arrays.copyOf(other.index, other.index.length); this.queryProvider = new QueryProvider(other.queryProvider); this.sourceFiltering = other.sourceFiltering == null ? null : new FetchSourceContext( other.sourceFiltering.fetchSource(), other.sourceFiltering.includes(), other.sourceFiltering.excludes()); this.runtimeMappings = Collections.unmodifiableMap(new HashMap<>(other.runtimeMappings)); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeStringArray(index); queryProvider.writeTo(out); out.writeOptionalWriteable(sourceFiltering); out.writeMap(runtimeMappings); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.array(INDEX.getPreferredName(), index); builder.field(QUERY.getPreferredName(), queryProvider.getQuery()); if (sourceFiltering != null) { builder.field(_SOURCE.getPreferredName(), sourceFiltering); } if (runtimeMappings.isEmpty() == false) { builder.field(SearchSourceBuilder.RUNTIME_MAPPINGS_FIELD.getPreferredName(), runtimeMappings); } builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (o == this) return true; if (o == null || getClass() != o.getClass()) return false; DataFrameAnalyticsSource other = (DataFrameAnalyticsSource) o; return Arrays.equals(index, other.index) && Objects.equals(queryProvider, other.queryProvider) && Objects.equals(sourceFiltering, other.sourceFiltering) && Objects.equals(runtimeMappings, other.runtimeMappings); } @Override public int hashCode() { return Objects.hash(Arrays.asList(index), queryProvider, sourceFiltering, runtimeMappings); } public String[] getIndex() { return index; } /** * Get the fully parsed query from the semi-parsed stored {@code Map<String, Object>} * * @return Fully parsed query */ public QueryBuilder getParsedQuery() { Exception exception = queryProvider.getParsingException(); if (exception != null) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new ElasticsearchException(queryProvider.getParsingException()); } } return queryProvider.getParsedQuery(); } public FetchSourceContext getSourceFiltering() { return sourceFiltering; } Exception getQueryParsingException() { return queryProvider.getParsingException(); } // visible for testing QueryProvider getQueryProvider() { return queryProvider; } /** * Calls the parser and returns any gathered deprecations * * @param namedXContentRegistry XContent registry to transform the lazily parsed query * @return The deprecations from parsing the query */ public List<String> getQueryDeprecations(NamedXContentRegistry namedXContentRegistry) { List<String> deprecations = new ArrayList<>(); try { XContentObjectTransformer.queryBuilderTransformer(namedXContentRegistry).fromMap(queryProvider.getQuery(), deprecations); } catch (Exception exception) { // Certain thrown exceptions wrap up the real Illegal argument making it hard to determine cause for the user if (exception.getCause() instanceof IllegalArgumentException) { exception = (Exception) exception.getCause(); } throw ExceptionsHelper.badRequestException(Messages.DATA_FRAME_ANALYTICS_BAD_QUERY_FORMAT, exception); } return deprecations; } // Visible for testing Map<String, Object> getQuery() { return queryProvider.getQuery(); } public Map<String, Object> getRuntimeMappings() { return runtimeMappings; } public boolean isFieldExcluded(String path) { if (sourceFiltering == null) { return false; } // First we check in the excludes as they are applied last for (String exclude : sourceFiltering.excludes()) { if (pathMatchesSourcePattern(path, exclude)) { return true; } } // Now we can check the includes // Empty includes means no further exclusions if (sourceFiltering.includes().length == 0) { return false; } for (String include : sourceFiltering.includes()) { if (pathMatchesSourcePattern(path, include)) { return false; } } return true; } private static boolean pathMatchesSourcePattern(String path, String sourcePattern) { if (sourcePattern.equals(path)) { return true; } if (Regex.isSimpleMatchPattern(sourcePattern)) { return Regex.simpleMatch(sourcePattern, path); } // At this stage sourcePattern is a concrete field name and path is not equal to it. // We should check if path is a nested field of pattern. // Let us take "foo" as an example. // Fields that are "foo.*" should also be matched. return Regex.simpleMatch(sourcePattern + ".*", path); } }
robin13/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/DataFrameAnalyticsSource.java
Java
apache-2.0
10,456
/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /** * @file tgSimView.cpp * @brief Contains the definitions of members of class tgSimView * @author Brian Mirletz, Ryan Adams * $Id$ */ // This module #include "tgSimulation.h" // This application #include "tgModelVisitor.h" #include "tgSimView.h" // The C++ Standard Library #include <cassert> #include <iostream> #include <stdexcept> tgSimView::tgSimView(tgWorld& world, double stepSize, double renderRate) : m_world(world), m_pSimulation(NULL), m_pModelVisitor(NULL), m_stepSize(stepSize), m_renderRate(renderRate), m_renderTime(0.0), m_initialized(false) { if (m_stepSize < 0.0) { throw std::invalid_argument("stepSize is not positive"); } else if (renderRate < m_stepSize) { throw std::invalid_argument("renderRate is less than stepSize"); } // Postcondition assert(invariant()); assert(m_pSimulation == NULL); assert(m_pModelVisitor == NULL); assert(m_stepSize == stepSize); assert(m_renderRate == renderRate); assert(m_renderTime == 0.0); assert(!m_initialized); } tgSimView::~tgSimView() { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation teardown(); } delete m_pModelVisitor; } void tgSimView::bindToSimulation(tgSimulation& simulation) { if (m_pSimulation != NULL) { throw std::invalid_argument("The view already belongs to a simulation."); } else { m_pSimulation = &simulation; tgWorld& world = simulation.getWorld(); bindToWorld(world); } // Postcondition assert(invariant()); assert(m_pSimulation == &simulation); } void tgSimView::releaseFromSimulation() { // The destructor that calls this must not fail, so don't assert or throw // on a precondition m_pSimulation = NULL; // The destructor that calls this must not fail, so don't assert a // postcondition } void tgSimView::bindToWorld(tgWorld& world) { } void tgSimView::setup() { assert(m_pSimulation != NULL); // Just note that this function was called. // tgSimViewGraphics needs to know for now. m_initialized = true; // Postcondition assert(invariant()); assert(m_initialized); } void tgSimView::teardown() { // Just note that this function was called. // tgSimViewGraphics needs to know for now. m_initialized = false; // Postcondition assert(invariant()); assert(!m_initialized); } void tgSimView::run() { // This would normally run forever, but this is just for testing run(10); } void tgSimView::run(int steps) { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation std::cout << "SimView::run("<<steps<<")" << std::endl; // This would normally run forever, but this is just for testing m_renderTime = 0; double totalTime = 0.0; for (int i = 0; i < steps; i++) { m_pSimulation->step(m_stepSize); m_renderTime += m_stepSize; totalTime += m_stepSize; if (m_renderTime >= m_renderRate) { render(); //std::cout << totalTime << std::endl; m_renderTime = 0; } } } } void tgSimView::render() const { if ((m_pSimulation != NULL) && (m_pModelVisitor != NULL)) { // The tgSimView has been passed to a tgSimulation m_pSimulation->onVisit(*m_pModelVisitor); } } void tgSimView::render(const tgModelVisitor& r) const { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation m_pSimulation->onVisit(r); } } void tgSimView::reset() { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation m_pSimulation->reset(); } } void tgSimView::setRenderRate(double renderRate) { m_renderRate = (renderRate > m_stepSize) ? renderRate : m_stepSize; // Postcondition assert(invariant()); } void tgSimView::setStepSize(double stepSize) { if (stepSize <= 0.0) { throw std::invalid_argument("stepSize is not positive"); } else { m_stepSize = stepSize; // Assure that the render rate is no less than the new step size setRenderRate(m_renderRate); } // Postcondition assert(invariant()); assert((stepSize <= 0.0) || (m_stepSize == stepSize)); } bool tgSimView::invariant() const { return (m_stepSize >= 0.0) && (m_renderRate >= m_stepSize) && (m_renderTime >= 0.0); }
MRNAS/NTRT
src/core/tgSimView.cpp
C++
apache-2.0
5,374
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <cctype> #include "BodyOnlyXmlParser.hh" #include "MdsException.hh" using namespace mdsd::details; void BodyOnlyXmlParser::ParseFile(std::string xmlFilePath) { m_xmlFilePath = std::move(xmlFilePath); std::ifstream infile{m_xmlFilePath}; if (!infile) { std::ostringstream strm; strm << "Failed to open file '" << m_xmlFilePath << "'."; throw MDSEXCEPTION(strm.str()); } std::string line; while(std::getline(infile, line)) { ParseChunk(line); } if (!infile.eof()) { std::ostringstream strm; strm << "Failed to parse file '" << m_xmlFilePath << "': "; if (infile.bad()) { strm << "Corrupted stream."; } else if (infile.fail()) { strm << "IO operation failed."; } else { strm << "std::getline() returned 0 for unknown reason."; } throw MDSEXCEPTION(strm.str()); } } void BodyOnlyXmlParser::OnCharacters(const std::string& chars) { bool isEmptyOrWhiteSpace = std::all_of(chars.cbegin(), chars.cend(), ::isspace); if (!isEmptyOrWhiteSpace) { m_body.append(chars); } }
Azure/azure-linux-extensions
Diagnostic/mdsd/mdscommands/BodyOnlyXmlParser.cc
C++
apache-2.0
1,350
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.msf4j.stockquote.example.exception; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; /** * EntityNotFoundMapper. */ public class EntityNotFoundMapper implements ExceptionMapper<EntityNotFoundException> { @Override public Response toResponse(EntityNotFoundException ex) { return Response.status(404). entity(ex.getMessage() + " [from EntityNotFoundMapper]"). type("text/plain"). build(); } }
callkalpa/product-mss
samples/stockquote/deployable-jar/src/main/java/org/wso2/msf4j/stockquote/example/exception/EntityNotFoundMapper.java
Java
apache-2.0
1,196
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.client; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import org.elasticsearch.client.http.HttpHost; import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; import org.elasticsearch.mocksocket.MockHttpServer; import org.junit.AfterClass; import org.junit.BeforeClass; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.security.KeyStore; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Integration test to validate the builder builds a client with the correct configuration */ //animal-sniffer doesn't like our usage of com.sun.net.httpserver.* classes @IgnoreJRERequirement public class RestClientBuilderIntegTests extends RestClientTestCase { private static HttpsServer httpsServer; @BeforeClass public static void startHttpServer() throws Exception { httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); httpsServer.setHttpsConfigurator(new HttpsConfigurator(getSslContext())); httpsServer.createContext("/", new ResponseHandler()); httpsServer.start(); } //animal-sniffer doesn't like our usage of com.sun.net.httpserver.* classes @IgnoreJRERequirement private static class ResponseHandler implements HttpHandler { @Override public void handle(HttpExchange httpExchange) throws IOException { httpExchange.sendResponseHeaders(200, -1); httpExchange.close(); } } @AfterClass public static void stopHttpServers() throws IOException { httpsServer.stop(0); httpsServer = null; } public void testBuilderUsesDefaultSSLContext() throws Exception { final SSLContext defaultSSLContext = SSLContext.getDefault(); try { try (RestClient client = buildRestClient()) { try { client.performRequest("GET", "/"); fail("connection should have been rejected due to SSL handshake"); } catch (Exception e) { assertThat(e.getMessage(), containsString("General SSLEngine problem")); } } SSLContext.setDefault(getSslContext()); try (RestClient client = buildRestClient()) { Response response = client.performRequest("GET", "/"); assertEquals(200, response.getStatusLine().getStatusCode()); } } finally { SSLContext.setDefault(defaultSSLContext); } } private RestClient buildRestClient() { InetSocketAddress address = httpsServer.getAddress(); return RestClient.builder(new HttpHost(address.getHostString(), address.getPort(), "https")).build(); } private static SSLContext getSslContext() throws Exception { SSLContext sslContext = SSLContext.getInstance("TLS"); try (InputStream in = RestClientBuilderIntegTests.class.getResourceAsStream("/testks.jks")) { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(in, "password".toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keyStore, "password".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(keyStore); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } return sslContext; } }
sneivandt/elasticsearch
client/rest/src/test/java/org/elasticsearch/client/RestClientBuilderIntegTests.java
Java
apache-2.0
4,718
<?php /* Copyright 2016 Rustici Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace TinCanTest; use TinCan\Document; class StubDocument extends Document {} class DocumentTest extends \PHPUnit_Framework_TestCase { public function testExceptionOnInvalidDateTime() { $this->setExpectedException( "InvalidArgumentException", 'type of arg1 must be string or DateTime' ); $obj = new StubDocument(); $obj->setTimestamp(1); } }
RusticiSoftware/TinCanPHP
tests/DocumentTest.php
PHP
apache-2.0
1,020
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.swiftpm.internal; import com.google.common.collect.ImmutableSet; import javax.annotation.Nullable; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class DefaultTarget implements Serializable { private final String name; private final File path; private final Collection<File> sourceFiles; private final List<String> requiredTargets = new ArrayList<String>(); private final List<String> requiredProducts = new ArrayList<String>(); private File publicHeaderDir; public DefaultTarget(String name, File path, Iterable<File> sourceFiles) { this.name = name; this.path = path; this.sourceFiles = ImmutableSet.copyOf(sourceFiles); } public String getName() { return name; } public File getPath() { return path; } public Collection<File> getSourceFiles() { return sourceFiles; } @Nullable public File getPublicHeaderDir() { return publicHeaderDir; } public void setPublicHeaderDir(File publicHeaderDir) { this.publicHeaderDir = publicHeaderDir; } public Collection<String> getRequiredTargets() { return requiredTargets; } public Collection<String> getRequiredProducts() { return requiredProducts; } }
gradle/gradle
subprojects/language-native/src/main/java/org/gradle/swiftpm/internal/DefaultTarget.java
Java
apache-2.0
2,004
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package symbolicexecutor; import com.google.common.collect.Sets; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ScriptableObject; import java.io.IOException; import java.util.Set; /** * An object that runs symbolic execution on one program to generate a bunch of * tests and their outputs, runs a second program with these tests, compares * against the first set of outputs, and reports the differences. * * @author elnatan@google.com (Elnatan Reisner) * */ public class CompareFiles { /** The file names of the original and new programs */ private final String originalProgram; private final String newProgram; /** The name of the function at which to start symbolic execution */ private final String entryFunction; /** The arguments to pass to the entry function to start execution */ private final String[] arguments; /** * @param originalProgram file name of the original version of the program * @param newProgram file name of the new version of the program * @param entryFunction the function at which to start symbolic execution * @param arguments the arguments to pass to the entry function */ public CompareFiles(String originalProgram, String newProgram, String entryFunction, String... arguments) { this.originalProgram = originalProgram; this.newProgram = newProgram; this.entryFunction = entryFunction; this.arguments = arguments; } /** * @param maxTests the maximum number of tests to generate * @return the set of differences between the old and new programs, given as * pairs (x, y), where x is the {@link Output} from the original * program and y is the new program's output on {@code x.input} * @throws IOException */ public Set<Pair<Output, Object>> compare(FileLoader loader, int maxTests) throws IOException { Cvc3Context cvc3Context = Cvc3Context.create(arguments.length, loader); NewInputGenerator inputGenerator = new ApiBasedInputGenerator(cvc3Context); SymbolicExecutor executor = SymbolicExecutor.create( originalProgram, loader, inputGenerator, maxTests, entryFunction, arguments); Context rhinoContext = Context.enter(); Set<Pair<Output, Object>> differences = Sets.newHashSet(); // Run symbolic execution, and iterate through all generated inputs for (Output output : executor.run()) { // Run the new program with the old arguments ScriptableObject scope = rhinoContext.initStandardObjects(); rhinoContext.evaluateString(scope, loader.toString(newProgram), "new program", 0, null); Object result = ScriptableObject.callMethod(scope, entryFunction, output.input.toArray(ContextFactory.getGlobal())); // If the results differ, add them to the set of differences if (!output.result.equals(result)) { differences.add(new Pair<Output, Object>(output, result)); } } return differences; } }
ehsan/js-symbolic-executor
js-symbolic-executor/src/symbolicexecutor/CompareFiles.java
Java
apache-2.0
3,614
# # Cookbook Name:: bork # Recipe:: configure # # Copyright 2015, GING, ETSIT, UPM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # node.set['bork']['version'] = '0.0.1' include_recipe 'bork::configure'
Fiware/ops.Validator
extras/ChefCookBook/bork/recipes/0.0.1_configure.rb
Ruby
apache-2.0
702
/* * Copyright 2016 The Closure Compiler Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Externs for Intersection Observer objects. * @see https://wicg.github.io/IntersectionObserver/ * @externs */ // TODO(user): Once the Intersection Observer spec is adopted by W3C, add // a w3c_ prefix to this file's name. /** * These contain the information provided from a change event. * @see https://wicg.github.io/IntersectionObserver/#intersection-observer-entry * @record */ function IntersectionObserverEntry() {} /** * The time the change was observed. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-time * @type {number} * @const */ IntersectionObserverEntry.prototype.time; /** * The root intersection rectangle, if target belongs to the same unit of * related similar-origin browsing contexts as the intersection root, null * otherwise. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-rootbounds * @type {{top: number, right: number, bottom: number, left: number, * height: number, width: number}} * @const */ IntersectionObserverEntry.prototype.rootBounds; /** * The rectangle describing the element being observed. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-boundingclientrect * @type {!{top: number, right: number, bottom: number, left: number, * height: number, width: number}} * @const */ IntersectionObserverEntry.prototype.boundingClientRect; /** * The rectangle describing the intersection between the observed element and * the viewport. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-intersectionrect * @type {!{top: number, right: number, bottom: number, left: number, * height: number, width: number}} * @const */ IntersectionObserverEntry.prototype.intersectionRect; /** * Ratio of intersectionRect area to boundingClientRect area. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-intersectionratio * @type {!number} * @const */ IntersectionObserverEntry.prototype.intersectionRatio; /** * The Element whose intersection with the intersection root changed. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-target * @type {!Element} * @const */ IntersectionObserverEntry.prototype.target; /** * Whether or not the target is intersecting with the root. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-isintersecting * @type {boolean} * @const */ IntersectionObserverEntry.prototype.isIntersecting; /** * Callback for the IntersectionObserver. * @see https://wicg.github.io/IntersectionObserver/#intersection-observer-callback * @typedef {function(!Array<!IntersectionObserverEntry>,!IntersectionObserver)} */ var IntersectionObserverCallback; /** * Options for the IntersectionObserver. * @see https://wicg.github.io/IntersectionObserver/#intersection-observer-init * @typedef {{ * threshold: (!Array<number>|number|undefined), * root: (!Element|undefined), * rootMargin: (string|undefined) * }} */ var IntersectionObserverInit; /** * This is the constructor for Intersection Observer objects. * @see https://wicg.github.io/IntersectionObserver/#intersection-observer-interface * @param {!IntersectionObserverCallback} handler The callback for the observer. * @param {!IntersectionObserverInit=} opt_options The object defining the * thresholds, etc. * @constructor */ function IntersectionObserver(handler, opt_options) {}; /** * The root Element to use for intersection, or null if the observer uses the * implicit root. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-root * @type {?Element} * @const */ IntersectionObserver.prototype.root; /** * Offsets applied to the intersection root’s bounding box, effectively growing * or shrinking the box that is used to calculate intersections. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin * @type {!string} * @const */ IntersectionObserver.prototype.rootMargin; /** * A list of thresholds, sorted in increasing numeric order, where each * threshold is a ratio of intersection area to bounding box area of an observed * target. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-thresholds * @type {!Array.<!number>} * @const */ IntersectionObserver.prototype.thresholds; /** * This is used to set which element to observe. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-observe * @param {!Element} element The element to observe. * @return {undefined} */ IntersectionObserver.prototype.observe = function(element) {}; /** * This is used to stop observing a given element. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-unobserve * @param {!Element} element The elmenent to stop observing. * @return {undefined} */ IntersectionObserver.prototype.unobserve = function(element) {}; /** * Disconnect. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-disconnect */ IntersectionObserver.prototype.disconnect = function() {}; /** * Take records. * @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-takerecords * @return {!Array.<!IntersectionObserverEntry>} */ IntersectionObserver.prototype.takeRecords = function() {};
MatrixFrog/closure-compiler
externs/browser/intersection_observer.js
JavaScript
apache-2.0
6,017
// PSI_ELEMENT: com.intellij.psi.PsiMethod // OPTIONS: usages // PLAIN_WHEN_NEEDED public class JavaWithGroovyInvoke_0 { public void <caret>invoke() { } public static class OtherJavaClass extends JavaWithGroovyInvoke_0 { } } // CRI_IGNORE
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/java/findJavaMethodUsages/JavaWithGroovyInvoke.0.java
Java
apache-2.0
257
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.application.common.model.test; import org.junit.Test; import org.wso2.carbon.identity.application.common.model.Property; import org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertFalse; /** * Testing the ProvisioningConnectorConfig class */ public class ProvisioningConnectorConfigTest { @Test public void shouldGenerateDifferentHashCodesForDifferentNames() { ProvisioningConnectorConfig config1 = new ProvisioningConnectorConfig(); config1.setName("Name1"); config1.setProvisioningProperties(new Property[0]); ProvisioningConnectorConfig config2 = new ProvisioningConnectorConfig(); config2.setName("Name2"); config2.setProvisioningProperties(new Property[0]); assertNotEquals(config1.hashCode(), config2.hashCode()); } @Test public void shouldReturnFalseByEqualsForDifferentNames() { ProvisioningConnectorConfig config1 = new ProvisioningConnectorConfig(); config1.setName("Name1"); config1.setProvisioningProperties(new Property[0]); ProvisioningConnectorConfig config2 = new ProvisioningConnectorConfig(); config2.setName("Name2"); config2.setProvisioningProperties(new Property[0]); assertFalse(config1.equals(config2)); } }
lakshani/carbon-identity
components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/ProvisioningConnectorConfigTest.java
Java
apache-2.0
2,091
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.jca.test; import org.apache.jackrabbit.jca.JCAConnectionRequestInfo; import javax.jcr.SimpleCredentials; import java.util.HashMap; /** * This case executes tests on the connection request info. */ public final class ConnectionRequestInfoTest extends AbstractTestCase { private SimpleCredentials creds1 = new SimpleCredentials("user", "password".toCharArray()); private SimpleCredentials creds2 = new SimpleCredentials("user", "password".toCharArray()); private SimpleCredentials creds3 = new SimpleCredentials("another_user", "password".toCharArray()); private JCAConnectionRequestInfo info1 = new JCAConnectionRequestInfo(creds1, "default"); private JCAConnectionRequestInfo info2 = new JCAConnectionRequestInfo(creds2, "default"); private JCAConnectionRequestInfo info3 = new JCAConnectionRequestInfo(creds3, "default"); /** * Test the JCAConnectionRequestInfo equals() method. */ public void testEquals() throws Exception { assertEquals("Object must be equal to itself", info1, info1); assertEquals("Infos with the same auth data must be equal", info1, info2); assertTrue("Infos with different auth data must not be equal", !info1.equals(info3)); } /** * Test the JCAConnectionRequestInfo hashCode() method. */ public void testHashCode() throws Exception { assertEquals("Object must be equal to itself", info1.hashCode(), info1.hashCode()); assertEquals("Infos with the same auth data must have same hashCode", info1.hashCode(), info2.hashCode()); assertTrue("Infos with different auth data must not have same hashCode", info1.hashCode() != info3.hashCode()); } /** * Tests that JCAConnectionRequestInfo works as a HashMap key correctly. */ public void testPutToHashMap() throws Exception { HashMap map = new HashMap(); map.put(info1, new Object()); assertTrue("Map must contain the info", map.containsKey(info2)); } }
sdmcraft/jackrabbit
jackrabbit-jca/src/test/java/org/apache/jackrabbit/jca/test/ConnectionRequestInfoTest.java
Java
apache-2.0
2,835
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <mesos/mesos.hpp> #include <mesos/resource_provider/resource_provider.hpp> #include <stout/error.hpp> #include <stout/gtest.hpp> #include <stout/option.hpp> #include <stout/uuid.hpp> #include "common/protobuf_utils.hpp" #include "resource_provider/validation.hpp" namespace call = mesos::internal::resource_provider::validation::call; using mesos::resource_provider::Call; namespace mesos { namespace internal { namespace tests { TEST(ResourceProviderCallValidationTest, Subscribe) { Call call; call.set_type(Call::SUBSCRIBE); // Expecting `Call::Subscribe`. Option<Error> error = call::validate(call); EXPECT_SOME(error); Call::Subscribe* subscribe = call.mutable_subscribe(); ResourceProviderInfo* info = subscribe->mutable_resource_provider_info(); info->set_type("org.apache.mesos.rp.test"); info->set_name("test"); error = call::validate(call); EXPECT_NONE(error); } TEST(ResourceProviderCallValidationTest, UpdateOperationStatus) { Call call; call.set_type(Call::UPDATE_OPERATION_STATUS); // Expecting a resource provider ID and `Call::UpdateOperationStatus`. Option<Error> error = call::validate(call); EXPECT_SOME(error); ResourceProviderID* id = call.mutable_resource_provider_id(); id->set_value(id::UUID::random().toString()); // Still expecting `Call::UpdateOperationStatus`. error = call::validate(call); EXPECT_SOME(error); Call::UpdateOperationStatus* update = call.mutable_update_operation_status(); update->mutable_framework_id()->set_value(id::UUID::random().toString()); update->mutable_operation_uuid()->CopyFrom(protobuf::createUUID()); OperationStatus* status = update->mutable_status(); status->mutable_operation_id()->set_value(id::UUID::random().toString()); status->set_state(OPERATION_FINISHED); error = call::validate(call); EXPECT_NONE(error); } TEST(ResourceProviderCallValidationTest, UpdateState) { Call call; call.set_type(Call::UPDATE_STATE); // Expecting a resource provider ID and `Call::UpdateState`. Option<Error> error = call::validate(call); EXPECT_SOME(error); ResourceProviderID* id = call.mutable_resource_provider_id(); id->set_value(id::UUID::random().toString()); // Still expecting `Call::UpdateState`. error = call::validate(call); EXPECT_SOME(error); Call::UpdateState* updateState = call.mutable_update_state(); updateState->mutable_resource_version_uuid()->CopyFrom( protobuf::createUUID()); error = call::validate(call); EXPECT_NONE(error); } } // namespace tests { } // namespace internal { } // namespace mesos {
chhsia0/mesos
src/tests/resource_provider_validation_tests.cpp
C++
apache-2.0
3,426
package rolebinding import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/conversion" "k8s.io/apimachinery/pkg/runtime" apirequest "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/apiserver/pkg/registry/rest" restclient "k8s.io/client-go/rest" rbacinternalversion "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/internalversion" authclient "github.com/openshift/origin/pkg/auth/client" authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization" "github.com/openshift/origin/pkg/authorization/registry/util" utilregistry "github.com/openshift/origin/pkg/util/registry" ) type REST struct { privilegedClient restclient.Interface } var _ rest.Lister = &REST{} var _ rest.Getter = &REST{} var _ rest.CreaterUpdater = &REST{} var _ rest.GracefulDeleter = &REST{} func NewREST(client restclient.Interface) utilregistry.NoWatchStorage { return utilregistry.WrapNoWatchStorageError(&REST{privilegedClient: client}) } func (s *REST) New() runtime.Object { return &authorizationapi.RoleBinding{} } func (s *REST) NewList() runtime.Object { return &authorizationapi.RoleBindingList{} } func (s *REST) List(ctx apirequest.Context, options *metainternal.ListOptions) (runtime.Object, error) { client, err := s.getImpersonatingClient(ctx) if err != nil { return nil, err } optv1 := metav1.ListOptions{} if err := metainternal.Convert_internalversion_ListOptions_To_v1_ListOptions(options, &optv1, nil); err != nil { return nil, err } bindings, err := client.List(optv1) if err != nil { return nil, err } ret := &authorizationapi.RoleBindingList{} for _, curr := range bindings.Items { role, err := util.RoleBindingFromRBAC(&curr) if err != nil { return nil, err } ret.Items = append(ret.Items, *role) } ret.ListMeta.ResourceVersion = bindings.ResourceVersion return ret, nil } func (s *REST) Get(ctx apirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { client, err := s.getImpersonatingClient(ctx) if err != nil { return nil, err } ret, err := client.Get(name, *options) if err != nil { return nil, err } binding, err := util.RoleBindingFromRBAC(ret) if err != nil { return nil, err } return binding, nil } func (s *REST) Delete(ctx apirequest.Context, name string, options *metav1.DeleteOptions) (runtime.Object, bool, error) { client, err := s.getImpersonatingClient(ctx) if err != nil { return nil, false, err } if err := client.Delete(name, options); err != nil { return nil, false, err } return &metav1.Status{Status: metav1.StatusSuccess}, true, nil } func (s *REST) Create(ctx apirequest.Context, obj runtime.Object, _ bool) (runtime.Object, error) { client, err := s.getImpersonatingClient(ctx) if err != nil { return nil, err } rb := obj.(*authorizationapi.RoleBinding) // Default the namespace if it is not specified so conversion does not error // Normally this is done during the REST strategy but we avoid those here to keep the proxies simple if ns, ok := apirequest.NamespaceFrom(ctx); ok && len(ns) > 0 && len(rb.Namespace) == 0 && len(rb.RoleRef.Namespace) > 0 { deepcopiedObj := rb.DeepCopy() deepcopiedObj.Namespace = ns rb = deepcopiedObj } convertedObj, err := util.RoleBindingToRBAC(rb) if err != nil { return nil, err } ret, err := client.Create(convertedObj) if err != nil { return nil, err } binding, err := util.RoleBindingFromRBAC(ret) if err != nil { return nil, err } return binding, nil } func (s *REST) Update(ctx apirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) { client, err := s.getImpersonatingClient(ctx) if err != nil { return nil, false, err } old, err := client.Get(name, metav1.GetOptions{}) if err != nil { return nil, false, err } oldRoleBinding, err := util.RoleBindingFromRBAC(old) if err != nil { return nil, false, err } obj, err := objInfo.UpdatedObject(ctx, oldRoleBinding) if err != nil { return nil, false, err } updatedRoleBinding, err := util.RoleBindingToRBAC(obj.(*authorizationapi.RoleBinding)) if err != nil { return nil, false, err } ret, err := client.Update(updatedRoleBinding) if err != nil { return nil, false, err } role, err := util.RoleBindingFromRBAC(ret) if err != nil { return nil, false, err } return role, false, err } func (s *REST) getImpersonatingClient(ctx apirequest.Context) (rbacinternalversion.RoleBindingInterface, error) { namespace, ok := apirequest.NamespaceFrom(ctx) if !ok { return nil, apierrors.NewBadRequest("namespace parameter required") } rbacClient, err := authclient.NewImpersonatingRBACFromContext(ctx, s.privilegedClient) if err != nil { return nil, err } return rbacClient.RoleBindings(namespace), nil } var cloner = conversion.NewCloner()
raffaelespazzoli/origin
pkg/authorization/registry/rolebinding/proxy.go
GO
apache-2.0
4,978
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Additional information of DPM Protected item. * */ class DPMProtectedItemExtendedInfo { /** * Create a DPMProtectedItemExtendedInfo. * @member {object} [protectableObjectLoadPath] Attribute to provide * information on various DBs. * @member {boolean} [protectedProperty] To check if backup item is disk * protected. * @member {boolean} [isPresentOnCloud] To check if backup item is cloud * protected. * @member {string} [lastBackupStatus] Last backup status information on * backup item. * @member {date} [lastRefreshedAt] Last refresh time on backup item. * @member {date} [oldestRecoveryPoint] Oldest cloud recovery point time. * @member {number} [recoveryPointCount] cloud recovery point count. * @member {date} [onPremiseOldestRecoveryPoint] Oldest disk recovery point * time. * @member {date} [onPremiseLatestRecoveryPoint] latest disk recovery point * time. * @member {number} [onPremiseRecoveryPointCount] disk recovery point count. * @member {boolean} [isCollocated] To check if backup item is collocated. * @member {string} [protectionGroupName] Protection group name of the backup * item. * @member {string} [diskStorageUsedInBytes] Used Disk storage in bytes. * @member {string} [totalDiskStorageSizeInBytes] total Disk storage in * bytes. */ constructor() { } /** * Defines the metadata of DPMProtectedItemExtendedInfo * * @returns {object} metadata of DPMProtectedItemExtendedInfo * */ mapper() { return { required: false, serializedName: 'DPMProtectedItemExtendedInfo', type: { name: 'Composite', className: 'DPMProtectedItemExtendedInfo', modelProperties: { protectableObjectLoadPath: { required: false, serializedName: 'protectableObjectLoadPath', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, protectedProperty: { required: false, serializedName: 'protected', type: { name: 'Boolean' } }, isPresentOnCloud: { required: false, serializedName: 'isPresentOnCloud', type: { name: 'Boolean' } }, lastBackupStatus: { required: false, serializedName: 'lastBackupStatus', type: { name: 'String' } }, lastRefreshedAt: { required: false, serializedName: 'lastRefreshedAt', type: { name: 'DateTime' } }, oldestRecoveryPoint: { required: false, serializedName: 'oldestRecoveryPoint', type: { name: 'DateTime' } }, recoveryPointCount: { required: false, serializedName: 'recoveryPointCount', type: { name: 'Number' } }, onPremiseOldestRecoveryPoint: { required: false, serializedName: 'onPremiseOldestRecoveryPoint', type: { name: 'DateTime' } }, onPremiseLatestRecoveryPoint: { required: false, serializedName: 'onPremiseLatestRecoveryPoint', type: { name: 'DateTime' } }, onPremiseRecoveryPointCount: { required: false, serializedName: 'onPremiseRecoveryPointCount', type: { name: 'Number' } }, isCollocated: { required: false, serializedName: 'isCollocated', type: { name: 'Boolean' } }, protectionGroupName: { required: false, serializedName: 'protectionGroupName', type: { name: 'String' } }, diskStorageUsedInBytes: { required: false, serializedName: 'diskStorageUsedInBytes', type: { name: 'String' } }, totalDiskStorageSizeInBytes: { required: false, serializedName: 'totalDiskStorageSizeInBytes', type: { name: 'String' } } } } }; } } module.exports = DPMProtectedItemExtendedInfo;
xingwu1/azure-sdk-for-node
lib/services/recoveryServicesBackupManagement/lib/models/dPMProtectedItemExtendedInfo.js
JavaScript
apache-2.0
5,048
//===-- FreeBSDSignals.cpp --------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "FreeBSDSignals.h" using namespace lldb_private; FreeBSDSignals::FreeBSDSignals() : UnixSignals() { Reset(); } void FreeBSDSignals::Reset() { UnixSignals::Reset(); // SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION // ====== ============ ======== ====== ====== // =================================================== AddSignal(32, "SIGTHR", false, false, false, "thread interrupt"); AddSignal(33, "SIGLIBRT", false, false, false, "reserved by real-time library"); AddSignal(65, "SIGRTMIN", false, false, false, "real time signal 0"); AddSignal(66, "SIGRTMIN+1", false, false, false, "real time signal 1"); AddSignal(67, "SIGRTMIN+2", false, false, false, "real time signal 2"); AddSignal(68, "SIGRTMIN+3", false, false, false, "real time signal 3"); AddSignal(69, "SIGRTMIN+4", false, false, false, "real time signal 4"); AddSignal(70, "SIGRTMIN+5", false, false, false, "real time signal 5"); AddSignal(71, "SIGRTMIN+6", false, false, false, "real time signal 6"); AddSignal(72, "SIGRTMIN+7", false, false, false, "real time signal 7"); AddSignal(73, "SIGRTMIN+8", false, false, false, "real time signal 8"); AddSignal(74, "SIGRTMIN+9", false, false, false, "real time signal 9"); AddSignal(75, "SIGRTMIN+10", false, false, false, "real time signal 10"); AddSignal(76, "SIGRTMIN+11", false, false, false, "real time signal 11"); AddSignal(77, "SIGRTMIN+12", false, false, false, "real time signal 12"); AddSignal(78, "SIGRTMIN+13", false, false, false, "real time signal 13"); AddSignal(79, "SIGRTMIN+14", false, false, false, "real time signal 14"); AddSignal(80, "SIGRTMIN+15", false, false, false, "real time signal 15"); AddSignal(81, "SIGRTMIN+16", false, false, false, "real time signal 16"); AddSignal(82, "SIGRTMIN+17", false, false, false, "real time signal 17"); AddSignal(83, "SIGRTMIN+18", false, false, false, "real time signal 18"); AddSignal(84, "SIGRTMIN+19", false, false, false, "real time signal 19"); AddSignal(85, "SIGRTMIN+20", false, false, false, "real time signal 20"); AddSignal(86, "SIGRTMIN+21", false, false, false, "real time signal 21"); AddSignal(87, "SIGRTMIN+22", false, false, false, "real time signal 22"); AddSignal(88, "SIGRTMIN+23", false, false, false, "real time signal 23"); AddSignal(89, "SIGRTMIN+24", false, false, false, "real time signal 24"); AddSignal(90, "SIGRTMIN+25", false, false, false, "real time signal 25"); AddSignal(91, "SIGRTMIN+26", false, false, false, "real time signal 26"); AddSignal(92, "SIGRTMIN+27", false, false, false, "real time signal 27"); AddSignal(93, "SIGRTMIN+28", false, false, false, "real time signal 28"); AddSignal(94, "SIGRTMIN+29", false, false, false, "real time signal 29"); AddSignal(95, "SIGRTMIN+30", false, false, false, "real time signal 30"); AddSignal(96, "SIGRTMAX-30", false, false, false, "real time signal 31"); AddSignal(97, "SIGRTMAX-29", false, false, false, "real time signal 32"); AddSignal(98, "SIGRTMAX-28", false, false, false, "real time signal 33"); AddSignal(99, "SIGRTMAX-27", false, false, false, "real time signal 34"); AddSignal(100, "SIGRTMAX-26", false, false, false, "real time signal 35"); AddSignal(101, "SIGRTMAX-25", false, false, false, "real time signal 36"); AddSignal(102, "SIGRTMAX-24", false, false, false, "real time signal 37"); AddSignal(103, "SIGRTMAX-23", false, false, false, "real time signal 38"); AddSignal(104, "SIGRTMAX-22", false, false, false, "real time signal 39"); AddSignal(105, "SIGRTMAX-21", false, false, false, "real time signal 40"); AddSignal(106, "SIGRTMAX-20", false, false, false, "real time signal 41"); AddSignal(107, "SIGRTMAX-19", false, false, false, "real time signal 42"); AddSignal(108, "SIGRTMAX-18", false, false, false, "real time signal 43"); AddSignal(109, "SIGRTMAX-17", false, false, false, "real time signal 44"); AddSignal(110, "SIGRTMAX-16", false, false, false, "real time signal 45"); AddSignal(111, "SIGRTMAX-15", false, false, false, "real time signal 46"); AddSignal(112, "SIGRTMAX-14", false, false, false, "real time signal 47"); AddSignal(113, "SIGRTMAX-13", false, false, false, "real time signal 48"); AddSignal(114, "SIGRTMAX-12", false, false, false, "real time signal 49"); AddSignal(115, "SIGRTMAX-11", false, false, false, "real time signal 50"); AddSignal(116, "SIGRTMAX-10", false, false, false, "real time signal 51"); AddSignal(117, "SIGRTMAX-9", false, false, false, "real time signal 52"); AddSignal(118, "SIGRTMAX-8", false, false, false, "real time signal 53"); AddSignal(119, "SIGRTMAX-7", false, false, false, "real time signal 54"); AddSignal(120, "SIGRTMAX-6", false, false, false, "real time signal 55"); AddSignal(121, "SIGRTMAX-5", false, false, false, "real time signal 56"); AddSignal(122, "SIGRTMAX-4", false, false, false, "real time signal 57"); AddSignal(123, "SIGRTMAX-3", false, false, false, "real time signal 58"); AddSignal(124, "SIGRTMAX-2", false, false, false, "real time signal 59"); AddSignal(125, "SIGRTMAX-1", false, false, false, "real time signal 60"); AddSignal(126, "SIGRTMAX", false, false, false, "real time signal 61"); }
apple/swift-lldb
source/Plugins/Process/Utility/FreeBSDSignals.cpp
C++
apache-2.0
5,613
define([ "dojo/_base/declare", // declare "dojo/dom-construct", // domConstruct.destroy domConstruct.place "dojo/keys", // keys.ENTER "dojo/_base/lang", "dojo/on", "dojo/sniff", // has("ie") has("mozilla") has("webkit") "dojo/_base/window", // win.withGlobal "dojo/window", // winUtils.scrollIntoView "../_Plugin", "../RichText", "../range", "../../_base/focus" ], function(declare, domConstruct, keys, lang, on, has, win, winUtils, _Plugin, RichText, rangeapi, baseFocus){ // module: // dijit/_editor/plugins/EnterKeyHandling return declare("dijit._editor.plugins.EnterKeyHandling", _Plugin, { // summary: // This plugin tries to make all browsers behave consistently with regard to // how ENTER behaves in the editor window. It traps the ENTER key and alters // the way DOM is constructed in certain cases to try to commonize the generated // DOM and behaviors across browsers. // // description: // This plugin has three modes: // // - blockNodeForEnter=BR // - blockNodeForEnter=DIV // - blockNodeForEnter=P // // In blockNodeForEnter=P, the ENTER key starts a new // paragraph, and shift-ENTER starts a new line in the current paragraph. // For example, the input: // // | first paragraph <shift-ENTER> // | second line of first paragraph <ENTER> // | second paragraph // // will generate: // // | <p> // | first paragraph // | <br/> // | second line of first paragraph // | </p> // | <p> // | second paragraph // | </p> // // In BR and DIV mode, the ENTER key conceptually goes to a new line in the // current paragraph, and users conceptually create a new paragraph by pressing ENTER twice. // For example, if the user enters text into an editor like this: // // | one <ENTER> // | two <ENTER> // | three <ENTER> // | <ENTER> // | four <ENTER> // | five <ENTER> // | six <ENTER> // // It will appear on the screen as two 'paragraphs' of three lines each. Markupwise, this generates: // // BR: // | one<br/> // | two<br/> // | three<br/> // | <br/> // | four<br/> // | five<br/> // | six<br/> // // DIV: // | <div>one</div> // | <div>two</div> // | <div>three</div> // | <div>&nbsp;</div> // | <div>four</div> // | <div>five</div> // | <div>six</div> // blockNodeForEnter: String // This property decides the behavior of Enter key. It can be either P, // DIV, BR, or empty (which means disable this feature). Anything else // will trigger errors. The default is 'BR' // // See class description for more details. blockNodeForEnter: 'BR', constructor: function(args){ if(args){ if("blockNodeForEnter" in args){ args.blockNodeForEnter = args.blockNodeForEnter.toUpperCase(); } lang.mixin(this, args); } }, setEditor: function(editor){ // Overrides _Plugin.setEditor(). if(this.editor === editor){ return; } this.editor = editor; if(this.blockNodeForEnter == 'BR'){ // While Moz has a mode tht mostly works, it's still a little different, // So, try to just have a common mode and be consistent. Which means // we need to enable customUndo, if not already enabled. this.editor.customUndo = true; editor.onLoadDeferred.then(lang.hitch(this, function(d){ this.own(on(editor.document, "keydown", lang.hitch(this, function(e){ if(e.keyCode == keys.ENTER){ // Just do it manually. The handleEnterKey has a shift mode that // Always acts like <br>, so just use it. var ne = lang.mixin({}, e); ne.shiftKey = true; if(!this.handleEnterKey(ne)){ e.stopPropagation(); e.preventDefault(); } } }))); if(has("ie") >= 9 && has("ie") <= 10){ this.own(on(editor.document, "paste", lang.hitch(this, function(e){ setTimeout(lang.hitch(this, function(){ // Use the old range/selection code to kick IE 9 into updating // its range by moving it back, then forward, one 'character'. var r = this.editor.document.selection.createRange(); r.move('character', -1); r.select(); r.move('character', 1); r.select(); }), 0); }))); } return d; })); }else if(this.blockNodeForEnter){ // add enter key handler var h = lang.hitch(this, "handleEnterKey"); editor.addKeyHandler(13, 0, 0, h); //enter editor.addKeyHandler(13, 0, 1, h); //shift+enter this.own(this.editor.on('KeyPressed', lang.hitch(this, 'onKeyPressed'))); } }, onKeyPressed: function(){ // summary: // Handler for after the user has pressed a key, and the display has been updated. // Connected to RichText's onKeyPressed() method. // tags: // private if(this._checkListLater){ if(win.withGlobal(this.editor.window, 'isCollapsed', baseFocus)){ // TODO: stop using withGlobal(), and baseFocus var liparent = this.editor.selection.getAncestorElement('LI'); if(!liparent){ // circulate the undo detection code by calling RichText::execCommand directly RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter); // set the innerHTML of the new block node var block = this.editor.selection.getAncestorElement(this.blockNodeForEnter); if(block){ block.innerHTML = this.bogusHtmlContent; if(has("ie") <= 9){ // move to the start by moving backwards one char var r = this.editor.document.selection.createRange(); r.move('character', -1); r.select(); } }else{ console.error('onKeyPressed: Cannot find the new block node'); // FIXME } }else{ if(has("mozilla")){ if(liparent.parentNode.parentNode.nodeName == 'LI'){ liparent = liparent.parentNode.parentNode; } } var fc = liparent.firstChild; if(fc && fc.nodeType == 1 && (fc.nodeName == 'UL' || fc.nodeName == 'OL')){ liparent.insertBefore(fc.ownerDocument.createTextNode('\xA0'), fc); var newrange = rangeapi.create(this.editor.window); newrange.setStart(liparent.firstChild, 0); var selection = rangeapi.getSelection(this.editor.window, true); selection.removeAllRanges(); selection.addRange(newrange); } } } this._checkListLater = false; } if(this._pressedEnterInBlock){ // the new created is the original current P, so we have previousSibling below if(this._pressedEnterInBlock.previousSibling){ this.removeTrailingBr(this._pressedEnterInBlock.previousSibling); } delete this._pressedEnterInBlock; } }, // bogusHtmlContent: [private] String // HTML to stick into a new empty block bogusHtmlContent: '&#160;', // &nbsp; // blockNodes: [private] Regex // Regex for testing if a given tag is a block level (display:block) tag blockNodes: /^(?:P|H1|H2|H3|H4|H5|H6|LI)$/, handleEnterKey: function(e){ // summary: // Handler for enter key events when blockNodeForEnter is DIV or P. // description: // Manually handle enter key event to make the behavior consistent across // all supported browsers. See class description for details. // tags: // private var selection, range, newrange, startNode, endNode, brNode, doc = this.editor.document, br, rs, txt; if(e.shiftKey){ // shift+enter always generates <br> var parent = this.editor.selection.getParentElement(); var header = rangeapi.getAncestor(parent, this.blockNodes); if(header){ if(header.tagName == 'LI'){ return true; // let browser handle } selection = rangeapi.getSelection(this.editor.window); range = selection.getRangeAt(0); if(!range.collapsed){ range.deleteContents(); selection = rangeapi.getSelection(this.editor.window); range = selection.getRangeAt(0); } if(rangeapi.atBeginningOfContainer(header, range.startContainer, range.startOffset)){ br = doc.createElement('br'); newrange = rangeapi.create(this.editor.window); header.insertBefore(br, header.firstChild); newrange.setStartAfter(br); selection.removeAllRanges(); selection.addRange(newrange); }else if(rangeapi.atEndOfContainer(header, range.startContainer, range.startOffset)){ newrange = rangeapi.create(this.editor.window); br = doc.createElement('br'); header.appendChild(br); header.appendChild(doc.createTextNode('\xA0')); newrange.setStart(header.lastChild, 0); selection.removeAllRanges(); selection.addRange(newrange); }else{ rs = range.startContainer; if(rs && rs.nodeType == 3){ // Text node, we have to split it. txt = rs.nodeValue; startNode = doc.createTextNode(txt.substring(0, range.startOffset)); endNode = doc.createTextNode(txt.substring(range.startOffset)); brNode = doc.createElement("br"); if(endNode.nodeValue == "" && has("webkit")){ endNode = doc.createTextNode('\xA0') } domConstruct.place(startNode, rs, "after"); domConstruct.place(brNode, startNode, "after"); domConstruct.place(endNode, brNode, "after"); domConstruct.destroy(rs); newrange = rangeapi.create(this.editor.window); newrange.setStart(endNode, 0); selection.removeAllRanges(); selection.addRange(newrange); return false; } return true; // let browser handle } }else{ selection = rangeapi.getSelection(this.editor.window); if(selection.rangeCount){ range = selection.getRangeAt(0); if(range && range.startContainer){ if(!range.collapsed){ range.deleteContents(); selection = rangeapi.getSelection(this.editor.window); range = selection.getRangeAt(0); } rs = range.startContainer; if(rs && rs.nodeType == 3){ // Text node, we have to split it. var endEmpty = false; var offset = range.startOffset; if(rs.length < offset){ //We are not splitting the right node, try to locate the correct one ret = this._adjustNodeAndOffset(rs, offset); rs = ret.node; offset = ret.offset; } txt = rs.nodeValue; startNode = doc.createTextNode(txt.substring(0, offset)); endNode = doc.createTextNode(txt.substring(offset)); brNode = doc.createElement("br"); if(!endNode.length){ endNode = doc.createTextNode('\xA0'); endEmpty = true; } if(startNode.length){ domConstruct.place(startNode, rs, "after"); }else{ startNode = rs; } domConstruct.place(brNode, startNode, "after"); domConstruct.place(endNode, brNode, "after"); domConstruct.destroy(rs); newrange = rangeapi.create(this.editor.window); newrange.setStart(endNode, 0); newrange.setEnd(endNode, endNode.length); selection.removeAllRanges(); selection.addRange(newrange); if(endEmpty && !has("webkit")){ this.editor.selection.remove(); }else{ this.editor.selection.collapse(true); } }else{ var targetNode; if(range.startOffset >= 0){ targetNode = rs.childNodes[range.startOffset]; } var brNode = doc.createElement("br"); var endNode = doc.createTextNode('\xA0'); if(!targetNode){ rs.appendChild(brNode); rs.appendChild(endNode); }else{ domConstruct.place(brNode, targetNode, "before"); domConstruct.place(endNode, brNode, "after"); } newrange = rangeapi.create(this.editor.window); newrange.setStart(endNode, 0); newrange.setEnd(endNode, endNode.length); selection.removeAllRanges(); selection.addRange(newrange); this.editor.selection.collapse(true); } } }else{ // don't change this: do not call this.execCommand, as that may have other logic in subclass RichText.prototype.execCommand.call(this.editor, 'inserthtml', '<br>'); } } return false; } var _letBrowserHandle = true; // first remove selection selection = rangeapi.getSelection(this.editor.window); range = selection.getRangeAt(0); if(!range.collapsed){ range.deleteContents(); selection = rangeapi.getSelection(this.editor.window); range = selection.getRangeAt(0); } var block = rangeapi.getBlockAncestor(range.endContainer, null, this.editor.editNode); var blockNode = block.blockNode; // if this is under a LI or the parent of the blockNode is LI, just let browser to handle it if((this._checkListLater = (blockNode && (blockNode.nodeName == 'LI' || blockNode.parentNode.nodeName == 'LI')))){ if(has("mozilla")){ // press enter in middle of P may leave a trailing <br/>, let's remove it later this._pressedEnterInBlock = blockNode; } // if this li only contains spaces, set the content to empty so the browser will outdent this item if(/^(\s|&nbsp;|&#160;|\xA0|<span\b[^>]*\bclass=['"]Apple-style-span['"][^>]*>(\s|&nbsp;|&#160;|\xA0)<\/span>)?(<br>)?$/.test(blockNode.innerHTML)){ // empty LI node blockNode.innerHTML = ''; if(has("webkit")){ // WebKit tosses the range when innerHTML is reset newrange = rangeapi.create(this.editor.window); newrange.setStart(blockNode, 0); selection.removeAllRanges(); selection.addRange(newrange); } this._checkListLater = false; // nothing to check since the browser handles outdent } return true; } // text node directly under body, let's wrap them in a node if(!block.blockNode || block.blockNode === this.editor.editNode){ try{ RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter); }catch(e2){ /*squelch FF3 exception bug when editor content is a single BR*/ } // get the newly created block node // FIXME block = {blockNode: this.editor.selection.getAncestorElement(this.blockNodeForEnter), blockContainer: this.editor.editNode}; if(block.blockNode){ if(block.blockNode != this.editor.editNode && (!(block.blockNode.textContent || block.blockNode.innerHTML).replace(/^\s+|\s+$/g, "").length)){ this.removeTrailingBr(block.blockNode); return false; } }else{ // we shouldn't be here if formatblock worked block.blockNode = this.editor.editNode; } selection = rangeapi.getSelection(this.editor.window); range = selection.getRangeAt(0); } var newblock = doc.createElement(this.blockNodeForEnter); newblock.innerHTML = this.bogusHtmlContent; this.removeTrailingBr(block.blockNode); var endOffset = range.endOffset; var node = range.endContainer; if(node.length < endOffset){ //We are not checking the right node, try to locate the correct one var ret = this._adjustNodeAndOffset(node, endOffset); node = ret.node; endOffset = ret.offset; } if(rangeapi.atEndOfContainer(block.blockNode, node, endOffset)){ if(block.blockNode === block.blockContainer){ block.blockNode.appendChild(newblock); }else{ domConstruct.place(newblock, block.blockNode, "after"); } _letBrowserHandle = false; // lets move caret to the newly created block newrange = rangeapi.create(this.editor.window); newrange.setStart(newblock, 0); selection.removeAllRanges(); selection.addRange(newrange); if(this.editor.height){ winUtils.scrollIntoView(newblock); } }else if(rangeapi.atBeginningOfContainer(block.blockNode, range.startContainer, range.startOffset)){ domConstruct.place(newblock, block.blockNode, block.blockNode === block.blockContainer ? "first" : "before"); if(newblock.nextSibling && this.editor.height){ // position input caret - mostly WebKit needs this newrange = rangeapi.create(this.editor.window); newrange.setStart(newblock.nextSibling, 0); selection.removeAllRanges(); selection.addRange(newrange); // browser does not scroll the caret position into view, do it manually winUtils.scrollIntoView(newblock.nextSibling); } _letBrowserHandle = false; }else{ //press enter in the middle of P/DIV/Whatever/ if(block.blockNode === block.blockContainer){ block.blockNode.appendChild(newblock); }else{ domConstruct.place(newblock, block.blockNode, "after"); } _letBrowserHandle = false; // Clone any block level styles. if(block.blockNode.style){ if(newblock.style){ if(block.blockNode.style.cssText){ newblock.style.cssText = block.blockNode.style.cssText; } } } // Okay, we probably have to split. rs = range.startContainer; var firstNodeMoved; if(rs && rs.nodeType == 3){ // Text node, we have to split it. var nodeToMove, tNode; endOffset = range.endOffset; if(rs.length < endOffset){ //We are not splitting the right node, try to locate the correct one ret = this._adjustNodeAndOffset(rs, endOffset); rs = ret.node; endOffset = ret.offset; } txt = rs.nodeValue; startNode = doc.createTextNode(txt.substring(0, endOffset)); endNode = doc.createTextNode(txt.substring(endOffset, txt.length)); // Place the split, then remove original nodes. domConstruct.place(startNode, rs, "before"); domConstruct.place(endNode, rs, "after"); domConstruct.destroy(rs); // Okay, we split the text. Now we need to see if we're // parented to the block element we're splitting and if // not, we have to split all the way up. Ugh. var parentC = startNode.parentNode; while(parentC !== block.blockNode){ var tg = parentC.tagName; var newTg = doc.createElement(tg); // Clone over any 'style' data. if(parentC.style){ if(newTg.style){ if(parentC.style.cssText){ newTg.style.cssText = parentC.style.cssText; } } } // If font also need to clone over any font data. if(parentC.tagName === "FONT"){ if(parentC.color){ newTg.color = parentC.color; } if(parentC.face){ newTg.face = parentC.face; } if(parentC.size){ // this check was necessary on IE newTg.size = parentC.size; } } nodeToMove = endNode; while(nodeToMove){ tNode = nodeToMove.nextSibling; newTg.appendChild(nodeToMove); nodeToMove = tNode; } domConstruct.place(newTg, parentC, "after"); startNode = parentC; endNode = newTg; parentC = parentC.parentNode; } // Lastly, move the split out tags to the new block. // as they should now be split properly. nodeToMove = endNode; if(nodeToMove.nodeType == 1 || (nodeToMove.nodeType == 3 && nodeToMove.nodeValue)){ // Non-blank text and non-text nodes need to clear out that blank space // before moving the contents. newblock.innerHTML = ""; } firstNodeMoved = nodeToMove; while(nodeToMove){ tNode = nodeToMove.nextSibling; newblock.appendChild(nodeToMove); nodeToMove = tNode; } } //lets move caret to the newly created block newrange = rangeapi.create(this.editor.window); var nodeForCursor; var innerMostFirstNodeMoved = firstNodeMoved; if(this.blockNodeForEnter !== 'BR'){ while(innerMostFirstNodeMoved){ nodeForCursor = innerMostFirstNodeMoved; tNode = innerMostFirstNodeMoved.firstChild; innerMostFirstNodeMoved = tNode; } if(nodeForCursor && nodeForCursor.parentNode){ newblock = nodeForCursor.parentNode; newrange.setStart(newblock, 0); selection.removeAllRanges(); selection.addRange(newrange); if(this.editor.height){ winUtils.scrollIntoView(newblock); } if(has("mozilla")){ // press enter in middle of P may leave a trailing <br/>, let's remove it later this._pressedEnterInBlock = block.blockNode; } }else{ _letBrowserHandle = true; } }else{ newrange.setStart(newblock, 0); selection.removeAllRanges(); selection.addRange(newrange); if(this.editor.height){ winUtils.scrollIntoView(newblock); } if(has("mozilla")){ // press enter in middle of P may leave a trailing <br/>, let's remove it later this._pressedEnterInBlock = block.blockNode; } } } return _letBrowserHandle; }, _adjustNodeAndOffset: function(/*DomNode*/node, /*Int*/offset){ // summary: // In the case there are multiple text nodes in a row the offset may not be within the node. If the offset is larger than the node length, it will attempt to find // the next text sibling until it locates the text node in which the offset refers to // node: // The node to check. // offset: // The position to find within the text node // tags: // private. while(node.length < offset && node.nextSibling && node.nextSibling.nodeType == 3){ //Adjust the offset and node in the case of multiple text nodes in a row offset = offset - node.length; node = node.nextSibling; } return {"node": node, "offset": offset}; }, removeTrailingBr: function(container){ // summary: // If last child of container is a `<br>`, then remove it. // tags: // private var para = /P|DIV|LI/i.test(container.tagName) ? container : this.editor.selection.getParentOfType(container, ['P', 'DIV', 'LI']); if(!para){ return; } if(para.lastChild){ if((para.childNodes.length > 1 && para.lastChild.nodeType == 3 && /^[\s\xAD]*$/.test(para.lastChild.nodeValue)) || para.lastChild.tagName == 'BR'){ domConstruct.destroy(para.lastChild); } } if(!para.childNodes.length){ para.innerHTML = this.bogusHtmlContent; } } }); });
denov/dojo-demo
src/main/webapp/js/dijit/_editor/plugins/EnterKeyHandling.js
JavaScript
apache-2.0
22,062
/** * Copyright (C) 2012 Iordan Iordanov * Copyright (C) 2010 Michael A. MacDonald * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ package com.iiordanov.bVNC; import java.io.IOException; public enum COLORMODEL { C24bit, C256, C64, C8, C4, C2; public int bpp() { switch (this) { case C24bit: return 4; default: return 1; } } public int[] palette() { switch (this) { case C24bit: return null; case C256: return ColorModel256.colors; case C64: return ColorModel64.colors; case C8: return ColorModel8.colors; case C4: return ColorModel64.colors; case C2: return ColorModel8.colors; default: return null; } } public String nameString() { return super.toString(); } public void setPixelFormat(RfbConnectable rfb) throws IOException { switch (this) { case C24bit: // 24-bit color rfb.writeSetPixelFormat(32, 24, false, true, 255, 255, 255, 16, 8, 0, false); break; case C256: rfb.writeSetPixelFormat(8, 8, false, true, 7, 7, 3, 0, 3, 6, false); break; case C64: rfb.writeSetPixelFormat(8, 6, false, true, 3, 3, 3, 4, 2, 0, false); break; case C8: rfb.writeSetPixelFormat(8, 3, false, true, 1, 1, 1, 2, 1, 0, false); break; case C4: // Greyscale rfb.writeSetPixelFormat(8, 6, false, true, 3, 3, 3, 4, 2, 0, true); break; case C2: // B&W rfb.writeSetPixelFormat(8, 3, false, true, 1, 1, 1, 2, 1, 0, true); break; default: // Default is 24 bit color rfb.writeSetPixelFormat(32, 24, false, true, 255, 255, 255, 16, 8, 0, false); break; } } public String toString() { switch (this) { case C24bit: return "24-bit color (4 bpp)"; case C256: return "256 colors (1 bpp)"; case C64: return "64 colors (1 bpp)"; case C8: return "8 colors (1 bpp)"; case C4: return "Greyscale (1 bpp)"; case C2: return "Black & White (1 bpp)"; default: return "24-bit color (4 bpp)"; } } }
x-hansong/aSpice
src/com/iiordanov/bVNC/COLORMODEL.java
Java
apache-2.0
3,262
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( "fmt" "reflect" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/runtime" "speter.net/go/exp/math/dec/inf" ) const ( // Annotation key used to identify mirror pods. mirrorAnnotationKey = "kubernetes.io/config.mirror" // Value used to identify mirror pods from pre-v1.1 kubelet. mirrorAnnotationValue_1_0 = "mirror" ) func addConversionFuncs(scheme *runtime.Scheme) { // Add non-generated conversion functions err := scheme.AddConversionFuncs( Convert_api_Pod_To_v1_Pod, Convert_api_PodSpec_To_v1_PodSpec, Convert_api_ReplicationControllerSpec_To_v1_ReplicationControllerSpec, Convert_api_ServiceSpec_To_v1_ServiceSpec, Convert_v1_Pod_To_api_Pod, Convert_v1_PodSpec_To_api_PodSpec, Convert_v1_ReplicationControllerSpec_To_api_ReplicationControllerSpec, Convert_v1_ServiceSpec_To_api_ServiceSpec, Convert_v1_ResourceList_To_api_ResourceList, Convert_api_VolumeSource_To_v1_VolumeSource, Convert_v1_VolumeSource_To_api_VolumeSource, Convert_v1_SecurityContextConstraints_To_api_SecurityContextConstraints, Convert_api_SecurityContextConstraints_To_v1_SecurityContextConstraints, ) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } // Add field label conversions for kinds having selectable nothing but ObjectMeta fields. for _, kind := range []string{ "Endpoints", "ResourceQuota", "PersistentVolumeClaim", "Service", "ServiceAccount", "ConfigMap", } { err = api.Scheme.AddFieldLabelConversionFunc("v1", kind, func(label, value string) (string, string, error) { switch label { case "metadata.namespace", "metadata.name": return label, value, nil default: return "", "", fmt.Errorf("field label %q not supported for %q", label, kind) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } } // Add field conversion funcs. err = api.Scheme.AddFieldLabelConversionFunc("v1", "Pod", func(label, value string) (string, string, error) { switch label { case "metadata.name", "metadata.namespace", "metadata.labels", "metadata.annotations", "status.phase", "status.podIP", "spec.nodeName", "spec.restartPolicy": return label, value, nil // This is for backwards compatibility with old v1 clients which send spec.host case "spec.host": return "spec.nodeName", value, nil default: return "", "", fmt.Errorf("field label not supported: %s", label) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } err = api.Scheme.AddFieldLabelConversionFunc("v1", "Node", func(label, value string) (string, string, error) { switch label { case "metadata.name": return label, value, nil case "spec.unschedulable": return label, value, nil default: return "", "", fmt.Errorf("field label not supported: %s", label) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } err = api.Scheme.AddFieldLabelConversionFunc("v1", "ReplicationController", func(label, value string) (string, string, error) { switch label { case "metadata.name", "metadata.namespace", "status.replicas": return label, value, nil default: return "", "", fmt.Errorf("field label not supported: %s", label) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } err = api.Scheme.AddFieldLabelConversionFunc("v1", "Event", func(label, value string) (string, string, error) { switch label { case "involvedObject.kind", "involvedObject.namespace", "involvedObject.name", "involvedObject.uid", "involvedObject.apiVersion", "involvedObject.resourceVersion", "involvedObject.fieldPath", "reason", "source", "type", "metadata.namespace", "metadata.name": return label, value, nil default: return "", "", fmt.Errorf("field label not supported: %s", label) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } err = api.Scheme.AddFieldLabelConversionFunc("v1", "Namespace", func(label, value string) (string, string, error) { switch label { case "status.phase", "metadata.name": return label, value, nil default: return "", "", fmt.Errorf("field label not supported: %s", label) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } err = api.Scheme.AddFieldLabelConversionFunc("v1", "PersistentVolume", func(label, value string) (string, string, error) { switch label { case "metadata.name": return label, value, nil default: return "", "", fmt.Errorf("field label not supported: %s", label) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } err = api.Scheme.AddFieldLabelConversionFunc("v1", "Secret", func(label, value string) (string, string, error) { switch label { case "type", "metadata.namespace", "metadata.name": return label, value, nil default: return "", "", fmt.Errorf("field label not supported: %s", label) } }) if err != nil { // If one of the conversion functions is malformed, detect it immediately. panic(err) } } func Convert_api_ReplicationControllerSpec_To_v1_ReplicationControllerSpec(in *api.ReplicationControllerSpec, out *ReplicationControllerSpec, s conversion.Scope) error { out.Replicas = new(int32) *out.Replicas = int32(in.Replicas) if in.Selector != nil { out.Selector = make(map[string]string) for key, val := range in.Selector { out.Selector[key] = val } } else { out.Selector = nil } //if in.TemplateRef != nil { // out.TemplateRef = new(ObjectReference) // if err := Convert_api_ObjectReference_To_v1_ObjectReference(in.TemplateRef, out.TemplateRef, s); err != nil { // return err // } //} else { // out.TemplateRef = nil //} if in.Template != nil { out.Template = new(PodTemplateSpec) if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(in.Template, out.Template, s); err != nil { return err } } else { out.Template = nil } return nil } func Convert_v1_ReplicationControllerSpec_To_api_ReplicationControllerSpec(in *ReplicationControllerSpec, out *api.ReplicationControllerSpec, s conversion.Scope) error { out.Replicas = *in.Replicas if in.Selector != nil { out.Selector = make(map[string]string) for key, val := range in.Selector { out.Selector[key] = val } } else { out.Selector = nil } //if in.TemplateRef != nil { // out.TemplateRef = new(api.ObjectReference) // if err := Convert_v1_ObjectReference_To_api_ObjectReference(in.TemplateRef, out.TemplateRef, s); err != nil { // return err // } //} else { // out.TemplateRef = nil //} if in.Template != nil { out.Template = new(api.PodTemplateSpec) if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in.Template, out.Template, s); err != nil { return err } } else { out.Template = nil } return nil } // The following two PodSpec conversions are done here to support ServiceAccount // as an alias for ServiceAccountName. func Convert_api_PodSpec_To_v1_PodSpec(in *api.PodSpec, out *PodSpec, s conversion.Scope) error { if in.Volumes != nil { out.Volumes = make([]Volume, len(in.Volumes)) for i := range in.Volumes { if err := Convert_api_Volume_To_v1_Volume(&in.Volumes[i], &out.Volumes[i], s); err != nil { return err } } } else { out.Volumes = nil } if in.Containers != nil { out.Containers = make([]Container, len(in.Containers)) for i := range in.Containers { if err := Convert_api_Container_To_v1_Container(&in.Containers[i], &out.Containers[i], s); err != nil { return err } } } else { out.Containers = nil } out.RestartPolicy = RestartPolicy(in.RestartPolicy) if in.TerminationGracePeriodSeconds != nil { out.TerminationGracePeriodSeconds = new(int64) *out.TerminationGracePeriodSeconds = *in.TerminationGracePeriodSeconds } else { out.TerminationGracePeriodSeconds = nil } if in.ActiveDeadlineSeconds != nil { out.ActiveDeadlineSeconds = new(int64) *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds } else { out.ActiveDeadlineSeconds = nil } out.DNSPolicy = DNSPolicy(in.DNSPolicy) if in.NodeSelector != nil { out.NodeSelector = make(map[string]string) for key, val := range in.NodeSelector { out.NodeSelector[key] = val } } else { out.NodeSelector = nil } out.ServiceAccountName = in.ServiceAccountName // DeprecatedServiceAccount is an alias for ServiceAccountName. out.DeprecatedServiceAccount = in.ServiceAccountName out.NodeName = in.NodeName if in.SecurityContext != nil { out.SecurityContext = new(PodSecurityContext) if err := Convert_api_PodSecurityContext_To_v1_PodSecurityContext(in.SecurityContext, out.SecurityContext, s); err != nil { return err } // the host namespace fields have to be handled here for backward compatibility // with v1.0.0 out.HostPID = in.SecurityContext.HostPID out.HostNetwork = in.SecurityContext.HostNetwork out.HostIPC = in.SecurityContext.HostIPC } if in.ImagePullSecrets != nil { out.ImagePullSecrets = make([]LocalObjectReference, len(in.ImagePullSecrets)) for i := range in.ImagePullSecrets { if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(&in.ImagePullSecrets[i], &out.ImagePullSecrets[i], s); err != nil { return err } } } else { out.ImagePullSecrets = nil } out.Hostname = in.Hostname out.Subdomain = in.Subdomain // carry conversion out.DeprecatedHost = in.NodeName return nil } func Convert_v1_PodSpec_To_api_PodSpec(in *PodSpec, out *api.PodSpec, s conversion.Scope) error { SetDefaults_PodSpec(in) if in.Volumes != nil { out.Volumes = make([]api.Volume, len(in.Volumes)) for i := range in.Volumes { if err := Convert_v1_Volume_To_api_Volume(&in.Volumes[i], &out.Volumes[i], s); err != nil { return err } } } else { out.Volumes = nil } if in.Containers != nil { out.Containers = make([]api.Container, len(in.Containers)) for i := range in.Containers { if err := Convert_v1_Container_To_api_Container(&in.Containers[i], &out.Containers[i], s); err != nil { return err } } } else { out.Containers = nil } out.RestartPolicy = api.RestartPolicy(in.RestartPolicy) if in.TerminationGracePeriodSeconds != nil { out.TerminationGracePeriodSeconds = new(int64) *out.TerminationGracePeriodSeconds = *in.TerminationGracePeriodSeconds } else { out.TerminationGracePeriodSeconds = nil } if in.ActiveDeadlineSeconds != nil { out.ActiveDeadlineSeconds = new(int64) *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds } else { out.ActiveDeadlineSeconds = nil } out.DNSPolicy = api.DNSPolicy(in.DNSPolicy) if in.NodeSelector != nil { out.NodeSelector = make(map[string]string) for key, val := range in.NodeSelector { out.NodeSelector[key] = val } } else { out.NodeSelector = nil } // We support DeprecatedServiceAccount as an alias for ServiceAccountName. // If both are specified, ServiceAccountName (the new field) wins. out.ServiceAccountName = in.ServiceAccountName if in.ServiceAccountName == "" { out.ServiceAccountName = in.DeprecatedServiceAccount } out.NodeName = in.NodeName // carry conversion if in.NodeName == "" { out.NodeName = in.DeprecatedHost } if in.SecurityContext != nil { out.SecurityContext = new(api.PodSecurityContext) if err := Convert_v1_PodSecurityContext_To_api_PodSecurityContext(in.SecurityContext, out.SecurityContext, s); err != nil { return err } } // the host namespace fields have to be handled specially for backward compatibility // with v1.0.0 if out.SecurityContext == nil { out.SecurityContext = new(api.PodSecurityContext) } out.SecurityContext.HostNetwork = in.HostNetwork out.SecurityContext.HostPID = in.HostPID out.SecurityContext.HostIPC = in.HostIPC if in.ImagePullSecrets != nil { out.ImagePullSecrets = make([]api.LocalObjectReference, len(in.ImagePullSecrets)) for i := range in.ImagePullSecrets { if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(&in.ImagePullSecrets[i], &out.ImagePullSecrets[i], s); err != nil { return err } } } else { out.ImagePullSecrets = nil } out.Hostname = in.Hostname out.Subdomain = in.Subdomain return nil } func Convert_api_Pod_To_v1_Pod(in *api.Pod, out *Pod, s conversion.Scope) error { if err := autoConvert_api_Pod_To_v1_Pod(in, out, s); err != nil { return err } // We need to reset certain fields for mirror pods from pre-v1.1 kubelet // (#15960). // TODO: Remove this code after we drop support for v1.0 kubelets. if value, ok := in.Annotations[mirrorAnnotationKey]; ok && value == mirrorAnnotationValue_1_0 { // Reset the TerminationGracePeriodSeconds. out.Spec.TerminationGracePeriodSeconds = nil // Reset the resource requests. for i := range out.Spec.Containers { out.Spec.Containers[i].Resources.Requests = nil } } return nil } func Convert_v1_Pod_To_api_Pod(in *Pod, out *api.Pod, s conversion.Scope) error { return autoConvert_v1_Pod_To_api_Pod(in, out, s) } func Convert_api_ServiceSpec_To_v1_ServiceSpec(in *api.ServiceSpec, out *ServiceSpec, s conversion.Scope) error { if err := autoConvert_api_ServiceSpec_To_v1_ServiceSpec(in, out, s); err != nil { return err } // Publish both externalIPs and deprecatedPublicIPs fields in v1. for _, ip := range in.ExternalIPs { out.DeprecatedPublicIPs = append(out.DeprecatedPublicIPs, ip) } // Carry conversion out.DeprecatedPortalIP = in.ClusterIP return nil } func Convert_v1_ServiceSpec_To_api_ServiceSpec(in *ServiceSpec, out *api.ServiceSpec, s conversion.Scope) error { if err := autoConvert_v1_ServiceSpec_To_api_ServiceSpec(in, out, s); err != nil { return err } // Prefer the legacy deprecatedPublicIPs field, if provided. if len(in.DeprecatedPublicIPs) > 0 { out.ExternalIPs = nil for _, ip := range in.DeprecatedPublicIPs { out.ExternalIPs = append(out.ExternalIPs, ip) } } return nil } func Convert_api_PodSecurityContext_To_v1_PodSecurityContext(in *api.PodSecurityContext, out *PodSecurityContext, s conversion.Scope) error { out.SupplementalGroups = in.SupplementalGroups if in.SELinuxOptions != nil { out.SELinuxOptions = new(SELinuxOptions) if err := Convert_api_SELinuxOptions_To_v1_SELinuxOptions(in.SELinuxOptions, out.SELinuxOptions, s); err != nil { return err } } else { out.SELinuxOptions = nil } if in.RunAsUser != nil { out.RunAsUser = new(int64) *out.RunAsUser = *in.RunAsUser } else { out.RunAsUser = nil } if in.RunAsNonRoot != nil { out.RunAsNonRoot = new(bool) *out.RunAsNonRoot = *in.RunAsNonRoot } else { out.RunAsNonRoot = nil } if in.FSGroup != nil { out.FSGroup = new(int64) *out.FSGroup = *in.FSGroup } else { out.FSGroup = nil } return nil } func Convert_v1_PodSecurityContext_To_api_PodSecurityContext(in *PodSecurityContext, out *api.PodSecurityContext, s conversion.Scope) error { out.SupplementalGroups = in.SupplementalGroups if in.SELinuxOptions != nil { out.SELinuxOptions = new(api.SELinuxOptions) if err := Convert_v1_SELinuxOptions_To_api_SELinuxOptions(in.SELinuxOptions, out.SELinuxOptions, s); err != nil { return err } } else { out.SELinuxOptions = nil } if in.RunAsUser != nil { out.RunAsUser = new(int64) *out.RunAsUser = *in.RunAsUser } else { out.RunAsUser = nil } if in.RunAsNonRoot != nil { out.RunAsNonRoot = new(bool) *out.RunAsNonRoot = *in.RunAsNonRoot } else { out.RunAsNonRoot = nil } if in.FSGroup != nil { out.FSGroup = new(int64) *out.FSGroup = *in.FSGroup } else { out.FSGroup = nil } return nil } func Convert_v1_ResourceList_To_api_ResourceList(in *ResourceList, out *api.ResourceList, s conversion.Scope) error { if *in == nil { return nil } converted := make(api.ResourceList) for key, val := range *in { value := val.Copy() // TODO(#18538): We round up resource values to milli scale to maintain API compatibility. // In the future, we should instead reject values that need rounding. const milliScale = 3 value.Amount.Round(value.Amount, milliScale, inf.RoundUp) converted[api.ResourceName(key)] = *value } *out = converted return nil } // This will Convert our internal represantation of VolumeSource to its v1 representation // Used for keeping backwards compatibility for the Metadata field func Convert_api_VolumeSource_To_v1_VolumeSource(in *api.VolumeSource, out *VolumeSource, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*api.VolumeSource))(in) } if err := s.DefaultConvert(in, out, conversion.IgnoreMissingFields); err != nil { return err } if in.DownwardAPI != nil { out.Metadata = new(MetadataVolumeSource) if err := Convert_api_DownwardAPIVolumeSource_To_v1_MetadataVolumeSource(in.DownwardAPI, out.Metadata, s); err != nil { return err } } return nil } // downward -> metadata (api -> v1) func Convert_api_DownwardAPIVolumeSource_To_v1_MetadataVolumeSource(in *api.DownwardAPIVolumeSource, out *MetadataVolumeSource, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*api.DownwardAPIVolumeSource))(in) } if in.Items != nil { out.Items = make([]MetadataFile, len(in.Items)) for i := range in.Items { if err := Convert_api_DownwardAPIVolumeFile_To_v1_MetadataFile(&in.Items[i], &out.Items[i], s); err != nil { return err } } } return nil } func Convert_api_DownwardAPIVolumeFile_To_v1_MetadataFile(in *api.DownwardAPIVolumeFile, out *MetadataFile, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*api.DownwardAPIVolumeFile))(in) } out.Name = in.Path if err := Convert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil { return err } return nil } // This will Convert the v1 representation of VolumeSource to our internal representation // Used for keeping backwards compatibility for the Metadata field func Convert_v1_VolumeSource_To_api_VolumeSource(in *VolumeSource, out *api.VolumeSource, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*VolumeSource))(in) } if err := s.DefaultConvert(in, out, conversion.IgnoreMissingFields); err != nil { return err } if in.Metadata != nil { out.DownwardAPI = new(api.DownwardAPIVolumeSource) if err := Convert_v1_MetadataVolumeSource_To_api_DownwardAPIVolumeSource(in.Metadata, out.DownwardAPI, s); err != nil { return err } } return nil } // metadata -> downward (v1 -> api) func Convert_v1_MetadataVolumeSource_To_api_DownwardAPIVolumeSource(in *MetadataVolumeSource, out *api.DownwardAPIVolumeSource, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*MetadataVolumeSource))(in) } if in.Items != nil { out.Items = make([]api.DownwardAPIVolumeFile, len(in.Items)) for i := range in.Items { if err := Convert_v1_MetadataFile_To_api_DownwardAPIVolumeFile(&in.Items[i], &out.Items[i], s); err != nil { return err } } } return nil } func Convert_v1_MetadataFile_To_api_DownwardAPIVolumeFile(in *MetadataFile, out *api.DownwardAPIVolumeFile, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*MetadataFile))(in) } out.Path = in.Name if err := Convert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil { return err } return nil } func Convert_v1_SecurityContextConstraints_To_api_SecurityContextConstraints(in *SecurityContextConstraints, out *api.SecurityContextConstraints, s conversion.Scope) error { return autoConvert_v1_SecurityContextConstraints_To_api_SecurityContextConstraints(in, out, s) } func Convert_api_SecurityContextConstraints_To_v1_SecurityContextConstraints(in *api.SecurityContextConstraints, out *SecurityContextConstraints, s conversion.Scope) error { if err := autoConvert_api_SecurityContextConstraints_To_v1_SecurityContextConstraints(in, out, s); err != nil { return err } if in.Volumes != nil { for _, v := range in.Volumes { // set the Allow* fields based on the existence in the volume slice switch v { case api.FSTypeHostPath, api.FSTypeAll: out.AllowHostDirVolumePlugin = true } } } return nil }
danmcp/source-to-image
vendor/k8s.io/kubernetes/pkg/api/v1/conversion.go
GO
apache-2.0
21,451
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui; import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; import java.awt.*; public final class MixedColorProducerTest { @Test public void checkFirstColorInstance() { Assert.assertSame(Color.BLACK, getBlackWhite(0).get()); Assert.assertSame(Color.WHITE, getWhiteBlack(0).get()); } @Test public void checkSecondColorInstance() { Assert.assertSame(Color.WHITE, getBlackWhite(1).get()); Assert.assertSame(Color.BLACK, getWhiteBlack(1).get()); } @Test public void checkCachedColorInstance() { MixedColorProducer producer = getTransparentRed(.999); Color color = producer.get(); producer.setMixer(.999); Assert.assertEquals(color, producer.get()); Assert.assertSame(color, producer.get()); producer.setMixer(.9999); Assert.assertEquals(color, producer.get()); Assert.assertNotSame(color, producer.get()); } private static void testInvalidValue(double mixer) { try { getTransparentRed(mixer); Assert.fail("invalid value: " + mixer); } catch (IllegalArgumentException ignore) { } } @Test public void testMinNegativeValue() { testInvalidValue(-Double.MIN_VALUE); } @Test public void testMaxNegativeValue() { testInvalidValue(-Double.MAX_VALUE); } @Test public void testMaxPositiveValue() { testInvalidValue(Double.MAX_VALUE); } @Test public void testNegativeInfinity() { testInvalidValue(Double.NEGATIVE_INFINITY); } @Test public void testPositiveInfinity() { testInvalidValue(Double.POSITIVE_INFINITY); } @Test public void testNaN() { testInvalidValue(Double.NaN); } @NotNull private static MixedColorProducer getBlackWhite(double mixer) { return new MixedColorProducer(Color.BLACK, Color.WHITE, mixer); } @Test public void testBlackWhite25() { assertColor(getBlackWhite(.25), 0x404040); } @Test public void testBlackWhite50() { assertColor(getBlackWhite(.50), 0x808080); } @Test public void testBlackWhite75() { assertColor(getBlackWhite(.75), 0xBFBFBF); } @Test public void testBlackWhiteAll() { MixedColorProducer producer = getBlackWhite(0); for (int i = 0; i <= 0xFF; i++) { producer.setMixer((float)i / 0xFF); assertGrayColor(producer, i); } } @NotNull private static MixedColorProducer getWhiteBlack(double mixer) { return new MixedColorProducer(Color.WHITE, Color.BLACK, mixer); } @Test public void testWhiteBlack25() { assertColor(getWhiteBlack(.25), 0xBFBFBF); } @Test public void testWhiteBlack50() { assertColor(getWhiteBlack(.50), 0x808080); } @Test public void testWhiteBlack75() { assertColor(getWhiteBlack(.75), 0x404040); } @Test public void testWhiteBlackAll() { MixedColorProducer producer = getWhiteBlack(0); for (int i = 0; i <= 0xFF; i++) { producer.setMixer((float)i / 0xFF); assertGrayColor(producer, 0xFF - i); } } @NotNull private static MixedColorProducer getTransparentRed(double mixer) { return new MixedColorProducer(new Color(0xFF, 0, 0, 0), Color.RED, mixer); } @Test public void testTransparentRed25() { assertColorWithAlpha(getTransparentRed(.25), 0x40FF0000); } @Test public void testTransparentRed50() { assertColorWithAlpha(getTransparentRed(.50), 0x80FF0000); } @Test public void testTransparentRed75() { assertColorWithAlpha(getTransparentRed(.75), 0xBFFF0000); } private static void assertColor(@NotNull MixedColorProducer producer, int expected) { assertColor(producer, new Color(expected, false)); } private static void assertColorWithAlpha(@NotNull MixedColorProducer producer, int expected) { assertColor(producer, new Color(expected, true)); } private static void assertGrayColor(@NotNull MixedColorProducer producer, int expected) { assertColor(producer, new Color(expected, expected, expected)); } private static void assertColor(@NotNull MixedColorProducer producer, @NotNull Color expected) { Assert.assertEquals(expected, producer.get()); } }
smmribeiro/intellij-community
platform/util/testSrc/com/intellij/ui/MixedColorProducerTest.java
Java
apache-2.0
4,269
/* * Copyright 2009-2013 by The Regents of the University of California * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * you may obtain a copy of the License from * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.hyracks.hdfs.api; import edu.uci.ics.hyracks.api.comm.IFrameWriter; import edu.uci.ics.hyracks.api.exceptions.HyracksDataException; /** * Users need to implement this interface to use the HDFSReadOperatorDescriptor. * * @param <K> * the key type * @param <V> * the value type */ public interface IKeyValueParser<K, V> { /** * Initialize the key value parser. * * @param writer * The hyracks writer for outputting data. * @throws HyracksDataException */ public void open(IFrameWriter writer) throws HyracksDataException; /** * @param key * @param value * @param writer * @param fileName * @throws HyracksDataException */ public void parse(K key, V value, IFrameWriter writer, String fileString) throws HyracksDataException; /** * Flush the residual tuples in the internal buffer to the writer. * This method is called in the close() of HDFSReadOperatorDescriptor. * * @param writer * The hyracks writer for outputting data. * @throws HyracksDataException */ public void close(IFrameWriter writer) throws HyracksDataException; }
ilovesoup/hyracks
hyracks/hyracks-hdfs/hyracks-hdfs-core/src/main/java/edu/uci/ics/hyracks/hdfs/api/IKeyValueParser.java
Java
apache-2.0
1,862
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.12.11 at 12:17:22 PM IST // package org.wso2.developerstudio.eclipse.security.project.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}service" maxOccurs="unbounded"/> * &lt;choice maxOccurs="unbounded"> * &lt;element ref="{}module" minOccurs="0"/> * &lt;element ref="{}parameter" minOccurs="0"/> * &lt;/choice> * &lt;/sequence> * &lt;attribute name="hashValue" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> * &lt;attribute name="successfullyAdded" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "service", "moduleOrParameter" }) @XmlRootElement(name = "serviceGroup", namespace = "") public class ServiceGroup { @XmlElement(namespace = "", required = true) protected List<Service> service; @XmlElements({ @XmlElement(name = "module", namespace = "", type = Module.class), @XmlElement(name = "parameter", namespace = "", type = Parameter.class) }) protected List<Object> moduleOrParameter; @XmlAttribute(name = "hashValue") @XmlSchemaType(name = "anySimpleType") protected String hashValue; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NCName") protected String name; @XmlAttribute(name = "successfullyAdded", required = true) protected boolean successfullyAdded; /** * Gets the value of the service property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the service property. * * <p> * For example, to add a new item, do as follows: * <pre> * getService().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Service } * * */ public List<Service> getService() { if (service == null) { service = new ArrayList<Service>(); } return this.service; } /** * Gets the value of the moduleOrParameter property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the moduleOrParameter property. * * <p> * For example, to add a new item, do as follows: * <pre> * getModuleOrParameter().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Module } * {@link Parameter } * * */ public List<Object> getModuleOrParameter() { if (moduleOrParameter == null) { moduleOrParameter = new ArrayList<Object>(); } return this.moduleOrParameter; } /** * Gets the value of the hashValue property. * * @return * possible object is * {@link String } * */ public String getHashValue() { return hashValue; } /** * Sets the value of the hashValue property. * * @param value * allowed object is * {@link String } * */ public void setHashValue(String value) { this.hashValue = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the successfullyAdded property. * */ public boolean isSuccessfullyAdded() { return successfullyAdded; } /** * Sets the value of the successfullyAdded property. * */ public void setSuccessfullyAdded(boolean value) { this.successfullyAdded = value; } }
knadikari/developer-studio
common/org.wso2.developerstudio.eclipse.artifact.security/src/org/wso2/developerstudio/eclipse/security/project/model/ServiceGroup.java
Java
apache-2.0
5,773
/* jshint globalstrict:false, strict:false, unused : false */ /* global assertEqual */ // ////////////////////////////////////////////////////////////////////////////// // / @brief tests for dump/reload // / // / @file // / // / DISCLAIMER // / // / Copyright 2010-2012 triagens GmbH, Cologne, Germany // / // / Licensed under the Apache License, Version 2.0 (the "License") // / you may not use this file except in compliance with the License. // / You may obtain a copy of the License at // / // / http://www.apache.org/licenses/LICENSE-2.0 // / // / Unless required by applicable law or agreed to in writing, software // / distributed under the License is distributed on an "AS IS" BASIS, // / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // / See the License for the specific language governing permissions and // / limitations under the License. // / // / Copyright holder is triAGENS GmbH, Cologne, Germany // / // / @author Jan Steemann // / @author Copyright 2012, triAGENS GmbH, Cologne, Germany // ////////////////////////////////////////////////////////////////////////////// var db = require('@arangodb').db; var internal = require('internal'); var jsunity = require('jsunity'); function runSetup () { 'use strict'; internal.debugClearFailAt(); db._drop('UnitTestsRecovery'); var c = db._create('UnitTestsRecovery'); // try to re-create collection with the same name try { db._create('UnitTestsRecovery'); } catch (err) { } c.save({ _key: 'foo' }, true); internal.debugTerminate('crashing server'); } // ////////////////////////////////////////////////////////////////////////////// // / @brief test suite // ////////////////////////////////////////////////////////////////////////////// function recoverySuite () { 'use strict'; jsunity.jsUnity.attachAssertions(); return { setUp: function () {}, tearDown: function () {}, // ////////////////////////////////////////////////////////////////////////////// // / @brief test whether we can restore the trx data // ////////////////////////////////////////////////////////////////////////////// testCollectionDuplicate: function () { var c = db._collection('UnitTestsRecovery'); assertEqual(1, c.count()); } }; } // ////////////////////////////////////////////////////////////////////////////// // / @brief executes the test suite // ////////////////////////////////////////////////////////////////////////////// function main (argv) { 'use strict'; if (argv[1] === 'setup') { runSetup(); return 0; } else { jsunity.run(recoverySuite); return jsunity.writeDone().status ? 0 : 1; } }
wiltonlazary/arangodb
tests/js/server/recovery/collection-duplicate.js
JavaScript
apache-2.0
2,684
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.store.avro; import io.netty.buffer.DrillBuf; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.security.PrivilegedExceptionAction; import org.apache.avro.Schema; import org.apache.avro.Schema.Type; import org.apache.avro.file.DataFileReader; import org.apache.avro.generic.GenericArray; import org.apache.avro.generic.GenericContainer; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.mapred.FsInput; import org.apache.avro.util.Utf8; import org.apache.drill.common.exceptions.DrillRuntimeException; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.common.expression.PathSegment; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.exec.expr.holders.BigIntHolder; import org.apache.drill.exec.expr.holders.BitHolder; import org.apache.drill.exec.expr.holders.Float4Holder; import org.apache.drill.exec.expr.holders.Float8Holder; import org.apache.drill.exec.expr.holders.IntHolder; import org.apache.drill.exec.expr.holders.VarBinaryHolder; import org.apache.drill.exec.expr.holders.VarCharHolder; import org.apache.drill.exec.ops.FragmentContext; import org.apache.drill.exec.ops.OperatorContext; import org.apache.drill.exec.physical.impl.OutputMutator; import org.apache.drill.exec.store.AbstractRecordReader; import org.apache.drill.exec.store.RecordReader; import org.apache.drill.exec.util.ImpersonationUtil; import org.apache.drill.exec.vector.complex.impl.VectorContainerWriter; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import com.google.common.base.Charsets; import com.google.common.base.Stopwatch; import org.apache.hadoop.security.UserGroupInformation; /** * A RecordReader implementation for Avro data files. * * @see RecordReader */ public class AvroRecordReader extends AbstractRecordReader { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AvroRecordReader.class); private final Path hadoop; private final long start; private final long end; private DrillBuf buffer; private VectorContainerWriter writer; private DataFileReader<GenericContainer> reader = null; private OperatorContext operatorContext; private FileSystem fs; private final String opUserName; private final String queryUserName; private static final int DEFAULT_BATCH_SIZE = 1000; public AvroRecordReader(final FragmentContext fragmentContext, final String inputPath, final long start, final long length, final FileSystem fileSystem, final List<SchemaPath> projectedColumns, final String userName) { this(fragmentContext, inputPath, start, length, fileSystem, projectedColumns, userName, DEFAULT_BATCH_SIZE); } public AvroRecordReader(final FragmentContext fragmentContext, final String inputPath, final long start, final long length, final FileSystem fileSystem, List<SchemaPath> projectedColumns, final String userName, final int defaultBatchSize) { hadoop = new Path(inputPath); this.start = start; this.end = start + length; buffer = fragmentContext.getManagedBuffer(); this.fs = fileSystem; this.opUserName = userName; this.queryUserName = fragmentContext.getQueryUserName(); setColumns(projectedColumns); } private DataFileReader getReader(final Path hadoop, final FileSystem fs) throws ExecutionSetupException { try { final UserGroupInformation ugi = ImpersonationUtil.createProxyUgi(this.opUserName, this.queryUserName); return ugi.doAs(new PrivilegedExceptionAction<DataFileReader>() { @Override public DataFileReader run() throws Exception { return new DataFileReader<>(new FsInput(hadoop, fs.getConf()), new GenericDatumReader<GenericContainer>()); } }); } catch (IOException | InterruptedException e) { throw new ExecutionSetupException( String.format("Error in creating avro reader for file: %s", hadoop), e); } } @Override public void setup(final OperatorContext context, final OutputMutator output) throws ExecutionSetupException { operatorContext = context; writer = new VectorContainerWriter(output); try { reader = getReader(hadoop, fs); logger.debug("Processing file : {}, start position : {}, end position : {} ", hadoop, start, end); reader.sync(this.start); } catch (IOException e) { throw new ExecutionSetupException(e); } } @Override public int next() { final Stopwatch watch = new Stopwatch().start(); if (reader == null) { throw new IllegalStateException("Avro reader is not open."); } if (!reader.hasNext()) { return 0; } int recordCount = 0; writer.allocate(); writer.reset(); try { // XXX - Implement batch size for (GenericContainer container = null; reader.hasNext() && !reader.pastSync(end); recordCount++) { writer.setPosition(recordCount); container = reader.next(container); processRecord(container, container.getSchema()); } writer.setValueCount(recordCount); } catch (IOException e) { throw new DrillRuntimeException(e); } logger.debug("Read {} records in {} ms", recordCount, watch.elapsed(TimeUnit.MILLISECONDS)); return recordCount; } private void processRecord(final GenericContainer container, final Schema schema) { final Schema.Type type = schema.getType(); switch (type) { case RECORD: process(container, schema, null, new MapOrListWriter(writer.rootAsMap())); break; default: throw new DrillRuntimeException("Root object must be record type. Found: " + type); } } private void process(final Object value, final Schema schema, final String fieldName, MapOrListWriter writer) { if (value == null) { return; } final Schema.Type type = schema.getType(); switch (type) { case RECORD: // list field of MapOrListWriter will be non null when we want to store array of maps/records. MapOrListWriter _writer = writer; for (final Schema.Field field : schema.getFields()) { if (field.schema().getType() == Schema.Type.RECORD || (field.schema().getType() == Schema.Type.UNION && field.schema().getTypes().get(0).getType() == Schema.Type.NULL && field.schema().getTypes().get(1).getType() == Schema.Type.RECORD)) { _writer = writer.map(field.name()); } process(((GenericRecord) value).get(field.name()), field.schema(), field.name(), _writer); } break; case ARRAY: assert fieldName != null; final GenericArray array = (GenericArray) value; Schema elementSchema = array.getSchema().getElementType(); Type elementType = elementSchema.getType(); if (elementType == Schema.Type.RECORD || elementType == Schema.Type.MAP){ writer = writer.list(fieldName).listoftmap(fieldName); } else { writer = writer.list(fieldName); } writer.start(); for (final Object o : array) { process(o, elementSchema, fieldName, writer); } writer.end(); break; case UNION: // currently supporting only nullable union (optional fields) like ["null", "some-type"]. if (schema.getTypes().get(0).getType() != Schema.Type.NULL) { throw new UnsupportedOperationException("Avro union type must be of the format : [\"null\", \"some-type\"]"); } process(value, schema.getTypes().get(1), fieldName, writer); break; case MAP: @SuppressWarnings("unchecked") final HashMap<Object, Object> map = (HashMap<Object, Object>) value; Schema valueSchema = schema.getValueType(); writer = writer.map(fieldName); writer.start(); for (Entry<Object, Object> entry : map.entrySet()) { process(entry.getValue(), valueSchema, entry.getKey().toString(), writer); } writer.end(); break; case FIXED: throw new UnsupportedOperationException("Unimplemented type: " + type.toString()); case ENUM: // Enum symbols are strings case NULL: // Treat null type as a primitive default: assert fieldName != null; if (writer.isMapWriter()) { SchemaPath path; if (writer.map.getField().getPath().getRootSegment().getPath().equals("")) { path = new SchemaPath(new PathSegment.NameSegment(fieldName)); } else { path = writer.map.getField().getPath().getChild(fieldName); } if (!selected(path)) { break; } } processPrimitive(value, schema.getType(), fieldName, writer); break; } } private void processPrimitive(final Object value, final Schema.Type type, final String fieldName, final MapOrListWriter writer) { if (value == null) { return; } switch (type) { case STRING: byte[] binary = null; if (value instanceof Utf8) { binary = ((Utf8) value).getBytes(); } else { binary = value.toString().getBytes(Charsets.UTF_8); } final int length = binary.length; final VarCharHolder vh = new VarCharHolder(); ensure(length); buffer.setBytes(0, binary); vh.buffer = buffer; vh.start = 0; vh.end = length; writer.varChar(fieldName).write(vh); break; case INT: final IntHolder ih = new IntHolder(); ih.value = (Integer) value; writer.integer(fieldName).write(ih); break; case LONG: final BigIntHolder bh = new BigIntHolder(); bh.value = (Long) value; writer.bigInt(fieldName).write(bh); break; case FLOAT: final Float4Holder fh = new Float4Holder(); fh.value = (Float) value; writer.float4(fieldName).write(fh); break; case DOUBLE: final Float8Holder f8h = new Float8Holder(); f8h.value = (Double) value; writer.float8(fieldName).write(f8h); break; case BOOLEAN: final BitHolder bit = new BitHolder(); bit.value = (Boolean) value ? 1 : 0; writer.bit(fieldName).write(bit); break; case BYTES: // XXX - Not sure if this is correct. Nothing prints from sqlline for byte fields. final VarBinaryHolder vb = new VarBinaryHolder(); final ByteBuffer buf = (ByteBuffer) value; final byte[] bytes = buf.array(); ensure(bytes.length); buffer.setBytes(0, bytes); vb.buffer = buffer; vb.start = 0; vb.end = bytes.length; writer.binary(fieldName).write(vb); break; case NULL: // Nothing to do for null type break; case ENUM: final String symbol = value.toString(); final byte[] b; try { b = symbol.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new DrillRuntimeException("Unable to read enum value for field: " + fieldName, e); } final VarCharHolder vch = new VarCharHolder(); ensure(b.length); buffer.setBytes(0, b); vch.buffer = buffer; vch.start = 0; vch.end = b.length; writer.varChar(fieldName).write(vch); break; default: throw new DrillRuntimeException("Unhandled Avro type: " + type.toString()); } } private boolean selected(SchemaPath field) { if (isStarQuery()) { return true; } for (final SchemaPath sp : getColumns()) { if (sp.contains(field)) { return true; } } return false; } private void ensure(final int length) { buffer = buffer.reallocIfNeeded(length); } @Override public void close() { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.warn("Error closing Avro reader", e); } finally { reader = null; } } } }
mehant/drill
exec/java-exec/src/main/java/org/apache/drill/exec/store/avro/AvroRecordReader.java
Java
apache-2.0
13,522
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.guice; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Provides; import org.apache.druid.collections.BlockingPool; import org.apache.druid.collections.DummyBlockingPool; import org.apache.druid.collections.DummyNonBlockingPool; import org.apache.druid.collections.NonBlockingPool; import org.apache.druid.guice.annotations.Global; import org.apache.druid.guice.annotations.Merging; import org.apache.druid.java.util.common.concurrent.Execs; import org.apache.druid.java.util.common.concurrent.ExecutorServiceConfig; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.query.DruidProcessingConfig; import org.apache.druid.query.ExecutorServiceMonitor; import org.apache.druid.query.ForwardingQueryProcessingPool; import org.apache.druid.query.QueryProcessingPool; import org.apache.druid.server.metrics.MetricsModule; import java.nio.ByteBuffer; /** * This module is used to fulfill dependency injection of query processing and caching resources: buffer pools and * thread pools on Router Druid node type. Router needs to inject those resources, because it depends on * {@link org.apache.druid.query.QueryToolChest}s, and they couple query type aspects not related to processing and * caching, which Router uses, and related to processing and caching, which Router doesn't use, but they inject the * resources. */ public class RouterProcessingModule implements Module { private static final Logger log = new Logger(RouterProcessingModule.class); @Override public void configure(Binder binder) { binder.bind(ExecutorServiceConfig.class).to(DruidProcessingConfig.class); MetricsModule.register(binder, ExecutorServiceMonitor.class); } @Provides @ManageLifecycle public QueryProcessingPool getProcessingExecutorPool(DruidProcessingConfig config) { if (config.getNumThreadsConfigured() != ExecutorServiceConfig.DEFAULT_NUM_THREADS) { log.error("numThreads[%d] configured, that is ignored on Router", config.getNumThreadsConfigured()); } return new ForwardingQueryProcessingPool(Execs.dummy()); } @Provides @LazySingleton @Global public NonBlockingPool<ByteBuffer> getIntermediateResultsPool() { return DummyNonBlockingPool.instance(); } @Provides @LazySingleton @Merging public BlockingPool<ByteBuffer> getMergeBufferPool(DruidProcessingConfig config) { if (config.getNumMergeBuffersConfigured() != DruidProcessingConfig.DEFAULT_NUM_MERGE_BUFFERS) { log.error( "numMergeBuffers[%d] configured, that is ignored on Router", config.getNumMergeBuffersConfigured() ); } return DummyBlockingPool.instance(); } }
nishantmonu51/druid
server/src/main/java/org/apache/druid/guice/RouterProcessingModule.java
Java
apache-2.0
3,537
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.oozie.ambari.view.assets; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import org.apache.ambari.view.ViewContext; import org.apache.oozie.ambari.view.*; import org.apache.oozie.ambari.view.assets.model.ActionAsset; import org.apache.oozie.ambari.view.assets.model.ActionAssetDefinition; import org.apache.oozie.ambari.view.assets.model.AssetDefintion; import org.apache.oozie.ambari.view.exception.ErrorCode; import org.apache.oozie.ambari.view.exception.WfmException; import org.apache.oozie.ambari.view.exception.WfmWebException; import org.apache.oozie.ambari.view.model.APIResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.*; import java.io.IOException; import java.util.*; import static org.apache.oozie.ambari.view.Constants.*; public class AssetResource { private final static Logger LOGGER = LoggerFactory .getLogger(AssetResource.class); private final AssetService assetService; private final ViewContext viewContext; private final HDFSFileUtils hdfsFileUtils; private final OozieUtils oozieUtils = new OozieUtils(); private final OozieDelegate oozieDelegate; public AssetResource(ViewContext viewContext) { this.viewContext = viewContext; this.assetService = new AssetService(viewContext); hdfsFileUtils = new HDFSFileUtils(viewContext); oozieDelegate = new OozieDelegate(viewContext); } @GET public Response getAssets() { try { Collection<ActionAsset> assets = assetService.getAssets(); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.getPaging().setTotal(assets != null ? assets.size() : 0L); result.setData(assets); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @GET @Path("/mine") public Response getMyAssets() { try { Collection<ActionAsset> assets = assetService.getMyAssets(); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.getPaging().setTotal(assets != null ? assets.size() : 0L); result.setData(assets); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @POST public Response saveAsset(@Context HttpHeaders headers, @QueryParam("id") String id, @Context UriInfo ui, String body) { try { Gson gson = new Gson(); AssetDefintion assetDefinition = gson.fromJson(body, AssetDefintion.class); Map<String, String> validateAsset = validateAsset(headers, assetDefinition.getDefinition(), ui.getQueryParameters()); if (!STATUS_OK.equals(validateAsset.get(STATUS_KEY))) { throw new WfmWebException(ErrorCode.ASSET_INVALID_FROM_OOZIE); } assetService.saveAsset(id, viewContext.getUsername(), assetDefinition); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); return Response.ok(result).build(); } catch (WfmWebException ex) { LOGGER.error(ex.getMessage(),ex); throw ex; } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } private List<String> getAsList(String string) { ArrayList<String> li = new ArrayList<>(1); li.add(string); return li; } public Map<String, String> validateAsset(HttpHeaders headers, String postBody, MultivaluedMap<String, String> queryParams) { String workflowXml = oozieUtils.generateWorkflowXml(postBody); Map<String, String> result = new HashMap<>(); String tempWfPath = "/tmp" + "/tmpooziewfs/tempwf_" + Math.round(Math.random() * 100000) + ".xml"; try { hdfsFileUtils.writeToFile(tempWfPath, workflowXml, true); } catch (IOException ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex, ErrorCode.FILE_ACCESS_UNKNOWN_ERROR); } queryParams.put("oozieparam.action", getAsList("dryrun")); queryParams.put("oozieconfig.rerunOnFailure", getAsList("false")); queryParams.put("oozieconfig.useSystemLibPath", getAsList("true")); queryParams.put("resourceManager", getAsList("useDefault")); String dryRunResp = oozieDelegate.submitWorkflowJobToOozie(headers, tempWfPath, queryParams, JobType.WORKFLOW); LOGGER.info(String.format("resp from validating asset=[%s]", dryRunResp)); try { hdfsFileUtils.deleteFile(tempWfPath); } catch (IOException ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex, ErrorCode.FILE_ACCESS_UNKNOWN_ERROR); } if (dryRunResp != null && dryRunResp.trim().startsWith("{")) { JsonElement jsonElement = new JsonParser().parse(dryRunResp); JsonElement idElem = jsonElement.getAsJsonObject().get("id"); if (idElem != null) { result.put(STATUS_KEY, STATUS_OK); } else { result.put(STATUS_KEY, STATUS_FAILED); result.put(MESSAGE_KEY, dryRunResp); } } else { result.put(STATUS_KEY, STATUS_FAILED); result.put(MESSAGE_KEY, dryRunResp); } return result; } @GET @Path("/assetNameAvailable") public Response assetNameAvailable(@QueryParam("name") String name){ try { boolean available = assetService.isAssetNameAvailable(name); return Response.ok(available).build(); }catch (Exception ex){ LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @GET @Path("/{id}") public Response getAssetDetail(@PathParam("id") String id) { try { AssetDefintion assetDefinition = assetService.getAssetDetail(id); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.setData(assetDefinition); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @GET @Path("/definition/id}") public Response getAssetDefinition(@PathParam("defnitionId") String id) { try { ActionAssetDefinition assetDefinition = assetService.getAssetDefinition(id); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.setData(assetDefinition); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @DELETE @Path("/{id}") public Response delete(@PathParam("id") String id) { try { ActionAsset asset = assetService.getAsset(id); if (asset == null) { throw new WfmWebException(ErrorCode.ASSET_NOT_EXIST); } if (!viewContext.getUsername().equals(asset.getOwner())){ throw new WfmWebException(ErrorCode.PERMISSION_ERROR); } assetService.deleteAsset(id); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); return Response.ok(result).build(); } catch (WfmWebException ex) { LOGGER.error(ex.getMessage(),ex); throw ex; } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } }
arenadata/ambari
contrib/views/wfmanager/src/main/java/org/apache/oozie/ambari/view/assets/AssetResource.java
Java
apache-2.0
8,219
/** * @copyright * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * @endcopyright * * @file org_apache_subversion_javahl_types_Version.cpp * @brief Implementation of the native methods in the Java class Version. */ #include "../include/org_apache_subversion_javahl_types_Version.h" #include "JNIStackElement.h" #include "svn_version.h" JNIEXPORT jint JNICALL Java_org_apache_subversion_javahl_types_Version_getMajor(JNIEnv *env, jobject jthis) { JNIEntry(Version, getMajor); return SVN_VER_MAJOR; } JNIEXPORT jint JNICALL Java_org_apache_subversion_javahl_types_Version_getMinor(JNIEnv *env, jobject jthis) { JNIEntry(Version, getMinor); return SVN_VER_MINOR; } JNIEXPORT jint JNICALL Java_org_apache_subversion_javahl_types_Version_getPatch(JNIEnv *env, jobject jthis) { JNIEntry(Version, getPatch); return SVN_VER_PATCH; } JNIEXPORT jstring JNICALL Java_org_apache_subversion_javahl_types_Version_getTag(JNIEnv *env, jobject jthis) { JNIEntry(Version, getTag); jstring tag = JNIUtil::makeJString(SVN_VER_TAG); if (JNIUtil::isJavaExceptionThrown()) return NULL; return tag; } JNIEXPORT jstring JNICALL Java_org_apache_subversion_javahl_types_Version_getNumberTag(JNIEnv *env, jobject jthis) { JNIEntry(Version, getNumberTag); jstring numtag = JNIUtil::makeJString(SVN_VER_NUMTAG); if (JNIUtil::isJavaExceptionThrown()) return NULL; return numtag; }
centic9/subversion-ppa
subversion/bindings/javahl/native/org_apache_subversion_javahl_types_Version.cpp
C++
apache-2.0
2,343
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.smtpserver.netty; import org.apache.james.lifecycle.api.LifecycleUtil; import org.apache.james.protocols.api.Encryption; import org.apache.james.protocols.api.Protocol; import org.apache.james.protocols.api.ProtocolSession.State; import org.apache.james.protocols.netty.BasicChannelUpstreamHandler; import org.apache.james.protocols.smtp.SMTPSession; import org.apache.james.smtpserver.SMTPConstants; import org.jboss.netty.channel.ChannelHandler.Sharable; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.slf4j.Logger; /** * {@link ChannelUpstreamHandler} which is used by the SMTPServer */ @Sharable public class SMTPChannelUpstreamHandler extends BasicChannelUpstreamHandler { public SMTPChannelUpstreamHandler(Protocol protocol, Logger logger, Encryption encryption) { super(protocol, encryption); } public SMTPChannelUpstreamHandler(Protocol protocol, Logger logger) { super(protocol); } /** * Cleanup temporary files * * @param ctx */ protected void cleanup(ChannelHandlerContext ctx) { // Make sure we dispose everything on exit on session close SMTPSession smtpSession = (SMTPSession) ctx.getAttachment(); if (smtpSession != null) { LifecycleUtil.dispose(smtpSession.getAttachment(SMTPConstants.MAIL, State.Transaction)); LifecycleUtil.dispose(smtpSession.getAttachment(SMTPConstants.DATA_MIMEMESSAGE_STREAMSOURCE, State.Transaction)); } super.cleanup(ctx); } }
chibenwa/james
protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/netty/SMTPChannelUpstreamHandler.java
Java
apache-2.0
2,858
<?php /** * The foo test class * * @author mepeisen */ class FooTest extends PHPUnit_Framework_TestCase { /** * tests the bar function */ public function testFoo() { include "folderA/MyClassA.php"; $o = new folderA\MyMavenTestClassA(); $this->assertEquals("foo", $o->getFoo()); include "folderB/MyClassB.php"; $o = new folderB\MyMavenTestClassB(); $this->assertEquals("foo", $o->getFoo()); } }
Vaysman/maven-php-plugin
maven-plugins/it/src/test/resources/org/phpmaven/test/projects/mojos-phar/phar-with-dep1-folders/src/test/php/FooTest.php
PHP
apache-2.0
423
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.credential.store.store.impl.db; import org.apache.airavata.common.utils.DBUtil; import org.apache.airavata.credential.store.credential.CommunityUser; import org.apache.airavata.credential.store.store.CredentialStoreException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Data access class for community_user table. */ public class CommunityUserDAO extends ParentDAO { public CommunityUserDAO() { super(); } public void addCommunityUser(CommunityUser user, String token, Connection connection) throws CredentialStoreException { String sql = "INSERT INTO COMMUNITY_USER VALUES (?, ?, ?, ?)"; PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, user.getGatewayName()); preparedStatement.setString(2, user.getUserName()); preparedStatement.setString(3, token); preparedStatement.setString(4, user.getUserEmail()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error persisting community user."); stringBuilder.append("gateway - ").append(user.getGatewayName()); stringBuilder.append("community user name - ").append(user.getUserName()); stringBuilder.append("community user email - ").append(user.getUserEmail()); stringBuilder.append("token id - ").append(token); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { DBUtil.cleanup(preparedStatement); } } public void deleteCommunityUser(CommunityUser user, Connection connection) throws CredentialStoreException { String sql = "DELETE FROM COMMUNITY_USER WHERE GATEWAY_ID=? AND COMMUNITY_USER_NAME=?"; PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, user.getGatewayName()); preparedStatement.setString(2, user.getUserName()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error deleting community user."); stringBuilder.append("gateway - ").append(user.getGatewayName()); stringBuilder.append("community user name - ").append(user.getUserName()); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { DBUtil.cleanup(preparedStatement); } } public void deleteCommunityUserByToken(CommunityUser user, String token, Connection connection) throws CredentialStoreException { String sql = "DELETE FROM COMMUNITY_USER WHERE GATEWAY_ID=? AND COMMUNITY_USER_NAME=? AND TOKEN_ID=?"; PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, user.getGatewayName()); preparedStatement.setString(2, user.getUserName()); preparedStatement.setString(3, token); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error deleting community user."); stringBuilder.append("gateway - ").append(user.getGatewayName()); stringBuilder.append("community user name - ").append(user.getUserName()); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { DBUtil.cleanup(preparedStatement); } } public void updateCommunityUser(CommunityUser user) throws CredentialStoreException { // TODO } public CommunityUser getCommunityUser(String gatewayName, String communityUserName, Connection connection) throws CredentialStoreException { String sql = "SELECT * FROM COMMUNITY_USER WHERE GATEWAY_ID=? AND COMMUNITY_USER_NAME=?"; PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, communityUserName); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String email = resultSet.getString("COMMUNITY_USER_EMAIL"); // TODO fix typo return new CommunityUser(gatewayName, communityUserName, email); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving community user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("community user name - ").append(communityUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { DBUtil.cleanup(preparedStatement); } return null; } public CommunityUser getCommunityUserByToken(String gatewayName, String tokenId, Connection connection) throws CredentialStoreException { String sql = "SELECT * FROM COMMUNITY_USER WHERE GATEWAY_ID=? AND TOKEN_ID=?"; PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, tokenId); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String communityUserName = resultSet.getString("COMMUNITY_USER_NAME"); String email = resultSet.getString("COMMUNITY_USER_EMAIL"); // TODO fix typo return new CommunityUser(gatewayName, communityUserName, email); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving community user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("token- ").append(tokenId); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { DBUtil.cleanup(preparedStatement); } return null; } public List<CommunityUser> getCommunityUsers(String gatewayName, Connection connection) throws CredentialStoreException { List<CommunityUser> userList = new ArrayList<CommunityUser>(); String sql = "SELECT * FROM COMMUNITY_USER WHERE GATEWAY_ID=?"; PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String userName = resultSet.getString("COMMUNITY_USER_NAME"); String email = resultSet.getString("COMMUNITY_USER_EMAIL"); // TODO fix typo userList.add(new CommunityUser(gatewayName, userName, email)); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving community users for "); stringBuilder.append("gateway - ").append(gatewayName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { DBUtil.cleanup(preparedStatement); } return userList; } }
hasinitg/airavata
modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java
Java
apache-2.0
9,093
'use strict'; (function (scope) { /** * Shape erased * * @class ShapeErased * @extends ShapeCandidate * @param {Object} [obj] * @constructor */ function ShapeErased(obj) { scope.ShapeCandidate.call(this, obj); } /** * Inheritance property */ ShapeErased.prototype = new scope.ShapeCandidate(); /** * Constructor property */ ShapeErased.prototype.constructor = ShapeErased; // Export scope.ShapeErased = ShapeErased; })(MyScript);
countshadow/MyScriptJS
src/output/shape/shapeErased.js
JavaScript
apache-2.0
532
/* * Copyright (c) 2009 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package nu.validator.htmlparser.annotation; public @interface Inline { }
googlearchive/caja
third_party/java/htmlparser/src/nu/validator/htmlparser/annotation/Inline.java
Java
apache-2.0
1,211
// ------------------------------------------------------------------------- // @FileName : NFCGameServerScriptModule.cpp // @Author : LvSheng.Huang // @Date : 2013-01-02 // @Module : NFCGameServerScriptModule // @Desc : // ------------------------------------------------------------------------- //#include "stdafx.h" #include "NFCGameServerScriptModule.h" #include "NFGameServerScriptPlugin.h" bool NFCGameServerScriptModule::Init() { m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule")); m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule")); assert(NULL != m_pEventProcessModule); assert(NULL != m_pKernelModule); assert(NULL != m_pLogicClassModule); return true; } bool NFCGameServerScriptModule::AfterInit() { return true; } bool NFCGameServerScriptModule::Shut() { return true; } bool NFCGameServerScriptModule::Execute(const float fLasFrametime, const float fStartedTime) { return true; }
MRunFoss/NoahGameFrame
NFServer/NFGameServerScriptPlugin/NFCGameServerScriptModule.cpp
C++
apache-2.0
1,286
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.lang.regexp; import com.intellij.psi.PsiElement; import org.intellij.lang.regexp.psi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.EnumSet; /** * @author yole */ public interface RegExpLanguageHost { EnumSet<RegExpGroup.Type> EMPTY_NAMED_GROUP_TYPES = EnumSet.noneOf(RegExpGroup.Type.class); boolean characterNeedsEscaping(char c); boolean supportsPerl5EmbeddedComments(); boolean supportsPossessiveQuantifiers(); boolean supportsPythonConditionalRefs(); boolean supportsNamedGroupSyntax(RegExpGroup group); boolean supportsNamedGroupRefSyntax(RegExpNamedGroupRef ref); @NotNull default EnumSet<RegExpGroup.Type> getSupportedNamedGroupTypes(RegExpElement context) { return EMPTY_NAMED_GROUP_TYPES; } boolean supportsExtendedHexCharacter(RegExpChar regExpChar); default boolean isValidGroupName(String name, @NotNull RegExpGroup group) { for (int i = 0, length = name.length(); i < length; i++) { final char c = name.charAt(i); if (!AsciiUtil.isLetterOrDigit(c) && c != '_') { return false; } } return true; } default boolean supportsSimpleClass(RegExpSimpleClass simpleClass) { return true; } default boolean supportsNamedCharacters(RegExpNamedCharacter namedCharacter) { return false; } default boolean isValidNamedCharacter(RegExpNamedCharacter namedCharacter) { return supportsNamedCharacters(namedCharacter); } default boolean supportsBoundary(RegExpBoundary boundary) { switch (boundary.getType()) { case UNICODE_EXTENDED_GRAPHEME: return false; case LINE_START: case LINE_END: case WORD: case NON_WORD: case BEGIN: case END: case END_NO_LINE_TERM: case PREVIOUS_MATCH: default: return true; } } default boolean supportsLiteralBackspace(RegExpChar aChar) { return true; } default boolean supportsInlineOptionFlag(char flag, PsiElement context) { return true; } boolean isValidCategory(@NotNull String category); @NotNull String[][] getAllKnownProperties(); @Nullable String getPropertyDescription(@Nullable final String name); @NotNull String[][] getKnownCharacterClasses(); /** * @param number the number element to extract the value from * @return the value, or null when the value is out of range */ @Nullable default Number getQuantifierValue(@NotNull RegExpNumber number) { return Double.parseDouble(number.getText()); } default Lookbehind supportsLookbehind(@NotNull RegExpGroup lookbehindGroup) { return Lookbehind.FULL; // to not break existing implementations, although rarely actually supported. } enum Lookbehind { /** Lookbehind not supported. */ NOT_SUPPORTED, /** * Alternation inside lookbehind (a|b|c) branches must have same length, * finite repetition with identical min, max values (a{3} or a{3,3}) allowed. */ FIXED_LENGTH_ALTERNATION, /** Alternation (a|bc|def) branches inside look behind may have different length */ VARIABLE_LENGTH_ALTERNATION, /** Finite repetition inside lookbehind with different minimum, maximum values allowed */ FINITE_REPETITION, /** Full regex syntax inside lookbehind, i.e. star (*) and plus (*) repetition and backreferences, allowed. */ FULL } }
goodwinnk/intellij-community
RegExpSupport/src/org/intellij/lang/regexp/RegExpLanguageHost.java
Java
apache-2.0
4,005
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueResourceQuotas; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; import org.apache.hadoop.yarn.server.resourcemanager.scheduler .SchedulerDynamicEditException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.queuemanagement.GuaranteedOrZeroCapacityOverTimePolicy; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica .FiCaSchedulerApp; import org.apache.hadoop.yarn.util.resource.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * Auto Creation enabled Parent queue. This queue initially does not have any * children to start with and all child * leaf queues will be auto created. Currently this does not allow other * pre-configured leaf or parent queues to * co-exist along with auto-created leaf queues. The auto creation is limited * to leaf queues currently. */ public class ManagedParentQueue extends AbstractManagedParentQueue { private boolean shouldFailAutoCreationWhenGuaranteedCapacityExceeded = false; private static final Logger LOG = LoggerFactory.getLogger( ManagedParentQueue.class); public ManagedParentQueue(final CapacitySchedulerQueueContext queueContext, final String queueName, final CSQueue parent, final CSQueue old) throws IOException { super(queueContext, queueName, parent, old); shouldFailAutoCreationWhenGuaranteedCapacityExceeded = queueContext.getConfiguration() .getShouldFailAutoQueueCreationWhenGuaranteedCapacityExceeded( getQueuePath()); leafQueueTemplate = initializeLeafQueueConfigs().build(); initializeQueueManagementPolicy(); } @Override public void reinitialize(CSQueue newlyParsedQueue, Resource clusterResource) throws IOException { writeLock.lock(); try { validate(newlyParsedQueue); shouldFailAutoCreationWhenGuaranteedCapacityExceeded = queueContext.getConfiguration() .getShouldFailAutoQueueCreationWhenGuaranteedCapacityExceeded( getQueuePath()); //validate if capacity is exceeded for child queues if (shouldFailAutoCreationWhenGuaranteedCapacityExceeded) { float childCap = sumOfChildCapacities(); if (getCapacity() < childCap) { throw new IOException( "Total of Auto Created leaf queues guaranteed capacity : " + childCap + " exceeds Parent queue's " + getQueuePath() + " guaranteed capacity " + getCapacity() + "" + ".Cannot enforce policy to auto" + " create queues beyond parent queue's capacity"); } } leafQueueTemplate = initializeLeafQueueConfigs().build(); super.reinitialize(newlyParsedQueue, clusterResource); // run reinitialize on each existing queue, to trigger absolute cap // recomputations for (CSQueue res : this.getChildQueues()) { res.reinitialize(res, clusterResource); } //clear state in policy reinitializeQueueManagementPolicy(); //reassign capacities according to policy final List<QueueManagementChange> queueManagementChanges = queueManagementPolicy.computeQueueManagementChanges(); validateAndApplyQueueManagementChanges(queueManagementChanges); LOG.info( "Reinitialized Managed Parent Queue: [{}] with capacity [{}]" + " with max capacity [{}]", getQueueName(), super.getCapacity(), super.getMaximumCapacity()); } catch (YarnException ye) { LOG.error("Exception while computing policy changes for leaf queue : " + getQueuePath(), ye); throw new IOException(ye); } finally { writeLock.unlock(); } } private void initializeQueueManagementPolicy() throws IOException { queueManagementPolicy = queueContext.getConfiguration().getAutoCreatedQueueManagementPolicyClass( getQueuePath()); queueManagementPolicy.init(this); } private void reinitializeQueueManagementPolicy() throws IOException { AutoCreatedQueueManagementPolicy managementPolicy = queueContext.getConfiguration().getAutoCreatedQueueManagementPolicyClass( getQueuePath()); if (!(managementPolicy.getClass().equals( this.queueManagementPolicy.getClass()))) { queueManagementPolicy = managementPolicy; queueManagementPolicy.init(this); } else{ queueManagementPolicy.reinitialize(this); } } protected AutoCreatedLeafQueueConfig.Builder initializeLeafQueueConfigs() throws IOException { AutoCreatedLeafQueueConfig.Builder builder = new AutoCreatedLeafQueueConfig.Builder(); CapacitySchedulerConfiguration configuration = queueContext.getConfiguration(); // TODO load configs into CapacitySchedulerConfiguration instead of duplicating them String leafQueueTemplateConfPrefix = getLeafQueueConfigPrefix( configuration); //Load template configuration into CapacitySchedulerConfiguration CapacitySchedulerConfiguration autoCreatedTemplateConfig = super.initializeLeafQueueConfigs(leafQueueTemplateConfPrefix); builder.configuration(autoCreatedTemplateConfig); QueueResourceQuotas queueResourceQuotas = new QueueResourceQuotas(); setAbsoluteResourceTemplates(configuration, queueResourceQuotas); QueuePath templateQueuePath = configuration .getAutoCreatedQueueObjectTemplateConfPrefix(getQueuePath()); Set<String> templateConfiguredNodeLabels = queueContext .getQueueManager().getConfiguredNodeLabelsForAllQueues() .getLabelsByQueue(templateQueuePath.getFullPath()); //Load template capacities QueueCapacities queueCapacities = new QueueCapacities(false); CSQueueUtils.loadCapacitiesByLabelsFromConf(templateQueuePath, queueCapacities, configuration, templateConfiguredNodeLabels); /** * Populate leaf queue template (of Parent resources configured in * ABSOLUTE_RESOURCE) capacities with actual values for which configured has * been defined in ABSOLUTE_RESOURCE format. * */ if (this.capacityConfigType.equals(CapacityConfigType.ABSOLUTE_RESOURCE)) { updateQueueCapacities(queueCapacities); } builder.capacities(queueCapacities); builder.resourceQuotas(queueResourceQuotas); return builder; } private void setAbsoluteResourceTemplates(CapacitySchedulerConfiguration configuration, QueueResourceQuotas queueResourceQuotas) throws IOException { QueuePath templateQueuePath = configuration .getAutoCreatedQueueObjectTemplateConfPrefix(getQueuePath()); Set<String> templateConfiguredNodeLabels = queueContext .getQueueManager().getConfiguredNodeLabelsForAllQueues() .getLabelsByQueue(templateQueuePath.getFullPath()); for (String nodeLabel : templateConfiguredNodeLabels) { Resource templateMinResource = configuration.getMinimumResourceRequirement( nodeLabel, templateQueuePath.getFullPath(), resourceTypes); queueResourceQuotas.setConfiguredMinResource(nodeLabel, templateMinResource); if (this.capacityConfigType.equals(CapacityConfigType.PERCENTAGE) && !templateMinResource.equals(Resources.none())) { throw new IOException("Managed Parent Queue " + this.getQueuePath() + " config type is different from leaf queue template config type"); } } } private void updateQueueCapacities(QueueCapacities queueCapacities) { CapacitySchedulerConfiguration configuration = queueContext.getConfiguration(); for (String label : queueCapacities.getExistingNodeLabels()) { queueCapacities.setCapacity(label, resourceCalculator.divide( queueContext.getClusterResource(), configuration.getMinimumResourceRequirement( label, configuration .getAutoCreatedQueueTemplateConfPrefix(getQueuePath()), resourceTypes), getQueueResourceQuotas().getConfiguredMinResource(label))); Resource childMaxResource = configuration .getMaximumResourceRequirement(label, configuration .getAutoCreatedQueueTemplateConfPrefix(getQueuePath()), resourceTypes); Resource parentMaxRes = getQueueResourceQuotas() .getConfiguredMaxResource(label); Resource effMaxResource = Resources.min( resourceCalculator, queueContext.getClusterResource(), childMaxResource.equals(Resources.none()) ? parentMaxRes : childMaxResource, parentMaxRes); queueCapacities.setMaximumCapacity( label, resourceCalculator.divide( queueContext.getClusterResource(), effMaxResource, getQueueResourceQuotas().getConfiguredMaxResource(label))); queueCapacities.setAbsoluteCapacity( label, queueCapacities.getCapacity(label) * getQueueCapacities().getAbsoluteCapacity(label)); queueCapacities.setAbsoluteMaximumCapacity(label, queueCapacities.getMaximumCapacity(label) * getQueueCapacities().getAbsoluteMaximumCapacity(label)); } } protected void validate(final CSQueue newlyParsedQueue) throws IOException { // Sanity check if (!(newlyParsedQueue instanceof ManagedParentQueue) || !newlyParsedQueue .getQueuePath().equals(getQueuePath())) { throw new IOException( "Trying to reinitialize " + getQueuePath() + " from " + newlyParsedQueue.getQueuePath()); } } @Override public void addChildQueue(CSQueue childQueue) throws SchedulerDynamicEditException, IOException { writeLock.lock(); try { if (childQueue == null || !(childQueue instanceof AutoCreatedLeafQueue)) { throw new SchedulerDynamicEditException( "Expected child queue to be an instance of AutoCreatedLeafQueue"); } CapacitySchedulerConfiguration conf = queueContext.getConfiguration(); ManagedParentQueue parentQueue = (ManagedParentQueue) childQueue.getParent(); if (parentQueue == null) { throw new SchedulerDynamicEditException( "Parent Queue is null, should not add child queue!"); } String leafQueuePath = childQueue.getQueuePath(); int maxQueues = conf.getAutoCreatedQueuesMaxChildQueuesLimit( parentQueue.getQueuePath()); if (parentQueue.getChildQueues().size() >= maxQueues) { throw new SchedulerDynamicEditException( "Cannot auto create leaf queue " + leafQueuePath + ".Max Child " + "Queue limit exceeded which is configured as : " + maxQueues + " and number of child queues is : " + parentQueue .getChildQueues().size()); } if (shouldFailAutoCreationWhenGuaranteedCapacityExceeded) { if (getLeafQueueTemplate().getQueueCapacities().getAbsoluteCapacity() + parentQueue.sumOfChildAbsCapacities() > parentQueue .getAbsoluteCapacity()) { throw new SchedulerDynamicEditException( "Cannot auto create leaf queue " + leafQueuePath + ". Child " + "queues capacities have reached parent queue : " + parentQueue.getQueuePath() + "'s guaranteed capacity"); } } ((GuaranteedOrZeroCapacityOverTimePolicy) queueManagementPolicy) .updateTemplateAbsoluteCapacities(parentQueue.getQueueCapacities()); AutoCreatedLeafQueue leafQueue = (AutoCreatedLeafQueue) childQueue; super.addChildQueue(leafQueue); /* Below is to avoid Setting Queue Capacity to NaN when ClusterResource is zero during RM Startup with DominantResourceCalculator */ if (this.capacityConfigType.equals( CapacityConfigType.ABSOLUTE_RESOURCE)) { QueueCapacities queueCapacities = getLeafQueueTemplate().getQueueCapacities(); updateQueueCapacities(queueCapacities); } final AutoCreatedLeafQueueConfig initialLeafQueueTemplate = queueManagementPolicy.getInitialLeafQueueConfiguration(leafQueue); leafQueue.reinitializeFromTemplate(initialLeafQueueTemplate); // Do one update cluster resource call to make sure all absolute resources // effective resources are updated. updateClusterResource(queueContext.getClusterResource(), new ResourceLimits(queueContext.getClusterResource())); } finally { writeLock.unlock(); } } public List<FiCaSchedulerApp> getScheduleableApplications() { readLock.lock(); try { List<FiCaSchedulerApp> apps = new ArrayList<>(); for (CSQueue childQueue : getChildQueues()) { apps.addAll(((AbstractLeafQueue) childQueue).getApplications()); } return Collections.unmodifiableList(apps); } finally { readLock.unlock(); } } public List<FiCaSchedulerApp> getPendingApplications() { readLock.lock(); try { List<FiCaSchedulerApp> apps = new ArrayList<>(); for (CSQueue childQueue : getChildQueues()) { apps.addAll(((AbstractLeafQueue) childQueue).getPendingApplications()); } return Collections.unmodifiableList(apps); } finally { readLock.unlock(); } } public List<FiCaSchedulerApp> getAllApplications() { readLock.lock(); try { List<FiCaSchedulerApp> apps = new ArrayList<>(); for (CSQueue childQueue : getChildQueues()) { apps.addAll(((AbstractLeafQueue) childQueue).getAllApplications()); } return Collections.unmodifiableList(apps); } finally { readLock.unlock(); } } public String getLeafQueueConfigPrefix(CapacitySchedulerConfiguration conf) { return CapacitySchedulerConfiguration.PREFIX + conf .getAutoCreatedQueueTemplateConfPrefix(getQueuePath()); } public boolean shouldFailAutoCreationWhenGuaranteedCapacityExceeded() { return shouldFailAutoCreationWhenGuaranteedCapacityExceeded; } /** * Asynchronously called from scheduler to apply queue management changes * * @param queueManagementChanges */ public void validateAndApplyQueueManagementChanges( List<QueueManagementChange> queueManagementChanges) throws IOException, SchedulerDynamicEditException { writeLock.lock(); try { validateQueueManagementChanges(queueManagementChanges); applyQueueManagementChanges(queueManagementChanges); AutoCreatedQueueManagementPolicy policy = getAutoCreatedQueueManagementPolicy(); //acquires write lock on policy policy.commitQueueManagementChanges(queueManagementChanges); } finally { writeLock.unlock(); } } public void validateQueueManagementChanges( List<QueueManagementChange> queueManagementChanges) throws SchedulerDynamicEditException { for (QueueManagementChange queueManagementChange : queueManagementChanges) { CSQueue childQueue = queueManagementChange.getQueue(); if (!(childQueue instanceof AutoCreatedLeafQueue)) { throw new SchedulerDynamicEditException( "queue should be " + "AutoCreatedLeafQueue. Found " + childQueue .getClass()); } if (!(AbstractManagedParentQueue.class. isAssignableFrom(childQueue.getParent().getClass()))) { LOG.error("Queue " + getQueuePath() + " is not an instance of PlanQueue or ManagedParentQueue." + " " + "Ignoring update " + queueManagementChanges); throw new SchedulerDynamicEditException( "Queue " + getQueuePath() + " is not a AutoEnabledParentQueue." + " Ignoring update " + queueManagementChanges); } if (queueManagementChange.getQueueAction() == QueueManagementChange.QueueAction.UPDATE_QUEUE) { AutoCreatedLeafQueueConfig template = queueManagementChange.getUpdatedQueueTemplate(); ((AutoCreatedLeafQueue) childQueue).validateConfigurations(template); } } } private void applyQueueManagementChanges( List<QueueManagementChange> queueManagementChanges) throws SchedulerDynamicEditException, IOException { for (QueueManagementChange queueManagementChange : queueManagementChanges) { if (queueManagementChange.getQueueAction() == QueueManagementChange.QueueAction.UPDATE_QUEUE) { AutoCreatedLeafQueue childQueueToBeUpdated = (AutoCreatedLeafQueue) queueManagementChange.getQueue(); //acquires write lock on leaf queue childQueueToBeUpdated.reinitializeFromTemplate( queueManagementChange.getUpdatedQueueTemplate()); } } } public void setLeafQueueConfigs(String leafQueueName) { CapacitySchedulerConfiguration templateConfig = leafQueueTemplate.getLeafQueueConfigs(); for (Map.Entry<String, String> confKeyValuePair : templateConfig) { final String name = confKeyValuePair.getKey() .replaceFirst(CapacitySchedulerConfiguration.AUTO_CREATED_LEAF_QUEUE_TEMPLATE_PREFIX, leafQueueName); queueContext.setConfigurationEntry(name, confKeyValuePair.getValue()); } } }
JingchengDu/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ManagedParentQueue.java
Java
apache-2.0
18,592
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.jobexecutor; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import org.activiti.engine.ActivitiException; import org.activiti.engine.ActivitiIllegalArgumentException; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.el.NoExecutionVariableScope; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.TimerJobEntity; import org.flowable.common.engine.api.delegate.Expression; import org.flowable.common.engine.impl.calendar.BusinessCalendar; import org.flowable.engine.impl.jobexecutor.TimerDeclarationType; import org.flowable.variable.api.delegate.VariableScope; import org.joda.time.DateTime; /** * @author Tom Baeyens */ public class TimerDeclarationImpl implements Serializable { private static final long serialVersionUID = 1L; protected Expression description; protected TimerDeclarationType type; protected Expression endDateExpression; protected Expression calendarNameExpression; protected String jobHandlerType; protected String jobHandlerConfiguration; protected String repeat; protected boolean exclusive = TimerJobEntity.DEFAULT_EXCLUSIVE; protected int retries = TimerJobEntity.DEFAULT_RETRIES; protected boolean isInterruptingTimer; // For boundary timers public TimerDeclarationImpl(Expression expression, TimerDeclarationType type, String jobHandlerType, Expression endDateExpression, Expression calendarNameExpression) { this(expression, type, jobHandlerType); this.endDateExpression = endDateExpression; this.calendarNameExpression = calendarNameExpression; } public TimerDeclarationImpl(Expression expression, TimerDeclarationType type, String jobHandlerType) { this.jobHandlerType = jobHandlerType; this.description = expression; this.type = type; } public Expression getDescription() { return description; } public String getJobHandlerType() { return jobHandlerType; } public String getJobHandlerConfiguration() { return jobHandlerConfiguration; } public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public boolean isExclusive() { return exclusive; } public void setExclusive(boolean exclusive) { this.exclusive = exclusive; } public int getRetries() { return retries; } public void setRetries(int retries) { this.retries = retries; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } public boolean isInterruptingTimer() { return isInterruptingTimer; } public void setInterruptingTimer(boolean isInterruptingTimer) { this.isInterruptingTimer = isInterruptingTimer; } public TimerJobEntity prepareTimerEntity(ExecutionEntity executionEntity) { // ACT-1415: timer-declaration on start-event may contain expressions NOT // evaluating variables but other context, evaluating should happen nevertheless VariableScope scopeForExpression = executionEntity; if (scopeForExpression == null) { scopeForExpression = NoExecutionVariableScope.getSharedInstance(); } String calendarNameValue = type.calendarName; if (this.calendarNameExpression != null) { calendarNameValue = (String) this.calendarNameExpression.getValue(scopeForExpression); } BusinessCalendar businessCalendar = Context .getProcessEngineConfiguration() .getBusinessCalendarManager() .getBusinessCalendar(calendarNameValue); if (description == null) { // Prevent NPE from happening in the next line throw new ActivitiIllegalArgumentException("Timer '" + executionEntity.getActivityId() + "' was not configured with a valid duration/time"); } String endDateString = null; String dueDateString = null; Date duedate = null; Date endDate = null; if (endDateExpression != null && !(scopeForExpression instanceof NoExecutionVariableScope)) { Object endDateValue = endDateExpression.getValue(scopeForExpression); if (endDateValue instanceof String) { endDateString = (String) endDateValue; } else if (endDateValue instanceof Date) { endDate = (Date) endDateValue; } else if (endDateValue instanceof DateTime) { // Joda DateTime support duedate = ((DateTime) endDateValue).toDate(); } else { throw new ActivitiException("Timer '" + executionEntity.getActivityId() + "' was not configured with a valid duration/time, either hand in a java.util.Date or a String in format 'yyyy-MM-dd'T'hh:mm:ss'"); } if (endDate == null) { endDate = businessCalendar.resolveEndDate(endDateString); } } Object dueDateValue = description.getValue(scopeForExpression); if (dueDateValue instanceof String) { dueDateString = (String) dueDateValue; } else if (dueDateValue instanceof Date) { duedate = (Date) dueDateValue; } else if (dueDateValue instanceof DateTime) { // Joda DateTime support duedate = ((DateTime) dueDateValue).toDate(); } else if (dueDateValue != null) { // dueDateValue==null is OK - but unexpected class type must throw an error. throw new ActivitiException("Timer '" + executionEntity.getActivityId() + "' was not configured with a valid duration/time, either hand in a java.util.Date or a String in format 'yyyy-MM-dd'T'hh:mm:ss'"); } if (duedate == null && dueDateString != null) { duedate = businessCalendar.resolveDuedate(dueDateString); } TimerJobEntity timer = null; // if dueDateValue is null -> this is OK - timer will be null and job not scheduled if (duedate != null) { timer = new TimerJobEntity(this); timer.setDuedate(duedate); timer.setEndDate(endDate); if (executionEntity != null) { timer.setExecution(executionEntity); timer.setProcessDefinitionId(executionEntity.getProcessDefinitionId()); timer.setProcessInstanceId(executionEntity.getProcessInstanceId()); // Inherit tenant identifier (if applicable) if (executionEntity.getTenantId() != null) { timer.setTenantId(executionEntity.getTenantId()); } } if (type == TimerDeclarationType.CYCLE) { // See ACT-1427: A boundary timer with a cancelActivity='true', doesn't need to repeat itself boolean repeat = !isInterruptingTimer; // ACT-1951: intermediate catching timer events shouldn't repeat according to spec if (TimerCatchIntermediateEventJobHandler.TYPE.equals(jobHandlerType)) { repeat = false; if (endDate != null) { long endDateMiliss = endDate.getTime(); long dueDateMiliss = duedate.getTime(); long dueDate = Math.min(endDateMiliss, dueDateMiliss); timer.setDuedate(new Date(dueDate)); } } if (repeat) { String prepared = prepareRepeat(dueDateString); timer.setRepeat(prepared); } } } return timer; } private String prepareRepeat(String dueDate) { if (dueDate.startsWith("R") && dueDate.split("/").length == 2) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); return dueDate.replace("/", "/" + sdf.format(Context.getProcessEngineConfiguration().getClock().getCurrentTime()) + "/"); } return dueDate; } }
dbmalkovsky/flowable-engine
modules/flowable5-engine/src/main/java/org/activiti/engine/impl/jobexecutor/TimerDeclarationImpl.java
Java
apache-2.0
8,975
/* * Copyright (c) 2005-2011 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.customers.checklist.business; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.mifos.customers.checklist.exceptions.CheckListException; import org.mifos.customers.checklist.persistence.CheckListPersistence; import org.mifos.customers.checklist.util.helpers.CheckListConstants; import org.mifos.customers.checklist.util.helpers.CheckListType; import org.mifos.framework.business.AbstractBusinessObject; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.util.DateTimeService; public abstract class CheckListBO extends AbstractBusinessObject { private final Short checklistId; private String checklistName; private Short checklistStatus; private Set<CheckListDetailEntity> checklistDetails; private Short supportedLocales; protected CheckListBO() { this.checklistId = null; checklistDetails = new LinkedHashSet<CheckListDetailEntity>(); } protected CheckListBO(String checkListName, Short checkListStatus, List<String> details, Short localeId, Short userId) throws CheckListException { setCreateDetails(userId, new DateTimeService().getCurrentJavaDateTime()); this.checklistId = null; if (details.size() > 0) { setCheckListDetails(details, localeId); } else { throw new CheckListException(CheckListConstants.CHECKLIST_CREATION_EXCEPTION); } if (checkListName != null) { this.checklistName = checkListName; } else { throw new CheckListException(CheckListConstants.CHECKLIST_CREATION_EXCEPTION); } this.checklistStatus = checkListStatus; this.supportedLocales = localeId; } public Short getChecklistId() { return checklistId; } public String getChecklistName() { return this.checklistName; } @SuppressWarnings("unused") // see .hbm.xml file private void setChecklistName(String checklistName) { this.checklistName = checklistName; } public Short getChecklistStatus() { return this.checklistStatus; } @SuppressWarnings("unused") // see .hbm.xml file private void setChecklistStatus(Short checklistStatus) { this.checklistStatus = checklistStatus; } public Set<CheckListDetailEntity> getChecklistDetails() { return this.checklistDetails; } @SuppressWarnings("unused") // see .hbm.xml file private void setChecklistDetails(Set<CheckListDetailEntity> checklistDetailSet) { this.checklistDetails = checklistDetailSet; } public Short getSupportedLocales() { return this.supportedLocales; } @SuppressWarnings("unused") // see .hbm.xml file private void setSupportedLocales(Short supportedLocales) { this.supportedLocales = supportedLocales; } public void addChecklistDetail(CheckListDetailEntity checkListDetailEntity) { checklistDetails.add(checkListDetailEntity); } protected CheckListPersistence getCheckListPersistence() { return new CheckListPersistence(); } private void setCheckListDetails(List<String> details, Short locale) { checklistDetails = new HashSet<CheckListDetailEntity>(); for (String detail : details) { CheckListDetailEntity checkListDetailEntity = new CheckListDetailEntity(detail, Short.valueOf("1"), this, locale); checklistDetails.add(checkListDetailEntity); } } public abstract CheckListType getCheckListType(); protected void update(String checkListName, Short checkListStatus, List<String> details, Short localeId, Short userId) throws CheckListException { setUpdateDetails(userId); if (details == null || details.size() <= 0) { throw new CheckListException(CheckListConstants.CHECKLIST_CREATION_EXCEPTION); } if (StringUtils.isBlank(checkListName)) { throw new CheckListException(CheckListConstants.CHECKLIST_CREATION_EXCEPTION); } this.checklistName = checkListName; getChecklistDetails().clear(); for (String detail : details) { CheckListDetailEntity checkListDetailEntity = new CheckListDetailEntity(detail, Short.valueOf("1"), this,localeId); getChecklistDetails().add(checkListDetailEntity); } this.checklistStatus = checkListStatus; this.supportedLocales = localeId; } protected void validateCheckListState(Short masterTypeId, Short stateId, boolean isCustomer) throws CheckListException { try { Long records = getCheckListPersistence().isValidCheckListState(masterTypeId, stateId, isCustomer); if (records.intValue() != 0) { throw new CheckListException(CheckListConstants.EXCEPTION_STATE_ALREADY_EXIST); } } catch (PersistenceException pe) { throw new CheckListException(pe); } } }
madhav123/gkmaster
appdomain/src/main/java/org/mifos/customers/checklist/business/CheckListBO.java
Java
apache-2.0
5,902
"use strict"; const HTMLElementImpl = require("./HTMLElement-impl").implementation; const Document = require("../generated/Document"); const DocumentFragment = require("../generated/DocumentFragment"); const { cloningSteps, domSymbolTree } = require("../helpers/internal-constants"); const { clone } = require("../node"); class HTMLTemplateElementImpl extends HTMLElementImpl { constructor(globalObject, args, privateData) { super(globalObject, args, privateData); const doc = this._appropriateTemplateContentsOwnerDocument(this._ownerDocument); this._templateContents = DocumentFragment.createImpl(this._globalObject, [], { ownerDocument: doc, host: this }); } // https://html.spec.whatwg.org/multipage/scripting.html#appropriate-template-contents-owner-document _appropriateTemplateContentsOwnerDocument(doc) { if (!doc._isInertTemplateDocument) { if (doc._associatedInertTemplateDocument === undefined) { const newDoc = Document.createImpl(this._globalObject, [], { options: { parsingMode: doc._parsingMode, encoding: doc._encoding } }); newDoc._isInertTemplateDocument = true; doc._associatedInertTemplateDocument = newDoc; } doc = doc._associatedInertTemplateDocument; } return doc; } // https://html.spec.whatwg.org/multipage/scripting.html#template-adopting-steps _adoptingSteps() { const doc = this._appropriateTemplateContentsOwnerDocument(this._ownerDocument); doc._adoptNode(this._templateContents); } get content() { return this._templateContents; } [cloningSteps](copy, node, document, cloneChildren) { if (!cloneChildren) { return; } for (const child of domSymbolTree.childrenIterator(node._templateContents)) { const childCopy = clone(child, copy._templateContents._ownerDocument, true); copy._templateContents.appendChild(childCopy); } } } module.exports = { implementation: HTMLTemplateElementImpl };
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/jsdom/lib/jsdom/living/nodes/HTMLTemplateElement-impl.js
JavaScript
apache-2.0
2,038
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.types; import com.google.common.collect.ImmutableSet; import com.google.template.soy.base.SoyBackendKind; /** * Type representing an object. Object types have a unique name, * and can have zero or more member fields. * * <p>Object types are always referred to by their fully-qualified name; That * is, there's no concept of packages or scopes in this type system (those * concepts are already factored out before the type definition reaches this * point.) * * <p> Important: Do not use outside of Soy code (treat as superpackage-private). * */ public interface SoyObjectType extends SoyType { /** * Return the fully-qualified name of this object type. */ String getName(); /** * Return the fully-qualified name of this type for a given output context. * * @param backend Which backend we're generating code for. */ String getNameForBackend(SoyBackendKind backend); /** * Return the data type of the field with the given name; If there's no such * field, then return {@code null}. * * @param fieldName The name of the field. * @return The field type, or null. */ SoyType getFieldType(String fieldName); /** * Return all the possible field names that can be referenced from this ObjectType. */ ImmutableSet<String> getFieldNames(); /** * Return the expression used to access the value of the field, for a given output context. * * @param fieldContainerExpr An expression that evaluates to the container of the named field. * This expression may have any operator precedence that binds more tightly than unary * operators. * @param fieldName Name of the field. * @param backend Which backend we're generating code for. * @return Expression used to access the field data. */ String getFieldAccessExpr(String fieldContainerExpr, String fieldName, SoyBackendKind backend); /** * In some cases, {@link #getFieldAccessExpr accessing a field} requires importing * symbols into the generated code (example being protobuf extension fields which * require importing the extension type). If this field requires imports, then this * method will return the strings representing the symbol needed to import. * Otherwise, returns the empty set. * * @param fieldName The name of the field being accessed. * @param backend Which backend we're generating code for. * @return String Symbols in the backend's output language. */ ImmutableSet<String> getFieldAccessImports(String fieldName, SoyBackendKind backend); }
atul-bhouraskar/closure-templates
java/src/com/google/template/soy/types/SoyObjectType.java
Java
apache-2.0
3,172
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dataverse.api.imports; /** * * @author ellenk */ public interface ImportUtil { public enum ImportType{ NEW, MIGRATION, HARVEST}; }
quarian/dataverse
src/main/java/edu/harvard/iq/dataverse/api/imports/ImportUtil.java
Java
apache-2.0
352
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hyracks.storage.am.btree; import java.io.DataOutput; import java.util.Random; import java.util.logging.Level; import org.apache.hyracks.storage.am.common.api.*; import org.junit.Test; import org.apache.hyracks.api.comm.IFrame; import org.apache.hyracks.api.comm.IFrameTupleAccessor; import org.apache.hyracks.api.comm.VSizeFrame; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.api.dataflow.value.ITypeTraits; import org.apache.hyracks.api.dataflow.value.RecordDescriptor; import org.apache.hyracks.data.std.accessors.PointableBinaryComparatorFactory; import org.apache.hyracks.data.std.primitive.IntegerPointable; import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAccessor; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAppender; import org.apache.hyracks.dataflow.common.data.accessors.FrameTupleReference; import org.apache.hyracks.dataflow.common.data.marshalling.IntegerSerializerDeserializer; import org.apache.hyracks.storage.am.btree.api.IBTreeInteriorFrame; import org.apache.hyracks.storage.am.btree.api.IBTreeLeafFrame; import org.apache.hyracks.storage.am.btree.frames.BTreeNSMInteriorFrameFactory; import org.apache.hyracks.storage.am.btree.frames.BTreeNSMLeafFrameFactory; import org.apache.hyracks.storage.am.btree.impls.BTree; import org.apache.hyracks.storage.am.btree.util.AbstractBTreeTest; import org.apache.hyracks.storage.am.common.TestOperationCallback; import org.apache.hyracks.storage.am.common.api.IMetaDataPageManager; import org.apache.hyracks.storage.am.common.frames.LIFOMetaDataFrameFactory; import org.apache.hyracks.storage.am.common.freepage.LinkedMetaDataPageManager; import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriterFactory; import org.apache.hyracks.storage.am.common.util.TreeIndexBufferCacheWarmup; import org.apache.hyracks.storage.am.common.util.TreeIndexStats; import org.apache.hyracks.storage.am.common.util.TreeIndexStatsGatherer; import org.apache.hyracks.storage.common.buffercache.IBufferCache; import org.apache.hyracks.storage.common.file.IFileMapProvider; import org.apache.hyracks.test.support.TestStorageManagerComponentHolder; import org.apache.hyracks.test.support.TestUtils; @SuppressWarnings("rawtypes") public class BTreeStatsTest extends AbstractBTreeTest { private static final int PAGE_SIZE = 4096; private static final int NUM_PAGES = 1000; private static final int MAX_OPEN_FILES = 10; private static final int HYRACKS_FRAME_SIZE = 128; private final IHyracksTaskContext ctx = TestUtils.create(HYRACKS_FRAME_SIZE); @Test public void test01() throws Exception { TestStorageManagerComponentHolder.init(PAGE_SIZE, NUM_PAGES, MAX_OPEN_FILES); IBufferCache bufferCache = harness.getBufferCache(); IFileMapProvider fmp = harness.getFileMapProvider(); // declare fields int fieldCount = 2; ITypeTraits[] typeTraits = new ITypeTraits[fieldCount]; typeTraits[0] = IntegerPointable.TYPE_TRAITS; typeTraits[1] = IntegerPointable.TYPE_TRAITS; // declare keys int keyFieldCount = 1; IBinaryComparatorFactory[] cmpFactories = new IBinaryComparatorFactory[keyFieldCount]; cmpFactories[0] = PointableBinaryComparatorFactory.of(IntegerPointable.FACTORY); TypeAwareTupleWriterFactory tupleWriterFactory = new TypeAwareTupleWriterFactory(typeTraits); ITreeIndexFrameFactory leafFrameFactory = new BTreeNSMLeafFrameFactory(tupleWriterFactory); ITreeIndexFrameFactory interiorFrameFactory = new BTreeNSMInteriorFrameFactory(tupleWriterFactory); ITreeIndexMetaDataFrameFactory metaFrameFactory = new LIFOMetaDataFrameFactory(); IBTreeLeafFrame leafFrame = (IBTreeLeafFrame) leafFrameFactory.createFrame(); IBTreeInteriorFrame interiorFrame = (IBTreeInteriorFrame) interiorFrameFactory.createFrame(); ITreeIndexMetaDataFrame metaFrame = metaFrameFactory.createFrame(); IMetaDataPageManager freePageManager = new LinkedMetaDataPageManager(bufferCache, metaFrameFactory); BTree btree = new BTree(bufferCache, fmp, freePageManager, interiorFrameFactory, leafFrameFactory, cmpFactories, fieldCount, harness.getFileReference()); btree.create(); btree.activate(); Random rnd = new Random(); rnd.setSeed(50); long start = System.currentTimeMillis(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("INSERTING INTO TREE"); } IFrame frame = new VSizeFrame(ctx); FrameTupleAppender appender = new FrameTupleAppender(); ArrayTupleBuilder tb = new ArrayTupleBuilder(fieldCount); DataOutput dos = tb.getDataOutput(); ISerializerDeserializer[] recDescSers = { IntegerSerializerDeserializer.INSTANCE, IntegerSerializerDeserializer.INSTANCE }; RecordDescriptor recDesc = new RecordDescriptor(recDescSers); IFrameTupleAccessor accessor = new FrameTupleAccessor(recDesc); accessor.reset(frame.getBuffer()); FrameTupleReference tuple = new FrameTupleReference(); ITreeIndexAccessor indexAccessor = btree.createAccessor(TestOperationCallback.INSTANCE, TestOperationCallback.INSTANCE); // 10000 for (int i = 0; i < 100000; i++) { int f0 = rnd.nextInt() % 100000; int f1 = 5; tb.reset(); IntegerSerializerDeserializer.INSTANCE.serialize(f0, dos); tb.addFieldEndOffset(); IntegerSerializerDeserializer.INSTANCE.serialize(f1, dos); tb.addFieldEndOffset(); appender.reset(frame, true); appender.append(tb.getFieldEndOffsets(), tb.getByteArray(), 0, tb.getSize()); tuple.reset(accessor, 0); if (LOGGER.isLoggable(Level.INFO)) { if (i % 10000 == 0) { long end = System.currentTimeMillis(); LOGGER.info("INSERTING " + i + " : " + f0 + " " + f1 + " " + (end - start)); } } try { indexAccessor.insert(tuple); } catch (TreeIndexException e) { } catch (Exception e) { e.printStackTrace(); } } int fileId = fmp.lookupFileId(harness.getFileReference()); TreeIndexStatsGatherer statsGatherer = new TreeIndexStatsGatherer(bufferCache, freePageManager, fileId, btree.getRootPageId()); TreeIndexStats stats = statsGatherer.gatherStats(leafFrame, interiorFrame, metaFrame); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("\n" + stats.toString()); } TreeIndexBufferCacheWarmup bufferCacheWarmup = new TreeIndexBufferCacheWarmup(bufferCache, freePageManager, fileId); bufferCacheWarmup.warmup(leafFrame, metaFrame, new int[] { 1, 2 }, new int[] { 2, 5 }); btree.deactivate(); btree.destroy(); bufferCache.close(); } }
apache/incubator-asterixdb-hyracks
hyracks/hyracks-tests/hyracks-storage-am-btree-test/src/test/java/org/apache/hyracks/storage/am/btree/BTreeStatsTest.java
Java
apache-2.0
8,109
require 'support/shared/integration/integration_helper' describe "Recipe DSL methods" do include IntegrationSupport module Namer extend self attr_accessor :current_index end before(:all) { Namer.current_index = 1 } before { Namer.current_index += 1 } context "with resource 'base_thingy' declared as BaseThingy" do before(:context) { class BaseThingy < Chef::Resource resource_name 'base_thingy' default_action :create class<<self attr_accessor :created_name attr_accessor :created_resource attr_accessor :created_provider end def provider Provider end class Provider < Chef::Provider def load_current_resource end def action_create BaseThingy.created_name = new_resource.name BaseThingy.created_resource = new_resource.class BaseThingy.created_provider = self.class end end end # Modules to put stuff in module RecipeDSLSpecNamespace; end module RecipeDSLSpecNamespace::Bar; end } before :each do BaseThingy.created_resource = nil BaseThingy.created_provider = nil end it "creates base_thingy when you call base_thingy in a recipe" do recipe = converge { base_thingy 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_name).to eq 'blah' expect(BaseThingy.created_resource).to eq BaseThingy end it "errors out when you call base_thingy do ... end in a recipe" do expect_converge { base_thingy do; end }.to raise_error(ArgumentError, 'You must supply a name when declaring a base_thingy resource') end it "emits a warning when you call base_thingy 'foo', 'bar' do ... end in a recipe" do Chef::Config[:treat_deprecation_warnings_as_errors] = false recipe = converge { base_thingy 'foo', 'bar' do end } expect(recipe.logged_warnings).to match(/Cannot create resource base_thingy with more than one argument. All arguments except the name \("foo"\) will be ignored. This will cause an error in Chef 13. Arguments: \["foo", "bar"\]/) expect(BaseThingy.created_name).to eq 'foo' expect(BaseThingy.created_resource).to eq BaseThingy end context "Deprecated automatic resource DSL" do before do Chef::Config[:treat_deprecation_warnings_as_errors] = false end context "with a resource 'backcompat_thingy' declared in Chef::Resource and Chef::Provider" do before(:context) { class Chef::Resource::BackcompatThingy < Chef::Resource default_action :create end class Chef::Provider::BackcompatThingy < Chef::Provider def load_current_resource end def action_create BaseThingy.created_resource = new_resource.class BaseThingy.created_provider = self.class end end } it "backcompat_thingy creates a Chef::Resource::BackcompatThingy" do recipe = converge { backcompat_thingy 'blah' do; end } expect(BaseThingy.created_resource).to eq Chef::Resource::BackcompatThingy expect(BaseThingy.created_provider).to eq Chef::Provider::BackcompatThingy end context "and another resource 'backcompat_thingy' in BackcompatThingy with 'provides'" do before(:context) { class RecipeDSLSpecNamespace::BackcompatThingy < BaseThingy provides :backcompat_thingy resource_name :backcompat_thingy end } it "backcompat_thingy creates a BackcompatThingy" do recipe = converge { backcompat_thingy 'blah' do; end } expect(recipe.logged_warnings).to match(/Class Chef::Provider::BackcompatThingy does not declare 'resource_name :backcompat_thingy'./) expect(BaseThingy.created_resource).not_to be_nil end end end context "with a resource named RecipeDSLSpecNamespace::Bar::BarThingy" do before(:context) { class RecipeDSLSpecNamespace::Bar::BarThingy < BaseThingy end } it "bar_thingy does not work" do expect_converge { bar_thingy 'blah' do; end }.to raise_error(NoMethodError) end end context "with a resource named Chef::Resource::NoNameThingy with resource_name nil" do before(:context) { class Chef::Resource::NoNameThingy < BaseThingy resource_name nil end } it "no_name_thingy does not work" do expect_converge { no_name_thingy 'blah' do; end }.to raise_error(NoMethodError) end end context "with a resource named AnotherNoNameThingy with resource_name :another_thingy_name" do before(:context) { class AnotherNoNameThingy < BaseThingy resource_name :another_thingy_name end } it "another_no_name_thingy does not work" do expect_converge { another_no_name_thingy 'blah' do; end }.to raise_error(NoMethodError) end it "another_thingy_name works" do recipe = converge { another_thingy_name 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq(AnotherNoNameThingy) end end context "with a resource named AnotherNoNameThingy2 with resource_name :another_thingy_name2; resource_name :another_thingy_name3" do before(:context) { class AnotherNoNameThingy2 < BaseThingy resource_name :another_thingy_name2 resource_name :another_thingy_name3 end } it "another_no_name_thingy does not work" do expect_converge { another_no_name_thingy2 'blah' do; end }.to raise_error(NoMethodError) end it "another_thingy_name2 does not work" do expect_converge { another_thingy_name2 'blah' do; end }.to raise_error(NoMethodError) end it "yet_another_thingy_name3 works" do recipe = converge { another_thingy_name3 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq(AnotherNoNameThingy2) end end context "provides overriding resource_name" do context "with a resource named AnotherNoNameThingy3 with provides :another_no_name_thingy3, os: 'blarghle'" do before(:context) { class AnotherNoNameThingy3 < BaseThingy resource_name :another_no_name_thingy_3 provides :another_no_name_thingy3, os: 'blarghle' end } it "and os = linux, another_no_name_thingy3 does not work" do expect_converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_no_name_thingy3 'blah' do; end }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy3 works" do recipe = converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'blarghle' another_no_name_thingy3 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy3) end end context "with a resource named AnotherNoNameThingy4 with two provides" do before(:context) { class AnotherNoNameThingy4 < BaseThingy resource_name :another_no_name_thingy_4 provides :another_no_name_thingy4, os: 'blarghle' provides :another_no_name_thingy4, platform_family: 'foo' end } it "and os = linux, another_no_name_thingy4 does not work" do expect_converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_no_name_thingy4 'blah' do; end }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy4 works" do recipe = converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'blarghle' another_no_name_thingy4 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy4) end it "and platform_family = foo, another_no_name_thingy4 works" do recipe = converge { # TODO this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:platform_family] = 'foo' another_no_name_thingy4 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy4) end end context "with a resource named AnotherNoNameThingy5, a different resource_name, and a provides with the original resource_name" do before(:context) { class AnotherNoNameThingy5 < BaseThingy resource_name :another_thingy_name_for_another_no_name_thingy5 provides :another_no_name_thingy5, os: 'blarghle' end } it "and os = linux, another_no_name_thingy5 does not work" do expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_no_name_thingy5 'blah' do; end }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy5 works" do recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'blarghle' another_no_name_thingy5 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy5) end it "the new resource name can be used in a recipe" do recipe = converge { another_thingy_name_for_another_no_name_thingy5 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy5) end end context "with a resource named AnotherNoNameThingy6, a provides with the original resource name, and a different resource_name" do before(:context) { class AnotherNoNameThingy6 < BaseThingy provides :another_no_name_thingy6, os: 'blarghle' resource_name :another_thingy_name_for_another_no_name_thingy6 end } it "and os = linux, another_no_name_thingy6 does not work" do expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_no_name_thingy6 'blah' do; end }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_no_name_thingy6 works" do recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'blarghle' another_no_name_thingy6 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy6) end it "the new resource name can be used in a recipe" do recipe = converge { another_thingy_name_for_another_no_name_thingy6 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy6) end end context "with a resource named AnotherNoNameThingy7, a new resource_name, and provides with that new resource name" do before(:context) { class AnotherNoNameThingy7 < BaseThingy resource_name :another_thingy_name_for_another_no_name_thingy7 provides :another_thingy_name_for_another_no_name_thingy7, os: 'blarghle' end } it "and os = linux, another_thingy_name_for_another_no_name_thingy7 does not work" do expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_thingy_name_for_another_no_name_thingy7 'blah' do; end }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_thingy_name_for_another_no_name_thingy7 works" do recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'blarghle' another_thingy_name_for_another_no_name_thingy7 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy7) end it "the old resource name does not work" do expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_no_name_thingy_7 'blah' do; end }.to raise_error(NoMethodError) end end # opposite order from the previous test (provides, then resource_name) context "with a resource named AnotherNoNameThingy8, a provides with a new resource name, and resource_name with that new resource name" do before(:context) { class AnotherNoNameThingy8 < BaseThingy provides :another_thingy_name_for_another_no_name_thingy8, os: 'blarghle' resource_name :another_thingy_name_for_another_no_name_thingy8 end } it "and os = linux, another_thingy_name_for_another_no_name_thingy8 does not work" do expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_thingy_name_for_another_no_name_thingy8 'blah' do; end }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "and os = blarghle, another_thingy_name_for_another_no_name_thingy8 works" do recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'blarghle' another_thingy_name_for_another_no_name_thingy8 'blah' do; end } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq (AnotherNoNameThingy8) end it "the old resource name does not work" do expect_converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' another_thingy_name8 'blah' do; end }.to raise_error(NoMethodError) end end end end context "provides" do context "when MySupplier provides :hemlock" do before(:context) { class RecipeDSLSpecNamespace::MySupplier < BaseThingy resource_name :hemlock end } it "my_supplier does not work in a recipe" do expect_converge { my_supplier 'blah' do; end }.to raise_error(NoMethodError) end it "hemlock works in a recipe" do expect_recipe { hemlock 'blah' do; end }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::MySupplier end end context "when Thingy3 has resource_name :thingy3" do before(:context) { class RecipeDSLSpecNamespace::Thingy3 < BaseThingy resource_name :thingy3 end } it "thingy3 works in a recipe" do expect_recipe { thingy3 'blah' do; end }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3 end context "and Thingy4 has resource_name :thingy3" do before(:context) { class RecipeDSLSpecNamespace::Thingy4 < BaseThingy resource_name :thingy3 end } it "thingy3 works in a recipe and yields Thingy3 (the alphabetical one)" do recipe = converge { thingy3 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3 end it "thingy4 does not work in a recipe" do expect_converge { thingy4 'blah' do; end }.to raise_error(NoMethodError) end it "resource_matching_short_name returns Thingy4" do expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy3 end end end context "when Thingy5 has resource_name :thingy5 and provides :thingy5reverse, :thingy5_2 and :thingy5_2reverse" do before(:context) { class RecipeDSLSpecNamespace::Thingy5 < BaseThingy resource_name :thingy5 provides :thingy5reverse provides :thingy5_2 provides :thingy5_2reverse end } it "thingy5 works in a recipe" do expect_recipe { thingy5 'blah' do; end }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy5 end context "and Thingy6 provides :thingy5" do before(:context) { class RecipeDSLSpecNamespace::Thingy6 < BaseThingy resource_name :thingy6 provides :thingy5 end } it "thingy6 works in a recipe and yields Thingy6" do recipe = converge { thingy6 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy6 end it "thingy5 works in a recipe and yields Foo::Thingy5 (the alphabetical one)" do recipe = converge { thingy5 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy5 end it "resource_matching_short_name returns Thingy5" do expect(Chef::Resource.resource_matching_short_name(:thingy5)).to eq RecipeDSLSpecNamespace::Thingy5 end context "and AThingy5 provides :thingy5reverse" do before(:context) { class RecipeDSLSpecNamespace::AThingy5 < BaseThingy resource_name :thingy5reverse end } it "thingy5reverse works in a recipe and yields AThingy5 (the alphabetical one)" do recipe = converge { thingy5reverse 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::AThingy5 end end context "and ZRecipeDSLSpecNamespace::Thingy5 provides :thingy5_2" do before(:context) { module ZRecipeDSLSpecNamespace class Thingy5 < BaseThingy resource_name :thingy5_2 end end } it "thingy5_2 works in a recipe and yields the RecipeDSLSpaceNamespace one (the alphabetical one)" do recipe = converge { thingy5_2 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy5 end end context "and ARecipeDSLSpecNamespace::Thingy5 provides :thingy5_2" do before(:context) { module ARecipeDSLSpecNamespace class Thingy5 < BaseThingy resource_name :thingy5_2reverse end end } it "thingy5_2reverse works in a recipe and yields the ARecipeDSLSpaceNamespace one (the alphabetical one)" do recipe = converge { thingy5_2reverse 'blah' do; end } expect(BaseThingy.created_resource).to eq ARecipeDSLSpecNamespace::Thingy5 end end end context "when Thingy3 has resource_name :thingy3" do before(:context) { class RecipeDSLSpecNamespace::Thingy3 < BaseThingy resource_name :thingy3 end } it "thingy3 works in a recipe" do expect_recipe { thingy3 'blah' do; end }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3 end context "and Thingy4 has resource_name :thingy3" do before(:context) { class RecipeDSLSpecNamespace::Thingy4 < BaseThingy resource_name :thingy3 end } it "thingy3 works in a recipe and yields Thingy3 (the alphabetical one)" do recipe = converge { thingy3 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3 end it "thingy4 does not work in a recipe" do expect_converge { thingy4 'blah' do; end }.to raise_error(NoMethodError) end it "resource_matching_short_name returns Thingy4" do expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy3 end end context "and Thingy4 has resource_name :thingy3" do before(:context) { class RecipeDSLSpecNamespace::Thingy4 < BaseThingy resource_name :thingy3 end } it "thingy3 works in a recipe and yields Thingy3 (the alphabetical one)" do recipe = converge { thingy3 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3 end it "thingy4 does not work in a recipe" do expect_converge { thingy4 'blah' do; end }.to raise_error(NoMethodError) end it "resource_matching_short_name returns Thingy4" do expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy3 end end end end context "when Thingy7 provides :thingy8" do before(:context) { class RecipeDSLSpecNamespace::Thingy7 < BaseThingy resource_name :thingy7 provides :thingy8 end } context "and Thingy8 has resource_name :thingy8" do before(:context) { class RecipeDSLSpecNamespace::Thingy8 < BaseThingy resource_name :thingy8 end } it "thingy7 works in a recipe and yields Thingy7" do recipe = converge { thingy7 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy7 end it "thingy8 works in a recipe and yields Thingy7 (alphabetical)" do recipe = converge { thingy8 'blah' do; end } expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy7 end it "resource_matching_short_name returns Thingy8" do expect(Chef::Resource.resource_matching_short_name(:thingy8)).to eq RecipeDSLSpecNamespace::Thingy8 end end end context "when Thingy12 provides :thingy12, :twizzle and :twizzle2" do before(:context) { class RecipeDSLSpecNamespace::Thingy12 < BaseThingy resource_name :thingy12 provides :twizzle provides :twizzle2 end } it "thingy12 works in a recipe and yields Thingy12" do expect_recipe { thingy12 'blah' do; end }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy12 end it "twizzle works in a recipe and yields Thingy12" do expect_recipe { twizzle 'blah' do; end }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy12 end it "twizzle2 works in a recipe and yields Thingy12" do expect_recipe { twizzle2 'blah' do; end }.to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy12 end end context "with platform-specific resources 'my_super_thingy_foo' and 'my_super_thingy_bar'" do before(:context) { class MySuperThingyFoo < BaseThingy resource_name :my_super_thingy_foo provides :my_super_thingy, platform: 'foo' end class MySuperThingyBar < BaseThingy resource_name :my_super_thingy_bar provides :my_super_thingy, platform: 'bar' end } it "A run with platform 'foo' uses MySuperThingyFoo" do r = Cheffish::ChefRun.new(chef_config) r.client.run_context.node.automatic['platform'] = 'foo' r.compile_recipe { my_super_thingy 'blah' do; end } r.converge expect(r).to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq MySuperThingyFoo end it "A run with platform 'bar' uses MySuperThingyBar" do r = Cheffish::ChefRun.new(chef_config) r.client.run_context.node.automatic['platform'] = 'bar' r.compile_recipe { my_super_thingy 'blah' do; end } r.converge expect(r).to emit_no_warnings_or_errors expect(BaseThingy.created_resource).to eq MySuperThingyBar end it "A run with platform 'x' reports that my_super_thingy is not supported" do r = Cheffish::ChefRun.new(chef_config) r.client.run_context.node.automatic['platform'] = 'x' expect { r.compile_recipe { my_super_thingy 'blah' do; end } }.to raise_error(Chef::Exceptions::NoSuchResourceType) end end context "when Thingy9 provides :thingy9" do before(:context) { class RecipeDSLSpecNamespace::Thingy9 < BaseThingy resource_name :thingy9 end } it "declaring a resource providing the same :thingy9 produces a warning" do expect(Chef::Log).to receive(:warn).with("You declared a new resource RecipeDSLSpecNamespace::Thingy9AlternateProvider for resource thingy9, but it comes alphabetically after RecipeDSLSpecNamespace::Thingy9 and has the same filters ({}), so it will not be used. Use override: true if you want to use it for thingy9.") class RecipeDSLSpecNamespace::Thingy9AlternateProvider < BaseThingy resource_name :thingy9 end end end context "when Thingy10 provides :thingy10" do before(:context) { class RecipeDSLSpecNamespace::Thingy10 < BaseThingy resource_name :thingy10 end } it "declaring a resource providing the same :thingy10 with override: true does not produce a warning" do expect(Chef::Log).not_to receive(:warn) class RecipeDSLSpecNamespace::Thingy10AlternateProvider < BaseThingy provides :thingy10, override: true end end end context "when Thingy11 provides :thingy11" do before(:context) { class RecipeDSLSpecNamespace::Thingy11 < BaseThingy resource_name :thingy10 end } it "declaring a resource providing the same :thingy11 with os: 'linux' does not produce a warning" do expect(Chef::Log).not_to receive(:warn) class RecipeDSLSpecNamespace::Thingy11AlternateProvider < BaseThingy provides :thingy11, os: 'linux' end end end end context "with a resource named 'B' with resource name :two_classes_one_dsl" do let(:two_classes_one_dsl) { :"two_classes_one_dsl#{Namer.current_index}" } let(:resource_class) { result = Class.new(BaseThingy) do def self.name "B" end def self.to_s; name; end def self.inspect; name.inspect; end end result.resource_name two_classes_one_dsl result } before { resource_class } # pull on it so it gets defined before the recipe runs context "and another resource named 'A' with resource_name :two_classes_one_dsl" do let(:resource_class_a) { result = Class.new(BaseThingy) do def self.name "A" end def self.to_s; name; end def self.inspect; name.inspect; end end result.resource_name two_classes_one_dsl result } before { resource_class_a } # pull on it so it gets defined before the recipe runs it "two_classes_one_dsl resolves to A (alphabetically earliest)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class_a end it "resource_matching_short_name returns B" do expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class_a end end context "and another resource named 'Z' with resource_name :two_classes_one_dsl" do let(:resource_class_z) { result = Class.new(BaseThingy) do def self.name "Z" end def self.to_s; name; end def self.inspect; name.inspect; end end result.resource_name two_classes_one_dsl result } before { resource_class_z } # pull on it so it gets defined before the recipe runs it "two_classes_one_dsl resolves to B (alphabetically earliest)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class end it "resource_matching_short_name returns B" do expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class end context "and a priority array [ Z, B ]" do before do Chef.set_resource_priority_array(two_classes_one_dsl, [ resource_class_z, resource_class ]) end it "two_classes_one_dsl resolves to Z (respects the priority array)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class_z end it "resource_matching_short_name returns B" do expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class end context "when Z provides(:two_classes_one_dsl) { false }" do before do resource_class_z.provides(two_classes_one_dsl) { false } end it "two_classes_one_dsl resolves to B (picks the next thing in the priority array)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class end it "resource_matching_short_name returns B" do expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class end end end context "and priority arrays [ B ] and [ Z ]" do before do Chef.set_resource_priority_array(two_classes_one_dsl, [ resource_class ]) Chef.set_resource_priority_array(two_classes_one_dsl, [ resource_class_z ]) end it "two_classes_one_dsl resolves to Z (respects the most recent priority array)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class_z end it "resource_matching_short_name returns B" do expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class end context "when Z provides(:two_classes_one_dsl) { false }" do before do resource_class_z.provides(two_classes_one_dsl) { false } end it "two_classes_one_dsl resolves to B (picks the first match from the other priority array)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class end it "resource_matching_short_name returns B" do expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class end end end context "and a priority array [ Z ]" do before do Chef.set_resource_priority_array(two_classes_one_dsl, [ resource_class_z ]) end context "when Z provides(:two_classes_one_dsl) { false }" do before do resource_class_z.provides(two_classes_one_dsl) { false } end it "two_classes_one_dsl resolves to B (picks the first match outside the priority array)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class end it "resource_matching_short_name returns B" do expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class end end end end context "and a provider named 'B' which provides :two_classes_one_dsl" do before do resource_class.send(:define_method, :provider) { nil } end let(:provider_class) { result = Class.new(BaseThingy::Provider) do def self.name "B" end def self.to_s; name; end def self.inspect; name.inspect; end end result.provides two_classes_one_dsl result } before { provider_class } # pull on it so it gets defined before the recipe runs context "and another provider named 'A'" do let(:provider_class_a) { result = Class.new(BaseThingy::Provider) do def self.name "A" end def self.to_s; name; end def self.inspect; name.inspect; end end result } context "which provides :two_classes_one_dsl" do before { provider_class_a.provides two_classes_one_dsl } it "two_classes_one_dsl resolves to A (alphabetically earliest)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class_a end end context "which provides(:two_classes_one_dsl) { false }" do before { provider_class_a.provides(two_classes_one_dsl) { false } } it "two_classes_one_dsl resolves to B (since A declined)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class end end end context "and another provider named 'Z'" do let(:provider_class_z) { result = Class.new(BaseThingy::Provider) do def self.name "Z" end def self.to_s; name; end def self.inspect; name.inspect; end end result } before { provider_class_z } # pull on it so it gets defined before the recipe runs context "which provides :two_classes_one_dsl" do before { provider_class_z.provides two_classes_one_dsl } it "two_classes_one_dsl resolves to B (alphabetically earliest)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class end context "with a priority array [ Z, B ]" do before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z, provider_class ] } it "two_classes_one_dsl resolves to Z (respects the priority map)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class_z end end end context "which provides(:two_classes_one_dsl) { false }" do before { provider_class_z.provides(two_classes_one_dsl) { false } } context "with a priority array [ Z, B ]" do before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z, provider_class ] } it "two_classes_one_dsl resolves to B (the next one in the priority map)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class end end context "with priority arrays [ B ] and [ Z ]" do before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class_z ] } before { Chef.set_provider_priority_array two_classes_one_dsl, [ provider_class ] } it "two_classes_one_dsl resolves to B (the one in the next priority map)" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { instance_eval("#{two_classes_one_dsl} 'blah'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class end end end end end context "and another resource Blarghle with provides :two_classes_one_dsl, os: 'blarghle'" do let(:resource_class_blarghle) { result = Class.new(BaseThingy) do def self.name "Blarghle" end def self.to_s; name; end def self.inspect; name.inspect; end end result.resource_name two_classes_one_dsl result.provides two_classes_one_dsl, os: 'blarghle' result } before { resource_class_blarghle } # pull on it so it gets defined before the recipe runs it "on os = blarghle, two_classes_one_dsl resolves to Blarghle" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'blarghle' instance_eval("#{two_classes_one_dsl} 'blah' do; end") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class_blarghle end it "on os = linux, two_classes_one_dsl resolves to B" do two_classes_one_dsl = self.two_classes_one_dsl recipe = converge { # this is an ugly way to test, make Cheffish expose node attrs run_context.node.automatic[:os] = 'linux' instance_eval("#{two_classes_one_dsl} 'blah' do; end") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class end end end context "with a resource MyResource" do let(:resource_class) { Class.new(BaseThingy) do def self.called_provides @called_provides end def to_s "MyResource" end end } let(:my_resource) { :"my_resource#{Namer.current_index}" } let(:blarghle_blarghle_little_star) { :"blarghle_blarghle_little_star#{Namer.current_index}" } context "with resource_name :my_resource" do before { resource_class.resource_name my_resource } context "with provides? returning true to my_resource" do before { my_resource = self.my_resource resource_class.define_singleton_method(:provides?) do |node, resource_name| @called_provides = true resource_name == my_resource end } it "my_resource returns the resource and calls provides?, but does not emit a warning" do dsl_name = self.my_resource recipe = converge { instance_eval("#{dsl_name} 'foo'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_resource).to eq resource_class expect(resource_class.called_provides).to be_truthy end end context "with provides? returning true to blarghle_blarghle_little_star and not resource_name" do before do blarghle_blarghle_little_star = self.blarghle_blarghle_little_star resource_class.define_singleton_method(:provides?) do |node, resource_name| @called_provides = true resource_name == blarghle_blarghle_little_star end end it "my_resource does not return the resource" do dsl_name = self.my_resource expect_converge { instance_eval("#{dsl_name} 'foo'") }.to raise_error(Chef::Exceptions::NoSuchResourceType) expect(resource_class.called_provides).to be_truthy end it "blarghle_blarghle_little_star 'foo' returns the resource and emits a warning" do Chef::Config[:treat_deprecation_warnings_as_errors] = false dsl_name = self.blarghle_blarghle_little_star recipe = converge { instance_eval("#{dsl_name} 'foo'") } expect(recipe.logged_warnings).to include "WARN: #{resource_class}.provides? returned true when asked if it provides DSL #{dsl_name}, but provides :#{dsl_name} was never called!" expect(BaseThingy.created_resource).to eq resource_class expect(resource_class.called_provides).to be_truthy end end context "and a provider" do let(:provider_class) do Class.new(BaseThingy::Provider) do def self.name "MyProvider" end def self.to_s; name; end def self.inspect; name.inspect; end def self.called_provides @called_provides end end end before do resource_class.send(:define_method, :provider) { nil } end context "that provides :my_resource" do before do provider_class.provides my_resource end context "with supports? returning true" do before do provider_class.define_singleton_method(:supports?) { |resource,action| true } end it "my_resource runs the provider and does not emit a warning" do my_resource = self.my_resource recipe = converge { instance_eval("#{my_resource} 'foo'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class end context "and another provider supporting :my_resource with supports? false" do let(:provider_class2) do Class.new(BaseThingy::Provider) do def self.name "MyProvider2" end def self.to_s; name; end def self.inspect; name.inspect; end def self.called_provides @called_provides end provides my_resource def self.supports?(resource, action) false end end end it "my_resource runs the first provider" do my_resource = self.my_resource recipe = converge { instance_eval("#{my_resource} 'foo'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class end end end context "with supports? returning false" do before do provider_class.define_singleton_method(:supports?) { |resource,action| false } end # TODO no warning? ick it "my_resource runs the provider anyway" do my_resource = self.my_resource recipe = converge { instance_eval("#{my_resource} 'foo'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class end context "and another provider supporting :my_resource with supports? true" do let(:provider_class2) do my_resource = self.my_resource Class.new(BaseThingy::Provider) do def self.name "MyProvider2" end def self.to_s; name; end def self.inspect; name.inspect; end def self.called_provides @called_provides end provides my_resource def self.supports?(resource, action) true end end end before { provider_class2 } # make sure the provider class shows up it "my_resource runs the other provider" do my_resource = self.my_resource recipe = converge { instance_eval("#{my_resource} 'foo'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class2 end end end end context "with provides? returning true" do before { my_resource = self.my_resource provider_class.define_singleton_method(:provides?) do |node, resource| @called_provides = true resource.declared_type == my_resource end } context "that provides :my_resource" do before { provider_class.provides my_resource } it "my_resource calls the provider (and calls provides?), but does not emit a warning" do my_resource = self.my_resource recipe = converge { instance_eval("#{my_resource} 'foo'") } expect(recipe.logged_warnings).to eq '' expect(BaseThingy.created_provider).to eq provider_class expect(provider_class.called_provides).to be_truthy end end context "that does not call provides :my_resource" do it "my_resource calls the provider (and calls provides?), and emits a warning" do Chef::Config[:treat_deprecation_warnings_as_errors] = false my_resource = self.my_resource recipe = converge { instance_eval("#{my_resource} 'foo'") } expect(recipe.logged_warnings).to include("WARN: #{provider_class}.provides? returned true when asked if it provides DSL #{my_resource}, but provides :#{my_resource} was never called!") expect(BaseThingy.created_provider).to eq provider_class expect(provider_class.called_provides).to be_truthy end end end context "with provides? returning false to my_resource" do before { my_resource = self.my_resource provider_class.define_singleton_method(:provides?) do |node, resource| @called_provides = true false end } context "that provides :my_resource" do before { provider_class.provides my_resource } it "my_resource fails to find a provider (and calls provides)" do my_resource = self.my_resource expect_converge { instance_eval("#{my_resource} 'foo'") }.to raise_error(Chef::Exceptions::ProviderNotFound) expect(provider_class.called_provides).to be_truthy end end context "that does not provide :my_resource" do it "my_resource fails to find a provider (and calls provides)" do my_resource = self.my_resource expect_converge { instance_eval("#{my_resource} 'foo'") }.to raise_error(Chef::Exceptions::ProviderNotFound) expect(provider_class.called_provides).to be_truthy end end end end end end end before(:all) { Namer.current_index = 0 } before { Namer.current_index += 1 } context "with an LWRP that declares actions" do let(:resource_class) { Class.new(Chef::Resource::LWRPBase) do provides :"recipe_dsl_spec#{Namer.current_index}" actions :create end } let(:resource) { resource_class.new("blah", run_context) } it "The actions are part of actions along with :nothing" do expect(resource_class.actions).to eq [ :nothing, :create ] end it "The actions are part of allowed_actions along with :nothing" do expect(resource.allowed_actions).to eq [ :nothing, :create ] end context "and a subclass that declares more actions" do let(:subresource_class) { Class.new(Chef::Resource::LWRPBase) do provides :"recipe_dsl_spec_sub#{Namer.current_index}" actions :delete end } let(:subresource) { subresource_class.new("subblah", run_context) } it "The parent class actions are not part of actions" do expect(subresource_class.actions).to eq [ :nothing, :delete ] end it "The parent class actions are not part of allowed_actions" do expect(subresource.allowed_actions).to eq [ :nothing, :delete ] end it "The parent class actions do not change" do expect(resource_class.actions).to eq [ :nothing, :create ] expect(resource.allowed_actions).to eq [ :nothing, :create ] end end end context "with a dynamically defined resource and regular provider" do before(:context) do Class.new(Chef::Resource) do resource_name :lw_resource_with_hw_provider_test_case default_action :create attr_accessor :created_provider end class Chef::Provider::LwResourceWithHwProviderTestCase < Chef::Provider def load_current_resource end def action_create new_resource.created_provider = self.class end end end it "looks up the provider in Chef::Provider converting the resource name from snake case to camel case" do resource = nil recipe = converge { resource = lw_resource_with_hw_provider_test_case 'blah' do; end } expect(resource.created_provider).to eq(Chef::Provider::LwResourceWithHwProviderTestCase) end end end
andrewpsp/chef
spec/integration/recipes/recipe_dsl_spec.rb
Ruby
apache-2.0
55,483