answer
stringlengths
15
1.25M
<?php require_once IA_INCLUDES . 'helpers/ia.category.interface.php'; abstract class <API key> extends abstractModuleFront { const ROOT_PARENT_ID = 0; const COL_PARENT_ID = 'parent_id'; const COL_LEVEL = 'level'; protected $_tableFlat; protected $_recountEnabled = true; protected $_recountOptions = []; // this to be extended by ancestor private $<API key> = [ 'listingsTable' => null, 'activeStatus' => iaCore::STATUS_ACTIVE, 'columnCounter' => 'num_listings', 'columnTotalCounter' => 'num_all_listings' ]; private $_root; public function init() { parent::init(); $this->_tableFlat = self::getTable() . '_flat'; } public function getTableFlat($prefix = false) { return ($prefix ? $this->iaDb->prefix : '') . $this->_tableFlat; } public function getRoot() { if (is_null($this->_root)) { $this->_root = $this->getOne(iaDb::convertIds(self::ROOT_PARENT_ID, self::COL_PARENT_ID)); } return $this->_root; } public function getRootId() { return $this->getRoot()['id']; } public function getTopLevel($fields = null) { return $this->getByLevel(1, $fields); } public function getByLevel($level, $fields = null) { $where = '`status` = :status and `level` = :level'; $this->iaDb->bind($where, ['status' => iaCOre::STATUS_ACTIVE, 'level' => $level]); return $this->getAll($where, $fields); } public function getParents($entryId) { $where = sprintf('`id` IN (SELECT `parent_id` FROM `%s` WHERE `child_id` = %d)', $this->getTableFlat(true), $entryId); return $this->getAll($where); } public function getChildren($entryId, $recursive = false) { $where = $recursive ? sprintf('`id` IN (SELECT `child_id` FROM `%s` WHERE `parent_id` = %d)', $this->getTableFlat(true), $entryId) : iaDb::convertIds($entryId, self::COL_PARENT_ID); return $this->getAll($where); } public function getTreeVars($id, $title) { $nodes = []; foreach ($this->getParents($id) as $category) { $nodes[] = $category['id']; } $result = [ 'url' => $this->getInfo('url') . 'add/tree.json', 'id' => $id, 'nodes' => implode(',', $nodes), 'title' => $title ]; return $result; } public function getJsonTree(array $data) { $output = []; $this->iaDb->setTable(self::getTable()); $dynamicLoadMode = ((int)$this->iaDb->one(iaDb::STMT_COUNT_ROWS) > 150); $rootId = $this->getRootId(); $parentId = isset($data['id']) && is_numeric($data['id']) ? (int)$data['id'] : $rootId; $where = $dynamicLoadMode ? iaDb::convertIds($parentId, self::COL_PARENT_ID) : iaDb::convertIds($rootId, 'id', false); $where .= ' ORDER BY `title`'; $fields = '`id`, `title_' . $this->iaCore->language['iso'] . '` `title`, `parent_id`, ' . '(SELECT COUNT(*) FROM `' . $this->getTableFlat(true) . '` f WHERE f.`parent_id` = `id`) `children_count`'; foreach ($this->iaDb->all($fields, $where) as $row) { $entry = ['id' => $row['id'], 'text' => $row['title']]; if ($dynamicLoadMode) { $entry['children'] = $row['children_count'] > 1; } else { $entry['state'] = []; $entry['parent'] = $rootId == $row[self::COL_PARENT_ID] ? '#' : $row[self::COL_PARENT_ID]; } $output[] = $entry; } return $output; } public function recountById($id, $factor = 1) { if (!$this->_recountEnabled) { return; } $options = array_merge($this-><API key>, $this->_recountOptions); $sql = <<<SQL UPDATE `:table_data` SET `:col_counter` = IF(`id` = :id, `:col_counter` + :factor, `:col_counter`), `:col_total_counter` = `:col_total_counter` + :factor WHERE `id` IN (SELECT `parent_id` FROM `:table_flat` WHERE `child_id` = :id) SQL; $sql = iaDb::printf($sql, [ 'table_data' => self::getTable(true), 'table_flat' => self::getTableFlat(true), 'col_counter' => $options['columnCounter'], 'col_total_counter' => $options['columnTotalCounter'], 'id' => (int)$id, 'factor' => (int)$factor ]); $this->iaDb->query($sql); } }
<?php /** * \PHPCompatibility\Sniffs\LanguageConstructs\<API key>. * * PHP version 5.5 * * @category PHP * @package PHPCompatibility * @author Juliette Reinders Folmer <<API key>@adviesenzo.nl> */ namespace PHPCompatibility\Sniffs\LanguageConstructs; use PHPCompatibility\Sniff; use <API key> as File; use <API key> as Tokens; /** * \PHPCompatibility\Sniffs\LanguageConstructs\<API key>. * * Verify that nothing but variables are passed to empty(). * * PHP version 5.5 * * @category PHP * @package PHPCompatibility * @author Juliette Reinders Folmer <<API key>@adviesenzo.nl> */ class <API key> extends Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array(\T_EMPTY); } /** * Processes this test, when one of its tokens is encountered. * * @param \<API key> $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(File $phpcsFile, $stackPtr) { if ($this->supportsBelow('5.4') === false) { return; } $tokens = $phpcsFile->getTokens(); $open = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true); if ($open === false || $tokens[$open]['code'] !== \T_OPEN_PARENTHESIS || isset($tokens[$open]['parenthesis_closer']) === false ) { return; } $close = $tokens[$open]['parenthesis_closer']; $nestingLevel = 0; if ($close !== ($open + 1) && isset($tokens[$open + 1]['nested_parenthesis'])) { $nestingLevel = count($tokens[$open + 1]['nested_parenthesis']); } if ($this->isVariable($phpcsFile, ($open + 1), $close, $nestingLevel) === true) { return; } $phpcsFile->addError( 'Only variables can be passed to empty() prior to PHP 5.5.', $stackPtr, 'Found' ); } }
%include lhs2TeX.fmt \usepackage{ stmaryrd } %format <?> = "~\lightning~"
*{ font-family: 'Raleway', sans-serif; } body{ background: #d6d6d6; color: #333; margin: 0; font-family: 'Raleway', sans-serif; } #masterContainer{ width: 100vw; height: 100vh; padding: 0; margin: 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; align-items: center; justify-content: center; } #logindiv{ background: #dfdfdf; padding: 50px 20px; border-radius: 3px; box-shadow: 0 0 3px #888; } #logindiv span { width: 80px; display: inline-block; font-size: 15px; } #logindiv input { width: 220px; height: 30px; padding: 5px; margin: 5px 0px; display: inline-block; font-size: 15px; outline: none; transition: 0.2s; border: 1px solid #aaa; } #logindiv input[type=submit] { display: block; width: 100%; margin: 20px 0 0 0; border: 0; border-radius: 3px; background-color: #29b0d0; color: #fff; height: 35px; } #logindiv input[type=submit]:hover { background: #2990a0; } .logo { background-image: url(./logo.png); background-size: contain; filter: hue-rotate(120); display: block; width: 80px; height: 80px; margin: 0 auto 20px auto; } #about{ width: 100%; text-align: center; bottom: 20px; position: fixed; color: #777; font-weight: 300; text-shadow: 0 0 0px #b1b1b1; } html { height: 100%; } .h1, .h2, .h3, .h4, .h5, .h6, h1, h2, h3, h4, h5, h6 { font-family: inherit; font-weight: 400; line-height: 1.1; color: inherit; } input[type=submit]{ padding: 10px; background-color: #29b0d0; color: #fff; border: 0; border-radius: 3px; font-size: 13px; outline: none; } input[type=text], input[type=password]{ padding: 10px; background-color: #eee; color: #000; border: 1px solid #ccc; font-size: 13px; border-radius: 3px; min-width: 270px; outline: none; transition: 0.2s; } input[type=text]:hover, input[type=password]:hover{ border: 1px solid #aaa; } input[type=text]:focus, input[type=password]:focus{ border: 1px solid #29b0d0; } nav { height: 60px; background: #fff; display: block; padding: 0; -webkit-box-shadow: 0 0px 2px #777; -moz-box-shadow: 0 0px 2px #777; box-shadow: 0 0px 2px #777; z-index: 9999; color: #333; box-shadow: 0 1px 0 rgba(12,13,14,0.1), 0 1px 3px rgba(12,13,14,0.1), 0 4px 20px rgba(12,13,14,0.035), 0 1px 1px rgba(12,13,14,0.025); } #title { width: 80px; background-size: 50px 50px; background-repeat: no-repeat; background-position: center; font-size: 14px; color: #655dff; display: inline-block; margin: 0; height: 59px; min-width: 60px; cursor: pointer; max-width: 200px; } #search{ display: inline-block; width: 250px; height: 40px; margin: 10px 25px; background-color: #29b0d0; position: absolute; border: 0; box-shadow: 0 0 2px #ddd; color: #fff; } #search::placeholder{ color: #ddd; } #headerRight { height: 60px; margin: 0; } .headerButton { margin: 10px 5px; background-color: #29b0d0; color: #fff; min-width: 40px; border: 0; border-radius: 4px; height: 40px; box-shadow: 0 0 3px #cccccc; } .headerButton:hover { background: #f0f0f0; transition: 0.2s; } .headerText { font-weight: 400; font-size: 15px; padding: 0; margin: 9px 12px 9px 2px; display: inline-block; vertical-align: top; text-align: center; } .userPhoto { width: 30px; height: 30px; margin: 5px; display: inline-block; border-radius: 15px; background-size: contain; } .mainContent{ padding-top: 100px; background-color: #f6f6f6; padding-bottom: 40px; box-shadow: 0 0 20px 2px #aaa; min-height: 100%; position: relative; } .post { min-width: 500px; max-width: 800px; min-height: 200px; position: relative; margin: 30px auto; margin-bottom: 60px; background-color: #fff; border-radius: 3px; border: 1px solid #ccc; box-shadow: 0 10px 0px 0px #29b0d0, 0 4px 8px 0 rgba(0,0,0,0.2); display: block; transition: 0.3s; } .post:hover { box-shadow: 0 10px 0px 0px #2292ac, 0 8px 16px 0 rgba(0,0,0,0.2); } .post .row > .col > *{ display: inline-block; vertical-align: middle; } .postText { padding-bottom: 60px; margin: 20px; } .postTitle { padding: 2px 20px 10px 20px; display: block; font-size: 1.5em; color: #333; text-align: center; } .react { width: 100%; left: 0; height: 60px; bottom: 0; left: 15px; position: absolute; background-color: #eee; overflow: hidden; border: 0; padding: 0; border-top: 1px solid #ddd; } .reactButton{ width: 40px; height: 40px; margin: 0; padding: 0; border-radius: 40px; border: 1px solid #ddd; display: inline-block; background: #fff; color: #555; position: relative; bottom: 0; transition: 0.2s; margin: 10px; } .reactButton:focus{ outline: none; } .react > input[type=submit]{ background: #eee; color: #666; } .react > input[type=submit]:hover { background: #e0e0e0; transition: 0.2s; color: #29b0d0; } .reactButton:hover { background-color: #555; color: #fff; border: 0; cursor: pointer; } ._thumbsup:hover { background-color: #29b0d0; } ._heart:hover { background-color: #f03; } ._comments{ } ._comments:hover { background-color: #555; } ._post:hover { background-color: #590; } .comments { left: 0; height: 0px; position: relative; background-color: #f4f4f4; overflow: hidden; border: 0; padding: 0; border-top: 1px solid #ddd; display: block; overflow-y: scroll; max-height: 199px; padding: 10px 10px 10px 0; } .UpostText { display: block; height: 180px; margin: 20px; margin-bottom: 0px; border: 1px solid #ccc; border-radius: 3px; background-color: #fcfcfc; max-height: 160px; outline: 0px; resize: none; padding: 10px; } .UpostText:hover { transition: 0.2s; border: 1px solid #aaa; } .UpostText:focus { transition: 0.2s; border: 1px solid #29b0d0; } hr { border: 0; height: 1px; background-image: -<API key>(left, #f0f0f0, #8c8b8b, #f0f0f0); background-image: -moz-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0); background-image: -ms-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0); background-image: -o-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0); } #register{ width: 380px; margin: 0 auto; margin-top: 100px; height: 550px; background-color: #fff; border-radius: 3px; font-size: 14px; border: 1px solid #ccc; box-shadow: 0 5px 10px -2px #888; font-weight: 300; } #register input{ display: block; margin-top: 15px; width: 270px; } #register form { padding-top: 15px; width: 270px; margin: auto; display: block; } #register h1 { margin: 15px; font-size: 30px; } #register h3 { margin-top: 10px; font-size: 20px; } .comment{ background: white; max-height: 50px; padding: 5px; border-radius: 10px; margin: 15px; box-shadow: 0 0 15px #d8d8d8; display: block; } .commentUserImage{ width: 30px; height: 30px; border-radius: 15px; margin: 5px; } .commentUser{ font-weight: 700; } .commentText{ font-weight: 200; font-family: monospace; } .commentInput{ height: 40px; width: 200px; border-radius: 20px; border: 1px solid #ddd; padding: 10px; margin: 10px; display: inline-block; background: #fff; color: #555; position: relative; bottom: 0; outline: 0; }
// This file is part of ROX Center. // ROX Center is free software: you can redistribute it and/or modify // (at your option) any later version. // ROX Center is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the App.autoModule('globalSettings', function() { var Settings = Backbone.Model.extend({ url: LegacyApiPath.builder('settings') }); var SettingsForm = Marionette.ItemView.extend({ template: 'globalSettings', ui: { ticketingSystemUrl: '#<API key>', reportsCacheSize: '#<API key>', tagCloudSize: '#<API key>', testOutdatedDays: '#<API key>', <API key>: '#<API key>', testRunsLifespan: '#<API key>', fields: 'form :input', saveButton: 'form button', formControls: 'form .form-controls' }, events: { 'submit form': 'save' }, modelEvents: { 'change': 'refresh' }, appEvents: { 'maintenance:changed': 'updateControls' }, model: new Settings(), initialize: function() { App.bindEvents(this); }, onRender: function() { this.$el.button(); this.model.fetch(this.requestOptions()); this.updateControls(); }, setBusy: function(busy) { this.busy = busy; this.updateControls(); }, updateControls: function() { this.ui.saveButton.attr('disabled', this.busy || !!App.maintenance); this.ui.fields.attr('disabled', !!App.maintenance); }, refresh: function() { this.ui.ticketingSystemUrl.val(this.model.get('<API key>')); this.ui.reportsCacheSize.val(this.model.get('reports_cache_size')); this.ui.tagCloudSize.val(this.model.get('tag_cloud_size')); this.ui.testOutdatedDays.val(this.model.get('test_outdated_days')); this.ui.<API key>.val(this.model.get('<API key>')); this.ui.testRunsLifespan.val(this.model.get('test_runs_lifespan')); }, save: function(e) { e.preventDefault(); this.setNotice(false); this.setBusy(true); var options = this.requestOptions(); options.type = 'PUT'; options.success = _.bind(this.onSaved, this, 'success'); options.error = _.bind(this.onSaved, this, 'error'); this.model.save({ <API key>: this.ui.ticketingSystemUrl.val(), reports_cache_size: this.ui.reportsCacheSize.val(), tag_cloud_size: this.ui.tagCloudSize.val(), test_outdated_days: this.ui.testOutdatedDays.val(), <API key>: this.ui.<API key>.val(), test_runs_lifespan: this.ui.testRunsLifespan.val() }, options).always(_.bind(this.setBusy, this, false)); }, onSaved: function(result) { this.setNotice(result); if (result == 'success') { this.refresh(); } }, setNotice: function(type) { this.ui.saveButton.next('.text-success,.text-danger').remove(); if (type == 'success') { $('<span class="text-success" />').text(I18n.t('jst.globalSettings.success')).insertAfter(this.ui.saveButton).hide().fadeIn('fast'); } else if (type == 'error') { $('<span class="text-danger" />').text(I18n.t('jst.globalSettings.error')).insertAfter(this.ui.saveButton).hide().fadeIn('fast'); } }, requestOptions: function() { return { dataType: 'json', accepts: { json: 'application/json' } }; } }); this.addAutoInitializer(function(options) { options.region.show(new SettingsForm()); }); });
@charset "utf-8"; html{ background: FloralWhite; /*background:#40A0DA; Ivory PowderBlue Lavender Azure Honeydew*/ } body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,form,fieldset,input,textarea,p,blockquote,th,td{ margin:0 auto; padding:0; } table{ border-collapse:collapse; border-spacing:0; } a{ text-decoration:none; } a:link{color: #fff;} a:visited {color: #fff;} a:hover{color: #fff;} a:active {color: #fff;} em,strong,b,u,i{ font-style:normal; font-weight:normal; } ul,ol{ list-style:none; } h1,h2,h3{ font-size:100%; font-weight:normal; } input,textarea,select{ font-family:inherit; font-size:inherit; font-weight:inherit; *font-size:100%; } input,textarea{ border:none; }
package com.glory.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Log { @Id @GeneratedValue private Long id; private Long transactionId; private String message; public Log() { } public Log(Long id, Long transactionId, String message) { super(); this.id = id; this.transactionId = transactionId; this.message = message; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTransactionId() { return transactionId; } public void setTransactionId(Long transactionId) { this.transactionId = transactionId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
::-webkit-scrollbar { width: 8px; height: 8px; } ::-<API key> { background-color: #222; } ::-<API key> { background-color: #ddd; } .no-select { user-select: none; -webkit-user-select: none; } html, body { height: 100%; margin: 0; overflow: hidden; font-family: var( --gsui-font ); background-color: var( --app-bg ); } a { color: inherit; text-decoration: none; }
<?php class BugtrackerViews { public static function build_body_view(View $view, $current_page, $bug_id = 0, $bug_type = "") { $lang = LangLoader::get_all_langs('bugtracker'); $config = BugtrackerConfig::load(); $types = $config->get_types(); $body_view = new FileTemplate('bugtracker/BugtrackerBody.tpl'); $body_view->add_lang($lang); $body_view->put_all(array( 'C_ROADMAP_ENABLED' => $config-><API key>(), 'C_STATS_ENABLED' => $config->are_stats_enabled(), 'C_DISPLAY_MENU' => in_array($current_page, array('unsolved', 'solved', 'roadmap', 'stats')), 'C_SYNDICATION' => $current_page == 'unsolved' || $current_page == 'solved', 'C_UNSOLVED' => $current_page == 'unsolved', 'C_SOLVED' => $current_page == 'solved', 'C_ROADMAP' => $current_page == 'roadmap', 'C_STATS' => $current_page == 'stats', 'L_TITLE' => $lang['bugtracker.' . $current_page] . (in_array($current_page, array('change_status', 'history', 'detail', 'edit')) ? " : " . $types[$bug_type] . ' #' .$bug_id : ''), 'TEMPLATE' => $view, '<API key>' => <API key>::rss('bugtracker', 0)->rel(), '<API key>' => <API key>::rss('bugtracker', 1)->rel() )); return $body_view; } public static function build_filters($current_page, $nbr_bugs = 0) { $lang = LangLoader::get_all_langs('bugtracker'); $object = new self(); $request = AppContext::get_request(); $page = $request->get_int('page', 1); $filter = $request->get_value('filter', ''); $filter_id = $request->get_value('filter_id', ''); if (!empty($filter) && empty($filter_id)) { $filter = $filter_id = ''; } $filters_tmp = $filters = !empty($filter) ? explode('-', $filter) : array(); $nb_filters = count($filters); $filters_ids_tmp = $filters_ids = !empty($filter_id) ? explode('-', $filter_id) : array(); $nb_filters_ids = count($filters_ids); if ($nb_filters != $nb_filters_ids) { for ($i = $nb_filters_ids; $i < $nb_filters; $i++) { $filters_ids[] = 0; } } $display_save_button = AppContext::get_current_user()->check_level(User::MEMBER_LEVEL) && count($filters) >= 1; $config = BugtrackerConfig::load(); $types = $config->get_types(); $categories = $config->get_categories(); $severities = $config->get_severities(); $versions = $config-><API key>(); $all_versions = $config->get_versions(); $display_types = count($types); $display_categories = count($categories); $display_severities = count($severities); $display_versions = count($versions); $<API key> = count($all_versions); $filters_number = 1; if ($display_types) $filters_number = $filters_number + 1; if ($display_categories) $filters_number = $filters_number + 1; if ($display_severities) $filters_number = $filters_number + 1; if ($display_versions || $<API key>) $filters_number = $filters_number + 1; if (!empty($filters)) $filters_number = $filters_number + 1; $filters_view = new FileTemplate('bugtracker/BugtrackerFilter.tpl'); $filters_view->add_lang($lang); $result = PersistenceContext::get_querier()->select("SELECT * FROM " . BugtrackerSetup::$<API key> . " WHERE page = :page AND user_id = :user_id", array( 'page' => $current_page, 'user_id' => AppContext::get_current_user()->get_id() ), SelectQueryResult::FETCH_ASSOC ); $saved_filters = false; while ($row = $result->fetch()) { $row_filters_tmp = $row_filters = !empty($row['filters']) ? explode('-', $row['filters']) : array(); $row_filters_ids_tmp = $row_filters_ids = !empty($row['filters_ids']) ? explode('-', $row['filters_ids']) : array(); sort($filters_tmp, SORT_STRING); sort($row_filters_tmp, SORT_STRING); sort($filters_ids_tmp, SORT_STRING); sort($row_filters_ids_tmp, SORT_STRING); if (implode('-', $filters_tmp) == implode('-', $row_filters_tmp) && implode('-', $filters_ids_tmp) == implode('-', $row_filters_ids_tmp)) $display_save_button = false; $<API key> = ' $filter_type_value = in_array('type', $row_filters) && $row_filters_ids[array_search('type', $row_filters)] && isset($types[$row_filters_ids[array_search('type', $row_filters)]]) ? $types[$row_filters_ids[array_search('type', $row_filters)]] : $<API key>; $<API key> = in_array('category', $row_filters) && $row_filters_ids[array_search('category', $row_filters)] && isset($categories[$row_filters_ids[array_search('category', $row_filters)]]) ? $categories[$row_filters_ids[array_search('category', $row_filters)]] : $<API key>; $<API key> = in_array('severity', $row_filters) && $row_filters_ids[array_search('severity', $row_filters)] && isset($severities[$row_filters_ids[array_search('severity', $row_filters)]]) ? $severities[$row_filters_ids[array_search('severity', $row_filters)]]['name'] : $<API key>; $filter_status_value = in_array('status', $row_filters) && $row_filters_ids[array_search('status', $row_filters)] && isset($lang['status.' . $row_filters_ids[array_search('status', $row_filters)]]) ? $lang['status.' . $row_filters_ids[array_search('status', $row_filters)]] : $<API key>; $<API key> = ($current_page == 'unsolved' ? (in_array('detected_in', $row_filters) && $row_filters_ids[array_search('detected_in', $row_filters)] && isset($versions[$row_filters_ids[array_search('detected_in', $row_filters)]]) ? $versions[$row_filters_ids[array_search('detected_in', $row_filters)]]['name'] : $<API key>) : (in_array('fixed_in', $row_filters) && $row_filters_ids[array_search('fixed_in', $row_filters)] && isset($all_versions[$row_filters_ids[array_search('fixed_in', $row_filters)]]) ? $all_versions[$row_filters_ids[array_search('fixed_in', $row_filters)]]['name'] : $<API key>)); $filters_view->assign_block_vars('filters', array( 'ID' => $row['id'], 'FILTER' => '| ' . $filter_type_value . ' | ' . $<API key> . ' | ' . $<API key> . ' | ' . $filter_status_value . ' | ' . $<API key> . ' |', 'LINK_FILTER' => ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, $row['filters'], $row['filters_ids'])->rel() : <API key>::solved('name', 'desc', 1, $row['filters'], $row['filters_ids'])->rel()), )); $saved_filters = true; } $result->dispose(); $filters_view->put_all(array( 'C_SEVERAL_FILTERS' => $filters_number > 1, 'C_DISPLAY_TYPES' => $display_types, '<API key>' => $display_categories, '<API key>' => $display_severities, 'C_DISPLAY_VERSIONS' => $current_page == 'solved' ? $<API key> : $display_versions, '<API key>' => $display_save_button, 'C_SAVED_FILTERS' => $saved_filters, '<API key>'=> $filters, 'FILTERS_NUMBER' => $filters_number, 'BUGS_NUMBER' => $nbr_bugs, 'LINK_FILTER_SAVE' => <API key>::add_filter($current_page, $filter, $filter_id)->rel(), 'SELECT_TYPE' => $object->build_types_form($current_page,($filter == 'type') ? $filter_id : (in_array('type', $filters) ? $filters_ids[array_search('type', $filters)] : 0), $filters, $filters_ids)->display(), 'SELECT_CATEGORY' => $object-><API key>($current_page, ($filter == 'category') ? $filter_id : (in_array('category', $filters) ? $filters_ids[array_search('category', $filters)] : 0), $filters, $filters_ids)->display(), 'SELECT_SEVERITY' => $object-><API key>($current_page, ($filter == 'severity') ? $filter_id : (in_array('severity', $filters) ? $filters_ids[array_search('severity', $filters)] : 0), $filters, $filters_ids)->display(), 'SELECT_STATUS' => $object->build_status_form($current_page, ($filter == 'status') ? $filter_id : (in_array('status', $filters) ? $filters_ids[array_search('status', $filters)] : 0), $filters, $filters_ids, $lang)->display(), 'SELECT_VERSION' => $object->build_versions_form($current_page, ($current_page == 'unsolved' ? (($filter == 'detected_in') ? $filter_id : (in_array('detected_in', $filters) ? $filters_ids[array_search('detected_in', $filters)] : 0)) : (($filter == 'fixed_in') ? $filter_id : (in_array('fixed_in', $filters) ? $filters_ids[array_search('fixed_in', $filters)] : 0))), $filters, $filters_ids)->display(), )); return $filters_view; } public static function build_legend($list, $current_page) { $lang = LangLoader::get_all_langs('bugtracker'); $config = BugtrackerConfig::load(); $severities = $config->get_severities(); $legend_view = new FileTemplate('bugtracker/BugtrackerLegend.tpl'); $legend_view->add_lang($lang); $legend_colspan = 0; foreach ($list as $element) { if (($current_page == 'solved') || (!empty($element) && isset($severities[$element]))) { $legend_view->assign_block_vars('legend', array( 'COLOR' => $current_page == 'solved' ? ($element == 'fixed' ? $config->get_fixed_bug_color() : $config-><API key>()) : stripslashes($severities[$element]['color']), 'NAME' => $current_page == 'solved' ? $lang['status.' . $element] : stripslashes($severities[$element]['name']) )); $legend_colspan = $legend_colspan + 3; } } $legend_view->put_all(array( 'LEGEND_COLSPAN' => $legend_colspan )); return ($legend_colspan ? $legend_view : new StringTemplate('')); } private function build_types_form($current_page, $requested_type, $filters, $filters_ids) { if (in_array('type', $filters)) { $key = array_search('type', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('type-form', '', false); $fieldset = new <API key>('filter-type'); $form->add_fieldset($fieldset); $fieldset->add_field(new <API key>('filter_type', '', $requested_type, $this->build_select_types(), array( 'events' => array('change' => ' if (HTMLForms.getField("filter_type").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'type', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : <API key>::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'type', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_type").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : <API key>::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }' ) ) )); return $form; } private function build_select_types() { $types = BugtrackerConfig::load()->get_types(); $array_types = array(); $array_types[] = new <API key>('&nbsp;', 0); foreach ($types as $key => $type) { $array_types[] = new <API key>(stripslashes($type), $key); } return $array_types; } private function <API key>($current_page, $requested_category, $filters, $filters_ids) { if (in_array('category', $filters)) { $key = array_search('category', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('category-form', '', false); $fieldset = new <API key>('filter-category'); $form->add_fieldset($fieldset); $fieldset->add_field(new <API key>('filter_category', '', $requested_category, $this-><API key>(), array('events' => array('change' => 'if (HTMLForms.getField("filter_category").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'category', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : <API key>::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'category', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_category").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : <API key>::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function <API key>() { $categories = BugtrackerConfig::load()->get_categories(); $array_categories = array(); $array_categories[] = new <API key>('&nbsp;', 0); foreach ($categories as $key => $category) { $array_categories[] = new <API key>(stripslashes($category), $key); } return $array_categories; } private function <API key>($current_page, $requested_severity, $filters, $filters_ids) { if (in_array('severity', $filters)) { $key = array_search('severity', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('severity-form', '', false); $fieldset = new <API key>('filter-severity'); $form->add_fieldset($fieldset); $fieldset->add_field(new <API key>('filter_severity', '', $requested_severity, $this-><API key>(), array('events' => array('change' => 'if (HTMLForms.getField("filter_severity").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'severity', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : <API key>::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'severity', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_severity").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : <API key>::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function <API key>() { $severities = BugtrackerConfig::load()->get_severities(); $array_categories = array(); $array_severities[] = new <API key>('&nbsp;', 0); foreach ($severities as $key => $severity) { $array_severities[] = new <API key>(stripslashes($severity['name']), $key); } return $array_severities; } private function build_status_form($current_page, $requested_status, $filters, $filters_ids, $lang) { if (in_array('status', $filters)) { $key = array_search('status', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('status-form', '', false); $fieldset = new <API key>('filter-status'); $form->add_fieldset($fieldset); $fieldset->add_field(new <API key>('filter_status', '', $requested_status, $this->build_select_status($current_page, $lang), array('events' => array('change' => 'if (HTMLForms.getField("filter_status").getValue()) { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'status', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : <API key>::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'status', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_status").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : <API key>::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function build_select_status($current_page, $lang) { $status_list = BugtrackerConfig::load()->get_status_list(); $array_status = array(); $array_status[] = new <API key>('&nbsp;', ''); foreach ($status_list as $status => $progress) { if (($current_page == 'unsolved' && !in_array($status, array(BugtrackerItem::FIXED, BugtrackerItem::REJECTED))) || ($current_page == 'solved' && in_array($status, array(BugtrackerItem::FIXED, BugtrackerItem::REJECTED)))) $array_status[] = new <API key>($lang['status.' . $status], $status); } return $array_status; } private function build_versions_form($current_page, $requested_version, $filters, $filters_ids) { $search_field = ($current_page == 'unsolved' ? 'detected_in' : 'fixed_in'); if (in_array($search_field , $filters)) { $key = array_search($search_field , $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('version-form', '', false); $fieldset = new <API key>('filter-version'); $form->add_fieldset($fieldset); $fieldset->add_field(new <API key>('filter_version', '', $requested_version, $this-><API key>($current_page), array('events' => array('change' => 'if (HTMLForms.getField("filter_version").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'detected_in', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : <API key>::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'fixed_in', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_version").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? <API key>::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : <API key>::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function <API key>($current_page) { $versions = ($current_page == 'unsolved' ? BugtrackerConfig::load()-><API key>() : BugtrackerConfig::load()->get_versions()); $versions = array_reverse($versions, true); $array_versions = array(); $array_versions[] = new <API key>('&nbsp;', ''); foreach ($versions as $key => $version) { $array_versions[] = new <API key>(stripslashes($version['name']), $key); } return $array_versions; } } ?>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public class Class1 { } }
package l2s.gameserver.network.l2.s2c; import java.util.ArrayList; import java.util.Collections; import java.util.List; import l2s.commons.lang.ArrayUtils; import l2s.gameserver.model.Player; import l2s.gameserver.model.items.ItemInfo; import l2s.gameserver.model.items.ItemInstance; import l2s.gameserver.model.items.Warehouse.ItemClassComparator; import l2s.gameserver.model.items.Warehouse.WarehouseType; public class <API key> extends L2GameServerPacket { private long _adena; private List<ItemInfo> _itemList = new ArrayList<ItemInfo>(); private int _type; private int _inventoryUsedSlots; public <API key>(Player player, WarehouseType type) { _adena = player.getAdena(); _type = type.ordinal(); ItemInstance[] items; switch(type) { case PRIVATE: items = player.getWarehouse().getItems(); break; case FREIGHT: items = player.getFreight().getItems(); break; case CLAN: case CASTLE: items = player.getClan().getWarehouse().getItems(); break; default: _itemList = Collections.emptyList(); return; } _itemList = new ArrayList<ItemInfo>(items.length); ArrayUtils.eqSort(items, ItemClassComparator.getInstance()); for(ItemInstance item : items) _itemList.add(new ItemInfo(item)); _inventoryUsedSlots = player.getInventory().getSize(); } @Override protected final void writeImpl() { writeH(_type); writeQ(_adena); writeH(_itemList.size()); if(_type == 1 || _type == 2) { if(_itemList.size() > 0) { writeH(0x01); writeD(0x1063); } else writeH(0x00); } writeD(_inventoryUsedSlots); for(ItemInfo item : _itemList) { writeItemInfo(item); writeD(item.getObjectId()); writeD(0); writeD(0); } } }
# -*- coding: utf-8 -*- from django.contrib import admin from models import FileMapping # Register your models here. admin.site.register(FileMapping)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Aviso de Privacidad</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Cinzel:400,700" rel="stylesheet" type="text/css"> <!-- Theme CSS --> <link href="css/creative.min.css" rel="stylesheet"> <!-- Pagina Inicial CSS --> <link href="css/pagina-inicial.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif] </head> <body id="page-top"> <!-- Navegacion inicia --> <nav id="mainNav" class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#<API key>"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="index.html">La Caja Blanca</a> </div> <div class="collapse navbar-collapse" id="<API key>"> <ul class="nav navbar-nav navbar-right"> <li> <a class="page-scroll" href="index.html </li> <li> <a class="page-scroll" href="index.html#contact">Contacto</a> </li> <li> <a class="page-scroll" href="#">Aviso de Privacidad</a> </li> <li> <a class="page-scroll" href="<API key>.html">Términos y Condiciones</a> </li> </ul> </div> </div> </nav> <!-- Navegacion termina --> <!-- Aviso inicia --> <section id="aviso"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h2 class="section-heading">Aviso de Privacidad</h2> <hr class="primary"> </div> <div class="col-lg-8 aviso-privacidad"> <p>Nemosíntesis SC de RL, mejor conocido como La Caja Blanca, con domicilio en calle Río de la Plata 209, colonia Navarro, ciudad Torreón, municipio o delegación Torreón, C.P. 27010, en la entidad de Coahuila, país México, y portal de internet www.lacajablanca.mx, es el responsable del uso y protección de sus datos personales, y al respecto le informamos lo siguiente:</p> <p>¿Para qué fines utilizaremos sus datos personales?</p> <p>Los datos personales que recabamos de usted, los utilizaremos para las siguientes finalidades que son necesarias para el servicio que solicita:</p> <ul> <li>Para verificar y confirmar su identidad</li> <li>Para entrega de productos a domicilio</li> <li>Para llevar a cabo encuestas de satisfacción</li> <li>Para informarle y/o contactarle con fines mercadológicos</li> <li>Para evaluar la calidad de los productos</li> </ul> <p>De manera adicional, utilizaremos su información personal para las siguientes <b>finalidades secundarias</b> que no son necesarias para el servicio solicitado, pero que nos permiten y facilitan brindarle una mejor atención:</p> <ul> <li>Mercadotecnia o publicidad</li> <li>Prospección comercial</li> </ul> <p>En caso de que no desee que sus datos personales se utilicen para estos <b>fines secundarios</b>, indíquelo por medio de un correo electrónico a sitiodelacaja@gmail.com con el mensaje:</p> <blockquote> No consiento que mis datos personales se utilicen para los fines de Mercadotecnia, publicidad o prospección comercial </blockquote> <p>La negativa para el uso de sus datos personales para estas finalidades no podrá ser un motivo para que le neguemos los servicios y productos que solicita o contrata con nosotros.</p> <p>¿Qué datos personales utilizaremos para estos fines?</p> Para llevar a cabo las finalidades descritas en el presente aviso de privacidad, utilizaremos los siguientes datos personales: <ul> <li>Nombre</li> <li>Nombre de su pareja o cónyuge</li> <li>Estado Civil</li> <li>Fecha de nacimiento</li> <li>Fecha de matrimonio civil</li> <li>Domicilio</li> <li>Teléfono particular</li> <li>Teléfono celular</li> <li> Correo electrónico</li> </ul> <p>¿Con quién compartimos su información personal y para qué fines?</p> <p>Le informamos que sus datos personales son compartidos dentro del país con empresas dedicadas al servicio de paquetería con la finalidad de hacer llegar los productos a su domicilio.</p> <p>¿Cómo puede acceder, rectificar o cancelar sus datos personales, u oponerse a su uso?</p> <p>Usted tiene derecho a conocer qué datos personales tenemos de usted, para qué los utilizamos y las condiciones del uso que les damos (Acceso). Asimismo, es su derecho solicitar la corrección de su información personal en caso de que esté desactualizada, sea inexacta o incompleta (Rectificación); que la eliminemos de nuestros registros o bases de datos cuando considere que la misma no está siendo utilizada adecuadamente (Cancelación); así como oponerse al uso de sus datos personales para fines específicos (Oposición). Estos derechos se conocen como derechos ARCO.</p> <p>Para el ejercicio de cualquiera de los derechos ARCO, usted deberá presentar la solicitud respectiva enviando un correo electrónico a sitiodelacaja@gmail.com</p> <p>Para conocer el procedimiento y requisitos para el ejercicio de los derechos ARCO, ponemos a su disposición el siguiente medio: www.lacajablanca.mx/aviso-privacidad.html</p> <p>Los datos de contacto de la persona o departamento de datos personales, que está a cargo de dar trámite a las solicitudes de derechos ARCO, son los siguientes:</p> <p> a) Nombre de la persona o departamento de datos personales: Atención a Clientes La Caja Blanca<br> b) Domicilio: Calle Río de la Plata 2019, Colonia Navarro, Ciudad Torreón, C.P. 27010<br> c) Correo electrónico: sitiodelacaja@gmail.com<br> d) Número telefónico: 8717179849<br></p> <p>Usted puede revocar el consentimiento que, en su caso, nos haya otorgado para el tratamiento de sus datos personales. Sin embargo, es importante que tenga en cuenta que no en todos los casos podremos atender su solicitud o concluir el uso de forma inmediata, ya que es posible que por alguna obligación legal requiramos seguir tratando sus datos personales. Asimismo, usted deberá considerar que para ciertos fines, la revocación de su consentimiento implicará que no le podamos seguir prestando el servicio que nos solicitó, o la conclusión de su relación con nosotros.</p> <p>Para revocar su consentimiento deberá presentar su solicitud a través del siguiente medio: sitiodelacaja@gmail.com</p> <p>Para conocer el procedimiento y requisitos para la revocación del consentimiento, ponemos a su disposición el siguiente medio: www.lacajablanca.mx/aviso-privacidad.html</p> <p>¿Cómo puede limitar el uso o divulgación de su información personal? <p>Con objeto de que usted pueda limitar el uso y divulgación de su información personal, le ofrecemos los siguientes medios: sitiodelacaja@gmail.com</p> <p>Asimismo, usted se podrá inscribir a los siguientes registros, en caso de que no desee obtener publicidad de nuestra parte:</p> <p>Registro Público para Evitar Publicidad, para mayor información consulte el portal de internet de la <a href="https: Registro Público de Usuarios, para mayor información consulte el portal de internet de la <a href="https: <p>¿Cómo puede conocer los cambios en este aviso de privacidad?</p> <p>El presente aviso de privacidad puede sufrir modificaciones, cambios o actualizaciones derivadas de nuevos requerimientos legals; de nuestras propias necesidades por los productos o servicios que ofrecemos; de nuestras prácticas de privacidad; de cambios en nuestro modelo de negocio, o por otras causas. Nos comprometemos a mantenerlo informado sobre los cambios que pueda sufrir el presente aviso de privacidad, a través de: www.lacajablanca.mx.</p> <p>El procedimiento a través del cual se llevarán a cabo las notificaciones sobre cambios o actualizaciones al presente aviso de privacidad es el siguiente: a través de la página de internet www.lacajablanca.mx</p> <p>Última actualización: 22/08/2017</p> </div> </div> </div> </section> <!-- Aviso termina --> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Theme JavaScript --> <script src="js/creative.min.js"></script> </body> </html>
<?php namespace BoldtWebservice\Component\BwPostman\Administrator\Field; defined('JPATH_PLATFORM') or die; use BoldtWebservice\Component\BwPostman\Administrator\Helper\BwPostmanHelper; use Exception; use Joomla\CMS\Factory; use Joomla\CMS\Form\Field\RadioField; use Joomla\CMS\Language\Text; use Joomla\CMS\Uri\Uri; use RuntimeException; /** * Form Field class for the Joomla Platform. * Supports a nested check box field listing user groups. * Multi select is available by default. * * @package BwPostman.Administrator * * @since 1.2.0 */ class TexttemplatesField extends RadioField { /** * The form field type. * * @var string * * @since 1.2.0 */ protected $type = 'Texttemplates'; /** * Method to get the Text template field input markup. * * @return string The field input markup. * * @throws Exception * * @since 1.2.0 */ protected function getInput(): string { $item = Factory::getApplication()->getUserState('com_bwpostman.edit.newsletter.data'); $html = array(); $selected = ''; // Initialize some field attributes. $readonly = $this->readonly; // Get the field options. $options = $this->getOptions(); // Get selected template. if (is_object($item)) { $selected = $item->text_template_id; } // note for old templates if ($selected < 1) { $html[] = Text::_('<API key>'); } if (count($options) > 0) { // Build the radio field output. foreach ($options as $i => $option) { // Initialize some option attributes. $checked = ((string) $option->value == (string) $selected) ? ' checked="checked"' : ''; $lblclass = ' class="mailinglists form-check-label"'; $inputclass = ' class="mailinglists form-check-input"'; $disabled = !empty($option->disable) || ($readonly && !$checked); $disabled = $disabled ? ' disabled' : ''; // Initialize some JavaScript option attributes. $onclick = !empty($option->onclick) ? ' onclick="' . $option->onclick . '"' : ''; $onchange = !empty($option->onchange) ? ' onchange="' . $option->onchange . '"' : ''; $html[] = '<div class="form-check" aria-describedby="tip-' . $this->id . $i . '">'; $html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="' . htmlspecialchars($option->value, ENT_COMPAT) . '"' . $checked . $inputclass . $onclick . $onchange . $disabled . ' />'; $html[] = '<label for="' . $this->id . $i . '"' . $lblclass . ' >'; $html[] = $option->title . '</label>'; $tooltip = '<strong>' . $option->description . '</strong><br /><br />' . '<div><img src="' . Uri::root() . $option->thumbnail . '" alt="' . $option->title . '"' .'style="max-width:160px; max-height:100px;" /></div>'; $html[] = '<div role="tooltip" id="tip-' . $this->id . $i . '">'.$tooltip.'</div>'; $html[] = '</div>'; } } else { $html[] = Text::_('<API key>'); } // End the radio field output. // $html[] = '</div>'; return implode($html); } /** * Method to get the field options. * * @return array The field option objects. * * @throws Exception * * @since 1.2.0 */ public function getOptions(): array { $app = Factory::getApplication(); // Initialize variables. $item = $app->getUserState('com_bwpostman.edit.newsletter.data'); $options = array(); // prepare query $db = BwPostmanHelper::getDbo(); // Build the select list for the templates $query = $db->getQuery(true); $query->select($db->quoteName('id') . ' AS ' . $db->quoteName('value')); $query->select($db->quoteName('title') . ' AS ' . $db->quoteName('title')); $query->select($db->quoteName('description') . ' AS ' . $db->quoteName('description')); $query->select($db->quoteName('thumbnail') . ' AS ' . $db->quoteName('thumbnail')); $query->from($db->quoteName('#<API key>')); // special for old newsletters with template_id < 1 if (is_object($item)) { if ($item->text_template_id < 1 && !is_null($item->text_template_id)) { $query->where($db->quoteName('id') . ' >= ' . $db->quote('-2')); } else { $query->where($db->quoteName('id') . ' > ' . $db->quote('0')); } } $query->where($db->quoteName('archive_flag') . ' = ' . $db->quote('0')); $query->where($db->quoteName('published') . ' = ' . $db->quote('1')); $query->where($db->quoteName('tpl_id') . ' > ' . $db->quote('997')); $query->order($db->quoteName('title') . ' ASC'); try { $db->setQuery($query); $options = $db->loadObjectList(); } catch (RuntimeException $e) { Factory::getApplication()->enqueueMessage($e->getMessage(), 'error'); } // Merge any additional options in the XML definition. return array_merge(parent::getOptions(), $options); } }
#ifndef __BACKTRACE_H__ #define __BACKTRACE_H__ #include <stdint.h> void __backtrace(uintptr_t rbp, uintptr_t stack_begin, uintptr_t stack_end); uintptr_t stack_begin(void); uintptr_t stack_end(void); void backtrace(void); #endif /*__BACKTRACE_H__*/
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Mon Jun 20 18:37:10 EEST 2016 --> <title>SimplePrintPart (JasperReports 6.3.0 API)</title> <meta name="date" content="2016-06-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SimplePrintPart (JasperReports 6.3.0 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SimplePrintPart.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/<API key>.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/SimpleReportContext.html" title="class in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/SimplePrintPart.html" target="_top">Frames</a></li> <li><a href="SimplePrintPart.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <div class="subTitle">net.sf.jasperreports.engine</div> <h2 title="Class SimplePrintPart" class="title">Class SimplePrintPart</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>net.sf.jasperreports.engine.SimplePrintPart</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, <a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">SimplePrintPart</span> extends java.lang.Object implements <a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a>, java.io.Serializable</pre> <dl><dt><span class="strong">Author:</span></dt> <dd>Teodor Danciu (teodord@users.sourceforge.net)</dd> <dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#net.sf.jasperreports.engine.SimplePrintPart">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#SimplePrintPart()">SimplePrintPart</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_summary"> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html" title="class in net.sf.jasperreports.engine">SimplePrintPart</a></code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#fromJasperPrint(net.sf.jasperreports.engine.JasperPrint,%20java.lang.String)">fromJasperPrint</a></strong>(<a href="../../../../net/sf/jasperreports/engine/JasperPrint.html" title="class in net.sf.jasperreports.engine">JasperPrint</a>&nbsp;partJasperPrint, java.lang.String&nbsp;partName)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#getName()">getName</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a></code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#getPageFormat()">getPageFormat</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#setName(java.lang.String)">setName</a></strong>(java.lang.String&nbsp;name)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#setPageFormat(net.sf.jasperreports.engine.PrintPageFormat)">setPageFormat</a></strong>(<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a>&nbsp;pageFormat)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="<API key>.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> </a> <h3>Constructor Detail</h3> <a name="SimplePrintPart()"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>SimplePrintPart</h4> <pre>public&nbsp;SimplePrintPart()</pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_detail"> </a> <h3>Method Detail</h3> <a name="fromJasperPrint(net.sf.jasperreports.engine.JasperPrint, java.lang.String)"> </a> <ul class="blockList"> <li class="blockList"> <h4>fromJasperPrint</h4> <pre>public static&nbsp;<a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html" title="class in net.sf.jasperreports.engine">SimplePrintPart</a>&nbsp;fromJasperPrint(<a href="../../../../net/sf/jasperreports/engine/JasperPrint.html" title="class in net.sf.jasperreports.engine">JasperPrint</a>&nbsp;partJasperPrint, java.lang.String&nbsp;partName)</pre> </li> </ul> <a name="getName()"> </a> <ul class="blockList"> <li class="blockList"> <h4>getName</h4> <pre>public&nbsp;java.lang.String&nbsp;getName()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html#getName()">getName</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></code></dd> </dl> </li> </ul> <a name="setName(java.lang.String)"> </a> <ul class="blockList"> <li class="blockList"> <h4>setName</h4> <pre>public&nbsp;void&nbsp;setName(java.lang.String&nbsp;name)</pre> </li> </ul> <a name="getPageFormat()"> </a> <ul class="blockList"> <li class="blockList"> <h4>getPageFormat</h4> <pre>public&nbsp;<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a>&nbsp;getPageFormat()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html#getPageFormat()">getPageFormat</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></code></dd> </dl> </li> </ul> <a name="setPageFormat(net.sf.jasperreports.engine.PrintPageFormat)"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setPageFormat</h4> <pre>public&nbsp;void&nbsp;setPageFormat(<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a>&nbsp;pageFormat)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SimplePrintPart.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/<API key>.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/SimpleReportContext.html" title="class in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/SimplePrintPart.html" target="_top">Frames</a></li> <li><a href="SimplePrintPart.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color: </small></p> </body> </html>
#include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[3]; atomic_int atom_0_r3_2; atomic_int atom_1_r1_1; void *t0(void *arg){ label_1:; <API key>(&vars[0], 2, <API key>); int v2_r3 = <API key>(&vars[0], <API key>); int v3_r4 = v2_r3 ^ v2_r3; <API key>(&vars[1+v3_r4], 1, <API key>); <API key>(&vars[2], 1, <API key>); int v14 = (v2_r3 == 2); <API key>(&atom_0_r3_2, v14, <API key>); return NULL; } void *t1(void *arg){ label_2:; int v5_r1 = <API key>(&vars[2], <API key>); int v6_r3 = v5_r1 ^ v5_r1; int v7_r3 = v6_r3 + 1; <API key>(&vars[0], v7_r3, <API key>); int v15 = (v5_r1 == 1); <API key>(&atom_1_r1_1, v15, <API key>); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[0], 0); atomic_init(&vars[2], 0); atomic_init(&vars[1], 0); atomic_init(&atom_0_r3_2, 0); atomic_init(&atom_1_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v8 = <API key>(&atom_0_r3_2, <API key>); int v9 = <API key>(&vars[0], <API key>); int v10 = (v9 == 2); int v11 = <API key>(&atom_1_r1_1, <API key>); int v12_conj = v10 & v11; int v13_conj = v8 & v12_conj; if (v13_conj == 1) assert(0); return 0; }
<?php namespace App\Model\Table; use App\Model\Entity\Guest; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; /** * Guests Model * * @property \Cake\ORM\Association\BelongsTo $Matchteams * @property \Cake\ORM\Association\BelongsToMany $Hosts */ class GuestsTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config) { parent::initialize($config); $this->table('guests'); $this->displayField('name'); $this->primaryKey('id'); $this->belongsTo('Matchteams', [ 'foreignKey' => 'matchteam_id' ]); $this->belongsToMany('Hosts', [ 'foreignKey' => 'guest_id', 'targetForeignKey' => 'host_id', 'joinTable' => 'hosts_guests' ]); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator) { $validator ->add('id', 'valid', ['rule' => 'numeric']) ->allowEmpty('id', 'create'); $validator ->add('primary_squad', 'valid', ['rule' => 'boolean']) ->allowEmpty('primary_squad'); $validator ->allowEmpty('name'); $validator ->allowEmpty('yellow'); $validator ->allowEmpty('red'); $validator ->allowEmpty('substitution'); $validator ->allowEmpty('goals'); $validator ->allowEmpty('rating'); $validator ->allowEmpty('assist'); $validator ->allowEmpty('injuries'); return $validator; } /** * Returns a rules checker object that will be used for validating * application integrity. * * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules) { $rules->add($rules->existsIn(['matchteam_id'], 'Matchteams')); return $rules; } }
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the require_once('../../config.php'); require_once($CFG->dirroot.'/mod/scorm/locallib.php'); $id = optional_param('id', '', PARAM_INT); // Course Module ID, or $a = optional_param('a', '', PARAM_INT); // scorm ID $scoid = required_param('scoid', PARAM_INT); // sco ID $attempt = required_param('attempt', PARAM_INT); // attempt number if (!empty($id)) { if (! $cm = <API key>('scorm', $id)) { print_error('invalidcoursemodule'); } if (! $course = $DB->get_record("course", array("id"=>$cm->course))) { print_error('coursemisconf'); } if (! $scorm = $DB->get_record("scorm", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } } else if (!empty($a)) { if (! $scorm = $DB->get_record("scorm", array("id"=>$a))) { print_error('invalidcoursemodule'); } if (! $course = $DB->get_record("course", array("id"=>$scorm->course))) { print_error('coursemisconf'); } if (! $cm = <API key>("scorm", $scorm->id, $course->id)) { print_error('invalidcoursemodule'); } } else { print_error('missingparameter'); } $PAGE->set_url('/mod/scorm/datamodel.php', array('scoid'=>$scoid, 'attempt'=>$attempt, 'id'=>$cm->id)); require_login($course, false, $cm); if (confirm_sesskey() && (!empty($scoid))) { $result = true; $request = null; if (has_capability('mod/scorm:savetrack', context_module::instance($cm->id))) { foreach (data_submitted() as $element => $value) { $element = str_replace('__', '.', $element); if (substr($element, 0, 3) == 'cmi') { $netelement = preg_replace('/\.N(\d+)\./', "\.\$1\.", $element); $result = scorm_insert_track($USER->id, $scorm->id, $scoid, $attempt, $element, $value, $scorm->forcecompleted) && $result; } if (substr($element, 0, 15) == 'adl.nav.request') { // SCORM 2004 Sequencing Request require_once($CFG->dirroot.'/mod/scorm/datamodels/scorm_13lib.php'); $search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@', '@exit@', '@exitAll@', '@abandon@', '@abandonAll@'); $replace = array('continue_', 'previous_', '\1', 'exit_', 'exitall_', 'abandon_', 'abandonall'); $action = preg_replace($search, $replace, $value); if ($action != $value) { // Evaluating navigation request $valid = scorm_seq_overall ($scoid, $USER->id, $action, $attempt); $valid = 'true'; // Set valid request $search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@'); $replace = array('true', 'true', 'true'); $matched = preg_replace($search, $replace, $value); if ($matched == 'true') { $request = 'adl.nav.request_valid["'.$action.'"] = "'.$valid.'";'; } } } } } if ($result) { echo "true\n0"; } else { echo "false\n101"; } if ($request != null) { echo "\n".$request; } }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Richard Benson In Memory</title> <link rel="stylesheet" href="build/benson.css"> <script type="text/javascript" src="../../node_modules/jquery/dist/jquery.js"></script> <script type="text/javascript" src="../../node_modules/materialize-css/dist/js/materialize.js"></script> </head> <body> <div id="all"> <nav> <a href="../Home/"> <div id="brand"> <img src="../Logo.png" alt="Yale School of Art" id="logo"> <h1>Yale School of Art</h1> </div> </a> <div class="menu-list"> <div class="menu-item"> <div class="sub-items-trigger">Academic</div> <ul class="sub-items"> <li><a href="../Calendar">Calendar</a></li> <li><a href="http://art.yale.edu/Courses">Courses</a></li> <li><a href="http://art.yale.edu/StudyAreas">Study Area</a></li> <li><a href="http://art.yale.edu/SummerPrograms">Summer Programs</a></li> <li><a href="http://art.yale.edu/gallery">Gallery</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">Admission</div> <ul class="sub-items"> <li><a href="http://art.yale.edu/Admissions">General</a></li> <li><a href="http://art.yale.edu/FinancialAid">Financial Aid</a></li> <li><a href="http://art.yale.edu/Visiting">Visiting</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">Events</div> <ul class="sub-items"> <li><a href="../Events/112days.html">112 Days in New Heaven</a></li> <li><a href="../Events/1971life.html">Life of Color</a></li> <li><a href="../Events/benson.html">Richard Benson</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">People</div> <ul class="sub-items"> <li><a href="http://art.yale.edu/Alums">Alums</a></li> <li><a href="http://art.yale.edu/CurrentStudents">Current Students</a></li> <li><a href="http://art.yale.edu/FacultyAndStaff">Faculty</a></li> <li><a href="http://art.yale.edu/undergraduate">Undergrads</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">About</div> <ul class="sub-items"> <li><a href="http://art.yale.edu/AboutThisSite">This Site</a></li> <li><a href="http://art.yale.edu/RecentChanges">Recent Changes</a></li> <li><a href="../Contact">Contact</a></li> </ul> </div> </div> </nav> <div class="section" id="content"> <div class="header"> <img src="memory.png" alt="good looking professor" id="prof-photo"> <h1>Richard Benson In Memory 1943 - 2017</h1> </div> <div class="articles"> <div class="article"> <h2>A Letter from Dean Marta Kuzma</h2> <p>Dear Members of the Yale School of Art Community,</p> <p>It is with sincere regret that I must inform you of the death of Richard Benson—a renowned authority on the history of photographic printing, an American photographer, an author, a former Yale University professor, and Dean of the Yale School of Art from 1996 to 2006. I hadn’t the opportunity to get to know my predecessor, although one does not need to look far to understand his immense contribution to the field of photography. Some years ago, The Guardian’s literary editor Liz Jobey aptly wrote:</p> <p>“A long time ago I read a New Yorker profile of a master photographic printer called Richard Benson. It was titled, with that deliberate matter-of-factness that New Yorker titles invariably have, ‘A single person making a single thing’. This man was a unique craftsman, who great photographers and great institutions turned to when they wanted their pictures printed better than ever before. He had printed photographs by Alfred Stieglitz, Paul Strand and Lee Friedlander, as well as three volumes of the works of great French photographer Eugène Atget for the Museum of Modern Art. He had made an unsurpassed volume of prints for the collector Howard Gilman, whose collection is now part of the Metropolitan Museum of Art in New York. And in 1986 Benson had been awarded a MacArthur Foundation grant worth nearly quarter of a million dollars to carry on doing what he did so well.”</p> <p>As a testimony to the series of lectures he had given at the Yale School of Art over a period of three decades, Richard Benson, more commonly known among friends as “Chip” co-curated with Peter Galassi an exhibition at New York’s MoMA in 2008 called “The Printed Picture.” The exhibition and accompanying book reflected Benson’s perspective on the evolution of the printed still image and traced the changing technology of making and distributing pictures from the Renaissance to the present. He was the recipient of numerous honors including two publication grants from the National Endowment of the Arts; two Guggenheim fellowships; the Rhode Island Governor’s Medal for the Arts; and a MacArthur Foundation fellowship. His work—located within the permanent collections of the Metropolitan Museum; New York’s MoMA; the Nelson-Atkins Museum of Art in Kansas City, Missouri; and the Yale University Art Gallery in New Haven; among others.</p> <p>Upon his retirement from Yale, the acclaimed photographer and Yale School of Art Professor Emeritus Tod Papageorge noted in his Tribute to Richard Benson, “He’s a special kind, the sort that reminds us that the words genius and genial share a common root. For who here doesn’t understand that Benson’s great good nature is at the core of his ability to accomplish so much in so many different ways?” Tod has written another tribute in memory of Chip, which you can read on the School of Art website by clicking here .</p> <p>I expect there are so many who would wish to express their sincere condolences and also to reflect upon Chip Benson as a friend, teacher, and dean. We ask that you kindly send your thoughts to the School of Art so that we may gather these respects in celebration of Richard Benson and share them with our community in the coming weeks.</p> With respectful wishes,<br> Marta Kuzma Dean Yale School of Art New Haven </div> <div class="article"> <h2>RICHARD BENSON: IN MEMORIAM</h2> <p>Richard Benson was born and raised in the seacoast town of Newport, Rhode Island, the third and youngest son of a Quaker mother and an ardent Catholic father. As a boy, he was so happy in his skin that his mother called him her “little ray of sunshine”; later on, befitting a child whose father was a stonecutter, she and nearly everyone else came to call him “Chip.”</p> <p>His father, John Howard Benson, considered the greatest calligrapher and stone-letterer of his time, died when Chip was twelve. The year before, W. K. Wimsatt, a chess partner of Benson’s and a legendary English professor at Yale, successfully championed his dying friend for an honorary degree at the university, joining, for the first time, the Benson name and the school. This, however, had no observable effect on Chip, who, left with only a few sharp memories of his father, and thereby insulated from having to measure his life against that of an extraordinary man, gave up his education after one semester at Brown, explaining to Brown’s president—another friend of John Howard Benson’s—that he was leaving the school so that he could work with his hands. (It’s worth adding that Richard was directed from the president’s office to the dean of students for his send-off, which, in its entirety, consisted of the dean reading to him the first chapter of Moby Dick.)</p> <p>From Providence, he took a crooked course for himself, moving on from the Navy to a minimum-wage job in a Connecticut printing plant and then an unparalleled career back in Newport as a photographer, master printer, and inventor of radical new techniques of photographic reproduction. Only after all of that did he himself cross paths with Yale, first as a great teacher in the Department of Photography and, fifteen years later, as an admired dean of the School of Art, before retiring in 2011 to pursue whatever interests attracted the sharp edge of his curiosity.</p> <p>In 1986, Richard was awarded a grant from the MacArthur Foundation, an achievement characterized in the popular press as the “genius” award. In his case, the description was appropriate, as anyone who was exposed to the range and depth of his understanding about any number of things, including, of course, photography—or sailing ships or electricity or hydraulics—would testify. But, to my mind, Richard more nearly demonstrated through his life and actions that “genius” shares a common root with the word “genial,” the subject I feel myself pressed to write about here. For his great, good nature was at the core of his ability to accomplish so much in so many different ways, and to earn effortlessly the admiration and love of so many people. After all, who can resist loving the person who, out of hand, has just offered to help by giving over his time and knowledge in response to an earnest, or even casual, request? And, moreover, a person who, it turns out, will give more greatly the more he’s asked to, as if, like the sun, he trusts his own energy will grow as its excess burns away serving others.</p> <p>We’ve recently learned that, put crudely, the more a person gives, the happier, or better, he or she will feel, a truth that’s now been traced in the workings of the brain. Richard Benson demonstrated that bit of science in how he lived, although, in his case, it appeared that feeling good, his natural state, directed his doing good, rather than the other way around. And, perhaps because of this difference, his mode and range of doing good, at least to me, seemed virtually Olympian, by being so outsized and barely earthbound (although, like the sailor he was, the man himself cantered his way bow-legged through the world). For as his students and friends all recognized, there was something large and unprecedented in his willingness to shower his energy and brilliance on everyone around him, more and yet more, today and forever. Until now.</p> <p>Perhaps, rather than invoking the sun and the Olympians, it would have been enough for me to say about Richard that whenever I worked through the logic of imagining a possible model of an achieved human being for my son, I invariably ended up with him, a man who straddled with natural ease—I’d guess because of his happy marriage to Barbara—what artists often find to be the intractable contradiction between loving and art that Yeats described as “the perfection of the life or of the work.” But this isn’t the time, immediately after his death, for teasing contradictions into sense. And so I’ve been led, at least at this moment, to invoke a star, and the Greek gods, to counter sense. For Richard Benson was so unrelentingly generous, and good, and spirited in the manner that only the very best of us have been, that a nod to the heavens—or more, as each of us is inclined—seems the least we can do to honor his memory. A small enough gesture to give back to our dear friend and extraordinary man.</p> <p>The first portion of this text was adapted from a talk presented by Tod Papageorge during a celebration of Richard Benson’s deanship, from 1995 to 2006, of the Yale School of Art.</p> </div> </div> </div> <footer id="footer"> <div id="about"> <h3>About This Page</h3> <p><b>A canvas for everyone.</b> This website is a wiki. All School of Art grad students, faculty, staff, and alums have the ability to change most of this site’s content (with some exceptions); and to add new content and pages.</p> <p> Content is the property of its various authors. When you contribute to this site, you agree to abide by Yale University academic and network use policy, and to act as a responsible member of our community. In this way, we hope the content of this site reflects the unique vitality of our school.</p> </div> <div id="contact"> <h3>Contact Us</h3> Yale School of Art<br> 1156 Chapel Street, POB 208339<br> New Haven, Connecticut, 06520-8339<br> (203) 432-2600 </div> </footer> </div> </body> </html>
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Force to "any" type, otherwise TypeScript thinks the type is too strict exports.<API key> = { type: 'object', properties: { time: { required: true, type: 'number' }, bioFilterReplaced: { required: true, type: 'boolean' }, <API key>: { required: true, type: 'boolean' }, spongeReplaced: { required: true, type: 'boolean' } } }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiSUNsZWFuaW5nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2NvbW1vbi9zcmMvSUNsZWFuaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTs7Ozs7Ozs7Ozs7Ozs7O0VBZUU7O0FBYUYsMEVBQTBFO0FBQzdELFFBQUEsd0JBQXdCLEdBQVE7SUFDM0MsSUFBSSxFQUFFLFFBQVE7SUFDZCxVQUFVLEVBQUU7UUFDVixJQUFJLEVBQUU7WUFDSixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxRQUFRO1NBQ2Y7UUFDRCxpQkFBaUIsRUFBRTtZQUNqQixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxTQUFTO1NBQ2hCO1FBQ0Qsd0JBQXdCLEVBQUU7WUFDeEIsUUFBUSxFQUFFLElBQUk7WUFDZCxJQUFJLEVBQUUsU0FBUztTQUNoQjtRQUNELGNBQWMsRUFBRTtZQUNkLFFBQVEsRUFBRSxJQUFJO1lBQ2QsSUFBSSxFQUFFLFNBQVM7U0FDaEI7S0FDRjtDQUNGLENBQUMifQ==
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; namespace Chess { public abstract class Screen : UserControl { public ScreenControl parentWindow; public ScreenControl ParentWindow { get { return parentWindow; } } protected Screen() { } public Screen(ScreenControl parentWindow) { this.parentWindow = parentWindow; } } }
package com.habitrpg.android.habitica.ui.activities; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.text.SpannableString; import android.text.style.UnderlineSpan; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TableRow; import android.widget.TextView; import com.amplitude.api.Amplitude; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.habitrpg.android.habitica.APIHelper; import com.habitrpg.android.habitica.HostConfig; import com.habitrpg.android.habitica.R; import com.habitrpg.android.habitica.callbacks.<API key>; import com.habitrpg.android.habitica.prefs.scanner.IntentIntegrator; import com.habitrpg.android.habitica.prefs.scanner.IntentResult; import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser; import com.magicmicky.habitrpgwrapper.lib.models.UserAuthResponse; import org.json.JSONException; import org.json.JSONObject; import butterknife.Bind; import butterknife.BindString; import butterknife.ButterKnife; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * @author Mickael Goubin */ public class LoginActivity extends AppCompatActivity implements Callback<UserAuthResponse>,<API key>.OnUserReceived { private final static String TAG_ADDRESS="address"; private final static String TAG_USERID="user"; private final static String TAG_APIKEY="key"; private APIHelper mApiHelper; public String mTmpUserToken; public String mTmpApiToken; public Boolean isRegistering; private Menu menu; @BindString(R.string.SP_address_default) String apiAddress; //private String apiAddress; private CallbackManager callbackManager; @Bind(R.id.login_btn) Button mLoginNormalBtn; @Bind(R.id.PB_AsyncTask) ProgressBar mProgressBar; @Bind(R.id.username) EditText mUsernameET; @Bind(R.id.password) EditText mPasswordET; @Bind(R.id.email) EditText mEmail; @Bind(R.id.confirm_password) EditText mConfirmPassword; @Bind(R.id.email_row) TableRow mEmailRow; @Bind(R.id.<API key>) TableRow mConfirmPasswordRow; @Bind(R.id.login_button) LoginButton mFacebookLoginBtn; @Bind(R.id.forgot_pw_tv) TextView mForgotPWTV; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_screen); //Set default values to avoid null-responses when requesting unedited settings PreferenceManager.setDefaultValues(this, R.xml.<API key>, false); PreferenceManager.setDefaultValues(this, R.xml.<API key>, false); ButterKnife.bind(this); mLoginNormalBtn.setOnClickListener(mLoginNormalClick); mFacebookLoginBtn.setReadPermissions("user_friends"); mForgotPWTV.setOnClickListener(mForgotPWClick); SpannableString content = new SpannableString(mForgotPWTV.getText()); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); mForgotPWTV.setText(content); callbackManager = CallbackManager.Factory.create(); mFacebookLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { AccessToken accessToken = AccessToken.<API key>(); mApiHelper.connectSocial(accessToken.getUserId(), accessToken.getToken(), LoginActivity.this); } @Override public void onCancel() { Log.d("FB Login", "Cancelled"); } @Override public void onError(FacebookException exception) { Log.e("FB Login", "Error", exception); } }); HostConfig hc= PrefsActivity.fromContext(this); if(hc ==null) { hc = new HostConfig(apiAddress, "80", "", ""); } mApiHelper = new APIHelper(hc); this.isRegistering = true; JSONObject eventProperties = new JSONObject(); try { eventProperties.put("eventAction", "navigate"); eventProperties.put("eventCategory", "navigation"); eventProperties.put("hitType", "pageview"); eventProperties.put("page", this.getClass().getSimpleName()); } catch (JSONException exception) { } Amplitude.getInstance().logEvent("navigate", eventProperties); } private void resetLayout() { if (this.isRegistering) { if (this.mEmailRow.getVisibility() == View.GONE) { expand(this.mEmailRow); } if (this.mConfirmPasswordRow.getVisibility() == View.GONE) { expand(this.mConfirmPasswordRow); } } else { if (this.mEmailRow.getVisibility() == View.VISIBLE) { collapse(this.mEmailRow); } if (this.mConfirmPasswordRow.getVisibility() == View.VISIBLE) { collapse(this.mConfirmPasswordRow); } } } private View.OnClickListener mLoginNormalClick = new View.OnClickListener() { @Override public void onClick(View v) { mProgressBar.setVisibility(View.VISIBLE); if (isRegistering) { String username, email,password,cpassword; username = String.valueOf(mUsernameET.getText()).trim(); email = String.valueOf(mEmail.getText()).trim(); password = String.valueOf(mPasswordET.getText()); cpassword = String.valueOf(mConfirmPassword.getText()); if (username.length() == 0 || password.length() == 0 || email.length() == 0 || cpassword.length() == 0) { showValidationError(R.string.<API key>); return; } mApiHelper.registerUser(username,email,password, cpassword, LoginActivity.this); } else { String username,password; username = String.valueOf(mUsernameET.getText()).trim(); password = String.valueOf(mPasswordET.getText()); if (username.length() == 0 || password.length() == 0) { showValidationError(R.string.<API key>); return; } mApiHelper.connectUser(username,password, LoginActivity.this); } } }; private View.OnClickListener mForgotPWClick = new View.OnClickListener() { @Override public void onClick(View v) { String url = getString(R.string.SP_address_default); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }; public static void expand(final View v) { v.setVisibility(View.VISIBLE); } public static void collapse(final View v) { v.setVisibility(View.GONE); } private void startMainActivity() { Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.addFlags(Intent.<API key> | Intent.<API key>); startActivity(intent); finish(); } private void startSetupActivity() { Intent intent = new Intent(LoginActivity.this, SetupActivity.class); intent.addFlags(Intent.<API key> | Intent.<API key>); startActivity(intent); finish(); } private void toggleRegistering() { this.isRegistering = !this.isRegistering; this.setRegistering(); } private void setRegistering() { MenuItem menuItem = menu.findItem(R.id.<API key>); if (this.isRegistering) { this.mLoginNormalBtn.setText(getString(R.string.register_btn)); menuItem.setTitle(getString(R.string.login_btn)); mUsernameET.setHint(R.string.username); mPasswordET.setImeOptions(EditorInfo.IME_ACTION_NEXT); } else { this.mLoginNormalBtn.setText(getString(R.string.login_btn)); menuItem.setTitle(getString(R.string.register_btn)); mUsernameET.setHint(R.string.email_username); mPasswordET.setImeOptions(EditorInfo.IME_ACTION_DONE); } this.resetLayout(); } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); callbackManager.onActivityResult(requestCode, resultCode, intent); IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { try { Log.d("scanresult", scanResult.getContents()); this.parse(scanResult.getContents()); } catch(Exception e) { Log.e("scanresult", "Could not parse scanResult", e); } } } private void parse(String contents) { String adr,user,key; try { JSONObject obj; obj = new JSONObject(contents); adr = obj.getString(TAG_ADDRESS); user = obj.getString(TAG_USERID); key = obj.getString(TAG_APIKEY); Log.d("", "adr" + adr + " user:" + user + " key" + key); SharedPreferences prefs = PreferenceManager.<API key>(this); SharedPreferences.Editor editor = prefs.edit(); boolean ans = editor.putString(getString(R.string.SP_address), adr) .putString(getString(R.string.SP_APIToken), key) .putString(getString(R.string.SP_userID), user) .commit(); if(!ans) { throw new Exception("PB_string_commit"); } startMainActivity(); } catch (JSONException e) { showSnackbar(getString(R.string.ERR_pb_barcode)); e.printStackTrace(); } catch(Exception e) { if("PB_string_commit".equals(e.getMessage())) { showSnackbar(getString(R.string.ERR_pb_barcode)); } } } private void showSnackbar(String content) { Snackbar snackbar = Snackbar .make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG); View snackbarView = snackbar.getView(); snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color; snackbar.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.login, menu); this.menu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean <API key>(MenuItem item) { switch(item.getItemId()) { case R.id.<API key>: toggleRegistering(); break; } return super.<API key>(item); } private void afterResults() { mProgressBar.setVisibility(View.INVISIBLE); } @Override public void success(UserAuthResponse userAuthResponse, Response response) { try { saveTokens(userAuthResponse.getToken(), userAuthResponse.getId()); } catch (Exception e) { e.printStackTrace(); } if (this.isRegistering) { this.startSetupActivity(); } else { JSONObject eventProperties = new JSONObject(); try { eventProperties.put("eventAction", "lofin"); eventProperties.put("eventCategory", "behaviour"); eventProperties.put("hitType", "event"); } catch (JSONException exception) { } Amplitude.getInstance().logEvent("login", eventProperties); this.startMainActivity(); } } private void saveTokens(String api, String user) throws Exception { SharedPreferences prefs = PreferenceManager.<API key>(LoginActivity.this); SharedPreferences.Editor editor = prefs.edit(); boolean ans = editor.putString(getString(R.string.SP_APIToken), api) .putString(getString(R.string.SP_userID), user) .putString(getString(R.string.SP_address),getString(R.string.SP_address_default)) .commit(); if(!ans) { throw new Exception("PB_string_commit"); } } @Override public void failure(RetrofitError error) { mProgressBar.setVisibility(View.GONE); } @Override public void onUserReceived(HabitRPGUser user) { try { saveTokens(mTmpApiToken, mTmpUserToken); } catch (Exception e) { e.printStackTrace(); } this.startMainActivity(); } @Override public void onUserFail() { mProgressBar.setVisibility(View.GONE); showSnackbar(getString(R.string.unknown_error)); } private void showValidationError(int <API key>) { mProgressBar.setVisibility(View.GONE); new android.support.v7.app.AlertDialog.Builder(this) .setTitle(R.string.<API key>) .setMessage(<API key>) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .setIcon(R.drawable.ic_warning_black) .show(); } }
<?php namespace hemio\html; class Figure extends Abstract_\ElementContent { use Trait_\<API key>; public static function tagName() { return 'figure'; } public function blnIsBlock() { return true; } }
#ifndef <API key> #define <API key> #include "script_interface/ScriptInterface.hpp" #include "core/comfixed_global.hpp" namespace ScriptInterface { class ComFixed : public AutoParameters<ComFixed> { public: ComFixed() { add_parameters({{"types", [](Variant const &v) { comfixed.set_fixed_types(get_value<std::vector<int>>(v)); }, []() { return comfixed.get_fixed_types(); }}}); } }; } // namespace ScriptInterface #endif
package org.structr.core.function; import org.structr.common.error.FrameworkException; import org.structr.common.error.SemanticErrorToken; import org.structr.core.GraphObject; import org.structr.core.app.StructrApp; import org.structr.core.property.PropertyKey; import org.structr.schema.action.ActionContext; import org.structr.schema.action.Function; public class ErrorFunction extends Function<Object, Object> { public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}"; @Override public String getName() { return "error()"; } @Override public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { final Class entityType; final String type; if (entity != null) { entityType = entity.getClass(); type = entity.getType(); } else { entityType = GraphObject.class; type = "Base"; } try { if (sources == null) { throw new <API key>(); } switch (sources.length) { case 1: throw new <API key>(); case 2: { <API key>(sources, 2); final PropertyKey key = StructrApp.getConfiguration().<API key>(entityType, sources[0].toString()); ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString())); break; } case 3: { <API key>(sources, 3); final PropertyKey key = StructrApp.getConfiguration().<API key>(entityType, sources[0].toString()); ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString(), sources[2])); break; } default: logParameterError(entity, sources, ctx.isJavaScriptContext()); break; } } catch (final <API key> e) { logParameterError(entity, sources, ctx.isJavaScriptContext()); return usage(ctx.isJavaScriptContext()); } return null; } @Override public String usage(boolean inJavaScriptContext) { return ERROR_MESSAGE_ERROR; } @Override public String shortDescription() { return "Signals an error to the caller"; } }
package com.risevision.gcslogs.delete; import com.risevision.gcslogs.auth.<API key>; import java.util.logging.Logger; import java.util.Map; import java.util.HashMap; import org.junit.*; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import static com.risevision.gcslogs.BuildConfig.*; public class <API key> { Map<String, String[]> params; <API key> deleter; @Before public void setUp() { params = new HashMap<String, String[]>(); params.put("jobId", new String[]{"testId"}); deleter = new <API key>(params, new <API key>()); } @Test public void itExists() { assertThat("it exists", deleter, isA(<API key>.class)); } @Test public void itGetsTheJobId() { assertThat("the id exists", deleter.jobId, is(not(nullValue()))); } @Test public void <API key>() { String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name"; assertThat("the name is correct", deleter.extractObjectName(uri), is("folder/name")); } @Test public void <API key>() { String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name"; assertThat("the bucket is correct", deleter.extractBucketName(uri), is(LOGS_BUCKET_NAME.toString())); } }
package org.maxgamer.rs.model.skill.prayer; import java.util.LinkedList; /** * @author netherfoam, alva */ public enum PrayerGroup { //Standard prayer book /** All prayers that boost defense */ DEFENSE(PrayerType.THICK_SKIN, PrayerType.ROCK_SKIN, PrayerType.STEEL_SKIN, PrayerType.CHIVALRY, PrayerType.PIETY, PrayerType.RIGOUR, PrayerType.AUGURY), /** All prayers that boost strength */ STRENGTH(PrayerType.BURST_OF_STRENGTH, PrayerType.SUPERHUMAN_STRENGTH, PrayerType.ULTIMATE_STRENGTH, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost attack */ ATTACK(PrayerType.CLARITY_OF_THOUGHT, PrayerType.IMPROVED_REFLEXES, PrayerType.INCREDIBLE_REFLEXES, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost range */ RANGE(PrayerType.SHARP_EYE, PrayerType.HAWK_EYE, PrayerType.EAGLE_EYE, PrayerType.RIGOUR), /** All prayers that boost magic */ MAGIC(PrayerType.MYSTIC_WILL, PrayerType.MYSTIC_LORE, PrayerType.MYSTIC_MIGHT, PrayerType.AUGURY), /** * most prayers that put a symbol above player head (Prot * (melee/magic/range), retribution, smite, redemption) */ STANDARD_SPECIAL(PrayerType.PROTECT_FROM_MELEE, PrayerType.<API key>, PrayerType.PROTECT_FROM_MAGIC, PrayerType.RETRIBUTION, PrayerType.REDEMPTION, PrayerType.SMITE), /** Protect from melee/range/magic prayers */ PROTECT_DAMAGE(PrayerType.PROTECT_FROM_MELEE, PrayerType.<API key>, PrayerType.PROTECT_FROM_MAGIC), //Curses prayer book /** Sap prayers (warrior, range, spirit) */ SAP(PrayerType.SAP_WARRIOR, PrayerType.SAP_RANGER, PrayerType.SAP_SPIRIT), /** * leech prayers (attack, range, magic, defence, strength, energy, special * attack) */ LEECH(PrayerType.LEECH_ATTACK, PrayerType.LEECH_RANGE, PrayerType.LEECH_MAGIC, PrayerType.LEECH_DEFENCE, PrayerType.LEECH_STRENGTH, PrayerType.LEECH_ENERGY, PrayerType.<API key>), /** * similar to standard_special. Wrath, Soulsplit, deflect (magic, missiles, * melee) */ CURSE_SPECIAL(PrayerType.WRATH, PrayerType.SOUL_SPLIT, PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE), /** All deflections (magic, missiles, melee) */ DEFLECT(PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE); private PrayerType[] types; private PrayerGroup(PrayerType... types) { this.types = types; } public PrayerType[] getTypes() { return types; } /** * Returns true if this prayer group contains the given prayer. * @param type the prayer * @return true if it is contained, else false. */ public boolean contains(PrayerType type) { for (PrayerType p : this.types) { if (type == p) { return true; } } return false; } /** * Returns an array of groups that the given prayer is in. * @param type the prayer * @return an array of groups that the given prayer is in. */ public static LinkedList<PrayerGroup> getGroups(PrayerType type) { LinkedList<PrayerGroup> groups = new LinkedList<PrayerGroup>(); for (PrayerGroup g : values()) { if (g.contains(type)) { groups.add(g); } } return groups; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Colorinator</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=410"> <!-- jQuery --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script> <!-- Wijmo CSS and script --> <link type="text/css" href="http://cdn.wijmo.com/themes/metro/jquery-wijmo.css" rel="stylesheet" title="metro-jqueryui" /> <link type="text/css" href="http://cdn.wijmo.com/jquery.wijmo-complete.all.2.1.5.min.css" rel="stylesheet" /> <script type="text/javascript" src="http://cdn.wijmo.com/jquery.wijmo-open.all.2.1.5.min.js"></script> <!-- KnockoutJS for MVVM--> <script type="text/javascript" src="http://cdn.wijmo.com/external/knockout-2.0.0.js"></script> <script type="text/javascript" src="http://cdn.wijmo.com/external/knockout.wijmo.js"></script> <script type="text/javascript"> //Create ViewModel var viewModel = function () { var self = this; self.red = ko.observable(120); self.green = ko.observable(120); self.blue = ko.observable(120); self.minRGB = ko.observable(0); self.maxRGB = ko.observable(255); self.rgbColor = ko.computed(function () { // Knockout tracks dependencies automatically. It knows that rgbColor depends on hue, saturation and lightness, because these get called when evaluating rgbColor. return "rgb(" + self.red() + ", " + self.green() + ", " + self.blue() + ")"; }, self); self.hslColor = ko.computed(function () { //Convert red, green and blue numbers to hue (degree), saturation (percentage) and lightness (percentage) var r = self.red() / 255, g = self.green() / 255, b = self.blue() / 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; var hue, saturation, lightness; if (max == min) { h = s = 0; } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } hue = Math.round(h * 360); saturation = Math.round(s * 100) + "%"; lightness = Math.round(l * 100) + "%"; return "hsl(" + hue + ", " + saturation + ", " + lightness + ")"; }, self); self.hexColor = ko.computed({ read: function () { //Convert red, green and blue numbers to base 16 strings var r = self.red(), g = self.green(), b = self.blue(); var hex = 1 << 24 | r << 16 | g << 8 | b; return '#' + hex.toString(16).substr(1); }, write: function (value) { //This is a writable computed observable so that one can type in a hex color to update the RGB values. var r, g, b; if (value[0] === " value = value.substr(1); } if (value.length < 3) { return; } else if (value.length > 6) { value = value.substr(0, 6); } else if (value.length === 3) { //Short code hex converted to full hex r = value.substr(0, 1) + value.substr(0, 1); g = value.substr(1, 1) + value.substr(1, 1); b = value.substr(2, 1) + value.substr(2, 1); value = r + g + b; } //Update ViewModel red, green and blue values self.red(parseInt(value.substr(0, 2), 16)); self.green(parseInt(value.substr(2, 2), 16)); self.blue(parseInt(value.substr(4, 2), 16)); }, owner: self }); }; //Bind ViewModel and Event Handlers $(document).ready(function () { var vm = new viewModel(); //check for hex color passed in URL getColorFromHash(); //Apply ViewModel bindings in markup ko.applyBindings(vm); //Trigger CSS3 animation to show color picker pane when ViewModel is initialized $(".wait").addClass("show").removeClass("wait"); //Check if browser supports hashchange event if ("onhashchange" in window) { window.onhashchange = getColorFromHash; } //Get hex color from URL and update ViewModel with value function getColorFromHash() { if (window.location.hash && window.location.hash != vm.hexColor()) { vm.hexColor(window.location.hash); } } }); </script> <style type="text/css"> body { font-family: "Segoe UI Light" , Frutiger, "Frutiger Linotype" , "Dejavu Sans" , "Helvetica Neue" , Arial, sans-serif; font-size: 14px; background: #000; } h1 { font-size: 2.4em; color: #fff; padding: 20px 0 0 6px; margin: 0; } .container { margin: 0 auto; width: 400px; } .wait { height: 1px; } .show { height: 530px; -webkit-transition: all 1.2s ease-out; -moz-transition: all 1.2s ease-out; -o-transition: all 1.2s ease-out; transition: all 1.2s ease-out; } .color-picker { overflow: hidden; background: #fff; padding: 20px; box-shadow: 5px 5px 50px rgba(0, 0, 0, 0.5); } .swatch { margin: 20px; width: 320px; height: 200px; box-shadow: 5px 5px 20px rgba(0, 0, 0, 0.5) inset; } .color-section { padding: 6px 0 0 0; } .color-label { width: 70px; display: inline-block; } .unit { width: 30px; } .color-value { width: 140px; } .color-slider { width: 200px; } .<API key> { display: inline-block; } </style> </head> <body data-bind="style: { background: hexColor }"> <div class="container"> <h1> Colorinator</h1> <div class="color-picker wait"> <div class="swatch" data-bind="style: { background: hexColor }"> </div> <div class="color-section"> <label class="color-label"> Red</label> <div data-bind="wijslider: { value: red, min: minRGB, max: maxRGB }" class="color-slider"> </div> <input type="text" data-bind="value: red, valueUpdate: 'keyup', wijtextbox: {}" class="unit" /> </div> <div class="color-section"> <label class="color-label"> Green</label> <div data-bind="wijslider: { value: green, min: minRGB, max: maxRGB }" class="color-slider"> </div> <input type="text" data-bind="value: green, valueUpdate: 'keyup', wijtextbox: {}" class="unit" /> </div> <div class="color-section"> <label class="color-label"> Blue</label> <div data-bind="wijslider: { value: blue, min: minRGB, max: maxRGB }" class="color-slider"> </div> <input type="text" data-bind="value: blue, valueUpdate: 'keyup', wijtextbox: {}" class="unit" /> </div> <div class="color-section"> <label class="color-label"> RGB Color</label> <input type="text" data-bind="value: rgbColor, disable: true, wijtextbox: { disabled: true }" class="color-value" /> <span data-bind="text: rgbColor"></span> </div> <div class="color-section"> <label class="color-label"> HSL Color</label> <input type="text" data-bind="value: hslColor, disable: true, wijtextbox: { disabled: true }" class="color-value" /> <span data-bind="text: hslColor"></span> </div> <div class="color-section"> <label class="color-label"> HEX Color</label> <input type="text" data-bind="value: hexColor, wijtextbox: { }" class="color-value" /> <a data-bind="text: hexColor, attr: { href: hexColor }" title="Link to this color"></a> </div> <p> Made with <a href="http: </div> </div> </body> </html>
import ast import json import arrow import elasticsearch from bson import ObjectId from flask import request from eve.utils import config from eve.io.base import DataLayer try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse def parse_date(date_str): """Parse elastic datetime string.""" try: date = arrow.get(date_str) except TypeError: date = arrow.get(date_str[0]) return date.datetime def get_dates(schema): """Return list of datetime fields for given schema.""" dates = [config.LAST_UPDATED, config.DATE_CREATED] for field, field_schema in schema.items(): if field_schema['type'] == 'datetime': dates.append(field) return dates def format_doc(hit, schema, dates): """Format given doc to match given schema.""" doc = hit.get('_source', {}) doc.setdefault(config.ID_FIELD, hit.get('_id')) doc.setdefault('_type', hit.get('_type')) for key in dates: if key in doc: doc[key] = parse_date(doc[key]) return doc def noop(): pass def is_elastic(datasource): """Detect if given resource uses elastic.""" return datasource.get('backend') == 'elastic' or datasource.get('search_backend') == 'elastic' class <API key>(elasticsearch.JSONSerializer): """Customize the JSON serializer used in Elastic""" def default(self, value): """Convert mongo.ObjectId.""" if isinstance(value, ObjectId): return str(value) return super(<API key>, self).default(value) class ElasticCursor(object): """Search results cursor.""" no_hits = {'hits': {'total': 0, 'hits': []}} def __init__(self, hits=None, docs=None): """Parse hits into docs.""" self.hits = hits if hits else self.no_hits self.docs = docs if docs else [] def __getitem__(self, key): return self.docs[key] def first(self): """Get first doc.""" return self.docs[0] if self.docs else None def count(self, **kwargs): """Get hits count.""" return int(self.hits['hits']['total']) def extra(self, response): """Add extra info to response.""" if 'facets' in self.hits: response['_facets'] = self.hits['facets'] if 'aggregations' in self.hits: response['_aggregations'] = self.hits['aggregations'] def set_filters(query, base_filters): """Put together all filters we have and set them as 'and' filter within filtered query. :param query: elastic query being constructed :param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup) """ filters = [f for f in base_filters if f is not None] query_filter = query['query']['filtered'].get('filter', None) if query_filter is not None: if 'and' in query_filter: filters.extend(query_filter['and']) else: filters.append(query_filter) if filters: query['query']['filtered']['filter'] = {'and': filters} def set_sort(query, sort): query['sort'] = [] for (key, sortdir) in sort: sort_dict = dict([(key, 'asc' if sortdir > 0 else 'desc')]) query['sort'].append(sort_dict) def get_es(url): o = urlparse(url) es = elasticsearch.Elasticsearch(hosts=[{'host': o.hostname, 'port': o.port}]) es.transport.serializer = <API key>() return es def get_indices(es): return elasticsearch.client.IndicesClient(es) class Elastic(DataLayer): """ElasticSearch data layer.""" serializers = { 'integer': int, 'datetime': parse_date, 'objectid': ObjectId, } def init_app(self, app): app.config.setdefault('ELASTICSEARCH_URL', 'http://localhost:9200/') app.config.setdefault('ELASTICSEARCH_INDEX', 'eve') self.index = app.config['ELASTICSEARCH_INDEX'] self.es = get_es(app.config['ELASTICSEARCH_URL']) self.create_index(self.index) self.put_mapping(app) def _get_field_mapping(self, schema): """Get mapping for given field schema.""" if 'mapping' in schema: return schema['mapping'] elif schema['type'] == 'datetime': return {'type': 'date'} elif schema['type'] == 'string' and schema.get('unique'): return {'type': 'string', 'index': 'not_analyzed'} def create_index(self, index=None): if index is None: index = self.index try: get_indices(self.es).create(self.index) except elasticsearch.TransportError: pass def put_mapping(self, app): """Put mapping for elasticsearch for current schema. It's not called automatically now, but rather left for user to call it whenever it makes sense. """ indices = get_indices(self.es) for resource, resource_config in app.config['DOMAIN'].items(): datasource = resource_config.get('datasource', {}) if not is_elastic(datasource): continue if datasource.get('source', resource) != resource: # only put mapping for core types continue properties = {} properties[config.DATE_CREATED] = self._get_field_mapping({'type': 'datetime'}) properties[config.LAST_UPDATED] = self._get_field_mapping({'type': 'datetime'}) for field, schema in resource_config['schema'].items(): field_mapping = self._get_field_mapping(schema) if field_mapping: properties[field] = field_mapping mapping = {'properties': properties} indices.put_mapping(index=self.index, doc_type=resource, body=mapping, ignore_conflicts=True) def find(self, resource, req, sub_resource_lookup): args = getattr(req, 'args', request.args if request else {}) source_config = config.SOURCES[resource] if args.get('source'): query = json.loads(args.get('source')) if 'filtered' not in query.get('query', {}): _query = query.get('query') query['query'] = {'filtered': {}} if _query: query['query']['filtered']['query'] = _query else: query = {'query': {'filtered': {}}} if args.get('q', None): query['query']['filtered']['query'] = _build_query_string(args.get('q'), default_field=args.get('df', '_all')) if 'sort' not in query: if req.sort: sort = ast.literal_eval(req.sort) set_sort(query, sort) elif self._default_sort(resource) and 'query' not in query['query']['filtered']: set_sort(query, self._default_sort(resource)) if req.max_results: query.setdefault('size', req.max_results) if req.page > 1: query.setdefault('from', (req.page - 1) * req.max_results) filters = [] filters.append(source_config.get('elastic_filter')) filters.append(source_config.get('<API key>', noop)()) filters.append({'term': sub_resource_lookup} if sub_resource_lookup else None) filters.append(json.loads(args.get('filter')) if 'filter' in args else None) set_filters(query, filters) if 'facets' in source_config: query['facets'] = source_config['facets'] if 'aggregations' in source_config: query['aggs'] = source_config['aggregations'] args = self._es_args(resource) hits = self.es.search(body=query, **args) return self._parse_hits(hits, resource) def find_one(self, resource, req, **lookup): def is_found(hit): if 'exists' in hit: hit['found'] = hit['exists'] return hit.get('found', False) args = self._es_args(resource) if config.ID_FIELD in lookup: try: hit = self.es.get(id=lookup[config.ID_FIELD], **args) except elasticsearch.NotFoundError: return if not is_found(hit): return docs = self._parse_hits({'hits': {'hits': [hit]}}, resource) return docs.first() else: query = { 'query': { 'term': lookup } } try: args['size'] = 1 hits = self.es.search(body=query, **args) docs = self._parse_hits(hits, resource) return docs.first() except elasticsearch.NotFoundError: return def find_one_raw(self, resource, _id): args = self._es_args(resource) hit = self.es.get(id=_id, **args) return self._parse_hits({'hits': {'hits': [hit]}}, resource).first() def find_list_of_ids(self, resource, ids, client_projection=None): args = self._es_args(resource) return self._parse_hits(self.es.multi_get(ids, **args), resource) def insert(self, resource, doc_or_docs, **kwargs): ids = [] kwargs.update(self._es_args(resource)) for doc in doc_or_docs: doc.update(self.es.index(body=doc, id=doc.get('_id'), **kwargs)) ids.append(doc['_id']) get_indices(self.es).refresh(self.index) return ids def update(self, resource, id_, updates): args = self._es_args(resource, refresh=True) return self.es.update(id=id_, body={'doc': updates}, **args) def replace(self, resource, id_, document): args = self._es_args(resource, refresh=True) return self.es.index(body=document, id=id_, **args) def remove(self, resource, lookup=None): args = self._es_args(resource) if lookup: try: return self.es.delete(id=lookup.get('_id'), refresh=True, **args) except elasticsearch.NotFoundError: return else: query = {'query': {'match_all': {}}} return self.es.delete_by_query(body=query, **args) def is_empty(self, resource): args = self._es_args(resource) res = self.es.count(body={'query': {'match_all': {}}}, **args) return res.get('count', 0) == 0 def get_mapping(self, index, doc_type=None): return get_indices(self.es).get_mapping(index=index, doc_type=doc_type) def _parse_hits(self, hits, resource): """Parse hits response into documents.""" datasource = self._datasource(resource) schema = config.DOMAIN[datasource[0]]['schema'] dates = get_dates(schema) docs = [] for hit in hits.get('hits', {}).get('hits', []): docs.append(format_doc(hit, schema, dates)) return ElasticCursor(hits, docs) def _es_args(self, resource, refresh=None): """Get index and doctype args.""" datasource = self._datasource(resource) args = { 'index': self.index, 'doc_type': datasource[0], } if refresh: args['refresh'] = refresh return args def _fields(self, resource): """Get projection fields for given resource.""" datasource = self._datasource(resource) keys = datasource[2].keys() return ','.join(keys) + ','.join([config.LAST_UPDATED, config.DATE_CREATED]) def _default_sort(self, resource): datasource = self._datasource(resource) return datasource[3] def build_elastic_query(doc): """ Builds a query which follows ElasticSearch syntax from doc. 1. Converts {"q":"cricket"} to the below elastic query { "query": { "filtered": { "query": { "query_string": { "query": "cricket", "lenient": false, "default_operator": "AND" } } } } } 2. Converts a faceted query {"q":"cricket", "type":['text'], "source": "AAP"} to the below elastic query { "query": { "filtered": { "filter": { "and": [ {"terms": {"type": ["text"]}}, {"term": {"source": "AAP"}} ] }, "query": { "query_string": { "query": "cricket", "lenient": false, "default_operator": "AND" } } } } } :param doc: A document object which is inline with the syntax specified in the examples. It's the developer responsibility to pass right object. :returns ElasticSearch query """ elastic_query, filters = {"query": {"filtered": {}}}, [] for key in doc.keys(): if key == 'q': elastic_query['query']['filtered']['query'] = _build_query_string(doc['q']) else: _value = doc[key] filters.append({"terms": {key: _value}} if isinstance(_value, list) else {"term": {key: _value}}) set_filters(elastic_query, filters) return elastic_query def _build_query_string(q, default_field=None): """ Builds "query_string" object from 'q'. :param: q of type String :param: default_field :return: dictionary object. """ query_string = {'query_string': {'query': q, 'default_operator': 'AND'}} query_string['query_string'].update({'lenient': False} if default_field else {'default_field': default_field}) return query_string
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc on Thu Nov 22 16:43:24 EST 2007 --> <TITLE> Xalan-Java 2.7.1: Uses of Interface org.apache.xml.serializer.<API key> </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <A NAME="navbar_top"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <HR> <CENTER> <H2> <B>Uses of Interface<br>org.apache.xml.serializer.<API key></B></H2> </CENTER> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.xalan.xsltc.dom"><B>org.apache.xalan.xsltc.dom</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.xalan.xsltc.runtime"><B>org.apache.xalan.xsltc.runtime</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.xml.serializer"><B>org.apache.xml.serializer</B></A></TD> <TD>Processes SAX events into streams.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.xalan.xsltc.dom"></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A> in <A HREF="../../../../../org/apache/xalan/xsltc/dom/package-summary.html">org.apache.xalan.xsltc.dom</A></FONT></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xalan/xsltc/dom/package-summary.html">org.apache.xalan.xsltc.dom</A> that implement <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/<API key>.html"><API key></A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<API key> is a adaptive DOM model for result tree fragments (RTF).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/<API key>.html"><API key></A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class represents a light-weight DOM model for simple result tree fragment(RTF).</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.xalan.xsltc.runtime"></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A> in <A HREF="../../../../../org/apache/xalan/xsltc/runtime/package-summary.html">org.apache.xalan.xsltc.runtime</A></FONT></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xalan/xsltc/runtime/package-summary.html">org.apache.xalan.xsltc.runtime</A> that implement <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/runtime/StringValueHandler.html">StringValueHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.xml.serializer"></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A> in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A></FONT></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TD COLSPAN=2>Subinterfaces of <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A> in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;interface</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This interface is the one that a serializer implements.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A> that implement <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><API key></A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/EmptySerializer.html">EmptySerializer</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class is an adapter class.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/SerializerBase.html">SerializerBase</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class acts as a base class for the XML "serializers" and the stream serializers.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToHTMLSAXHandler.html">ToHTMLSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I>As of Xalan 2.7.1, replaced by the use of <A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html"><CODE>ToXMLSAXHandler</CODE></A>.</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToHTMLStream.html">ToHTMLStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This serializer takes a series of SAX or SAX-like events and writes its output to the given stream.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToSAXHandler.html">ToSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class is used to provide a base behavior to be inherited by other To...SAXHandler serializers.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToStream.html">ToStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This abstract class is a base class for other stream serializers (xml, html, text ...) that write output to a stream.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToTextSAXHandler.html">ToTextSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I>As of Xalan 2.7.1, replaced by the use of <A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html"><CODE>ToXMLSAXHandler</CODE></A>.</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToTextStream.html">ToTextStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class is not a public API.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToUnknownStream.html">ToUnknownStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class wraps another <API key>.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html">ToXMLSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class receives notification of SAX-like events, and with gathered information over these calls it will invoke the equivalent SAX methods on a handler, the ultimate xsl:output method is known to be "xml".</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToXMLStream.html">ToXMLStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class converts SAX or SAX-like calls to a serialized xml document.</TD> </TR> </TABLE> &nbsp; <P> <HR> <A NAME="navbar_bottom"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xml/serializer/<API key>.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <HR> Copyright © 2006 Apache XML Project. All Rights Reserved. </BODY> </HTML>
ProjectTop := /Volumes/Polaris/polymake include ${ProjectTop}/support/extension.make
=head1 NAME EPrints::Plugin::Screen::Search =cut package EPrints::Plugin::Screen::Search; use EPrints::Plugin::Screen::AbstractSearch; @ISA = ( 'EPrints::Plugin::Screen::AbstractSearch' ); use strict; sub new { my( $class, %params ) = @_; my $self = $class->SUPER::new(%params); $self->{appears} = []; push @{$self->{actions}}, "advanced", "savesearch"; return $self; } sub datasets { my( $self ) = @_; my $session = $self->{session}; my @datasets; foreach my $datasetid ($session->get_dataset_ids) { local $self->{processor}->{dataset} = $session->dataset( $datasetid ); next if !$self->can_be_viewed(); push @datasets, $datasetid; } return @datasets; } sub search_dataset { my( $self ) = @_; return $self->{processor}->{dataset}; } sub allow_advanced { shift->can_be_viewed( @_ ) } sub allow_export { shift->can_be_viewed( @_ ) } sub allow_export_redir { shift->can_be_viewed( @_ ) } sub allow_savesearch { my( $self ) = @_; return 0 if !$self->can_be_viewed(); my $user = $self->{session}->current_user; return defined $user && $user->allow( "create_saved_search" ); } sub can_be_viewed { my( $self ) = @_; # note this method is also used by $self->datasets() my $dataset = $self->{processor}->{dataset}; return 0 if !defined $dataset; my $searchid = $self->{processor}->{searchid}; if( $dataset->id eq "archive" ) { return $self->allow( "eprint_search" ); } elsif( defined($searchid) && (my $rc = $self->allow( $dataset->id . "/search/$searchid" )) ) { return $rc; } { return $self->allow( $dataset->id . "/search" ); } } sub get_controls_before { my( $self ) = @_; my @controls = $self-><API key>; my $cacheid = $self->{processor}->{results}->{cache_id}; my $escexp = $self->{processor}->{search}->serialise; my $baseurl = URI->new( $self->{session}->get_uri ); $baseurl->query_form( cache => $cacheid, exp => $escexp, screen => $self->{processor}->{screenid}, dataset => $self->search_dataset->id, order => $self->{processor}->{search}->{custom_order}, ); # Maybe add links to the pagination controls to switch between simple/advanced # if( $self->{processor}->{searchid} eq "simple" ) # push @controls, { # url => "advanced", # label => $self->{session}->html_phrase( "lib/searchexpression:advanced_link" ), my $user = $self->{session}->current_user; if( defined $user && $user->allow( "create_saved_search" ) ) { #my $cacheid = $self->{processor}->{results}->{cache_id}; #my $exp = $self->{processor}->{search}->serialise; my $url = $baseurl->clone; $url->query_form( $url->query_form, _action_savesearch => 1 ); push @controls, { url => "$url", label => $self->{session}->html_phrase( "lib/searchexpression:savesearch" ), }; } return @controls; } sub hidden_bits { my( $self ) = @_; my %bits = $self->SUPER::hidden_bits; my @datasets = $self->datasets; # if there's more than 1 dataset, then the search form will render the list of "search-able" datasets - see render_dataset below if( scalar( @datasets ) < 2 ) { $bits{dataset} = $self->{processor}->{dataset}->id; } return %bits; } sub render_result_row { my( $self, $session, $result, $searchexp, $n ) = @_; my $staff = $self->{processor}->{sconf}->{staff}; my $citation = $self->{processor}->{sconf}->{citation}; if( $staff ) { return $result-><API key>( $citation, n => [$n,"INTEGER"] ); } else { return $result-><API key>( $citation, n => [$n,"INTEGER"] ); } } sub export_url { my( $self, $format ) = @_; my $plugin = $self->{session}->plugin( "Export::".$format ); if( !defined $plugin ) { EPrints::abort( "No such plugin: $format\n" ); } my $url = URI->new( $self->{session}->current_url() . "/export_" . $self->{session}->get_repository->get_id . "_" . $format . $plugin->param( "suffix" ) ); $url->query_form( $self->hidden_bits, _action_export => 1, output => $format, exp => $self->{processor}->{search}->serialise, n => scalar($self->{session}->param( "n" )), ); return $url; } sub action_advanced { my( $self ) = @_; my $adv_url; my $datasetid = $self->{session}->param( "dataset" ); $datasetid = "archive" if !defined $datasetid; # something odd happened if( $datasetid eq "archive" ) { $adv_url = $self->{session}->current_url( path => "cgi", "search/advanced" ); } else { $adv_url = $self->{session}->current_url( path => "cgi", "search/$datasetid/advanced" ); } $self->{processor}->{redirect} = $adv_url; } sub action_savesearch { my( $self ) = @_; my $ds = $self->{session}->dataset( "saved_search" ); my $searchexp = $self->{processor}->{search}; $searchexp->{searchid} = $self->{processor}->{searchid}; my $name = $searchexp-><API key>; my $userid = $self->{session}->current_user->id; my $spec = $searchexp->freeze; my $results = $ds->search( filters => [ { meta_fields => [qw( userid )], value => $userid, }, { meta_fields => [qw( spec )], value => $spec, match => "EX" }, ]); my $savedsearch = $results->item( 0 ); my $screen; if( defined $savedsearch ) { $screen = "View"; } else { $screen = "Edit"; $savedsearch = $ds->create_dataobj( { userid => $self->{session}->current_user->id, name => $self->{session}->xml->text_contents_of( $name ), spec => $searchexp->freeze } ); } $self->{session}->xml->dispose( $name ); my $url = URI->new( $self->{session}->config( "userhome" ) ); $url->query_form( screen => "Workflow::$screen", dataset => "saved_search", dataobj => $savedsearch->id, ); $self->{session}->redirect( $url ); exit; } sub render_search_form { my( $self ) = @_; if( $self->{processor}->{searchid} eq "simple" && @{$self->{processor}->{sconf}->{search_fields}} == 1 ) { return $self->render_simple_form; } else { return $self->SUPER::render_search_form; } } sub render_preamble { my( $self ) = @_; my $pphrase = $self->{processor}->{sconf}->{"preamble_phrase"}; return $self->{session}->make_doc_fragment if !defined $pphrase; return $self->{session}->html_phrase( $pphrase ); } sub render_simple_form { my( $self ) = @_; my $session = $self->{session}; my $xhtml = $session->xhtml; my $xml = $session->xml; my $input; my $div = $xml->create_element( "div", class => "ep_block" ); my $form = $self->{session}->render_form( "get" ); $div->appendChild( $form ); my $label = $xml->create_element( "label", for => "q_merge", class => "ep_lbl_merge" ); $label->appendChild( $session->html_phrase( "lib/searchexpression:merge" ) ); $form->appendChild( $label ); # avoid adding "dataset", which is selectable here $form->appendChild( $self->SUPER::render_hidden_bits ); # maintain the order if it was specified (might break if dataset is # changed) $input = $xhtml->hidden_field( "order", $session->param( "order" ) ); $form->appendChild( $input ); $form->appendChild( $self->render_preamble ); $form->appendChild( $self->{processor}->{search}-><API key>( 'aria-labelledby' => $session->phrase( "lib/searchexpression:action_search" ) ) ); $input = $xml->create_element( "input", type => "submit", name => "_action_search", value => $session->phrase( "lib/searchexpression:action_search" ), class => "<API key>", id => $session->phrase( "lib/searchexpression:action_search" ), ); $form->appendChild( $input ); $input = $xml->create_element( "input", type => "submit", name => "_action_advanced", value => $self->{session}->phrase( "lib/searchexpression:advanced_link" ), class => "<API key> <API key>", ); $form->appendChild( $input ); $form->appendChild( $xml->create_element( "br" ) ); $form->appendChild( $self->render_dataset ); return( $div ); } sub render_dataset { my( $self ) = @_; my $session = $self->{session}; my $xhtml = $session->xhtml; my $xml = $session->xml; my $frag = $xml-><API key>; my @datasetids = $self->datasets; return $frag if @datasetids <= 1; foreach my $datasetid (sort @datasetids) { my $input = $xml->create_element( "input", name => "dataset", type => "radio", value => $datasetid ); if( $datasetid eq $self->{processor}->{dataset}->id ) { $input->setAttribute( checked => "yes" ); } my $label = $xml->create_element( "label", id=>$datasetid ); $frag->appendChild( $label ); $label->appendChild( $input ); $label->appendChild( $session->html_phrase( "datasetname_$datasetid" ) ); } return $frag; } sub properties_from { my( $self ) = @_; $self->SUPER::properties_from(); my $processor = $self->{processor}; my $repo = $self->{session}; my $dataset = $processor->{dataset}; my $searchid = $processor->{searchid}; return if !defined $dataset; return if !defined $searchid; # get the dataset's search configuration my $sconf = $dataset->search_config( $searchid ); $sconf = $self-><API key> if !%$sconf; $processor->{sconf} = $sconf; $processor->{template} = $sconf->{template}; } sub <API key> {} sub from { my( $self ) = @_; my $session = $self->{session}; my $processor = $self->{processor}; my $sconf = $processor->{sconf}; # This rather oddly now checks for the special case of one parameter, but # that parameter being a screenid, in which case the search effectively has # no parameters and should not default to action = 'search'. # maybe this can be removed later, but for a minor release this seems safest. if( !EPrints::Utils::is_set( $self->{processor}->{action} ) ) { my %params = map { $_ => 1 } $self->{session}->param(); foreach my $param (keys %{{$self->hidden_bits}}) { delete $params{$param}; } if( EPrints::Utils::is_set( $self->{session}->param( "output" ) ) ) { $self->{processor}->{action} = "export"; } elsif( scalar keys %params ) { $self->{processor}->{action} = "search"; } else { $self->{processor}->{action} = ""; } } my $satisfy_all = $self->{session}->param( "satisfyall" ); $satisfy_all = !defined $satisfy_all || $satisfy_all eq "ALL"; my $searchexp = $processor->{search}; if( !defined $searchexp ) { my $format = $processor->{searchid} . "/" . $processor->{dataset}->base_id; if( !defined $sconf ) { EPrints->abort( "No available configuration for search type $format" ); } $searchexp = $session->plugin( "Search" )->plugins( { session => $session, dataset => $self->search_dataset, keep_cache => 1, satisfy_all => $satisfy_all, %{$sconf}, filters => [ $self->search_filters, @{$sconf->{filters} || []}, ], }, type => "Search", can_search => $format, ); if( !defined $searchexp ) { EPrints->abort( "No available search plugin for $format" ); } $processor->{search} = $searchexp; } if( $searchexp->is_blank && $self->{processor}->{action} ne "newsearch" ) { my $ok = 0; if( my $id = $session->param( "cache" ) ) { $ok = $searchexp->from_cache( $id ); } if( !$ok && (my $exp = $session->param( "exp" )) ) { # cache expired $ok = $searchexp->from_string( $exp ); } if( !$ok ) { for( $searchexp->from_form ) { $self->{processor}->add_message( "warning", $_ ); } } } $sconf->{order_methods} = {} if !defined $sconf->{order_methods}; if( $searchexp->param( "result_order" ) ) { $sconf->{order_methods}->{"byrelevance"} = ""; } # have we been asked to reorder? if( defined( my $order_opt = $self->{session}->param( "order" ) ) ) { my $allowed_order = 0; foreach my $custom_order ( values %{$sconf->{order_methods}} ) { $allowed_order = 1 if $order_opt eq $custom_order; } my $custom_order; if( $allowed_order ) { $custom_order = $order_opt; } elsif( defined $sconf->{default_order} ) { $custom_order = $sconf->{order_methods}->{$sconf->{default_order}}; } else { $custom_order = ""; } $searchexp->{custom_order} = $custom_order; } # use default order else { $searchexp->{custom_order} = $sconf->{order_methods}->{$sconf->{default_order}}; } # feeds are always limited and ordered by -datestamp if( $self->{processor}->{action} eq "export" ) { my $output = $self->{session}->param( "output" ); my $export_plugin = $self->{session}->plugin( "Export::$output" ); if( !defined($self->{session}->param( "order" )) && defined($export_plugin) && $export_plugin->is_feed ) { # borrow the max from latest_tool (which we're replicating anyway) my $limit = $self->{session}->config( "latest_tool_modes", "default", "max" ); $limit = 20 if !$limit; my $n = $self->{session}->param( "n" ); if( $n && $n > 0 && $n < $limit) { $limit = $n; } $searchexp->{limit} = $limit; $searchexp->{custom_order} = "-datestamp"; } } # do actions $self->EPrints::Plugin::Screen::from; if( $searchexp->is_blank && $self->{processor}->{action} ne "export" ) { if( $self->{processor}->{action} eq "search" ) { $self->{processor}->add_message( "warning", $self->{session}->html_phrase( "lib/searchexpression:least_one" ) ); } $self->{processor}->{search_subscreen} = "form"; } } 1; =head1 COPYRIGHT =for COPYRIGHT BEGIN Copyright 2000-2011 University of Southampton. =for COPYRIGHT END =for LICENSE BEGIN This file is part of EPrints L<http: EPrints 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. EPrints 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 EPrints. If not, see L<http: =for LICENSE END
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>PHP MySQL Database Interface: <API key> Klassenreferenz</title> <link href="../../tabs.css" rel="stylesheet" type="text/css"> <link href="../../doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Erzeugt von Doxygen 1.5.9 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="../../main.html"><span>Hauptseite</span></a></li> <li><a href="../../namespaces.html"><span>Namensbereiche</span></a></li> <li class="current"><a href="../../annotated.html"><span>Datenstrukturen</span></a></li> <li><a href="../../files.html"><span>Dateien</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="../../annotated.html"><span>Datenstrukturen</span></a></li> <li><a href="../../hierarchy.html"><span>Klassenhierarchie</span></a></li> <li><a href="../../functions.html"><span><API key></span></a></li> </ul> </div> </div> <div class="contents"> <h1><API key> Klassenreferenz</h1><!-- doxytag: class="<API key>" --><!-- doxytag: inherits="DatabaseException" --><div class="dynheader"> Klassendiagramm für <API key>:</div> <div class="dynsection"> <p><center><img src="../../dc/daa/<API key>.png" usemap="#<API key>" border="0" alt=""></center> <map name="<API key>"> <area href="../../d1/d5d/<API key>.html" alt="DatabaseException" shape="rect" coords="0,0,171,24"> </map> </div> <table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Öffentliche Methoden</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="../../dc/daa/<API key>.html#<API key>">__construct</a> ($message=null, $code=0, Exception $previous=null)</td></tr> </table> <hr><a name="_details"></a><h2>Ausführliche Beschreibung</h2> <a class="el" href="../../dc/daa/<API key>.html"><API key></a> <hr><h2>Beschreibung der Konstruktoren und Destruktoren</h2> <a class="anchor" name="<API key>"></a><!-- doxytag: member="<API key>::__construct" ref="<API key>" args="($message=null, $code=0, Exception $previous=null)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__construct </td> <td>(</td> <td class="paramtype">$&nbsp;</td> <td class="paramname"> <em>message</em> = <code>null</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">$&nbsp;</td> <td class="paramname"> <em>code</em> = <code>0</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">Exception $&nbsp;</td> <td class="paramname"> <em>previous</em> = <code>null</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p> <dl compact><dt><b>Parameter:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>string</em>&nbsp;</td><td>$message </td></tr> <tr><td valign="top"></td><td valign="top"><em>number</em>&nbsp;</td><td>$code </td></tr> <tr><td valign="top"></td><td valign="top"><em>Exception</em>&nbsp;</td><td>$previous </td></tr> </table> </dl> <p>Erneute Implementation von <a class="el" href="../../d1/d5d/<API key>.html#<API key>">DatabaseException</a>.</p> </div> </div><p> <hr>Die Dokumentation für diese Klasse wurde erzeugt aufgrund der Datei:<ul> <li>S:/Documents/Projekte/phpDBI/workbench/0.02/classes/exception/<a class="el" href="../../d1/d9b/<API key>.html"><API key>.php</a></ul> </div> <hr size="1"><address style="text-align: right;"><small>Erzeugt am Fri Dec 25 15:32:56 2009 für PHP MySQL Database Interface von&nbsp; <a href="http: <img src="../../doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.9 </small></address> </body> </html>
package nikoladasm.aspark; import java.io.IOException; import java.io.InputStream; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.netty.buffer.ByteBuf; import static nikoladasm.aspark.HttpMethod.*; public final class ASparkUtil { private static final String PARAMETERS_PATTERN = "(?i)(:[A-Z_][A-Z_0-9]*)"; private static final Pattern PATTERN = Pattern.compile(PARAMETERS_PATTERN); private static final String DEFAULT_ACCEPT_TYPE = "*/*"; private static final String REGEXP_METACHARS = "<([{\\^-=$!|]})?*+.>"; private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private static final String FOLDER_SEPARATOR = "/"; private static final String <API key> = "\\"; private static final String TOP_PATH = ".."; private static final String CURRENT_PATH = "."; private static final String QUERY_KEYS_PATTERN = "\\s*\\[?\\s*([^\\]\\[\\s]+)\\s*\\]?\\s*"; private static final Pattern QK_PATTERN = Pattern.compile(QUERY_KEYS_PATTERN); private ASparkUtil() {} private static String processRegexPath(String path, String asteriskReplacement, String <API key>) { String pathToUse = sanitizePath(path); int length = pathToUse.length(); StringBuilder sb = new StringBuilder(); boolean startWithWildcard = false; for (int i = 0; i < length; i++) { char c = pathToUse.charAt(i); if (i == 0 && c == '*') { sb.append(asteriskReplacement); startWithWildcard = true; continue; } if (i == length-2 && c == '/' && pathToUse.charAt(i+1) == '*') { if (startWithWildcard) throw new <API key>("Path can't contain first and last star wildcard"); sb.append(<API key>); break; } if (i == length-1 && c == '*') { if (startWithWildcard) throw new <API key>("Path can't contain first and last star wildcard"); sb.append(asteriskReplacement); continue; } if (REGEXP_METACHARS.contains(String.valueOf(c))) { sb.append('\\').append(c); continue; } sb.append(c); } return sb.toString(); } public static Pattern <API key>(String path, Map<String, Integer> parameterNamesMap, Boolean startWithWildcard) { String pathToUse = processRegexPath(path, "(.*)", "(?:/?|/(.+))"); Matcher parameterMatcher = PATTERN.matcher(pathToUse); int i = 1; while (parameterMatcher.find()) { String parameterName = parameterMatcher.group(1); if (parameterNamesMap.containsKey(parameterName)) throw new ASparkException("Duplicate parameter name."); parameterNamesMap.put(parameterName, i); i++; } return Pattern.compile("^"+parameterMatcher.replaceAll("([^/]+)")+"$"); } public static Pattern buildPathPattern(String path) { String pathToUse = processRegexPath(path, ".*", "(?:/?|/.+)"); return Pattern.compile("^"+pathToUse+"$"); } public static boolean isAcceptContentType(String requestAcceptTypes, String routeAcceptType) { if (requestAcceptTypes == null) return routeAcceptType.trim().equals(DEFAULT_ACCEPT_TYPE); String[] <API key> = requestAcceptTypes.split(","); String[] rtat = routeAcceptType.trim().split("/"); for (int i=0; i<<API key>.length; i++) { String requestAcceptType = <API key>[i].split(";")[0]; String[] rqat = requestAcceptType.trim().split("/"); if (((rtat[0].equals("*")) ? true : rqat[0].trim().equals(rtat[0])) && ((rtat[1].equals("*")) ? true : rqat[1].equals(rtat[1]))) return true; } return false; } public static long copyStreamToByteBuf(InputStream input, ByteBuf buf) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while ((n = input.read(buffer)) != -1) { buf.writeBytes(buffer, 0, n); count += n; } return count; } public static String collapsePath(String path) { String pathToUse = path.trim(); if (pathToUse.isEmpty()) return pathToUse; String rpath = pathToUse.replace(<API key>, FOLDER_SEPARATOR); String[] directories = rpath.split(FOLDER_SEPARATOR); Deque<String> newDirectories = new LinkedList<>(); for (int i=0; i<directories.length; i++) { String directory = directories[i].trim(); if (directory.equals(TOP_PATH) && !newDirectories.isEmpty()) newDirectories.removeLast(); else if (!directory.equals(CURRENT_PATH) && !directory.isEmpty()) newDirectories.addLast(directory); } String result = FOLDER_SEPARATOR; for (String directory : newDirectories) result += directory + FOLDER_SEPARATOR; if (!path.startsWith(FOLDER_SEPARATOR)) result = result.substring(1); if (!path.endsWith(FOLDER_SEPARATOR) && result.equals(FOLDER_SEPARATOR)) result = result.substring(0, result.length()-1); return result; } public static boolean isEqualHttpMethod(HttpMethod requestHttpMethod, HttpMethod routeHttpMethod) { if (requestHttpMethod.equals(HEAD) && routeHttpMethod.equals(GET)) return true; return requestHttpMethod.equals(routeHttpMethod); } public static ParamsMap parseParams(Map<String, List<String>> params) { ParamsMap result = new ParamsMap(); params.forEach((keys, values) -> { ParamsMap root = result; Matcher keyMatcher = QK_PATTERN.matcher(keys); while (keyMatcher.find()) { String key = keyMatcher.group(1); root = root.<API key>(key); } root.values(values.toArray(new String[values.size()])); }); return result; } public static ParamsMap parseUniqueParams(Map<String, String> params) { ParamsMap result = new ParamsMap(); params.forEach((key, value) -> { result.<API key>(key).value(value); }); return result; } public static String sanitizePath(String path) { String pathToUse = collapsePath(path); if (pathToUse.isEmpty()) return pathToUse; if (pathToUse.endsWith("/")) pathToUse = pathToUse.substring(0, pathToUse.length()-1); return pathToUse; } public static String mimeType(String file, Properties mimeTypes) { int extIndex = file.lastIndexOf('.'); extIndex = (extIndex < 0 ) ? 0 : extIndex; String ext = file.substring(extIndex); return mimeTypes.getProperty(ext, "application/octet-stream"); } }
package controller; import java.io.IOException; import java.sql.Time; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONObject; import utils.Common; import utils.Constant; import utils.MessageProperties; import dao.HocKyDao; import dao.OnlDao; import dao.WeekDao; import dao.impl.HocKyDaoImpl; import dao.impl.OnlDaoImpl; import dao.impl.PositionDaoImpl; import dao.impl.WeekDaoImpl; import entity.HocKy; import entity.Onl; import entity.Position; import entity.User; import entity.Week; /** * Servlet implementation class OnlController */ @WebServlet("/jsp/onl.htm") public class OnlController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); HocKyDao hocKyDao = new HocKyDaoImpl(); List<HocKy> listHocKy = hocKyDao.getListHocKy(); request.setAttribute("listHocKy", listHocKy); String currentHocKy = hocKyDao.getHocKy(Common.getNow()); request.setAttribute("currentHocKy", currentHocKy); WeekDao weekDao = new WeekDaoImpl(); List<Week> listWeek = weekDao.getListWeek(currentHocKy); request.setAttribute("listWeek", listWeek); Week currentWeek = weekDao.getCurrentWeek(Common.getNow()); request.setAttribute("currentWeek", currentWeek); List<Onl> listOnl = new OnlDaoImpl().getListOnl(null, currentWeek.getWeekId(), user.getUserId()); request.setAttribute(Constant.ACTION, "viewOnl"); request.setAttribute("listOnl", listOnl); request.<API key>("view_onl_cal.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ @SuppressWarnings({ "unchecked", "deprecation" }) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ("position".equals(action)) { double latitude = Double.parseDouble(request .getParameter("latitude")); double longitude = Double.parseDouble(request .getParameter("longitude")); long onlId = Long.parseLong(request.getParameter("id")); Position position = new PositionDaoImpl().getPositionById("B1-502"); JSONObject jsonObject = new JSONObject(); ServletOutputStream out = response.getOutputStream(); if (position == null) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR12")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } if (!checkPosition(position, latitude, longitude)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR13")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } // if (!(latitude >= 20 && latitude <= 22 && longitude >= 105 && // longitude <= 106)) { // String error = MessageProperties.getData("ERR09"); // jsonObject.put(Constant.STATUS, false); // jsonObject.put(Constant.DATA, error); // out.write(jsonObject.toJSONString().getBytes()); // out.flush(); // return; Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("Asia/Ho_Chi_Minh")); Time now = new Time(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); OnlDao onlDao = new OnlDaoImpl(); Onl onl = onlDao.getOnlById(onlId); if (now.after(onl.getTimeStart()) && now.before(onl.getTimeEnd())) { int lateMin = (int) Math.round((double) ((now.getTime() - onl .getTimeStart().getTime()) / 1000) / 60); onl.setLate(true); onl.setLateMin(lateMin); } else if (now.after(onl.getTimeEnd())) { String error = MessageProperties.getData("ERR14"); jsonObject.put(Constant.STATUS, false); jsonObject.put("flagHol", true); jsonObject.put(Constant.DATA, error); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } onl.setHol(false); if (!onlDao.update(onl, true)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR10")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } jsonObject.put(Constant.STATUS, true); jsonObject.put(Constant.DATA, MessageProperties.getData("MSG04")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } else if ("addReason".equals(action)) { JSONObject jsonObject = new JSONObject(); ServletOutputStream out = response.getOutputStream(); String reason = request.getParameter("reason"); long onlId = Long.parseLong(request.getParameter("id")); if (!new OnlDaoImpl().setReason(reason, onlId)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR10")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } jsonObject.put(Constant.STATUS, true); jsonObject.put(Constant.DATA, MessageProperties.getData("MSG01")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } } public boolean checkPosition(Position position, double latitude, double longitude) { double latitudeMin = Math.floor(position.getLatitude() * 1000000) / 1000000; double latitudeMax = Math.ceil(position.getLatitude() * 1000000) / 1000000; double longitudeMin = Math.floor(position.getLongitude() * 10000000) / 10000000; double longitudeMax = Math.ceil((position.getLongitude()) * 10000000) / 10000000; System.out.println(latitudeMin + " <= " + latitude + " <= "+ latitudeMax); System.out.println(longitudeMin + " <= " + longitude + " <= "+ longitudeMax); return latitudeMin <= latitude && latitude <= latitudeMax && longitudeMin <= longitude && longitude <= longitudeMax; } }
#ifndef __PLATFORM_H_ #define __PLATFORM_H_ #define STDOUT_IS_PS7_UART #define UART_DEVICE_ID 0 #include "xil_io.h" #include "xtmrctr.h" #include "assert.h" /* Write to memory location or register */ #define X_mWriteReg(BASE_ADDRESS, RegOffset, data) \ *(unsigned volatile int *)(BASE_ADDRESS + RegOffset) = ((unsigned volatile int) data); /* Read from memory location or register */ #define X_mReadReg(BASE_ADDRESS, RegOffset) \ *(unsigned volatile int *)(volatile)(BASE_ADDRESS + RegOffset); #define <API key>(BaseAddress) \ ((Xil_In32((BaseAddress) + 0x2C) & \ 0x10) == 0x10) void wait_ms(unsigned int time); void init_platform(); void cleanup_platform(); void ChangedPrint(char *ptr); void timer_init(); void tic(); void toc(); u64 elapsed_time_us(); #endif
<!DOCTYPE html> <! Copyright (C) 2017 ss 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: <div style="min-height: 100px;"> <div [hidden]="result.length > 0"> <h4 style="text-align: center;" [translate]="'transport-map.search-result.no-result'"></h4> <h5 [translate]="'transport-map.search-result.no-result-desc'"></h5> <h5 [translate]="'transport-map.search-result.no-result-geocoder'"></h5> <h5>{{'transport-map.search-result.<API key>' | translate}} <span class="sr-link" (click)="goToSchedule()">{{'transport-map.search-result.<API key>' | translate}}</span></h5> <h5 [translate]="'transport-map.search-result.no-result-tooltip'"></h5> </div> <md-list *ngIf="mapComponent.activeProfile && result.length === 0"> <h3 md-subheader class="srl-result-h" [translate]="'transport-map.search-result.legend'"></h3> <md-list-item *ngFor="let typ of mapComponent.activeProfile.routeProfiles"> <span md-list-icon [style.background-color]="typ.lineColor" class="srl-route-label-2"></span> <p md-line style="line-height: 30px;" [translate]="'route-type.' + typ.name"></p> </md-list-item> </md-list> <div [hidden]="result.length < 1"> <md-list *ngIf="!flags.isDetailsOpen"> <h3 md-subheader class="srl-result-h" [translate]="'transport-map.search-result.found-results'" [translateParams]="{count: result.length}"></h3> <md-list-item *ngFor="let op of result" class="srl-item" (click)="showPath(op)" [@flyInOut]="op.animationTrigger"> <md-icon *ngIf="!mapComponent.isMobile()" md-list-icon [ngClass]="{'srl-selected-path': op === activePath}">chevron_right</md-icon> <p md-line style="line-height: 30px; height: 30px;"> <span *ngFor="let path of op.path" class="srl-route-label" [style.background-color]="path.route.type.lineColor" [style.font-size]="mapComponent.isMobile() ? '12px' : null" mdTooltip="{{path.description}}" mdTooltipPosition="above">{{path.route.namePrefix}}{{path.route.namePostfix}}</span> <span class="srl-time-lbl">{{tripPeriod(op)}}</span> </p> <md-icon mdTooltip="{{'transport-map.search-result.open-details' | translate }}" mdTooltipPosition="above" (click)="openDetails(op, $event)" style="margin-left: 5px" [ngClass]="{'srl-selected-path': op === activePath}">access_time</md-icon> </md-list-item> </md-list> <!-- DETAILS --> <div *ngIf="flags.isDetailsOpen" [@flyInOut]="detailsTrigger"> <md-grid-list cols="7" rowHeight="56px" > <md-grid-tile> <md-icon>schedule</md-icon> </md-grid-tile> <md-grid-tile colspan="5"> <h3 class="srl-details-h" [translate]="'transport-map.search-result.trip-details'"></h3> </md-grid-tile> <md-grid-tile> <button md-mini-fab mdTooltip="{{'transport-map.search-result.back-to-summary' | translate }}" mdTooltipPosition="above" (click)="closeDetails()" color="accent"> <md-icon>close</md-icon> </button> </md-grid-tile> </md-grid-list> <hr/> <div *ngFor="let p of activePath.path; let i = index;"> <md-grid-list cols="10" rowHeight="50px"> <md-grid-tile colspan="2"> <img [src]="'/rest/data/transport-profile/route/marker/' + p.route.type.id"> </md-grid-tile> <md-grid-tile colspan="6" class="srl-details-item" (click)="flyToBusStop(activePath.way[i][0])"> <p class="srl-d-bs-lbl">{{activePath.way[i][0].name}}</p> </md-grid-tile> <md-grid-tile colspan="2">{{getBusStopTime(i, 'start')}}</md-grid-tile> <md-grid-tile colspan="2"> <span class="srl-route-label" [style.background-color]="p.route.type.lineColor">{{p.route.namePrefix}}{{p.route.namePostfix}}</span> </md-grid-tile> <md-grid-tile colspan="6" class="srl-details-item" (click)="flyToWay(activePath.way[i])"> <p class="srl-d-bs-lbl">{{p.description}}</p> </md-grid-tile> <md-grid-tile colspan="2">{{pathTripDuration(i, p)}} {{'common.time.min' | translate}}</md-grid-tile> <md-grid-tile colspan="2"> <img [src]="'/rest/data/transport-profile/route/marker/' + p.route.type.id"> </md-grid-tile> <md-grid-tile colspan="6" class="srl-details-item" (click)="flyToBusStop(activePath.way[i][activePath.way[i].length - 1])"> <p class="srl-d-bs-lbl">{{activePath.way[i][activePath.way[i].length - 1].name}}</p> </md-grid-tile> <md-grid-tile colspan="2">{{getBusStopTime(i, 'end')}}</md-grid-tile> </md-grid-list> <hr/> </div> <!-- Summary --> <md-grid-list cols="8" rowHeight="50px"> <md-grid-tile> <md-icon>directions_run</md-icon> </md-grid-tile> <md-grid-tile colspan="5"> <p class="srl-d-bs-lbl" [translate]="'transport-map.search-result.full-distance'"></p> </md-grid-tile> <md-grid-tile colspan="2"> {{summaryDistance()}} {{'common.unit.km' | translate}} </md-grid-tile> <md-grid-tile> <md-icon>alarm</md-icon> </md-grid-tile> <md-grid-tile colspan="5"> <p class="srl-d-bs-lbl" [translate]="'transport-map.search-result.full-time'"></p> </md-grid-tile> <md-grid-tile colspan="2"> {{summaryTime()}} {{'common.time.min' | translate}} </md-grid-tile> </md-grid-list> <button md-raised-button (click)="closeDetails()" class="full-width"> <md-icon>chevron_left</md-icon> {{'transport-map.search-result.back-to-summary' | translate }} </button> </div> </div> </div>
import platform import glob from .io import DxlIO, Dxl320IO, DxlError from .error import BaseErrorHandler from .controller import BaseDxlController from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor from ..robot import Robot def <API key>(): """ Tries to find the available usb2serial port on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') elif platform.system() == 'Windows': import _winreg import itertools ports = [] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) for i in itertools.count(): try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports return [] def get_available_ports(only_free=False): ports = <API key>() if only_free: ports = list(set(ports) - set(DxlIO.get_used_ports())) return ports def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned. """ for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): try: with DxlIOCls(port) as dxl: founds = len(dxl.scan(ids)) if strict and founds == len(ids): return port if not strict and founds >= len(ids) / 2: return port except DxlError: continue raise IndexError('No suitable port found for ids {}!'.format(ids)) def autodetect_robot(): """ Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """ motor_controllers = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): dxl_io = DxlIOCls(port) ids = dxl_io.scan() if not ids: dxl_io.close() continue models = dxl_io.get_model(ids) motorcls = { 'MX': DxlMXMotor, 'RX': DxlAXRXMotor, 'AX': DxlAXRXMotor, 'XL': DxlXL320Motor } motors = [motorcls[model[:2]](id, model=model) for id, model in zip(ids, models)] c = BaseDxlController(dxl_io, motors) motor_controllers.append(c) return Robot(motor_controllers)
package ppm_java._dev.concept.example.event; import ppm_java.backend.TController; import ppm_java.typelib.IControllable; import ppm_java.typelib.IEvented; import ppm_java.typelib.VBrowseable; class TSink extends VBrowseable implements IEvented, IControllable { public TSink (String id) { super (id); } public void OnEvent (int e, String arg0) { String msg; msg = GetID () + ": " + "Received messaging event. Message: " + arg0; System.out.println (msg); } public void Start () {/* Do nothing */} public void Stop () {/* Do nothing */} public void OnEvent (int e) {/* Do nothing */} public void OnEvent (int e, int arg0) {/* Do nothing */} public void OnEvent (int e, long arg0) {/* Do nothing */} protected void _Register () { TController.Register (this); } }
<?php // VPL for Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // VPL for Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the require_once dirname(__FILE__).'/../../../config.php'; require_once dirname(__FILE__).'/../locallib.php'; require_once dirname(__FILE__).'/../vpl.class.php'; require_once dirname(__FILE__).'/../vpl_submission.class.php'; require_once dirname(__FILE__).'/../views/sh_base.class.php'; require_once dirname(__FILE__).'/similarity_factory.class.php'; require_once dirname(__FILE__).'/similarity_base.class.php'; class vpl_diff{ /** * Remove chars and digits * @param $line string to process * @return string without chars and digits */ static function removeAlphaNum($line){ $ret=''; $l= strlen($line); //Parse line to remove alphanum chars for($i=0; $i<$l; $i++){ $c=$line[$i]; if(!ctype_alnum($c) && $c != ' '){ $ret.=$c; } } return $ret; } /** * Calculate the similarity of two lines * @param $line1 * @param $line2 * @return int (3 => trimmed equal, 2 =>removeAlphaNum , 1 => start of line , 0 => not equal) */ static function diffLine($line1,$line2){ //TODO Refactor. //This is a bad solution that must be rebuild to consider diferent languages //Compare trimed text $line1=trim($line1); $line2=trim($line2); if($line1==$line2){ if(strlen($line1)>0){ return 3; }else{ return 1; } } //Compare filtered text (removing alphanum) $rAN1=self::removeAlphaNum($line1); $limit = strlen($rAN1); if($limit>0){ if($limit>3){ $limite = 3; } if(strncmp($rAN1,self::removeAlphaNum($line2),$limit) == 0){ return 2; } } //Compare start of line $l=4; if($l>strlen($line1)){ $l=strlen($line1); } if($l>strlen($line2)){ $l=strlen($line2); } for($i=0; $i<$l; ++$i){ if($line1[$i] !=$line2[$i]){ break; } } return $i>0 ? 1:0; } static function newLineInfo($type,$ln1,$ln2=0){ $ret = new StdClass(); $ret->type = $type; $ret->ln1 = $ln1; $ret->ln2 = $ln2; return $ret; } /** * Initialize used matrix * @param $matrix matrix to initialize * @param $prev matrix to initialize * @param $nl1 number of rows * @param $nl2 number of columns * @return void */ static function <API key>(&$matrix,&$prev,$nl1,$nl2){ // matrix[0..nl1+1][0..nl2+1]=0 $row = array_pad(array(),$nl2+1,0); $matrix = array_pad(array(),$nl1+1,$row); // prev[0..nl1+1][0..nl2+1]=0 $prev = $matrix; //update first column for($i=0; $i<=$nl1;$i++){ $matriz[$i][0]=0; $prev[$i][0]=-1; } //update first row for($j=1; $j<=$nl2;$j++){ $matriz[0][$j]=0; $prev[0][$j]=1; } } /** * Calculate diff for two array of lines * @param $lines1 array of string * @param $lines2 array of string * @return array of objects with info to show the two array of lines */ static function calculateDiff($lines1,$lines2){ $ret = array(); $nl1=count($lines1); $nl2=count($lines2); if($nl1==0 && $nl2==0){ return false; } if($nl1==0){ //There is no first file foreach($lines2 as $pos => $line){ $ret[] = self::newLineInfo('>',0,$pos+1); } return $ret; } if($nl2==0){ //There is no second file foreach($lines1 as $pos => $line){ $ret[] = self::newLineInfo('<',$pos+1); } return $ret; } self::<API key>($matrix,$prev,$nl1,$nl2); //Matrix processing for($i=1; $i <= $nl1;$i++){ $line=$lines1[$i-1]; for($j=1; $j<=$nl2;$j++){ if($matrix[$i][$j-1]>$matrix[$i-1][$j]) { $max=$matrix[$i][$j-1]; $best = 1; }else{ $max=$matrix[$i-1][$j]; $best = -1; } $prize=self::diffLine($line,$lines2[$j-1]); if($matrix[$i-1][$j-1]+$prize>=$max){ $max=$matrix[$i-1][$j-1]+$prize; $best = 0; } $matrix[$i][$j]=$max; $prev[$i][$j]=$best; } } //Calculate show info $limit=$nl1+$nl2; $pairs = array(); $pi=$nl1; $pj=$nl2; while((!($pi == 0 && $pj == 0)) && $limit>0){ $pair = new stdClass(); $pair->i = $pi; $pair->j = $pj; $pairs[]=$pair; $p = $prev[$pi][$pj]; if($p == 0){ $pi $pj }elseif($p == -1){ $pi }else{ $pj } $limit } krsort($pairs); $prevpair = new stdClass(); $prevpair->i=0; $prevpair->j=0; foreach($pairs as $pair){ if($pair->i == $prevpair->i+1 && $pair->j == $prevpair->j+1){ //Regular advance if($lines1[$pair->i-1] == $lines2[$pair->j-1]){ //Equals $ret[]=self::newLineInfo('=',$pair->i,$pair->j); }else{ $ret[]=self::newLineInfo('#',$pair->i,$pair->j); } }elseif($pair->i == $prevpair->i+1){ //Removed next line $ret[]=self::newLineInfo('<',$pair->i); }elseif($pair->j == $prevpair->j+1){ //Added one line $ret[]=self::newLineInfo('>',0,$pair->j); }else{ debugging("Internal error ".print_r($pair,true)." ".print_r($prevpair,true)); } $prevpair=$pair; } return $ret; } static function show($filename1, $data1, $HTMLheader1, $filename2, $data2, $HTMLheader2) { //Get file lines $nl = vpl_detect_newline($data1); $lines1 = explode($nl,$data1); $nl = vpl_detect_newline($data2); $lines2 = explode($nl,$data2); //Get dif as an array of info $diff = self::calculateDiff($lines1,$lines2); if($diff === false){ return; } $separator= array('<'=>' <<< ', '>'=>' >>> ','='=>' === ',' $emptyline="&nbsp;\n"; $data1=''; $data2=''; $datal1=''; $datal2=''; $diffl=''; $lines1[-1]=''; $lines2[-1]=''; foreach($diff as $line){ $diffl.= $separator[$line->type]."\n"; if($line->ln1){ $datal1.=$line->ln1." \n"; $data1.=$lines1[$line->ln1-1]."\n"; }else{ $data1.=" \n"; $datal1.=$emptyline; } if($line->ln2){ $datal2.=$line->ln2." \n"; $data2.=$lines2[$line->ln2-1]."\n"; }else{ $data2.=" \n"; $datal2.=$emptyline; } } echo '<div style="width: 100%;min-width: 950px; overflow: auto">'; //Header echo '<div style="float:left; width: 445px">'; echo $HTMLheader1; echo '</div>'; echo '<div style="float:left; width: 445px">'; echo $HTMLheader2; echo '</div>'; echo '<div style="clear:both;"></div>'; //Files echo '<div style="float:left; text-align: right">'; echo '<pre class="'.vpl_sh_base::c_general.'">'; echo $datal1; echo '</pre>'; echo '</div>'; echo '<div style="float:left; width: 390px; overflow:auto">'; $shower= vpl_sh_factory::get_sh($filename1); $shower->print_file($filename1,$data1,false); echo '</div>'; echo '<div style="float:left">'; echo '<pre class="'.vpl_sh_base::c_general.'">'; echo $diffl; echo '</pre>'; echo '</div>'; echo '<div style="float:left; text-align: right;">'; echo '<pre class="'.vpl_sh_base::c_general.'">'; echo $datal2; echo '</pre>'; echo '</div>'; echo '<div style="float:left; width: 390px; overflow:auto">'; $shower= vpl_sh_factory::get_sh($filename2); $shower->print_file($filename2,$data2,false); echo '</div>'; echo '</div>'; echo '<div style="clear:both;"></div>'; } static function vpl_get_similfile($f,$vpl,&$HTMLheader,&$filename,&$data){ global $DB; $HTMLheader=''; $filename=''; $data=''; $type = required_param('type'.$f, PARAM_INT); if($type==1){ $subid = required_param('subid'.$f, PARAM_INT); $filename = required_param('filename'.$f, PARAM_TEXT); $subinstance = $DB->get_record('vpl_submissions',array('id' => $subid)); if($subinstance !== false){ $vpl = new mod_vpl(false,$subinstance->vpl); $vpl->require_capability(<API key>); $submission = new mod_vpl_submission($vpl,$subinstance); $user = $DB->get_record('user', array('id' => $subinstance->userid)); if($user){ $HTMLheader .='<a href="'.vpl_mod_href('/forms/submissionview.php', 'id',$vpl->get_course_module()->id,'userid',$subinstance->userid).'">'; } $HTMLheader .=s($filename).' '; if($user){ $HTMLheader .= '</a>'; $HTMLheader .= $vpl-><API key>($user); } $fg = $submission->get_submitted_fgm(); $data = $fg->getFileData($filename); \mod_vpl\event\vpl_diff_viewed::log($submission); } }elseif($type == 2){ //FIXME adapt to moodle 2.x /* global $CFG; $dirname = required_param('dirname'.$f,PARAM_RAW); $filename = required_param('filename'.$f,PARAM_RAW); $base=$CFG->dataroot.'/'.$vpl->get_course()->id.'/'; $data = file_get_contents($base.$dirname.'/'.$filename); $HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT); */ }elseif($type == 3){ global $CFG; $data=''; $zipname = required_param('zipfile'.$f,PARAM_RAW); $filename = required_param('filename'.$f,PARAM_RAW); $HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT); $ext = strtoupper(pathinfo($zipfile,PATHINFO_EXTENSION)); if($ext != 'ZIP'){ print_error('nozipfile'); } $zip = new ZipArchive(); $zipfilename=self::get_zip_filepath($zipname); if($zip->open($zipfilename)){ $data=$zip->getFromName($filename); $zip->close(); } }else{ print_error('type error'); } } }
package org.runnerup.notification; import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.app.NotificationCompat; import org.runnerup.R; import org.runnerup.common.util.Constants; import org.runnerup.view.MainLayout; @TargetApi(Build.VERSION_CODES.FROYO) public class GpsBoundState implements NotificationState { private final Notification notification; public GpsBoundState(Context context) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); Intent i = new Intent(context, MainLayout.class); i.setFlags(Intent.<API key> | Intent.<API key>); i.putExtra(Constants.Intents.FROM_NOTIFICATION, true); PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0); builder.setContentIntent(pi); builder.setContentTitle(context.getString(R.string.activity_ready)); builder.setContentText(context.getString(R.string.<API key>)); builder.setSmallIcon(R.drawable.icon); builder.setOnlyAlertOnce(true); org.runnerup.util.NotificationCompat.setLocalOnly(builder); notification = builder.build(); } @Override public Notification createNotification() { return notification; } }
package pl.idedyk.japanese.dictionary.web.html; import java.util.List; public class Ul extends HtmlElementCommon { public Ul() { super(); } public Ul(String clazz) { super(clazz); } public Ul(String clazz, String style) { super(clazz, style); } @Override protected String getTagName() { return "ul"; } @Override protected boolean <API key>() { return true; } @Override protected List<String[]> <API key>() { return null; } }
<?php class checkLink { const LINKFOUND = 1; const LINKNOTFOUND = 0; const LINKFOUNDNOFOLLOW = 2; const LINKDATAERROR = 3; public function get_data($url) { $ch = curl_init(); $timeout = 5; $userAgent = 'Googlebot/2.1 (http: curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,<API key>,1); curl_setopt($ch,<API key>,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } public function linkChoices($link) { $array = parse_url($link); $link1 = $array['host']; if (isset($array['port'])) { $link1 .= ":" . $array['port']; } if (isset($array['path'])) { $link1 .= $array['path']; } $links[0] = rtrim($link1,"/"); $links[1] = str_replace("www.", "", $links[0]); $links[2] = "http://".trim($links[1]); $links[3] = "http: return $links; } public function validateLink($url, $url_tofind) { $page = $this->get_data($url); if (!$page) return LINKDATAERROR; $urlchoices = $this->linkChoices($url_tofind); $dom = new DOMDocument(); @$dom->loadHTML($page); $x = new DOMXPath($dom); foreach($x->query("//a") as $node) { $link = rtrim($node->getAttribute("href"), "/"); $rel = $node->getAttribute("rel"); if (in_array($link, $urlchoices)) { if(strtolower($rel) == "nofollow") { return LINKFOUNDNOFOLLOW; } else { return LINKFOUND; } } } return LINKNOTFOUND; } } ?>
"use strict"; function HelpTutorial() { let _getText = function() { return "HelpTutorial_Base"; }; this.getName = function(){ return "HelpTutorial_Base"; }; this.getImageId = function(){ return "button_help"; }; this.getText = _getText; } function <API key>(name, image) { this.getName = function(){ return name; }; this.getImageId = function(){ return image; }; } function HelpQueueData(colonyState) { let queue = [new HelpTutorial()]; let available = []; let discovery = colonyState.getDiscovery(); for(let i = 0; i < discovery.length; i++) { if(discovery[i].startsWith("Resource_")) { queue.push(new <API key>(discovery[i], discovery[i])); } } let technology = colonyState.getTechnology(); for(let i = 0; i < technology.length; i++) { let item = PrototypeLib.get(technology[i]); available.push(new <API key>(technology[i], item.getBuildingImageId())); } QueueData.call(this, queue, available); this.getInfo = function(item) { let text = ""; if(item != null) { let imgSize = GetImageSize(ImagesLib.getImage(item.getImageId())); text += '<div class="queueInfo">'; if(item.getText != undefined) { text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">'; text += '<img class="queueInfoTitleImage" style="height: ' + imgSize.height + 'px;" src="' + ImagesLib.getFileName(item.getImageId()) + '">'; text += '<div class="queueInfoTitleData queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>'; text += '</div>'; text += '<div class="queueInfoDetails">' + TextRepository.get(item.getName() + "Description") + '</div>'; } else { let baseImgSize = GetImageSize(ImagesLib.getImage("baseTile")); text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">'; text += '<div style="float: left; height: ' + imgSize.height + 'px; background: url(\'' + ImagesLib.getFileName("baseTile") + '\') no-repeat; background-position: 0 ' + (imgSize.height - baseImgSize.height) + 'px;">'; text += '<img style="height: ' + imgSize.height + 'px; border-size: 0;" src="' + ImagesLib.getFileName(item.getImageId()) + '">'; text += '</div>'; text += '<div class="queueInfoTitleData">'; text += '<div class="queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>'; text += '<div class="<API key>">' + TextRepository.get(item.getName() + "Description") + '</div>'; text += '</div>'; text += '</div>'; text += '<div class="queueInfoDetails">'; let proto = PrototypeLib.get(item.getName()); text += '<table>'; text += '<tr><td class="tableMainColumn">' + TextRepository.get("TerrainLayer") + ':</td><td></td><td>' + TextRepository.get(proto.getTerrainLayer()) + '</td></tr>'; let list; let listItem; if(proto.getBuildingTime() > 0 || Object.keys(proto.getBuildingCost()).length > 0) { //text += '<tr><td>' + TextRepository.get("BuildingTitle") + '</td></tr>'; text += '<tr><td>' + TextRepository.get("BuildingTime") + ':</td><td class="tableDataRight">' + proto.getBuildingTime() + '</td><td>' + TextRepository.get("TimeUnit") + '</td></tr>'; list = proto.getBuildingCost(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingCost") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td>'; if(list[listItem] > colonyState.getProduced(listItem)) { text += '<td class="colorError">' + TextRepository.get("unavailable") + '</td>'; } text += '</tr>'; } } } } if(proto.getRequiredResource() != null) { text += '<tr><td>' + TextRepository.get("Requirements") + ':</td><td>' + TextRepository.get(proto.getRequiredResource()) + '</td></tr>'; } list = proto.getCapacity(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingCapacity") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } if((Object.keys(proto.getConsumption()).length + Object.keys(proto.getProduction()).length + Object.keys(proto.getProductionWaste()).length) > 0) { //text += '<tr><td>' + TextRepository.get("ProductionTitle") + '</td></tr>'; list = proto.getConsumption(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingConsumption") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } list = proto.getProduction(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingProduction") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } list = proto.getProductionWaste(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingWaste") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } } text += '</table>'; text += '</div>'; } text += '</div>'; } return text; }; this.isSortable = function() { return false; }; this.getTitle = function() { return "HelpTitle"; }; this.getQueueTitle = function() { return "HelpBase"; }; this.getAvailableTitle = function() { return "Buildings"; }; } HelpQueueData.inherits(QueueData);
/* Dylan Secreast * dsecrea2@uoregon.edu * CIS 415 Project 0 * This is my own work except for the base * code that was provided by Prof. Sventek */ #ifndef _DATE_H_INCLUDED_ #define _DATE_H_INCLUDED_ typedef struct date Date; /* * date_create creates a Date structure from `datestr` * `datestr' is expected to be of the form "dd/mm/yyyy" * returns pointer to Date structure if successful, * NULL if not (syntax error) */ Date *date_create(char *datestr); /* * date_duplicate creates a duplicate of `d' * returns pointer to new Date structure if successful, * NULL if not (memory allocation failure) */ Date *date_duplicate(Date *d); /* * date_compare compares two dates, returning <0, 0, >0 if * date1<date2, date1==date2, date1>date2, respectively */ int date_compare(Date *date1, Date *date2); /* * date_destroy returns any storage associated with `d' to the system */ void date_destroy(Date *d); #endif /* _DATE_H_INCLUDED_ */
#include "test-music.hpp" class test_mus_got: public test_music { public: test_mus_got() { this->type = "got"; this->numInstruments = 1; this->indexInstrumentOPL = 0; this->indexInstrumentMIDI = -1; this->indexInstrumentPCM = -1; } void addTests() { this->test_music::addTests(); // c00: Normal this->isInstance(MusicType::Certainty::PossiblyYes, this->standard()); // c01: Too short this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x01" "\x00\x00\x00" "\x00" )); // c02: Uneven length this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x01\x00" "\x00\x20\xAE" "\x00" "\x00\x00\x00" "\x00" )); // c03: Bad signature this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x02\x00" "\x00\x20\xAE" "\x00\x40\x7F" "\x00\x60\xED" "\x00\x80\xCB" "\x00\xE0\x06" "\x00\x23\xA7" "\x00\x43\x1F" "\x00\x63\x65" "\x00\x83\x43" "\x00\xE3\x02" "\x00\xC0\x04" "\x00\xA0\x44" "\x01\xB0\x32" "\x00\xB0\x12" "\x00\x00\x00" "\x00" )); // c04: Missing/incomplete loop-to-start marker this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x01\x00" "\x00\x20\xAE" "\x00\x40\x7F" "\x00\x60\xED" "\x00\x80\xCB" "\x00\xE0\x06" "\x00\x23\xA7" "\x00\x43\x1F" "\x00\x63\x65" "\x00\x83\x43" "\x00\xE3\x02" "\x00\xC0\x04" "\x00\xA0\x44" "\x01\xB0\x32" "\x00\xB0\x12" "\x00\x00\x00" )); } virtual std::string standard() { return STRING_WITH_NULLS( "\x01\x00" "\x00\x20\xFF" "\x00\x40\xFF" "\x00\x60\xFF" "\x00\x80\xFF" "\x00\xE0\x07" "\x00\x23\x0E" "\x00\x43\xBE" "\x00\x63\xEE" "\x00\x83\xEE" "\x00\xE3\x06" "\x00\xC0\x0F" "\x00\xA0\x44" "\x01\xB0\x32" "\x00\xB0\x12" "\x00\x00\x00" "\x00" ); } }; IMPLEMENT_TESTS(mus_got);
#include <fstream> #include <algorithm> #include "anime_db.hpp" #include "trim.hpp" bool anime_database::dump_anime_db(const astd::filesystem::path& db_path, const anime_database& db) { bool result = false; std::ofstream stream{ db_path.c_str(), std::ios::out | std::ios::trunc }; if (stream) { result = true; configuration_input::dump_config(stream, db.input); for (auto& num : db.number_fetched) { stream << num << std::endl; } } return result; } std::pair<bool, anime_database> anime_database::parse_anime_db(const astd::filesystem::path& db_path) { std::pair<bool, anime_database> result{ false, anime_database() }; std::ifstream stream{ db_path.c_str() }; if (stream) { std::string line; result.first = true; bool ok = true; std::size_t line_num = 1; while (result.first && std::getline(stream, line)) { auto trimmed_line = xts::trim<char>(line); ok = ok && configuration_input::parse_line(trimmed_line, result.second.input); if (!ok) { if (std::all_of(trimmed_line.begin(), trimmed_line.end(), [](auto& c) { return std::isdigit(c) != 0 || c == '.'; })) //if the line is a interger/float { result.second.number_fetched.emplace_back(trimmed_line.to_string()); } else //something when bad { result.first = false; } } if (!result.first) std::cerr << "error at line : no " << line_num << " : " << line << std::endl; line_num++; } } return result; }
public class Main { public static void main(String[] args) { ProdutoContext manga = new ProdutoContext(); System.out.println("Quantia: " + manga.getQuantia()); manga.fazerCompra(5); manga.reestocar(5); manga.fazerCompra(5); manga.reestocar(15); System.out.println("Quantia: " + manga.getQuantia()); manga.fazerCompra(5); System.out.println("Quantia: " + manga.getQuantia()); } }
using CatalokoService.Helpers.DTO; using CatalokoService.Helpers.FacebookAuth; using CatalokoService.Models; using System; using System.Web.Mvc; namespace CatalokoService.Controllers { public class HomeController : Controller { CatalokoEntities bd = new CatalokoEntities(); public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
var Util = require( 'findhit-util' ); // Data handles wizard data into session function Data ( route ) { var session = route.req[ route.router.options.reqSessionKey ]; // If there isn't a `wiz` object on session, just add it if( ! session.wiz ) { session.wiz = {}; } // Save route on this instance this.route = route; // Gather session from session, or just create a new one this.session = session.wiz[ route.id ] || ( session.wiz[ route.id ] = {} ); // Add a control variable for changed state this.changed = false; return this; }; // Export Data module.exports = Data; /* instance methods */ Data.prototype.currentStep = function ( step ) { // If there is no `step` provided, it means that we wan't to get! // Otherwise, lets set it! }; /* Data.prototype.save = function () { }; Data.prototype.destroy = function () { }; */ Data.prototype.getFromStep = function ( step ) { };
using System; namespace RadarrAPI { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
package com.delcyon.capo.protocol.server; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author jeremiah * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface <API key> { String name(); }
<html> <head> <title>datypus</title> <link rel="stylesheet" type="text/css" href="/css/datystyle.css"> <body> <div class="chart"></div> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script type="text/javascript"> var data = [4, 8, 15, 16, 2, 42]; var x = d3.scale.linear() .domain([0, d3.max(data)]) .range([0, 420]); d3.select(".chart") .selectAll("div") .data(data) .enter().append("div") .style("width", function(d) { return x(d) + "px"; }) .text(function(d) { return d; }); </script> </body> </html>
package weka.filters.unsupervised.attribute; import weka.filters.Filter; import weka.filters.UnsupervisedFilter; import weka.filters.unsupervised.attribute.Remove; import weka.clusterers.Clusterer; import weka.clusterers.<API key>; import weka.core.Attribute; import weka.core.Instances; import weka.core.Instance; import weka.core.OptionHandler; import weka.core.Range; import weka.core.FastVector; import weka.core.Option; import weka.core.Utils; import java.util.Enumeration; import java.util.Vector; /** * A filter that uses a clusterer to obtain cluster membership values * for each input instance and outputs them as new instances. The * clusterer needs to be a density-based clusterer. If * a (nominal) class is set, then the clusterer will be run individually * for each class.<p> * * Valid filter-specific options are: <p> * * Full class name of clusterer to use. Clusterer options may be * specified at the end following a -- .(required)<p> * * -I range string <br> * The range of attributes the clusterer should ignore. Note: * the class attribute (if set) is automatically ignored during clustering.<p> * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author Eibe Frank * @version $Revision: 1.7 $ */ public class ClusterMembership extends Filter implements UnsupervisedFilter, OptionHandler { /** The clusterer */ protected <API key> m_clusterer = new weka.clusterers.EM(); /** Array for storing the clusterers */ protected <API key>[] m_clusterers; /** Range of attributes to ignore */ protected Range <API key>; /** Filter for removing attributes */ protected Filter m_removeAttributes; /** The prior probability for each class */ protected double[] m_priors; /** * Sets the format of the input instances. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - only the * structure is required). * @return true if the outputFormat may be collected immediately * @exception Exception if the inputFormat can't be set successfully */ public boolean setInputFormat(Instances instanceInfo) throws Exception { super.setInputFormat(instanceInfo); m_removeAttributes = null; m_priors = null; return false; } /** * Signify that this batch of input to the filter is finished. * * @return true if there are instances pending output * @exception <API key> if no input structure has been defined */ public boolean batchFinished() throws Exception { if (getInputFormat() == null) { throw new <API key>("No input instance format defined"); } if (outputFormatPeek() == null) { Instances toFilter = getInputFormat(); Instances[] <API key>; // Make subsets if class is nominal if ((toFilter.classIndex() >= 0) && toFilter.classAttribute().isNominal()) { <API key> = new Instances[toFilter.numClasses()]; for (int i = 0; i < toFilter.numClasses(); i++) { <API key>[i] = new Instances(toFilter, toFilter.numInstances()); } for (int i = 0; i < toFilter.numInstances(); i++) { <API key>[(int)toFilter.instance(i).classValue()].add(toFilter.instance(i)); } m_priors = new double[toFilter.numClasses()]; for (int i = 0; i < toFilter.numClasses(); i++) { <API key>[i].compactify(); m_priors[i] = <API key>[i].sumOfWeights(); } Utils.normalize(m_priors); } else { <API key> = new Instances[1]; <API key>[0] = toFilter; m_priors = new double[1]; m_priors[0] = 1; } // filter out attributes if necessary if (<API key> != null || toFilter.classIndex() >= 0) { m_removeAttributes = new Remove(); String rangeString = ""; if (<API key> != null) { rangeString += <API key>.getRanges(); } if (toFilter.classIndex() >= 0) { if (rangeString.length() > 0) { rangeString += (","+(toFilter.classIndex()+1)); } else { rangeString = ""+(toFilter.classIndex()+1); } } ((Remove)m_removeAttributes).setAttributeIndices(rangeString); ((Remove)m_removeAttributes).setInvertSelection(false); ((Remove)m_removeAttributes).setInputFormat(toFilter); for (int i = 0; i < <API key>.length; i++) { <API key>[i] = Filter.useFilter(<API key>[i], m_removeAttributes); } } // build the clusterers if ((toFilter.classIndex() <= 0) || !toFilter.classAttribute().isNominal()) { m_clusterers = <API key>.makeCopies(m_clusterer, 1); m_clusterers[0].buildClusterer(<API key>[0]); } else { m_clusterers = <API key>.makeCopies(m_clusterer, toFilter.numClasses()); for (int i = 0; i < m_clusterers.length; i++) { if (<API key>[i].numInstances() == 0) { m_clusterers[i] = null; } else { m_clusterers[i].buildClusterer(<API key>[i]); } } } // create output dataset FastVector attInfo = new FastVector(); for (int j = 0; j < m_clusterers.length; j++) { if (m_clusterers[j] != null) { for (int i = 0; i < m_clusterers[j].numberOfClusters(); i++) { attInfo.addElement(new Attribute("pCluster_" + j + "_" + i)); } } } if (toFilter.classIndex() >= 0) { attInfo.addElement(toFilter.classAttribute().copy()); } attInfo.trimToSize(); Instances filtered = new Instances(toFilter.relationName()+"_clusterMembership", attInfo, 0); if (toFilter.classIndex() >= 0) { filtered.setClassIndex(filtered.numAttributes() - 1); } setOutputFormat(filtered); // build new dataset for (int i = 0; i < toFilter.numInstances(); i++) { convertInstance(toFilter.instance(i)); } } flushInput(); m_NewBatch = true; return (numPendingOutput() != 0); } /** * Input an instance for filtering. Ordinarily the instance is processed * and made available for output immediately. Some filters require all * instances be read before producing output. * * @param instance the input instance * @return true if the filtered instance may now be * collected with output(). * @exception <API key> if no input format has been defined. */ public boolean input(Instance instance) throws Exception { if (getInputFormat() == null) { throw new <API key>("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } if (outputFormatPeek() != null) { convertInstance(instance); return true; } bufferInput(instance); return false; } /** * Converts logs back to density values. */ protected double[] logs2densities(int j, Instance in) throws Exception { double[] logs = m_clusterers[j].<API key>(in); for (int i = 0; i < logs.length; i++) { logs[i] += Math.log(m_priors[j]); } return logs; } /** * Convert a single instance over. The converted instance is added to * the end of the output queue. * * @param instance the instance to convert */ protected void convertInstance(Instance instance) throws Exception { // set up values double [] instanceVals = new double[outputFormatPeek().numAttributes()]; double [] tempvals; if (instance.classIndex() >= 0) { tempvals = new double[outputFormatPeek().numAttributes() - 1]; } else { tempvals = new double[outputFormatPeek().numAttributes()]; } int pos = 0; for (int j = 0; j < m_clusterers.length; j++) { if (m_clusterers[j] != null) { double [] probs; if (m_removeAttributes != null) { m_removeAttributes.input(instance); probs = logs2densities(j, m_removeAttributes.output()); } else { probs = logs2densities(j, instance); } System.arraycopy(probs, 0, tempvals, pos, probs.length); pos += probs.length; } } tempvals = Utils.logs2probs(tempvals); System.arraycopy(tempvals, 0, instanceVals, 0, tempvals.length); if (instance.classIndex() >= 0) { instanceVals[instanceVals.length - 1] = instance.classValue(); } push(new Instance(instance.weight(), instanceVals)); } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector newVector = new Vector(2); newVector. addElement(new Option("\tFull name of clusterer to use (required).\n" + "\teg: weka.clusterers.EM", "W", 1, "-W <clusterer name>")); newVector. addElement(new Option("\tThe range of attributes the clusterer should ignore." +"\n\t(the class attribute is automatically ignored)", "I", 1,"-I <att1,att2-att4,...>")); return newVector.elements(); } /** * Parses the options for this object. Valid options are: <p> * * -W clusterer string <br> * Full class name of clusterer to use. Clusterer options may be * specified at the end following a -- .(required)<p> * * -I range string <br> * The range of attributes the clusterer should ignore. Note: * the class attribute (if set) is automatically ignored during clustering.<p> * * @param options the list of options as an array of strings * @exception Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String clustererString = Utils.getOption('W', options); if (clustererString.length() == 0) { throw new Exception("A clusterer must be specified" + " with the -W option."); } <API key>((<API key>)Utils. forName(<API key>.class, clustererString, Utils.partitionOptions(options))); <API key>(Utils.getOption('I', options)); Utils.<API key>(options); } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ public String [] getOptions() { String [] clustererOptions = new String [0]; if ((m_clusterer != null) && (m_clusterer instanceof OptionHandler)) { clustererOptions = ((OptionHandler)m_clusterer).getOptions(); } String [] options = new String [clustererOptions.length + 5]; int current = 0; if (!<API key>().equals("")) { options[current++] = "-I"; options[current++] = <API key>(); } if (m_clusterer != null) { options[current++] = "-W"; options[current++] = <API key>().getClass().getName(); } options[current++] = " System.arraycopy(clustererOptions, 0, options, current, clustererOptions.length); current += clustererOptions.length; while (current < options.length) { options[current++] = ""; } return options; } /** * Returns a string describing this filter * * @return a description of the filter suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "A filter that uses a density-based clusterer to generate cluster " + "membership values; filtered instances are composed of these values " + "plus the class attribute (if set in the input data). If a (nominal) " + "class attribute is set, the clusterer is run separately for each " + "class. The class attribute (if set) and any user-specified " + "attributes are ignored during the clustering operation"; } /** * Returns a description of this option suitable for display * as a tip text in the gui. * * @return description of this option */ public String clustererTipText() { return "The clusterer that will generate membership values for the instances."; } /** * Set the clusterer for use in filtering * * @param newClusterer the clusterer to use */ public void <API key>(<API key> newClusterer) { m_clusterer = newClusterer; } /** * Get the clusterer used by this filter * * @return the clusterer used */ public <API key> <API key>() { return m_clusterer; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String <API key>() { return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last"; } /** * Gets ranges of attributes to be ignored. * * @return a string containing a comma-separated list of ranges */ public String <API key>() { if (<API key> == null) { return ""; } else { return <API key>.getRanges(); } } /** * Sets the ranges of attributes to be ignored. If provided string * is null, no attributes will be ignored. * * @param rangeList a string representing the list of attributes. * eg: first-3,5,6-last * @exception <API key> if an invalid range list is supplied */ public void <API key>(String rangeList) { if ((rangeList == null) || (rangeList.length() == 0)) { <API key> = null; } else { <API key> = new Range(); <API key>.setRanges(rangeList); } } /** * Main method for testing this class. * * @param argv should contain arguments to the filter: use -h for help */ public static void main(String [] argv) { try { if (Utils.getFlag('b', argv)) { Filter.batchFilterFile(new ClusterMembership(), argv); } else { Filter.filterFile(new ClusterMembership(), argv); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
package org.mycore.util.concurrent; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; public class MCRPrioritySupplier<T> implements Supplier<T>, MCRPrioritizable { private static AtomicLong CREATION_COUNTER = new AtomicLong(0); private Supplier<T> delegate; private int priority; private long created; public MCRPrioritySupplier(Supplier<T> delegate, int priority) { this.delegate = delegate; this.priority = priority; this.created = CREATION_COUNTER.incrementAndGet(); } @Override public T get() { return delegate.get(); } @Override public int getPriority() { return this.priority; } @Override public long getCreated() { return created; } /** * use this instead of {@link CompletableFuture#supplyAsync(Supplier, Executor)} * * This method keep the priority * @param es * @return */ public CompletableFuture<T> runAsync(ExecutorService es) { CompletableFuture<T> result = new CompletableFuture<>(); MCRPrioritySupplier<T> supplier = this; class <API key> implements Runnable, MCRPrioritizable, CompletableFuture.<API key> { @Override @SuppressWarnings("PMD.<API key>") public void run() { try { if (!result.isDone()) { result.complete(supplier.get()); } } catch (Throwable t) { result.<API key>(t); } } @Override public int getPriority() { return supplier.getPriority(); } @Override public long getCreated() { return supplier.getCreated(); } } es.execute(new <API key>()); return result; } }
<ion-header> <ion-navbar> <ion-title>Login</ion-title> </ion-navbar> </ion-header> <ion-content padding> <!-- Shows error message is socket is not connected. --> <ion-item no-lines *ngIf="!loginManager.loginAvailable()"> <ion-label style="color: #ea6153"> Login service unavailable as cannot connect to server. </ion-label> </ion-item> <!-- Shows a login error message if one exists. --> <ion-item no-lines *ngIf="loginErrorMessage"> <ion-label style="color: #ea6153"> {{loginErrorMessage}} </ion-label> </ion-item> <form (ngSubmit)="doLogin()" [formGroup]="loginForm"> <!-- Username input field --> <ion-item> <ion-label>Username</ion-label> <ion-input type="text" formControlName="username"></ion-input> </ion-item> <!-- Invalid username error --> <ion-item no-lines *ngIf="!loginForm.controls.username.valid && loginForm.controls.username.dirty"> <ion-label style="color: #ea6153"> Invalid username. </ion-label> </ion-item> <!-- Password input field --> <ion-item> <ion-label>Password</ion-label> <ion-input type="password" formControlName="password"></ion-input> </ion-item> <!-- Invalid password error --> <ion-item no-lines *ngIf="!loginForm.controls.password.valid && loginForm.controls.password.dirty"> <ion-label style="color: #ea6153"> Invalid password </ion-label> </ion-item> <br /> <!-- Login button --> <span> <button ion-button type="submit" color="primary" [disabled]="!loginManager.loginAvailable()">Login</button> </span> <!-- Skip login button --> <span *ngIf="!popped"> <button type="button" ion-button color="dark" (click)="doLeavePage()" clear>Skip</button> </span> </form> </ion-content>
#include <iostream> using namespace std; int main() { int n, x, y; cin >> n; int a[n]; for (int i = 0; i < n; ++i) { cin >> a[i]; } x = a[1] - a[0]; y = a[2] - a[0]; for (int i = 2; i < n; ++i) { x = max(a[i] - a[i - 1], x); y = min(a[i] - a[i - 2], y); } cout << max(x, y); }
<?php namespace PrivCode; defined('ROOT_DIR') or die('Forbidden'); use PrivCode\Database\Database; class BaseModel extends Database { public function __construct() { parent::__construct(); } } /* End of file URI.php */ /* Location: ./System/URI/URI.php */
package com.power.text.Run; import static com.power.text.dialogs.WebSearch.squerry; import java.awt.Desktop; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.swing.JOptionPane; import static com.power.text.Main.searchbox; /** * * @author thecarisma */ public class WikiSearch { public static void wikisearch(){ String searchqueryw = searchbox.getText(); searchqueryw = searchqueryw.replace(' ', '-'); String squeryw = squerry.getText(); squeryw = squeryw.replace(' ', '-'); if ("".equals(searchqueryw)){ searchqueryw = squeryw ; } else {} String url = "https: try { URI uri = new URL(url).toURI(); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) desktop.browse(uri); } catch (URISyntaxException | IOException e) { /* * I know this is bad practice * but we don't want to do anything clever for a specific error */ JOptionPane.showMessageDialog(null, e.getMessage()); // Copy URL to the clipboard so the user can paste it into their browser StringSelection stringSelection = new StringSelection(url); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(stringSelection, null); // Notify the user of the failure System.out.println("This program just tried to open a webpage." + "\n" + "The URL has been copied to your clipboard, simply paste into your browser to accessWebpage: " + url); } } }
package org.jbpt.pm.bpmn; import org.jbpt.pm.IDataNode; /** * Interface class for BPMN Document. * * @author Cindy Fhnrich */ public interface IDocument extends IDataNode { /** * Marks this Document as list. */ public void markAsList(); /** * Unmarks this Document as list. */ public void unmarkAsList(); /** * Checks whether the current Document is a list. * @return */ public boolean isList(); }
#include <QtGui/QApplication> #include "xmlparser.h" #include "myfiledialog.h" #include <iostream> #include <QMessageBox> using namespace std; int main(int argc, char *argv[]) { QApplication a(argc, argv);/* MainWindow w; w.show();*/ MyFileDialog my;//Create dialog QString name=my.openFile();//Open dialog, and chose file. We get file path and file name as result cout<<name.toUtf8().constData()<<"Podaci uspješno uèitani!"; return 0; }
// SuperTuxKart - a fun racing game with go-kart // This program is free software; you can redistribute it and/or // as published by the Free Software Foundation; either version 3 // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef <API key> #define <API key> #include "config/player.hpp" #include "karts/controller/controller.hpp" class AbstractKart; class Player; class SFXBase; /** PlayerKart manages control events from the player and moves * them to the Kart * * \ingroup controller */ class PlayerController : public Controller { private: int m_steer_val, m_steer_val_l, m_steer_val_r; int m_prev_accel; bool m_prev_brake; bool m_prev_nitro; float m_penalty_time; SFXBase *m_bzzt_sound; SFXBase *m_wee_sound; SFXBase *m_ugh_sound; SFXBase *m_grab_sound; SFXBase *m_full_sound; void steer(float, int); public: PlayerController (AbstractKart *kart, StateManager::ActivePlayer *_player, unsigned int player_index); ~PlayerController (); void update (float); void action (PlayerAction action, int value); void handleZipper (bool play_sound); void collectedItem (const Item &item, int add_info=-1, float previous_energy=0); virtual void skidBonusTriggered(); virtual void setPosition (int p); virtual void finishedRace (float time); virtual bool isPlayerController() const {return true;} virtual bool isNetworkController() const { return false; } virtual void reset (); void resetInputState (); virtual void crashed (const AbstractKart *k) {} virtual void crashed (const Material *m) {} /** Player will always be able to get a slipstream bonus. */ virtual bool <API key>() const { return false; } /** Callback whenever a new lap is triggered. Used by the AI * to trigger a recomputation of the way to use. */ virtual void newLap(int lap) {} }; #endif
// ArduinoJson - arduinojson.org #pragma once #include "../Array/ArrayShortcuts.hpp" #include "../Object/ObjectShortcuts.hpp" namespace <API key> { template <typename TVariant> class VariantShortcuts : public ObjectShortcuts<TVariant>, public ArrayShortcuts<TVariant> { public: using ArrayShortcuts<TVariant>::createNestedArray; using ArrayShortcuts<TVariant>::createNestedObject; using ArrayShortcuts<TVariant>::operator[]; using ObjectShortcuts<TVariant>::createNestedArray; using ObjectShortcuts<TVariant>::createNestedObject; using ObjectShortcuts<TVariant>::operator[]; }; } // namespace <API key>
// NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin #ifndef <API key> #define <API key> #include "MantidAPI/IPeaksWorkspace.h" #include "MantidAPI/Run.h" #include "MantidDataObjects/PeakShapeSpherical.h" #include "MantidDataObjects/PeaksWorkspace.h" #include "MantidKernel/WarningSuppressions.h" #include "MantidVatesAPI/<API key>.h" #include "MockObjects.h" #include <vtkPolyData.h> #include <vtkSmartPointer.h> #include <cxxtest/TestSuite.h> #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace Mantid; using namespace Mantid::Kernel; using namespace Mantid::API; using namespace Mantid::Geometry; using namespace Mantid::DataObjects; using namespace ::testing; using namespace Mantid::VATES; using Mantid::VATES::<API key>; <API key> class MockPeakShape : public Peak { public: MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getPeakShape, const Mantid::Geometry::PeakShape &(void)); }; class MockPeak : public Peak { public: MOCK_CONST_METHOD0(getHKL, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQLabFrame, Mantid::Kernel::V3D(void)); MOCK_CONST_METHOD0(getQSampleFrame, Mantid::Kernel::V3D(void)); }; class MockPeaksWorkspace : public PeaksWorkspace { using Mantid::DataObjects::PeaksWorkspace::addPeak; public: MOCK_METHOD1(setInstrument, void(const Mantid::Geometry::<API key> &inst)); MOCK_CONST_METHOD0(clone, Mantid::DataObjects::PeaksWorkspace *()); MOCK_CONST_METHOD0(getNumberPeaks, int()); MOCK_METHOD1(removePeak, void(int peakNum)); MOCK_METHOD1(addPeak, void(const IPeak &ipeak)); MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak &(int peakNum)); MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak &(int peakNum)); }; <API key> // Functional Tests class <API key> : public CxxTest::TestSuite { public: void do_test(MockPeak &peak1, <API key>::ePeakDimensions dims) { FakeProgressAction updateProgress; auto pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; // Peaks workspace will return 5 identical peaks EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(5)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); <API key> factory("signal", dims); factory.initialize(pw_ptr); auto set = factory.create(updateProgress); // As the marker type are three axes(2 points), we expect 5*2*3 points // The angle is 0 degrees and the size is 0.3 TS_ASSERT(set); TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 30); TS_ASSERT(testing::Mock::<API key>(&pw)); TS_ASSERT(testing::Mock::<API key>(&peak1)); } void <API key>() { MockPeak peak1; EXPECT_CALL(peak1, getQLabFrame()).WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getHKL()).Times(AnyNumber()); EXPECT_CALL(peak1, getQSampleFrame()).Times(AnyNumber()); MockProgressAction mockProgress; // Expectation checks that progress should be >= 0 and <= 100 and called at // least once! EXPECT_CALL(mockProgress, eventRaised(AllOf(Le(100), Ge(0)))) .Times(AtLeast(1)); boost::shared_ptr<MockPeaksWorkspace> pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; // Peaks workspace will return 5 identical peaks EXPECT_CALL(pw, getNumberPeaks()).WillRepeatedly(Return(5)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); <API key> factory("signal", <API key>::Peak_in_Q_lab); factory.initialize(pw_ptr); auto set = factory.create(mockProgress); TSM_ASSERT("Progress Updates not used as expected.", Mock::<API key>(&mockProgress)); } void test_q_lab() { MockPeak peak1; EXPECT_CALL(peak1, getQLabFrame()) .Times(5) .WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getHKL()).Times(0); EXPECT_CALL(peak1, getQSampleFrame()).Times(0); do_test(peak1, <API key>::Peak_in_Q_lab); } void test_q_sample() { MockPeak peak1; EXPECT_CALL(peak1, getQSampleFrame()) .Times(5) .WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getHKL()).Times(0); EXPECT_CALL(peak1, getQLabFrame()).Times(0); do_test(peak1, <API key>::Peak_in_Q_sample); } void test_hkl() { MockPeak peak1; EXPECT_CALL(peak1, getHKL()).Times(5).WillRepeatedly(Return(V3D(1, 2, 3))); EXPECT_CALL(peak1, getQLabFrame()).Times(0); EXPECT_CALL(peak1, getQSampleFrame()).Times(0); do_test(peak1, <API key>::Peak_in_HKL); } void <API key>() { using namespace Mantid::VATES; using namespace Mantid::API; IMDWorkspace *nullWorkspace = nullptr; Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace); <API key> factory("signal"); TSM_ASSERT_THROWS( "No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::runtime_error); } void <API key>() { FakeProgressAction progressUpdate; <API key> factory("signal"); TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error); } void testTypeName() { <API key> factory("signal"); TS_ASSERT_EQUALS("<API key>", factory.getFactoryTypeName()); } void <API key>() { <API key> factory("signal"); TS_ASSERT_EQUALS(-1, factory.<API key>()); } void <API key>() { <API key> factory("signal"); TS_ASSERT_EQUALS(false, factory.<API key>()); } void <API key>() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); const double expectedRadius = -1; // The default // Note that no PeaksRadius property has been set. <API key> factory("signal"); factory.initialize( Mantid::API::<API key>(std::move(mockWorkspace))); TS_ASSERT_EQUALS(expectedRadius, factory.<API key>()); } void <API key>() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); // Note that no PeaksRadius property has been set. <API key> factory("signal"); factory.initialize( Mantid::API::<API key>(std::move(mockWorkspace))); TS_ASSERT_EQUALS( false, factory.<API key>()); // false is the default } void <API key>() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); const double expectedRadius = 4; mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius, true); // Has a PeaksRadius so must // have been processed via // IntegratePeaksMD <API key> factory("signal"); factory.initialize( Mantid::API::<API key>(std::move(mockWorkspace))); TS_ASSERT_EQUALS(expectedRadius, factory.<API key>()); } void <API key>() { auto mockWorkspace = Mantid::Kernel::make_unique<MockPeaksWorkspace>(); const double expectedRadius = 4; mockWorkspace->mutableRun().addProperty("PeakRadius", expectedRadius, true); // Has a PeaksRadius so must // have been processed via // IntegratePeaksMD <API key> factory("signal"); factory.initialize( Mantid::API::<API key>(std::move(mockWorkspace))); TS_ASSERT_EQUALS(true, factory.<API key>()); } void testShapeOfSphere() { FakeProgressAction updateProgress; auto pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; double actualRadius = 2.0; PeakShapeSpherical sphere(actualRadius, Kernel::<API key>::QLab); MockPeakShape peak1; EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(1)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); EXPECT_CALL(peak1, getQLabFrame()).WillRepeatedly(Return(V3D(0., 0., 0.))); EXPECT_CALL(peak1, getPeakShape()).WillRepeatedly(ReturnRef(sphere)); <API key> factory("signal"); factory.initialize(pw_ptr); auto set = factory.create(updateProgress); TS_ASSERT(set); TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 300); for (vtkIdType i = 0; i < set->GetNumberOfPoints(); ++i) { double pt[3]; set->GetPoint(i, pt); double radius = std::sqrt(pt[0] * pt[0] + pt[1] * pt[1] + pt[2] * pt[2]); TS_ASSERT_DELTA(radius, actualRadius, 1.0e-5); } TS_ASSERT(testing::Mock::<API key>(&pw)); TS_ASSERT(testing::Mock::<API key>(&peak1)); } void <API key>() { FakeProgressAction updateProgress; auto pw_ptr = boost::make_shared<MockPeaksWorkspace>(); MockPeaksWorkspace &pw = *pw_ptr; // rotate in 60 degree increments in the x-y plane. for (size_t dir = 0; dir < 6; ++dir) { double theta = 2. * M_PI * static_cast<double>(dir) / 6.; std::vector<Mantid::Kernel::V3D> directions{ {cos(theta), -1. * sin(theta), 0.}, {sin(theta), cos(theta), 0.}, {0., 0., 1.}}; std::vector<double> abcRadii{1., 2., 3.}; // not using these but the constructor requires we set a value. std::vector<double> <API key>{1., 2., 3.}; std::vector<double> <API key>{1., 2., 3.}; PeakShapeEllipsoid ellipsoid( directions, abcRadii, <API key>, <API key>, Kernel::<API key>::QLab); MockPeakShape peak1; EXPECT_CALL(pw, getNumberPeaks()).WillOnce(Return(1)); EXPECT_CALL(pw, getPeak(_)).WillRepeatedly(ReturnRef(peak1)); EXPECT_CALL(peak1, getQLabFrame()) .WillRepeatedly(Return(V3D(0., 0., 0.))); EXPECT_CALL(peak1, getPeakShape()).WillRepeatedly(ReturnRef(ellipsoid)); <API key> factory("signal"); factory.initialize(pw_ptr); auto set = factory.create(updateProgress); TS_ASSERT(set); TS_ASSERT_EQUALS(set->GetNumberOfPoints(), 300); // Use the standard equation of an ellipsoid to test the resulting // workspace. for (vtkIdType i = 0; i < set->GetNumberOfPoints(); ++i) { double pt[3]; set->GetPoint(i, pt); double rot_x = pt[0] * cos(theta) - pt[1] * sin(theta); double rot_y = pt[0] * sin(theta) + pt[1] * cos(theta); double test = rot_x * rot_x / (abcRadii[0] * abcRadii[0]) + rot_y * rot_y / (abcRadii[1] * abcRadii[1]) + pt[2] * pt[2] / (abcRadii[2] * abcRadii[2]); TS_ASSERT_DELTA(test, 1., 1.0e-5); } TS_ASSERT(testing::Mock::<API key>(&pw)); TS_ASSERT(testing::Mock::<API key>(&peak1)); } } }; #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace SimpleDownload { public partial class Downloader : Form { public Downloader() { InitializeComponent(); } public void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Download dn=new Download(); dn.DownloadFile(url.Text, @"c:\NewImages\"); } } }
<patTemplate:tmpl name="_widget"> <script type="text/javascript"> //<![CDATA[ function addItem(){ if (!window.confirm('?')) return false; document.main.act.value = 'add'; document.main.submit(); return true; } function updateItem(){ if (!window.confirm('?')) return false; document.main.act.value='update'; document.main.submit(); return true; } function selectItem() { document.main.act.value = 'select'; document.main.submit(); return true; } function listItem(){ document.main.task.value = 'list'; document.main.submit(); return true; } $(function(){ // WYSIWYG m3SetWysiwygEditor('item_html', 450); }); </script> <div align="center"> <br /> <!-- m3:ErrorMessage --> <form method="post" name="main"> <input type="hidden" name="task" /> <input type="hidden" name="act" /> <input type="hidden" name="serial" value="{SERIAL}" /> <!-- m3:PostParam --> <table width="90%"> <tr><td><label>HTML</label></td> <td align="right"><input type="button" class="button" onclick="listItem();" value="" /> </td></tr> <tr><td colspan="2"> <table class="simple-table" style="margin: 0 auto;width:950px;"> <tbody> <tr> <td class="table-headside" width="150"></td> <td> <select name="item_id" onchange="selectItem();" {ID_DISABLED}> <option value="0">-- --</option> <patTemplate:tmpl name="title_list"> <option value="{VALUE}" {SELECTED}>{NAME}</option> </patTemplate:tmpl> </select> <patTemplate:tmpl name="item_name_visible" visibility="hidden"> <input type="text" name="item_name" value="{NAME}" size="40" maxlength="40" /> </patTemplate:tmpl> </td> </tr> <tr class="even"> <td class="table-headside">HTML</td> <td><textarea name="item_html">{HTML}</textarea></td> </tr> <tr> <td align="right" colspan="2"> <patTemplate:tmpl name="del_button" visibility="hidden"> <input type="button" class="button" onclick="deleteItem();" value="" /> </patTemplate:tmpl> <patTemplate:tmpl name="update_button" visibility="hidden"> <input type="button" class="button" onclick="updateItem();" value="" /> </patTemplate:tmpl> <patTemplate:tmpl name="add_button" visibility="hidden"> <input type="button" class="button" onclick="addItem();" value="" /> </patTemplate:tmpl> </td> </tr> </tbody> </table> </td></tr> </table> </form> </div> </patTemplate:tmpl>
<?php header('Content-Type: text/html; charset=iso-8859-1'); $sufijo= "col_"; echo ' <html> <link rel= "stylesheet" href= "./css/queryStyle.css"></style> <div id="paginado" style="display:none"> <input id="pagina" type="text" value="1"> <input id="pgcolonia" type="text" value=""> <input id="pgestado" type="text" value=""> <input id="pgciudad" type="text" value=""> <input id="pgcp" type="text" value=""> </div> <center><div id= "divbusqueda"> <form id="frmbusqueda" method="post" action=""> <table class="queryTable" colspan= "7"> <tr><td class= "queryRowsnormTR" width ="180">Por nombre de la colonia: </td><td class= "queryRowsnormTR" width ="250"><input type= "text" id= "nomcolonia"></td><td rowspan= "4"><img id="'.$sufijo.'buscar" align= "left" src= "./img/grids/view.png" width= "25" height= "25" alt="Buscar"/></td></tr> <tr><td class= "queryRowsnormTR">Por codigo postal: </td><td class= "queryRowsnormTR"><input type= "text" id= "cpcolonia"></td><td></td></tr> <tr><td class= "queryRowsnormTR">Por ciudad: </td><td class= "queryRowsnormTR"><input type= "text" id= "ciucolonia"></td><td></td></tr> <tr><td class= "queryRowsnormTR">Por estado: </td><td class= "queryRowsnormTR"><input type= "text" id= "estcolonia"></td><td></td></tr> </table> </form> </div></center>'; echo '<div id= "busRes">'; include_once("catColonias.php"); echo '</div> </html>'; ?>
from numpy import sqrt from pacal.standard_distr import NormalDistr, ChiSquareDistr from pacal.distr import Distr, SumDistr, DivDistr, InvDistr from pacal.distr import sqrt as distr_sqrt class NoncentralTDistr(DivDistr): def __init__(self, df = 2, mu = 0): d1 = NormalDistr(mu, 1) d2 = distr_sqrt(ChiSquareDistr(df) / df) super(NoncentralTDistr, self).__init__(d1, d2) self.df = df self.mu = mu def __str__(self): return "NoncentralTDistr(df={0},mu={1})#{2}".format(self.df, self.mu, self.id()) def getName(self): return "NoncT({0},{1})".format(self.df, self.mu) class <API key>(SumDistr): def __new__(cls, df, lmbda = 0): assert df >= 1 d1 = NormalDistr(sqrt(lmbda))**2 if df == 1: return d1 d2 = ChiSquareDistr(df - 1) ncc2 = super(<API key>, cls).__new__(cls, d1, d2) super(<API key>, ncc2).__init__(d1, d2) ncc2.df = df ncc2.lmbda = lmbda return ncc2 def __init__(self, df, lmbda = 0): pass def __str__(self): return "NoncentralChiSquare(df={0},lambda={1})#{2}".format(self.df, self.lmbda, self.id()) def getName(self): return "NoncChi2({0},{1})".format(self.df, self.lmbda) class NoncentralBetaDistr(InvDistr): def __init__(self, alpha = 1, beta = 1, lmbda = 0): d = 1 + ChiSquareDistr(2.0 * beta) / <API key>(2 * alpha, lmbda) super(NoncentralBetaDistr, self).__init__(d) self.alpha = alpha self.beta = beta self.lmbda = lmbda def __str__(self): return "NoncentralBetaDistr(alpha={0},beta={1},lambda={2})#{3}".format(self.alpha, self.beta, self.lmbda, self.id()) def getName(self): return "NoncBeta({0},{1},{2})".format(self.alpha, self.beta, self.lmbda) class NoncentralFDistr(DivDistr): def __init__(self, df1 = 1, df2 = 1, lmbda = 0): d1 = <API key>(df1, lmbda) / df1 d2 = ChiSquareDistr(df2) / df2 super(NoncentralFDistr, self).__init__(d1, d2) self.df1 = df1 self.df2 = df2 self.lmbda = lmbda def __str__(self): return "NoncentralFDistr(df1={0},df2={1},lambda={2})#{3}".format(self.df1, self.df2, self.lmbda, self.id()) def getName(self): return "NoncF({0},{1},{2})".format(self.df1, self.df2, self.lmbda)
IWitness.ErrorsView = Ember.View.extend({ classNames: ["error-bubble"], classNameBindings: ["isError"], isError: function() { return !!this.get("error"); }.property("error") });
package ch.ethz.dcg.jukefox.model.collection; public class MapTag extends BaseTag { float[] coordsPca2D; private float varianceOverPCA; public MapTag(int id, String name, float[] coordsPca2D, float varianceOverPCA) { super(id, name); this.coordsPca2D = coordsPca2D; this.varianceOverPCA = varianceOverPCA; } public float[] getCoordsPca2D() { return coordsPca2D; } public float getVarianceOverPCA() { return varianceOverPCA; } }
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the require_once(dirname(dirname(__FILE__)) . '/config.php'); require_once($CFG->libdir . '/badgeslib.php'); $badgeid = required_param('id', PARAM_INT); $copy = optional_param('copy', 0, PARAM_BOOL); $activate = optional_param('activate', 0, PARAM_BOOL); $deactivate = optional_param('lock', 0, PARAM_BOOL); $confirm = optional_param('confirm', 0, PARAM_BOOL); $return = optional_param('return', 0, PARAM_LOCALURL); require_login(); $badge = new badge($badgeid); $context = $badge->get_context(); $navurl = new moodle_url('/badges/index.php', array('type' => $badge->type)); if ($badge->type == BADGE_TYPE_COURSE) { require_login($badge->courseid); $navurl = new moodle_url('/badges/index.php', array('type' => $badge->type, 'id' => $badge->courseid)); $PAGE->set_pagelayout('standard'); navigation_node::override_active_url($navurl); } else { $PAGE->set_pagelayout('admin'); navigation_node::override_active_url($navurl, true); } $PAGE->set_context($context); $PAGE->set_url('/badges/action.php', array('id' => $badge->id)); if ($return !== 0) { $returnurl = new moodle_url($return); } else { $returnurl = new moodle_url('/badges/overview.php', array('id' => $badge->id)); } $returnurl->remove_params('awards'); if ($copy) { require_sesskey(); require_capability('moodle/badges:createbadge', $context); $cloneid = $badge->make_clone(); // If a user can edit badge details, they will be redirected to the edit page. if (has_capability('moodle/badges:configuredetails', $context)) { redirect(new moodle_url('/badges/edit.php', array('id' => $cloneid, 'action' => 'details'))); } redirect(new moodle_url('/badges/overview.php', array('id' => $cloneid))); } if ($activate) { require_capability('moodle/badges:configurecriteria', $context); $PAGE->url->param('activate', 1); $status = ($badge->status == <API key>) ? BADGE_STATUS_ACTIVE : <API key>; if ($confirm == 1) { require_sesskey(); list($valid, $message) = $badge->validate_criteria(); if ($valid) { $badge->set_status($status); if ($badge->type == BADGE_TYPE_SITE) { // Review on cron if there are more than 1000 users who can earn a site-level badge. $sql = 'SELECT COUNT(u.id) as num FROM {user} u LEFT JOIN {badge_issued} bi ON u.id = bi.userid AND bi.badgeid = :badgeid WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0'; $toearn = $DB->get_record_sql($sql, array('badgeid' => $badge->id, 'guestid' => $CFG->siteguest)); if ($toearn->num < 1000) { $awards = $badge->review_all_criteria(); $returnurl->param('awards', $awards); } else { $returnurl->param('awards', 'cron'); } } else { $awards = $badge->review_all_criteria(); $returnurl->param('awards', $awards); } redirect($returnurl); } else { echo $OUTPUT->header(); echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . $message); echo $OUTPUT->continue_button($returnurl); echo $OUTPUT->footer(); die(); } } $strheading = get_string('reviewbadge', 'badges'); $PAGE->navbar->add($strheading); $PAGE->set_title($strheading); $PAGE->set_heading($badge->name); echo $OUTPUT->header(); echo $OUTPUT->heading($strheading); $params = array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(), 'confirm' => 1, 'return' => $return); $url = new moodle_url('/badges/action.php', $params); if (!$badge->has_criteria()) { echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . get_string('nocriteria', 'badges')); echo $OUTPUT->continue_button($returnurl); } else { $message = get_string('reviewconfirm', 'badges', $badge->name); echo $OUTPUT->confirm($message, $url, $returnurl); } echo $OUTPUT->footer(); die; } if ($deactivate) { require_sesskey(); require_capability('moodle/badges:configurecriteria', $context); $status = ($badge->status == BADGE_STATUS_ACTIVE) ? <API key> : <API key>; $badge->set_status($status); redirect($returnurl); }
package de.ailis.microblinks.l.lctrl.shell; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.util.Arrays; import de.ailis.microblinks.l.lctrl.resources.Resources; /** * Base class for all CLI programs. * * @author Klaus Reimer (k@ailis.de) */ public abstract class CLI { /** The command-line program name. */ private final String name; /** The short options. */ private final String shortOpts; /** The long options. */ private final LongOpt[] longOpts; /** Debug mode. */ private boolean debug = false; /** * Constructor. * * @param name * The command-line program name. * @param shortOpts * The short options. * @param longOpts * The long options. */ protected CLI(final String name, final String shortOpts, final LongOpt[] longOpts) { this.name = name; this.shortOpts = shortOpts; this.longOpts = longOpts; } /** * Displays command-line help. */ private void showHelp() { System.out.println(Resources.getText("help.txt")); } /** * Displays version information. */ private void showVersion() { System.out.println(Resources.getText("version.txt")); } /** * Displays the help hint. */ protected void showHelpHint() { System.out.println("Use --help to show usage information."); } /** * Prints error message to stderr and then exits with error code 1. * * @param message * The error message. * @param args * The error message arguments. */ protected void error(final String message, final Object... args) { System.err.print(this.name); System.err.print(": "); System.err.format(message, args); System.err.println(); showHelpHint(); System.exit(1); } /** * Processes all command line options. * * @param args * The command line arguments. * @throws Exception * When error occurs. * @return The index of the first non option argument. */ private int processOptions(final String[] args) throws Exception { final Getopt opts = new Getopt(this.name, args, this.shortOpts, this.longOpts); int opt; while ((opt = opts.getopt()) >= 0) { switch (opt) { case 'h': showHelp(); System.exit(0); break; case 'V': showVersion(); System.exit(0); break; case 'D': this.debug = true; break; case '?': showHelpHint(); System.exit(111); break; default: processOption(opt, opts.getOptarg()); } } return opts.getOptind(); } /** * Processes a single option. * * @param option * The option to process * @param arg * The optional option argument * @throws Exception * When an error occurred. */ protected abstract void processOption(final int option, final String arg) throws Exception; /** * Executes the program with the specified arguments. This is called from the run() method after options has been * processed. The specified arguments array only contains the non-option arguments. * * @param args * The non-option command-line arguments. * @throws Exception * When something goes wrong. */ protected abstract void execute(String[] args) throws Exception; /** * Runs the program. * * @param args * The command line arguments. */ public void run(final String[] args) { try { final int commandStart = processOptions(args); execute(Arrays.copyOfRange(args, commandStart, args.length)); } catch (final Exception e) { if (this.debug) { e.printStackTrace(System.err); } error(e.getMessage()); System.exit(1); } } /** * Checks if program runs in debug mode. * * @return True if debug mode, false if not. */ public boolean isDebug() { return this.debug; } }
#include "vistoolspline.h" #include <QLineF> #include <QPainterPath> #include <QSharedPointer> #include <Qt> #include <new> #include "../ifc/ifcdef.h" #include "../vgeometry/vabstractcurve.h" #include "../vgeometry/vgeometrydef.h" #include "../vgeometry/vpointf.h" #include "../vgeometry/vspline.h" #include "../vpatterndb/vcontainer.h" #include "../vwidgets/vcontrolpointspline.h" #include "../vwidgets/scalesceneitems.h" #include "../visualization.h" #include "vispath.h" #include "../vmisc/vmodifierkey.h" const int EMPTY_ANGLE = -1; VisToolSpline::VisToolSpline(const VContainer *data, QGraphicsItem *parent) : VisPath(data, parent), object4Id(NULL_ID), point1(nullptr), point4(nullptr), angle1(EMPTY_ANGLE), angle2(EMPTY_ANGLE), kAsm1(1), kAsm2(1), kCurve(1), isLeftMousePressed(false), p2Selected(false), p3Selected(false), p2(), p3(), controlPoints() { point1 = InitPoint(supportColor, this); point4 = InitPoint(supportColor, this); //-V656 auto *controlPoint1 = new VControlPointSpline(1, SplinePointPosition::FirstPoint, this); controlPoint1->hide(); controlPoints.append(controlPoint1); auto *controlPoint2 = new VControlPointSpline(1, SplinePointPosition::LastPoint, this); controlPoint2->hide(); controlPoints.append(controlPoint2); } VisToolSpline::~VisToolSpline() { emit ToolTip(QString()); } void VisToolSpline::RefreshGeometry() { //Radius of point circle, but little bigger. Need handle with hover sizes. const static qreal radius = ScaledRadius(SceneScale(qApp->getCurrentScene()))*1.5; if (object1Id > NULL_ID) { const auto first = Visualization::data->GeometricObject<VPointF>(object1Id); DrawPoint(point1, static_cast<QPointF>(*first), supportColor); if (mode == Mode::Creation) { if (isLeftMousePressed && not p2Selected) { p2 = Visualization::scenePos; controlPoints[0]->RefreshCtrlPoint(1, SplinePointPosition::FirstPoint, p2, static_cast<QPointF>(*first)); if (not controlPoints[0]->isVisible()) { if (QLineF(static_cast<QPointF>(*first), p2).length() > radius) { controlPoints[0]->show(); } else { p2 = static_cast<QPointF>(*first); } } } else { p2Selected = true; } } if (object4Id <= NULL_ID) { VSpline spline(*first, p2, Visualization::scenePos, VPointF(Visualization::scenePos)); spline.<API key>(<API key>); DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap); } else { const auto second = Visualization::data->GeometricObject<VPointF>(object4Id); DrawPoint(point4, static_cast<QPointF>(*second), supportColor); if (mode == Mode::Creation) { if (isLeftMousePressed && not p3Selected) { QLineF ctrlLine (static_cast<QPointF>(*second), Visualization::scenePos); ctrlLine.setAngle(ctrlLine.angle()+180); p3 = ctrlLine.p2(); controlPoints[1]->RefreshCtrlPoint(1, SplinePointPosition::LastPoint, p3, static_cast<QPointF>(*second)); if (not controlPoints[1]->isVisible()) { if (QLineF(static_cast<QPointF>(*second), p3).length() > radius) { controlPoints[1]->show(); } else { p3 = static_cast<QPointF>(*second); } } } else { p3Selected = true; } } if (<API key>(angle1, EMPTY_ANGLE) || <API key>(angle2, EMPTY_ANGLE)) { VSpline spline(*first, p2, p3, *second); spline.<API key>(<API key>); DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap); } else { VSpline spline(*first, *second, angle1, angle2, kAsm1, kAsm2, kCurve); spline.<API key>(<API key>); DrawPath(this, spline.GetPath(), spline.DirectionArrows(), mainColor, lineStyle, Qt::RoundCap); Visualization::toolTip = tr("Use <b>%1</b> for sticking angle!") .arg(VModifierKey::Shift()); emit ToolTip(Visualization::toolTip); } } } } void VisToolSpline::setObject4Id(const quint32 &value) { object4Id = value; } void VisToolSpline::SetAngle1(const qreal &value) { angle1 = value; } void VisToolSpline::SetAngle2(const qreal &value) { angle2 = value; } void VisToolSpline::SetKAsm1(const qreal &value) { kAsm1 = value; } void VisToolSpline::SetKAsm2(const qreal &value) { kAsm2 = value; } void VisToolSpline::SetKCurve(const qreal &value) { kCurve = value; } QPointF VisToolSpline::GetP2() const { return p2; } QPointF VisToolSpline::GetP3() const { return p3; } void VisToolSpline::MouseLeftPressed() { if (mode == Mode::Creation) { isLeftMousePressed = true; } } void VisToolSpline::MouseLeftReleased() { if (mode == Mode::Creation) { isLeftMousePressed = false; RefreshGeometry(); } }
<?php require_once(ROOT_DIR . 'Pages/Admin/<API key>.php'); require_once(ROOT_DIR . 'Presenters/ActionPresenter.php'); class ConfigActions { const Update = 'update'; } class <API key> extends ActionPresenter { /** * @var <API key> */ private $page; /** * @var <API key> */ private $configSettings; /** * @var */ private $configFilePath; private $deletedSettings = array('password.pattern'); public function __construct(<API key> $page, <API key> $settings) { parent::__construct($page); $this->page = $page; $this->configSettings = $settings; $this->configFilePath = ROOT_DIR . 'config/config.php'; $this->configFilePathDist = ROOT_DIR . 'config/config.dist.php'; $this->AddAction(ConfigActions::Update, 'Update'); } public function PageLoad() { $shouldShowConfig = Configuration::Instance()->GetSectionKey(ConfigSection::PAGES, ConfigKeys::<API key>, new BooleanConverter()); $this->page->SetIsPageEnabled($shouldShowConfig); if (!$shouldShowConfig) { Log::Debug('Show configuration UI is turned off. Not displaying the config values'); return; } $configFiles = $this->GetConfigFiles(); $this->page-><API key>($configFiles); $this-><API key>($configFiles); $isFileWritable = $this->configSettings->CanOverwriteFile($this->configFilePath); $this->page-><API key>($isFileWritable); if (!$isFileWritable) { Log::Debug('Config file is not writable'); return; } Log::Debug('Loading and displaying config file for editing by %s', ServiceLocator::GetServer()->GetUserSession()->Email); $this-><API key>(); $settings = $this->configSettings->GetSettings($this->configFilePath); foreach ($settings as $key => $value) { if (is_array($value)) { $section = $key; foreach ($value as $sectionkey => $sectionvalue) { if (!$this->ShouldBeSkipped($sectionkey, $section)) { $this->page->AddSectionSetting(new ConfigSetting($sectionkey, $section, $sectionvalue)); } } } else { if (!$this->ShouldBeSkipped($key)) { $this->page->AddSetting(new ConfigSetting($key, null, $value)); } } } $this->PopulateHomepages(); } private function PopulateHomepages() { $homepageValues = array(); $homepageOutput = array(); $pages = Pages::GetAvailablePages(); foreach ($pages as $pageid => $page) { $homepageValues[] = $pageid; $homepageOutput[] = Resources::GetInstance()->GetString($page['name']); } $this->page->SetHomepages($homepageValues, $homepageOutput); } public function Update() { $shouldShowConfig = Configuration::Instance()->GetSectionKey(ConfigSection::PAGES, ConfigKeys::<API key>, new BooleanConverter()); if (!$shouldShowConfig) { Log::Debug('Show configuration UI is turned off. No updates are allowed'); return; } $configSettings = $this->page-><API key>(); $configFiles = $this->GetConfigFiles(); $this-><API key>($configFiles); $newSettings = array(); foreach ($configSettings as $setting) { if (!empty($setting->Section)) { $newSettings[$setting->Section][$setting->Key] = $setting->Value; } else { $newSettings[$setting->Key] = $setting->Value; } } $existingSettings = $this->configSettings->GetSettings($this->configFilePath); $mergedSettings = array_merge($existingSettings, $newSettings); foreach ($this->deletedSettings as $deletedSetting) { if (array_key_exists($deletedSetting, $mergedSettings)) { unset($mergedSettings[$deletedSetting]); } } Log::Debug("Saving %s settings", count($configSettings)); $this->configSettings->WriteSettings($this->configFilePath, $mergedSettings); Log::Debug('Config file saved by %s', ServiceLocator::GetServer()->GetUserSession()->Email); } private function ShouldBeSkipped($key, $section = null) { if ($section == ConfigSection::DATABASE || $section == ConfigSection::API) { return true; } if (in_array($key, $this->deletedSettings)) { return true; } switch ($key) { case ConfigKeys::<API key>: case ConfigKeys::<API key> && $section == ConfigSection::PAGES: return true; default: return false; } } private function GetConfigFiles() { $files = array(new ConfigFileOption('config.php', '')); $pluginBaseDir = ROOT_DIR . 'plugins/'; if ($h = opendir($pluginBaseDir)) { while (false !== ($entry = readdir($h))) { $pluginDir = $pluginBaseDir . $entry; if (is_dir($pluginDir) && $entry != "." && $entry != "..") { $plugins = scandir($pluginDir); foreach ($plugins as $plugin) { if (is_dir("$pluginDir/$plugin") && $plugin != "." && $plugin != ".." && strpos($plugin,'Example') === false) { /** @var $file ConfigFileOption */
#include <stdlib.h> #include <stdio.h> #include "array_heap.h" int array_init(array* arr, int size) { arr->data = realloc(NULL, sizeof(void*) * size); if (0 == (size_t)arr->data) { return -1; } arr->length = size; arr->index = 0; return 0; } int array_push(array* arr, void* data) { ((size_t*)arr->data)[arr->index] = (size_t)data; arr->index += 1; if (arr->index >= arr->length) { if (-1 == array_grow(arr, arr->length * 2)) { return -1; } } return arr->index - 1; } int array_grow(array* arr, int size) { if (size <= arr->length) { return -1; } arr->data = realloc(arr->data, sizeof(void*) * size); if (-1 == (size_t)arr->data) { return -1; } arr->length = size; return 0; } void array_free(array* arr, void (*free_element)(void*)) { int i; for (i = 0; i < arr->index; i += 1) { free_element((void*)((size_t*)arr->data)[i]); } free(arr->data); arr->index = -1; arr->length = 0; arr->data = NULL; }
from ert.cwrap import CWrapper, BaseCClass from ert.enkf import ENKF_LIB from ert.util import StringList class SummaryKeyMatcher(BaseCClass): def __init__(self): c_ptr = SummaryKeyMatcher.cNamespace().alloc() super(SummaryKeyMatcher, self).__init__(c_ptr) def addSummaryKey(self, key): assert isinstance(key, str) return SummaryKeyMatcher.cNamespace().add_key(self, key) def __len__(self): return SummaryKeyMatcher.cNamespace().size(self) def __contains__(self, key): return SummaryKeyMatcher.cNamespace().match_key(self, key) def isRequired(self, key): """ @rtype: bool """ return SummaryKeyMatcher.cNamespace().is_required(self, key) def keys(self): """ @rtype: StringList """ return SummaryKeyMatcher.cNamespace().keys(self) def free(self): SummaryKeyMatcher.cNamespace().free(self) cwrapper = CWrapper(ENKF_LIB) cwrapper.registerObjectType("summary_key_matcher", SummaryKeyMatcher) SummaryKeyMatcher.cNamespace().alloc = cwrapper.prototype("c_void_p <API key>()") SummaryKeyMatcher.cNamespace().free = cwrapper.prototype("void <API key>(summary_key_matcher)") SummaryKeyMatcher.cNamespace().size = cwrapper.prototype("int <API key>(summary_key_matcher)") SummaryKeyMatcher.cNamespace().add_key = cwrapper.prototype("void <API key>(summary_key_matcher, char*)") SummaryKeyMatcher.cNamespace().match_key = cwrapper.prototype("bool <API key>(summary_key_matcher, char*)") SummaryKeyMatcher.cNamespace().keys = cwrapper.prototype("stringlist_obj <API key>(summary_key_matcher)") SummaryKeyMatcher.cNamespace().is_required = cwrapper.prototype("bool <API key>(summary_key_matcher, char*)")
<?php // include class.secure.php to protect this file and the whole CMS! if (defined('WB_PATH')) { include(WB_PATH.'/framework/class.secure.php'); } else { $oneback = "../"; $root = $oneback; $level = 1; while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) { $root .= $oneback; $level += 1; } if (file_exists($root.'/framework/class.secure.php')) { include($root.'/framework/class.secure.php'); } else { trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR); } } // end include class.secure.php // end include class.secure.php $database->query("DROP TABLE IF EXISTS `".TABLE_PREFIX."mod_editor_admin`"); $table = TABLE_PREFIX ."mod_wysiwyg_admin"; $database->query("DROP TABLE IF EXISTS `".$table."`"); $database->query("DELETE from `".TABLE_PREFIX."sections` where `section_id`='-1' AND `page_id`='-120'"); $database->query("DELETE from `".TABLE_PREFIX."mod_wysiwyg` where `section_id`='-1' AND `page_id`='-120'"); ?>
#include <cmath> #include <iostream> #include <fstream> #include <cstdlib> #include "params.h" #include "pdg_name.h" #include "parameters.h" #include "LeptonMass.h" //#include "jednostki.h" #include "grv94_bodek.h" #include "dis_cr_sec.h" #include "fragmentation.h" #include "vect.h" #include "charge.h" #include "event1.h" #include <TMCParticle.h> #include <TPythia6.h> TPythia6 *pythia2 = new TPythia6 (); extern "C" int pycomp_ (const int *); void dishadr (event & e, bool current, double hama, double entra) { // Setting Pythia parameters // Done by Jaroslaw Nowak //stabilne pi0 pythia2->SetMDCY (pycomp_ (&pizero), 1, 0); //C Thorpe: Adding Hyperons as stable dis particles pythia2->SetMDCY (pycomp_ (&Lambda), 1, 0); pythia2->SetMDCY (pycomp_ (&Sigma), 1, 0); pythia2->SetMDCY (pycomp_ (&SigmaP), 1, 0); pythia2->SetMDCY (pycomp_ (&SigmaM), 1, 0); // C Thorpe: Stablize kaons pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kplus) , 1, 0); pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kzero) , 1, 0); pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kminus) , 1, 0); pythia2->SetMSTU (20, 1); //advirsory warning for unphysical flavour switch off pythia2->SetMSTU (23, 1); //It sets counter of errors at 0 pythia2->SetMSTU (26, 0); //no warnings printed // PARJ(32)(D=1GeV) is, with quark masses added, used to define the minimum allowable enrgy of a colour singlet parton system pythia2->SetPARJ (33, 0.1); // PARJ(33)-PARJ(34)(D=0.8GeV, 1.5GeV) are, with quark masses added, used to define the remaining energy below which //the fragmentation of a parton system is stopped and two final hadrons formed. pythia2->SetPARJ (34, 0.5); pythia2->SetPARJ (35, 1.0); //PARJ(36) (D=2.0GeV) represents the dependence of the mass of final quark pair for defining the stopping point of the //fragmentation. Strongly corlated with PARJ(33-35) pythia2->SetPARJ (37, 1.); //MSTJ(17) (D=2) number of attemps made to find two hadrons that have a combined mass below the cluster mass and thus allow // a cluster to decay rather than collaps pythia2->SetMSTJ (18, 3); //do not change // End of setting Pythia parameters double Mtrue = (PDG::mass_proton+PDG::mass_neutron)/2; double Mtrue2 = Mtrue * Mtrue; double W2 = hama * hama; double nu = entra; vect nuc0 = e.in[1]; vect nu0 = e.in[0]; nu0.boost (-nuc0.speed ()); //neutrino 4-momentum in the target rest frame vec nulab = vec (nu0.x, nu0.y, nu0.z); //can be made simpler ??? int lepton = e.in[0].pdg; int nukleon = e.in[1].pdg; double m = lepton_mass (abs (lepton), current); //mass of the given lepton (see pgd header file) double m2 = m * m; double E = nu0.t; double E2 = E * E; int nParticle = 0; int nCharged = 0; int NPar = 0; Pyjets_t *pythiaParticle; //deklaracja event recordu double W1 = hama / GeV; //W1 w GeV-ach potrzebne do Pythii while (NPar < 5) { hadronization (E, hama, entra, m, lepton, nukleon, current); pythiaParticle = pythia2->GetPyjets (); NPar = pythia2->GetN (); } //////////////Kinematics ///////// The input data is: neutrinoo 4-momentum, invariant hadronic mass and energy transfer ///////// With this data the kinematics is resolved //////// We know that nu^2-q^2= (k-k')^2=m^2-2*k.k'= m^2-2*E*(E-nu)+ 2*E*sqrt((E-nu)^2-m^2)*cos theta //////// (M+nu)^2-q^2=W^2 ///////// (k-q)^2= m^2 = nu^2-q^2 -2*E*nu + 2*E*q*cos beta ////////// theta is an angle between leptons and beta is an angle between neutrino and momentum transfer ///////// Of course it is not necessary to calculate vectors k' and q separately because of momentum conservation double q = sqrt (kwad (Mtrue + nu) - W2); double kprim = sqrt (kwad (E - nu) - m2); double cth = (E2 + kprim * kprim - q * q) / 2 / E / kprim; vec kkprim; //the unit vector in the direction of scattered lepton kinfinder (nulab, kkprim, cth); //hopefully should produce kkprim kkprim = kprim * kkprim; //multiplied by its length vect lepton_out = vect (E - nu, kkprim.x, kkprim.y, kkprim.z); vec momtran = nulab - kkprim; vec hadrspeed = momtran / sqrt (W2 + q * q); nParticle = pythia2->GetN (); if (nParticle == 0) { cout << "nie ma czastek" << endl; cin.get (); } vect par[100]; double ks[100]; //int czy double ??? par[0] = lepton_out; //powrot do ukladu spoczywajacej tarczy par[0] = par[0].boost (nuc0.speed ()); particle lept (par[0]); if (current == true && lepton > 0) { lept.pdg = lepton - 1; } if (current == true && lepton < 0) { lept.pdg = lepton + 1; } if (current == false) { lept.pdg = lepton; } e.out.push_back (lept); //final lepton; ok for (int i = 0; i < nParticle; i++) { par[i].t = pythiaParticle->P[3][i] * GeV; par[i].x = pythiaParticle->P[0][i] * GeV; par[i].y = pythiaParticle->P[1][i] * GeV; par[i].z = pythiaParticle->P[2][i] * GeV; rotation (par[i], momtran); ks[i] = pythiaParticle->K[0][i]; par[i] = par[i].boost (hadrspeed); //correct direction ??? par[i] = par[i].boost (nuc0.speed ()); particle part (par[i]); part.ks = pythiaParticle->K[0][i]; part.pdg = pythiaParticle->K[1][i]; part.orgin = pythiaParticle->K[2][i]; e.temp.push_back (part); if (ks[i] == 1) //condition for a real particle in the final state { e.out.push_back (part); } } }
package example; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Test; import com.piedra.excel.annotation.ExcelExport; import com.piedra.excel.util.ExcelExportor; /** * @Description: Excel * @Creatorlinwb 2014-12-19 */ public class <API key> { public static void main(String[] args) { new <API key>().testSingleHeader(); new <API key>().testMulHeaders(); } /** * @Description: * @History * 1. 2014-12-19 linwb */ @Test public void testSingleHeader(){ OutputStream out = null; try { out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST.xls")); List<ExcelRow> stus = new ArrayList<ExcelRow>(); for(int i=0; i<11120; i++){ stus.add(new ExcelRow()); } new ExcelExportor<ExcelRow>().exportExcel("", stus, out); System.out.println("excel"); } catch (Exception e) { e.printStackTrace(); } finally { if(out!=null){ try { out.close(); } catch (IOException e) { //Ignore.. } finally{ out = null; } } } } /** * @Description: * @History * 1. 2014-12-19 linwb */ @Test public void testMulHeaders(){ OutputStream out = null; try { out = new FileOutputStream(new File("C://<API key>.xls")); List<<API key>> stus = new ArrayList<<API key>>(); for(int i=0; i<1120; i++){ stus.add(new <API key>()); } new ExcelExportor<<API key>>().exportExcel("", stus, out); System.out.println("excel"); } catch (Exception e) { e.printStackTrace(); } finally { if(out!=null){ try { out.close(); } catch (IOException e) { //Ignore.. } finally{ out = null; } } } } } /** * @Description: ExcelJavaBean * @Creatorlinwb 2014-12-19 */ class ExcelRow { @ExcelExport(header="",colWidth=50) private String name="<API key>"; @ExcelExport(header="") private int age=80; /** ,excel*/ private String clazz="SSSSSSSSS"; @ExcelExport(header="") private String country="RRRRRRR"; @ExcelExport(header="") private String city="EEEEEEEEE"; @ExcelExport(header="") private String town="WWWWWWW"; /** ,excel*/ private String common="DDDDDDDD"; /** colWidth <= 0 15 */ @ExcelExport(header="",colWidth=-1) private Date birth = new Date(); public ExcelRow(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } } /** * @Description: ExcelJavaBean * @Creatorlinwb 2014-12-19 */ class <API key> { @ExcelExport(header="",colspan="1",rowspan="3") private String name=""; @ExcelExport(header=",",colspan="1,5",rowspan="1,2") private String province=""; @ExcelExport(header="",colspan="1",rowspan="1") private String city=""; @ExcelExport(header="",colspan="1",rowspan="1") private String town=""; @ExcelExport(header=",",colspan="1,2",rowspan="1,1") private int age=80; @ExcelExport(header="?",colspan="1",rowspan="1") private String common=","; @ExcelExport(header="",colspan="1",rowspan="3",datePattern="yyyy-MM-dd HH:mm:ss") private Date birth = new Date(); /** ,excel*/ private String clazz=", @ExcelExport "; public <API key>(){ } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } }
package fr.ribesg.com.mojang.api.http; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.util.List; public class BasicHttpClient implements HttpClient { private static BasicHttpClient instance; private BasicHttpClient() { } public static BasicHttpClient getInstance() { if (instance == null) { instance = new BasicHttpClient(); } return instance; } @Override public String post(final URL url, final HttpBody body, final List<HttpHeader> headers) throws IOException { return this.post(url, null, body, headers); } @Override public String post(final URL url, Proxy proxy, final HttpBody body, final List<HttpHeader> headers) throws IOException { if (proxy == null) { proxy = Proxy.NO_PROXY; } final HttpURLConnection connection = (HttpURLConnection)url.openConnection(proxy); connection.setRequestMethod("POST"); for (final HttpHeader header : headers) { connection.setRequestProperty(header.getName(), header.getValue()); } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); final DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.write(body.getBytes()); writer.flush(); writer.close(); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; final StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); response.append('\r'); } reader.close(); return response.toString(); } }
#import <RoutingHTTPServer/RoutingConnection.h> @interface RoutingConnection (Secure) @end
#!/usr/bin/env node /*jshint -W100*/ 'use strict'; /** * * * usernamepassword */ var username = 'hogehoge'; var password = 'fugafuga'; var client = require('../index'); console.info('TOP'); client.fetch('http://nicovideo.jp/') .then(function (result) { console.info(''); return result.$('#sideNav .loginBtn').click(); }) .then(function (result) { console.info(''); return result.$('#login_form').submit({ mail_tel: username, password: password }); }) .then(function (result) { console.info(''); if (! result.response.headers['x-niconico-id']) { throw new Error('login failed'); } console.info('', result.response.cookies); console.info(''); return client.fetch('http: }) .then(function (result) { console.info(''); console.info(result.$('#<API key>').text()); }) .catch(function (err) { console.error('', err.message); }) .finally(function () { console.info(''); });
// Kainote is free software: you can redistribute it and/or modify // (at your option) any later version. // Kainote is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #pragma once #include <wx/window.h> #include <wx/thread.h> //#define Get_Log LogHandler::Get() class LogWindow; class LogHandler { friend class LogWindow; private: LogHandler(wxWindow *parent); ~LogHandler(); static LogHandler *sthis; wxString logToAppend; wxString lastLog; LogWindow *lWindow = NULL; wxMutex mutex; wxWindow *parent; public: static void Create(wxWindow *parent); static LogHandler *Get(){ return sthis; } static void Destroy(); void LogMessage(const wxString &format, bool showMessage = true); static void ShowLogWindow(); //void LogMessage1(const wxString &format, ...); }; static void KaiLog(const wxString &text){ LogHandler * handler = LogHandler::Get(); if (handler) handler->LogMessage(text); } static void KaiLogSilent(const wxString &text) { LogHandler * handler = LogHandler::Get(); if (handler) handler->LogMessage(text, false); } static void KaiLogDebug(const wxString &text){ #if _DEBUG LogHandler * handler = LogHandler::Get(); if (handler) handler->LogMessage(text); #endif }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_66) on Sat Nov 28 10:51:55 EST 2015 --> <title><API key> (MG4J (big) 5.4.1)</title> <meta name="date" content="2015-11-28"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="<API key> (MG4J (big) 5.4.1)"; } } catch(err) { } var methods = {"i0":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../it/unimi/di/big/mg4j/index/<API key>.html" title="class in it.unimi.di.big.mg4j.index"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?it/unimi/di/big/mg4j/index/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <div class="subTitle">it.unimi.di.big.mg4j.index</div> <h2 title="Interface <API key>" class="title">Interface <API key></h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../../it/unimi/di/big/mg4j/index/<API key>.html" title="class in it.unimi.di.big.mg4j.index"><API key></a>, <a href="../../../../../../it/unimi/di/big/mg4j/index/<API key>.html" title="class in it.unimi.di.big.mg4j.index"><API key></a></dd> </dl> <hr> <br> <pre>public interface <span class="typeNameLabel"><API key></span></pre> <div class="block">An index writer supporting variable quanta. <p>This interface provides an additional <a href="../../../../../../it/unimi/di/big/mg4j/index/<API key>.html#<API key>-"><code>newInvertedList(long, double, long, long)</code></a> method that accepts additional information. That information is used to compute the correct quantum size for a specific list. This approach makes it possible to specify a target fraction of the index that will be used to store skipping information.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="method.summary"> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../it/unimi/di/big/mg4j/index/<API key>.html#<API key>-">newInvertedList</a></span>(long&nbsp;predictedFrequency, double&nbsp;skipFraction, long&nbsp;predictedSize, long&nbsp;<API key>)</code> <div class="block">Starts a new inverted list.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="method.detail"> </a> <h3>Method Detail</h3> <a name="<API key>-"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>newInvertedList</h4> <pre>long&nbsp;newInvertedList(long&nbsp;predictedFrequency, double&nbsp;skipFraction, long&nbsp;predictedSize, long&nbsp;<API key>) throws <a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre> <div class="block">Starts a new inverted list. The previous inverted list, if any, is actually written to the underlying bit stream. <p>This method provides additional information that will be used to compute the correct quantum for the skip structure of the inverted list.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>predictedFrequency</code> - the predicted frequency of the inverted list; this might just be an approximation.</dd> <dd><code>skipFraction</code> - the fraction of the inverted list that will be dedicated to skipping structures.</dd> <dd><code>predictedSize</code> - the predicted size of the part of the inverted list that stores terms and counts.</dd> <dd><code><API key></code> - the predicted size of the part of the inverted list that stores positions.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the position (in bits) of the underlying bit stream where the new inverted list starts.</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/<API key>.html?is-external=true" title="class or interface in java.lang"><API key></a></code> - if too few records were written for the previous inverted list.</dd> <dd><code><a href="http://download.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../it/unimi/di/big/mg4j/index/IndexWriter.html#newInvertedList--"><code>IndexWriter.newInvertedList()</code></a></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../it/unimi/di/big/mg4j/index/<API key>.html" title="class in it.unimi.di.big.mg4j.index"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?it/unimi/di/big/mg4j/index/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
#!/usr/bin/python # coding: utf8 import os import subprocess from '{% if cookiecutter.namespace %}{{ cookiecutter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}'.commands.base import BaseCommand from '{% if cookiecutter.namespace %}{{ cookiecutter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}' import PROJECT_DIR class Configure(BaseCommand): def execute(self): os.chdir(os.path.join(PROJECT_DIR, 'build')) subprocess.run(['cmake', PROJECT_DIR])
<a href tabindex="-1" ng-attr-title="{{match.label}}"> <span ng-bind-html="match.label.artist | <API key>:query"></span> <br> <small ng-bind-html="match.label.title | <API key>:query"></small> </a>
package Eac.event; import Eac.Eac; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import net.minecraft.item.ItemStack; public class EacOnItemPickup extends Eac { @SubscribeEvent public void EacOnItemPickup(PlayerEvent.ItemPickupEvent e) { if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreAir))) { e.player.addStat(airoremined, 1); } else if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreShadow))) { e.player.addStat(shadoworemined, 1); } } }
class <API key> < <API key> def new end def create @user = User.find_by_email(params[:email]) if @user @user.<API key>! redirect_to root_path, notice: 'Instructions have been sent to your email.' else flash.now[:alert] = "Sorry but we don't recognise the email address \"#{params[:email]}\"." render :new end end def edit @user = User.<API key>(params[:id]) @token = params[:id] if @user.blank? not_authenticated return end end def update @user = User.<API key>(params[:id]) @token = params[:id] if @user.blank? not_authenticated return end @user.<API key> = params[:user][:<API key>] if @user.change_password!(params[:user][:password]) redirect_to signin_path, notice: 'Password was successfully updated.' else render :edit end end end
/* * Filename: BuildNr.h */ /* application build number: */ #define PRODUCT_BUILD 4001 /* EOF */
// <API key>.h // ScrollView+PaperFold+PageControl #import <UIKit/UIKit.h> #import "PaperFoldView.h" #import "SwipeView.h" @interface <API key> : UIViewController <<API key>,<API key>,SwipeViewDataSource, SwipeViewDelegate> @property (strong, nonatomic) id detailItem; @property (nonatomic, strong) IBOutlet PaperFoldView *paperFoldView; @property (nonatomic, strong) UIView *topView; @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; @property (weak, nonatomic) IBOutlet UILabel *<API key>; @property (nonatomic, strong) IBOutlet SwipeView *swipeView; @property (nonatomic, strong) NSMutableArray *items; @end
#ifndef _OPT_H #define _OPT_H #include <assert.h> #define OPT_RELAX_CAPACITY 0 #define <API key> "capacity" #define OPT_RELAX_QUANTITY 1 #define <API key> "quantity" typedef struct { double alpha; char *file; int relax; int verbose; } Options; void opt_free (Options * opt); static inline double opt_get_alpha (Options * opt) { return opt->alpha; } static inline char * opt_get_file (Options * opt) { return opt->file; } static inline int opt_get_relax (Options * opt) { return opt->relax; } static inline int opt_get_verbose (Options * opt) { return opt->verbose; } Options *opt_new (); static inline void opt_set_alpha (Options * opt, double alpha) { opt->alpha = alpha; } static inline void opt_set_file (Options * opt, char *file) { opt->file = file; } static inline void opt_set_relax (Options * opt, int relax) { opt->relax = relax; } static inline void opt_set_verbose (Options * opt, int verbose) { opt->verbose = verbose; } #endif
#pragma once #include "real.h" #include <mirheo/core/mesh/membrane.h> #include <mirheo/core/pvs/object_vector.h> #include <mirheo/core/pvs/views/ov.h> #include <mirheo/core/utils/cpu_gpu_defines.h> #include <mirheo/core/utils/cuda_common.h> #include <mirheo/core/utils/cuda_rng.h> namespace mirheo { /** Compute triangle area \param [in] v0 Vertex coordinates \param [in] v1 Vertex coordinates \param [in] v2 Vertex coordinates \return The triangle area */ __D__ inline mReal triangleArea(mReal3 v0, mReal3 v1, mReal3 v2) { return 0.5_mr * length(cross(v1 - v0, v2 - v0)); } /** Compute the volume of the tetrahedron spanned by the origin and the three input coordinates. The result is negative if the normal of the triangle points inside the tetrahedron. \param [in] v0 Vertex coordinates \param [in] v1 Vertex coordinates \param [in] v2 Vertex coordinates \return The signed volume of the tetrahedron */ __D__ inline mReal <API key>(mReal3 v0, mReal3 v1, mReal3 v2) { return 0.1666666667_mr * (- v0.z*v1.y*v2.x + v0.z*v1.x*v2.y + v0.y*v1.z*v2.x - v0.x*v1.z*v2.y - v0.y*v1.x*v2.z + v0.x*v1.y*v2.z); } /** Compute the angle between two adjacent triangles. It is the positive angle between the two normals. \param [in] v0 Vertex coordinates \param [in] v1 Vertex coordinates \param [in] v2 Vertex coordinates \param [in] v3 Vertex coordinates \return The supplementary dihedral angle */ __D__ inline mReal <API key>(mReal3 v0, mReal3 v1, mReal3 v2, mReal3 v3) { mReal3 n, k, nk; n = cross(v1 - v0, v2 - v0); k = cross(v2 - v0, v3 - v0); nk = cross(n, k); mReal theta = atan2(length(nk), dot(n, k)); theta = dot(v2-v0, nk) < 0 ? theta : -theta; return theta; } } // namespace mirheo
package de.fhffm.jad.demo.jad; import java.util.ArrayList; import de.fhffm.jad.data.DataWrapper; import de.fhffm.jad.data.EInputFields; import de.fhffm.jad.data.IDataFieldEnum; /** * This class synchronizes the access to our Data.Frame * Added Observations are stored in a local ArrayList. * Use 'write' to send everything to GNU R. * @author Denis Hock */ public class DataFrame { private static DataWrapper dw = null; private static ArrayList<String[]> rows = new ArrayList<>(); /** * @return Singleton Instance of the GNU R Data.Frame */ public static DataWrapper getDataFrame(){ if (dw == null){ //Create the data.frame for GNU R: dw = new DataWrapper("data"); clear(); } return dw; } /** * Delete the old observations and send all new observations to Gnu R * @return */ public synchronized static boolean write(){ if (rows.size() < 1){ return false; } //Clear the R-Data.Frame clear(); //Send all new Observations to Gnu R for(String[] row : rows) dw.addObservation(row); //Clear the local ArrayList rows.clear(); return true; } /** * These Observations are locally stored and wait for the write() command * @param row */ public synchronized static void add(String[] row){ //Store everything in an ArrayList rows.add(row); } /** * Clear local ArrayList and GNU R Data.Frame */ private static void clear(){ ArrayList<IDataFieldEnum> fields = new ArrayList<IDataFieldEnum>(); fields.add(EInputFields.ipsrc); fields.add(EInputFields.tcpdstport); fields.add(EInputFields.framelen); dw.<API key>(fields); } }
package de.dominicscheurer.quicktxtview.view; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.<API key>; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFText2HTML; import de.dominicscheurer.quicktxtview.model.DirectoryTreeItem; import de.dominicscheurer.quicktxtview.model.FileSize; import de.dominicscheurer.quicktxtview.model.FileSize.FileSizeUnits; public class <API key> { public static final Comparator<File> FILE_ACCESS_CMP = (f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()); public static final Comparator<File> <API key> = (f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified()); public static final Comparator<File> FILE_NAME_CMP = (f1, f2) -> f1.getName().compareTo(f2.getName()); public static final Comparator<File> <API key> = (f1, f2) -> f2.getName().compareTo(f1.getName()); private static final String <API key> = "FileViewer.css"; private static final String <API key> = "errorTextField"; private FileSize fileSizeThreshold = new FileSize(1, FileSizeUnits.MB); private Charset charset = Charset.defaultCharset(); private Comparator<File> fileComparator = FILE_ACCESS_CMP; @FXML private TreeView<File> fileSystemView; @FXML private WebView <API key>; @FXML private TextField <API key>; @FXML private Label <API key>; private boolean <API key> = false; private String fileTreeViewerCSS; private Pattern filePattern; @FXML private void initialize() { filePattern = Pattern.compile(<API key>.getText()); <API key>.setOnKeyReleased(event -> { final String input = <API key>.getText(); try { Pattern p = Pattern.compile(input); filePattern = p; <API key>.getStyleClass().remove(<API key>); if (!fileSystemView.getSelectionModel().isEmpty()) { <API key>(fileSystemView.getSelectionModel().getSelectedItem()); } } catch (<API key> e) { <API key>.getStyleClass().add(<API key>); } <API key>.applyCss(); }); fileSystemView.getSelectionModel().<API key>().addListener( (observable, oldValue, newValue) -> <API key>(newValue)); { Scanner s = new Scanner(getClass().getResourceAsStream(<API key>)); s.useDelimiter("\\A"); fileTreeViewerCSS = s.hasNext() ? s.next() : ""; s.close(); } DirectoryTreeItem[] roots = DirectoryTreeItem.getFileSystemRoots(); if (roots.length > 1) { TreeItem<File> dummyRoot = new TreeItem<File>(); dummyRoot.getChildren().addAll(roots); fileSystemView.setShowRoot(false); fileSystemView.setRoot(dummyRoot); } else { fileSystemView.setRoot(roots[0]); } fileSystemView.getRoot().setExpanded(true); <API key>(); } public void <API key>() { <API key> = !<API key>; <API key>(); } public void <API key>(FileSize fileSizeThreshold) { this.fileSizeThreshold = fileSizeThreshold; <API key>(); <API key>(); } public FileSize <API key>() { return fileSizeThreshold; } public void setCharset(Charset charset) { this.charset = charset; <API key>(); } public Charset getCharset() { return charset; } public Comparator<File> getFileComparator() { return fileComparator; } public void setFileComparator(Comparator<File> fileComparator) { this.fileComparator = fileComparator; <API key>(); } private void <API key>() { <API key>.setText(fileSizeThreshold.getSize() + " " + fileSizeThreshold.getUnit().toString()); } private void <API key>() { if (!fileSystemView.getSelectionModel().isEmpty()) { <API key>(fileSystemView.getSelectionModel().getSelectedItem()); } } public void expandToDirectory(File file) { Iterator<Path> it = file.toPath().iterator(); //FIXME: The below root directory selection *might* not work for Windows systems. // => Do something with `file.toPath().getRoot()`. TreeItem<File> currentDir = fileSystemView.getRoot(); while (it.hasNext()) { final String currDirName = it.next().toString(); FilteredList<TreeItem<File>> matchingChildren = currentDir.getChildren().filtered(elem -> elem.getValue().getName().equals(currDirName)); if (matchingChildren.size() == 1) { matchingChildren.get(0).setExpanded(true); currentDir = matchingChildren.get(0); } } fileSystemView.getSelectionModel().clearSelection(); fileSystemView.getSelectionModel().select(currentDir); fileSystemView.scrollTo(fileSystemView.getSelectionModel().getSelectedIndex()); } private void <API key>(TreeItem<File> selectedDirectory) { if (selectedDirectory == null) { return; } final WebEngine webEngine = <API key>.getEngine(); webEngine.loadContent(!<API key> ? <API key>(selectedDirectory.getValue()) : <API key>(selectedDirectory.getValue())); } private void <API key>() { <API key>(fileSystemView.getSelectionModel().getSelectedItem()); } private String <API key>(File directory) { final StringBuilder sb = new StringBuilder(); final DecimalFormat df = new DecimalFormat("0.00"); final File[] files = listFiles(directory); if (files == null) { return ""; } sb.append("<html><head>") .append("<style type=\"text/css\">") .append(fileTreeViewerCSS) .append("</style>") .append("</head><body><div id=\"fileList\"><ul>"); boolean even = false; for (File file : files) { sb.append("<li class=\"") .append(even ? "even" : "odd") .append("\"><span class=\"fileName\">") .append(file.getName()) .append("</span> <span class=\"fileSize\">(") .append(df.format((float) file.length() / 1024)) .append("K)</span>") .append("</li>"); even = !even; } sb.append("</ul></div></body></html>"); return sb.toString(); } private String <API key>(File directory) { final StringBuilder sb = new StringBuilder(); final File[] files = listFiles(directory); if (files == null) { return ""; } sb.append("<html>") .append("<body>") .append("<style type=\"text/css\">") .append(fileTreeViewerCSS) .append("</style>"); for (File file : files) { try { String contentsString; if (file.getName().endsWith(".pdf")) { final PDDocument doc = PDDocument.load(file); final StringWriter writer = new StringWriter(); new PDFText2HTML("UTF-8").writeText(doc, writer); contentsString = writer.toString(); writer.close(); doc.close(); } else { byte[] encoded = Files.readAllBytes(file.toPath()); contentsString = new String(encoded, charset); contentsString = contentsString.replace("<", "&lt;"); contentsString = contentsString.replace(">", "&gt;"); contentsString = contentsString.replace("\n", "<br/>"); } sb.append("<div class=\"entry\"><h3>") .append(file.getName()) .append("</h3>") .append("<div class=\"content\">") .append(contentsString) .append("</div>") .append("</div>"); } catch (IOException e) {} } sb.append("</body></html>"); return sb.toString(); } private File[] listFiles(File directory) { if (directory == null) { return new File[0]; } File[] files = directory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && filePattern.matcher(pathname.getName().toString()).matches() && pathname.length() <= fileSizeThreshold.toBytes(); } }); if (files == null) { return new File[0]; } Arrays.sort(files, fileComparator); return files; } }
object rec{ def main(args: Array[String]){ def factorial(num: Int): BigInt={ if(num<=1){ 1 } else{ num*factorial(num-1) } } print("Factorial of 4 is: "+factorial(4)) } }
Ext.define("Voyant.notebook.util.Embed", { transferable: ['embed'], embed: function() { // this is for instances embed.apply(this, arguments); }, constructor: function(config) { var me = this; }, statics: { i18n: {}, api: { embeddedParameters: undefined, embeddedConfig: undefined }, embed: function(cmp, config) { if (this.then) { this.then(function(embedded) { embed.call(embedded, cmp, config) }) } else if (Ext.isArray(cmp)) { Voyant.notebook.util.Show.SINGLE_LINE_MODE=true; show("<table><tr>"); cmp.forEach(function(embeddable) { show("<td>"); if (Ext.isArray(embeddable)) { if (embeddable[0].embeddable) { embeddable[0].embed.apply(embeddable[0], embeddable.slice(1)) } else { embed.apply(this, embeddable) } } else { embed.apply(this, embeddable); } show("</td>") }) // for (var i=0; i<arguments.length; i++) { // var unit = arguments[i]; // show("<td>") // unit[0].embed.call(unit[0], unit[1], unit[2]); // show("</td>") show("</tr></table>") Voyant.notebook.util.Show.SINGLE_LINE_MODE=false; return } else { // use the default (first) embeddable panel if no panel is specified if (this.embeddable && (!cmp || Ext.isObject(cmp))) { // if the first argument is an object, use it as config instead if (Ext.isObject(cmp)) {config = cmp;} cmp = this.embeddable[0]; } if (Ext.isString(cmp)) { cmp = Ext.ClassManager.getByAlias('widget.'+cmp.toLowerCase()) || Ext.ClassManager.get(cmp); } var isEmbedded = false; if (Ext.isFunction(cmp)) { var name = cmp.getName(); if (this.embeddable && Ext.Array.each(this.embeddable, function(item) { if (item==name) { config = config || {}; var embeddedParams = {}; for (key in Ext.ClassManager.get(Ext.getClassName(cmp)).api) { if (key in config) { embeddedParams[key] = config[key] } } if (!embeddedParams.corpus) { if (Ext.getClassName(this)=='Voyant.data.model.Corpus') { embeddedParams.corpus = this.getId(); } else if (this.getCorpus) { var corpus = this.getCorpus(); if (corpus) { embeddedParams.corpus = this.getCorpus().getId(); } } } Ext.applyIf(config, { style: 'width: '+(config.width || '90%') + (Ext.isNumber(config.width) ? 'px' : '')+ '; height: '+(config.height || '400px') + (Ext.isNumber(config.height) ? 'px' : '') }); delete config.width; delete config.height; var corpus = embeddedParams.corpus; delete embeddedParams.corpus; Ext.applyIf(embeddedParams, Voyant.application.<API key>()); var <API key> = Ext.encode(embeddedParams); var embeddedConfigParam = encodeURIComponent(<API key>); var iframeId = Ext.id(); var url = Voyant.application.getBaseUrlFull()+"tool/"+name.substring(name.lastIndexOf(".")+1)+'/?'; if (true || embeddedConfigParam.length>1800) { show('<iframe style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>'); var dfd = Voyant.application.getDeferred(this); Ext.Ajax.request({ url: Voyant.application.getTromboneUrl(), params: { tool: 'resource.StoredResource', storeResource: embeddedConfigParam } }).then(function(response) { var json = Ext.util.JSON.decode(response.responseText); var params = { minimal: true, embeddedApiId: json.storedResource.id } if (corpus) { params.corpus = corpus; } Ext.applyIf(params, Voyant.application.<API key>()); document.getElementById(iframeId).setAttribute("src",url+Ext.Object.toQueryString(params)); dfd.resolve(); }).otherwise(function(response) { showError(response); dfd.reject(); }) } else { show('<iframe src="'+url+embeddedConfigParam+'" style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>'); } isEmbedded = true; return false; } }, this)===true) { Voyant.notebook.util.Embed.<API key>.call(this); } if (!isEmbedded) { var embedded = Ext.create(cmp, config); embedded.embed(config); isEmbedded = true; } } if (!isEmbedded) { Voyant.notebook.util.Embed.<API key>.call(this); } } }, <API key>: function() { var msg = Voyant.notebook.util.Embed.i18n.widgetNotRecognized; if (this.embeddable) { msg += Voyant.notebook.util.Embed.i18n.tryWidget+'<ul>'+this.embeddable.map(function(cmp) { var widget = cmp.substring(cmp.lastIndexOf(".")+1).toLowerCase() return "\"<a href='../../docs/#!/guide/"+widget+"' target='voyantdocs'>"+widget+"</a>\"" }).join(", ")+"</ul>" } showError(msg) } } }) embed = Voyant.notebook.util.Embed.embed
<! This test case covers the following situation: 1. an open tag for a void element 2. the next token is a close tag that does not match (1) <html><head><basefont color="blue"></head><body></body></html>
// Summary: // Usage: // Remarks: // Null // 2011-9-15 // Zhang JingDan (zhangjingdan@duokan.com) #ifndef <API key> #define <API key> #include "KernelRetCode.h" #include "DKPTypeDef.h" class IDKPOutline; class IDKPPage; class IDKPPageEx; class IDkStream; class IDKPDoc { public: enum <API key> { PREV_PAGE, LOCATION_PAGE, NEXT_PAGE, }; // Summary: // Parameters: virtual DK_ReturnCode OpenDoc(IDkStream* pFileOP) = 0; // Summary: // Parameters: virtual DK_ReturnCode OpenDoc(IDkStream* pFileOP, const DK_BYTE* pPwd, DK_INT length) = 0; // Summary: virtual DK_VOID CloseDoc() = 0; // Summary: // Returns: virtual DK_INT GetPageCount() = 0; // Summary: // Parameters: // Returns: virtual DK_INT RenderPage(DK_RENDERINFO* parrRenderInfo) = 0; // Summary: // Parameters: // Returns: virtual IDKPPage* GetPage(DK_INT nPageNum) = 0; // Summary: // Parameters: virtual DK_VOID ReleasePage(IDKPPage* pPage, DK_BOOL bAll = DK_FALSE) = 0; // Summary: // Parameters: // Return Value: // Null // Availability: virtual DK_VOID SetTypeSetting(const DKTYPESETTING &typeSetting) = 0; // Summary: // Parameters: // Returns: virtual DK_ReturnCode GetPageEx(const DK_FLOWPOSITION& pos, const <API key>& option, <API key> posType, IDKPPageEx** ppPageEx) = 0; // Summary: // Parameters: virtual DK_VOID ReleasePageEx(IDKPPageEx* pPage, DK_BOOL bAll = DK_FALSE) = 0; // Summary: // Returns: virtual IDKPOutline* GetOutline() = 0; // Summary: // Parameters: virtual DK_VOID <API key>(const DK_WCHAR* <API key>, DK_CHARSET_TYPE charset) = 0; // Summary: // Parameters: virtual DK_BOOL GetDocMetaData(PDKPMETADATA& pMetaData) = 0; virtual DK_BOOL ReleaseMetaData() = 0; // Summary: // Parameters: virtual DKP_REARRANGE_MODE GetRearrangeMode() = 0; public: virtual ~IDKPDoc() {} }; #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace <API key> { public class Settings { public List<Animation> AnimatedTiles { get; set; } = new List<Animation>(); } }