code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
/*
* LibreNMS
*
* Copyright (c) 2018 Søren Friis Rosiak <sorenrosiak@gmail.com>
* 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. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
$pagetitle[] = 'Oxidized';
?>
<div class="col-xs-12">
<h2>Oxidized</h2>
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active"><a href="#list" data-toggle="tab">Node List</a></li>
<li><a href="#search" data-toggle="tab">Config Search</a></li>
<li><a href="<?php echo \LibreNMS\Util\Url::generate(['page' => 'tools', 'tool' => 'oxidized-cfg-check']); ?>">Oxidized config validation</a></li>
</ul>
</div>
<div class="panel with-nav-tabs panel-default">
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane fade in active" id="list">
<div class="table-responsive">
<table id="oxidized-nodes" class="table table-hover table-condensed table-striped">
<thead>
<tr>
<th data-column-id="id" data-visible="false">ID</th>
<th data-column-id="hostname" data-formatter="hostname" data-order="asc">Hostname</th>
<th data-column-id="sysname" data-visible=" <?php echo ! Config::get('force_ip_to_sysname') ? 'true' : 'false' ?>">SysName</th>
<th data-column-id="last_status" data-formatter="status">Last Status</th>
<th data-column-id="last_update">Last Update</th>
<th data-column-id="model">Model</th>
<th data-column-id="group">Group</th>
<th data-column-id="actions" data-formatter="actions"></th>
</tr>
</thead>
<tbody>
<?php get_oxidized_nodes_list(); ?>
</tbody>
</table>
</div>
</div>
<div class="tab-pane fade" id="search">
<form class="form-horizontal" action="" method="post">
<?php echo csrf_field() ?>
<br/>
<div class="input-group">
<input type="text" class="form-control" id="input-parameter"
placeholder="service password-encryption etc.">
<span class="input-group-btn">
<button type="submit" name="btn-search" id="btn-search" class="btn btn-primary">Search</button>
</span>
</div>
</form>
<br/>
<div id="search-output" class="alert alert-success" style="display: none;"></div>
<br/>
</div>
</div>
</div>
</div>
</div>
<script>
var grid = $("#oxidized-nodes").bootgrid({
templates: {
header: '<div id="{{ctx.id}}" class="{{css.header}}"><div class="row">\
<div class="col-sm-8 actionBar">\
<span class="pull-left">\
<button type="submit" class="btn btn-success btn-sm" name="btn-reload-nodes" id="btn-reload-nodes"\
title="Update Oxidized\'s node list from LibreNMS data"><i class="fa fa-refresh"></i>\
Reload node list</button>\
</span>\
</div>\
<div class="col-sm-4 actionBar"><p class="{{css.search}}"></p><p class="{{css.actions}}"></p></div>\
</div></div>'
},
rowCount: [50, 100, 250, -1],
formatters: {
"hostname": function(column, row) {
if (row.id) {
return '<a href="<?= url('device') ?>/' + row.id + '">' + row.hostname + '</a>';
} else {
return row.hostname;
}
},
"actions": function(column, row) {
if (row.id) {
return '<button class="btn btn-default btn-sm" name="btn-refresh-node-devId' + row.id +
'" id="btn-refresh-node-devId' + row.id + '" onclick="refresh_oxidized_node(\'' + row.hostname + '\');" title="Refetch config">' +
'<i class="fa fa-refresh"></i></button> ' +
'<a href="<?= url('device') ?>/' + row.id + '/tab=showconfig/" title="View config"><i class="fa fa-align-justify fa-lg icon-theme"></i></a>';
}
},
"status": function(column, row) {
var color = ((row.last_status == 'success') ? 'success' : 'danger');
return '<i class="fa fa-square text-' + color + '" title="' + row.last_status + '"></i>';
}
}
});
$("[name='btn-search']").on('click', function (event) {
event.preventDefault();
var $this = $(this);
var search_in_conf_textbox = $("#input-parameter").val();
$.ajax({
type: 'POST',
url: 'ajax_form.php',
data: {
type: "search-oxidized-config",
search_in_conf_textbox: search_in_conf_textbox
},
dataType: "json",
success: function (data) {
$('#search-output').empty();
$("#search-output").show();
if (data.output) {
$('#search-output').append('<p>Config appears on the following device(s):</p>');
$.each(data.output, function (row, value) {
if (value['dev_id']) {
$('#search-output').append('<p><a href="<?= url('device') ?>/' + value['dev_id'] + '/tab=showconfig/">' + value['full_name'] + '</p>');
} else {
$('#search-output').append('<p>' + value['full_name'] + '</p>');
}
});
}
},
error: function () {
toastr.error('Error');
}
});
});
$("[name='btn-reload-nodes']").on('click', function (event) {
$.ajax({
type: 'POST',
url: 'ajax_form.php',
data: { type: "reload-oxidized-nodes-list" },
dataType: "json",
success: function (data) {
if(data['status'] == 'ok') {
toastr.success(data['message']);
} else {
toastr.error(data['message']);
}
},
error:function(){
toastr.error('An error occured while reloading the Oxidized nodes list');
}
});
});
</script>
| arrmo/librenms | includes/html/pages/oxidized.inc.php | PHP | gpl-3.0 | 7,347 |
<?php defined('SYSPATH') or die('No direct script access.');?>
<?if ($widget->rss_title!=''):?>
<div class="panel-heading">
<h3 class="panel-title"><?=$widget->rss_title?></h3>
</div>
<?endif?>
<div class="panel-body">
<ul>
<?foreach ($widget->rss_items as $item):?>
<li><a target="_blank" href="<?=$item['link']?>" title="<?=HTML::chars($item['title'])?>"><?=$item['title']?></a></li>
<?endforeach?>
</ul>
</div> | oliverds/open-eshop | oc/common/modules/widgets/views/widget/widget_rss.php | PHP | gpl-3.0 | 428 |
package edu.isi.bmkeg.lapdf.xml.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="document")
public class LapdftextXMLDocument implements Serializable {
static final long serialVersionUID = 8047039304729208683L;
private Long vpdmfId;
private List<LapdftextXMLPage> pages = new ArrayList<LapdftextXMLPage>();
private List<LapdftextXMLFontStyle> fontStyles = new ArrayList<LapdftextXMLFontStyle>();
@XmlAttribute
public Long getVpdmfId() {
return vpdmfId;
}
public void setVpdmfId(Long vpdmfId) {
this.vpdmfId = vpdmfId;
}
@XmlElementWrapper( name="pages" )
@XmlElement( name="page" )
public List<LapdftextXMLPage> getPages() {
return pages;
}
public void setPages(List<LapdftextXMLPage> pages) {
this.pages = pages;
}
@XmlElementWrapper( name="fontStyles" )
@XmlElement( name="fontStyle" )
public List<LapdftextXMLFontStyle> getFontStyles() {
return fontStyles;
}
public void setFontStyles(List<LapdftextXMLFontStyle> fontStyles) {
this.fontStyles = fontStyles;
}
}
| benmccann/lapdftext | src/main/java/edu/isi/bmkeg/lapdf/xml/model/LapdftextXMLDocument.java | Java | gpl-3.0 | 1,272 |
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver 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.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomtrak.h"
#include "mediaformats/readers/mp4/mp4document.h"
#include "mediaformats/readers/mp4/atomtkhd.h"
AtomTRAK::AtomTRAK(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: BoxAtom(pDocument, type, size, start) {
_pTKHD = NULL;
_pMDIA = NULL;
_pHDLR = NULL;
_pMINF = NULL;
_pDINF = NULL;
_pSTBL = NULL;
_pUDTA = NULL;
}
AtomTRAK::~AtomTRAK() {
}
uint32_t AtomTRAK::GetId() {
if (_pTKHD != NULL)
return _pTKHD->GetTrackId();
return 0;
}
bool AtomTRAK::AtomCreated(BaseAtom *pAtom) {
switch (pAtom->GetTypeNumeric()) {
case A_TKHD:
_pTKHD = (AtomTKHD *) pAtom;
return true;
case A_MDIA:
_pMDIA = (AtomMDIA *) pAtom;
return true;
case A_HDLR:
_pHDLR = (AtomHDLR *) pAtom;
return true;
case A_MINF:
_pMINF = (AtomMINF *) pAtom;
return true;
case A_DINF:
_pDINF = (AtomDINF *) pAtom;
return true;
case A_STBL:
_pSTBL = (AtomSTBL *) pAtom;
return true;
case A_UDTA:
_pUDTA = (AtomUDTA *) pAtom;
return true;
case A_META:
_pMETA = (AtomMETA *) pAtom;
return true;
default:
{
FATAL("Invalid atom type: %s", STR(pAtom->GetTypeString()));
return false;
}
}
}
#endif /* HAS_MEDIA_MP4 */
| mich181189/crtmpserver-YSTV | sources/thelib/src/mediaformats/readers/mp4/atomtrak.cpp | C++ | gpl-3.0 | 2,029 |
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: System.CLSCompliant(true)]
[assembly: InternalsVisibleTo("GitExtensionsTest")]
| ArsenShnurkov/gitextensions | GitCommands/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 413 |
/*
Copyright (c) 1990-2001 Info-ZIP. All rights reserved.
See the accompanying file LICENSE, version 2000-Apr-09 or later
(the contents of which are also included in unzip.h) for terms of use.
If, for some reason, all these files are missing, the Info-ZIP license
also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
*/
/*---------------------------------------------------------------------------
unzipstb.c
Simple stub function for UnZip DLL (or shared library, whatever); does
exactly the same thing as normal UnZip, except for additional printf()s
of various version numbers, solely as a demonstration of what can/should
be checked when using the DLL. (If major version numbers ever differ,
assume program is incompatible with DLL--especially if DLL version is
older. This is not likely to be a problem with *this* simple program,
but most user programs will be much more complex.)
---------------------------------------------------------------------------*/
#include <stdio.h>
#include "unzip.h"
#include "unzvers.h"
int main(int argc, char *argv[])
{
static UzpVer *pVersion; /* no pervert jokes, please... */
pVersion = UzpVersion();
printf("UnZip stub: checking version numbers (DLL is dated %s)\n",
pVersion->date);
printf(" UnZip versions: expecting %d.%d%d, using %d.%d%d%s\n",
UZ_MAJORVER, UZ_MINORVER, UZ_PATCHLEVEL, pVersion->unzip.major,
pVersion->unzip.minor, pVersion->unzip.patchlevel, pVersion->betalevel);
printf(" ZipInfo versions: expecting %d.%d%d, using %d.%d%d\n",
ZI_MAJORVER, ZI_MINORVER, UZ_PATCHLEVEL, pVersion->zipinfo.major,
pVersion->zipinfo.minor, pVersion->zipinfo.patchlevel);
/*
D2_M*VER and os2dll.* are obsolete, though retained for compatibility:
printf(" OS2 DLL versions: expecting %d.%d%d, using %d.%d%d\n",
D2_MAJORVER, D2_MINORVER, D2_PATCHLEVEL, pVersion->os2dll.major,
pVersion->os2dll.minor, pVersion->os2dll.patchlevel);
*/
if (pVersion->flag & 2)
printf(" using zlib version %s\n", pVersion->zlib_version);
printf("\n");
/* call the actual UnZip routine (string-arguments version) */
return UzpMain(argc, argv);
}
const char *BOINC_RCSID_0df1c7c635 = "$Id: unzipstb.c 4979 2005-01-02 18:29:53Z ballen $";
| asimonov-im/boinc | zip/unzip/unzipstb.c | C | gpl-3.0 | 2,328 |
var Conditions;
Conditions = function() {
var self = this;
this.compare = function( leftValue, rightValue, operator ) {
switch ( operator ) {
/* eslint-disable eqeqeq */
case '==':
return leftValue == rightValue;
case '!=':
return leftValue != rightValue;
/* eslint-enable eqeqeq */
case '!==':
return leftValue !== rightValue;
case 'in':
return -1 !== rightValue.indexOf( leftValue );
case '!in':
return -1 === rightValue.indexOf( leftValue );
case 'contains':
return -1 !== leftValue.indexOf( rightValue );
case '!contains':
return -1 === leftValue.indexOf( rightValue );
case '<':
return leftValue < rightValue;
case '<=':
return leftValue <= rightValue;
case '>':
return leftValue > rightValue;
case '>=':
return leftValue >= rightValue;
default:
return leftValue === rightValue;
}
};
this.check = function( conditions, comparisonObject ) {
var isOrCondition = 'or' === conditions.relation,
conditionSucceed = ! isOrCondition;
jQuery.each( conditions.terms, function() {
var term = this,
comparisonResult;
if ( term.terms ) {
comparisonResult = self.check( term, comparisonObject );
} else {
var parsedName = term.name.match( /(\w+)(?:\[(\w+)])?/ ),
value = comparisonObject[ parsedName[ 1 ] ];
if ( parsedName[ 2 ] ) {
value = value[ parsedName[ 2 ] ];
}
comparisonResult = self.compare( value, term.value, term.operator );
}
if ( isOrCondition ) {
if ( comparisonResult ) {
conditionSucceed = true;
}
return ! comparisonResult;
}
if ( ! comparisonResult ) {
return conditionSucceed = false;
}
} );
return conditionSucceed;
};
};
module.exports = new Conditions();
| ramiy/elementor | assets/dev/js/editor/utils/conditions.js | JavaScript | gpl-3.0 | 1,771 |
/**
* SqueezeBox - Expandable Lightbox
*
* Allows to open various content as modal,
* centered and animated box.
*
* Dependencies: MooTools 1.2
*
* Inspired by
* ... Lokesh Dhakar - The original Lightbox v2
*
* @version 1.1 rc4
*
* @license MIT-style license
* @author Harald Kirschner <mail [at] digitarald.de>
* @copyright Author
*/
var SqueezeBox = {
presets: {
onOpen: $empty,
onClose: $empty,
onUpdate: $empty,
onResize: $empty,
onMove: $empty,
onShow: $empty,
onHide: $empty,
size: {x: 600, y: 450},
sizeLoading: {x: 200, y: 150},
marginInner: {x: 20, y: 20},
marginImage: {x: 50, y: 75},
handler: false,
target: null,
closable: true,
closeBtn: true,
zIndex: 65555,
overlayOpacity: 0.7,
classWindow: '',
classOverlay: '',
overlayFx: {},
resizeFx: {},
contentFx: {},
parse: false, // 'rel'
parseSecure: false,
shadow: true,
document: null,
ajaxOptions: {}
},
initialize: function(presets) {
if (this.options) return this;
this.presets = $merge(this.presets, presets);
this.doc = this.presets.document || document;
this.options = {};
this.setOptions(this.presets).build();
this.bound = {
window: this.reposition.bind(this, [null]),
scroll: this.checkTarget.bind(this),
close: this.close.bind(this),
key: this.onKey.bind(this)
};
this.isOpen = this.isLoading = false;
return this;
},
build: function() {
this.overlay = new Element('div', {
id: 'sbox-overlay',
styles: {display: 'none', zIndex: this.options.zIndex}
});
this.win = new Element('div', {
id: 'sbox-window',
styles: {display: 'none', zIndex: this.options.zIndex + 2}
});
if (this.options.shadow) {
if (Browser.Engine.webkit420) {
this.win.setStyle('-webkit-box-shadow', '0 0 10px rgba(0, 0, 0, 0.7)');
} else if (!Browser.Engine.trident4) {
var shadow = new Element('div', {'class': 'sbox-bg-wrap'}).inject(this.win);
var relay = function(e) {
this.overlay.fireEvent('click', [e]);
}.bind(this);
['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
new Element('div', {'class': 'sbox-bg sbox-bg-' + dir}).inject(shadow).addEvent('click', relay);
});
}
}
this.content = new Element('div', {id: 'sbox-content'}).inject(this.win);
this.closeBtn = new Element('a', {id: 'sbox-btn-close', href: '#'}).inject(this.win);
this.fx = {
overlay: new Fx.Tween(this.overlay, $merge({
property: 'opacity',
onStart: Events.prototype.clearChain,
duration: 250,
link: 'cancel'
}, this.options.overlayFx)).set(0),
win: new Fx.Morph(this.win, $merge({
onStart: Events.prototype.clearChain,
unit: 'px',
duration: 750,
transition: Fx.Transitions.Quint.easeOut,
link: 'cancel',
unit: 'px'
}, this.options.resizeFx)),
content: new Fx.Tween(this.content, $merge({
property: 'opacity',
duration: 250,
link: 'cancel'
}, this.options.contentFx)).set(0)
};
$(this.doc.body).adopt(this.overlay, this.win);
},
assign: function(to, options) {
return ($(to) || $$(to)).addEvent('click', function() {
return !SqueezeBox.fromElement(this, options);
});
},
open: function(subject, options) {
this.initialize();
if (this.element != null) this.trash();
this.element = $(subject) || false;
this.setOptions($merge(this.presets, options || {}));
if (this.element && this.options.parse) {
var obj = this.element.getProperty(this.options.parse);
if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj);
}
this.url = ((this.element) ? (this.element.get('href')) : subject) || this.options.url || '';
this.assignOptions();
var handler = handler || this.options.handler;
if (handler) return this.setContent(handler, this.parsers[handler].call(this, true));
var ret = false;
return this.parsers.some(function(parser, key) {
var content = parser.call(this);
if (content) {
ret = this.setContent(key, content);
return true;
}
return false;
}, this);
},
fromElement: function(from, options) {
return this.open(from, options);
},
assignOptions: function() {
this.overlay.set('class', this.options.classOverlay);
this.win.set('class', this.options.classWindow);
if (Browser.Engine.trident4) this.win.addClass('sbox-window-ie6');
},
close: function(e) {
var stoppable = ($type(e) == 'event');
if (stoppable) e.stop();
if (!this.isOpen || (stoppable && !$lambda(this.options.closable).call(this, e))) return this;
this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this));
this.win.setStyle('display', 'none');
this.fireEvent('onClose', [this.content]);
this.trash();
this.toggleListeners();
this.isOpen = false;
return this;
},
trash: function() {
this.element = this.asset = null;
this.content.empty();
this.options = {};
this.removeEvents().setOptions(this.presets).callChain();
},
onError: function() {
this.asset = null;
this.setContent('string', this.options.errorMsg || 'An error occurred');
},
setContent: function(handler, content) {
if (!this.handlers[handler]) return false;
this.content.className = 'sbox-content-' + handler;
this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, this.handlers[handler].call(this, content));
if (this.overlay.retrieve('opacity')) return this;
this.toggleOverlay(true);
this.fx.overlay.start(this.options.overlayOpacity);
return this.reposition();
},
applyContent: function(content, size) {
if (!this.isOpen && !this.applyTimer) return;
this.applyTimer = $clear(this.applyTimer);
this.hideContent();
if (!content) {
this.toggleLoading(true);
} else {
if (this.isLoading) this.toggleLoading(false);
this.fireEvent('onUpdate', [this.content], 20);
}
if (content) {
if (['string', 'array'].contains($type(content))) this.content.set('html', content);
else if (!this.content.hasChild(content)) this.content.adopt(content);
}
this.callChain();
if (!this.isOpen) {
this.toggleListeners(true);
this.resize(size, true);
this.isOpen = true;
this.fireEvent('onOpen', [this.content]);
} else {
this.resize(size);
}
},
resize: function(size, instantly) {
this.showTimer = $clear(this.showTimer || null);
var box = this.doc.getSize(), scroll = this.doc.getScroll();
this.size = $merge((this.isLoading) ? this.options.sizeLoading : this.options.size, size);
var to = {
width: this.size.x,
height: this.size.y,
left: (scroll.x + (box.x - this.size.x - this.options.marginInner.x) / 2).toInt(),
top: (scroll.y + (box.y - this.size.y - this.options.marginInner.y) / 2).toInt()
};
this.hideContent();
if (!instantly) {
this.fx.win.start(to).chain(this.showContent.bind(this));
} else {
this.win.setStyles(to).setStyle('display', '');
this.showTimer = this.showContent.delay(50, this);
}
return this.reposition();
},
toggleListeners: function(state) {
var fn = (state) ? 'addEvent' : 'removeEvent';
this.closeBtn[fn]('click', this.bound.close);
this.overlay[fn]('click', this.bound.close);
this.doc[fn]('keydown', this.bound.key)[fn]('mousewheel', this.bound.scroll);
this.doc.getWindow()[fn]('resize', this.bound.window)[fn]('scroll', this.bound.window);
},
toggleLoading: function(state) {
this.isLoading = state;
this.win[(state) ? 'addClass' : 'removeClass']('sbox-loading');
if (state) this.fireEvent('onLoading', [this.win]);
},
toggleOverlay: function(state) {
var full = this.doc.getSize().x;
this.overlay.setStyle('display', (state) ? '' : 'none');
this.doc.body[(state) ? 'addClass' : 'removeClass']('body-overlayed');
if (state) {
this.scrollOffset = this.doc.getWindow().getSize().x - full;
this.doc.body.setStyle('margin-right', this.scrollOffset);
} else {
this.doc.body.setStyle('margin-right', '');
}
},
showContent: function() {
if (this.content.get('opacity')) this.fireEvent('onShow', [this.win]);
this.fx.content.start(1);
},
hideContent: function() {
if (!this.content.get('opacity')) this.fireEvent('onHide', [this.win]);
this.fx.content.cancel().set(0);
},
onKey: function(e) {
switch (e.key) {
case 'esc': this.close(e);
case 'up': case 'down': return false;
}
},
checkTarget: function(e) {
return this.content.hasChild(e.target);
},
reposition: function() {
var size = this.doc.getSize(), scroll = this.doc.getScroll(), ssize = this.doc.getScrollSize();
this.overlay.setStyles({
width: ssize.x + 'px',
height: ssize.y + 'px'
});
this.win.setStyles({
left: (scroll.x + (size.x - this.win.offsetWidth) / 2 - this.scrollOffset).toInt() + 'px',
top: (scroll.y + (size.y - this.win.offsetHeight) / 2).toInt() + 'px'
});
return this.fireEvent('onMove', [this.overlay, this.win]);
},
removeEvents: function(type){
if (!this.$events) return this;
if (!type) this.$events = null;
else if (this.$events[type]) this.$events[type] = null;
return this;
},
extend: function(properties) {
return $extend(this, properties);
},
handlers: new Hash(),
parsers: new Hash()
};
SqueezeBox.extend(new Events($empty)).extend(new Options($empty)).extend(new Chain($empty));
SqueezeBox.parsers.extend({
image: function(preset) {
return (preset || (/\.(?:jpg|png|gif)$/i).test(this.url)) ? this.url : false;
},
clone: function(preset) {
if ($(this.options.target)) return $(this.options.target);
if (this.element && !this.element.parentNode) return this.element;
var bits = this.url.match(/#([\w-]+)$/);
return (bits) ? $(bits[1]) : (preset ? this.element : false);
},
ajax: function(preset) {
return (preset || (this.url && !(/^(?:javascript|#)/i).test(this.url))) ? this.url : false;
},
iframe: function(preset) {
return (preset || this.url) ? this.url : false;
},
string: function(preset) {
return true;
}
});
SqueezeBox.handlers.extend({
image: function(url) {
var size, tmp = new Image();
this.asset = null;
tmp.onload = tmp.onabort = tmp.onerror = (function() {
tmp.onload = tmp.onabort = tmp.onerror = null;
if (!tmp.width) {
this.onError.delay(10, this);
return;
}
var box = this.doc.getSize();
box.x -= this.options.marginImage.x;
box.y -= this.options.marginImage.y;
size = {x: tmp.width, y: tmp.height};
for (var i = 2; i--;) {
if (size.x > box.x) {
size.y *= box.x / size.x;
size.x = box.x;
} else if (size.y > box.y) {
size.x *= box.y / size.y;
size.y = box.y;
}
}
size.x = size.x.toInt();
size.y = size.y.toInt();
this.asset = $(tmp);
tmp = null;
this.asset.width = size.x;
this.asset.height = size.y;
this.applyContent(this.asset, size);
}).bind(this);
tmp.src = url;
if (tmp && tmp.onload && tmp.complete) tmp.onload();
return (this.asset) ? [this.asset, size] : null;
},
clone: function(el) {
if (el) return el.clone();
return this.onError();
},
adopt: function(el) {
if (el) return el;
return this.onError();
},
ajax: function(url) {
var options = this.options.ajaxOptions || {};
this.asset = new Request.HTML($merge({
method: 'get',
evalScripts: false
}, this.options.ajaxOptions)).addEvents({
onSuccess: function(resp) {
this.applyContent(resp);
if (options.evalScripts !== null && !options.evalScripts) $exec(this.asset.response.javascript);
this.fireEvent('onAjax', [resp, this.asset]);
this.asset = null;
}.bind(this),
onFailure: this.onError.bind(this)
});
this.asset.send.delay(10, this.asset, [{url: url}]);
},
iframe: function(url) {
this.asset = new Element('iframe', $merge({
src: url,
frameBorder: 0,
width: this.options.size.x,
height: this.options.size.y
}, this.options.iframeOptions));
if (this.options.iframePreload) {
this.asset.addEvent('load', function() {
this.applyContent(this.asset.setStyle('display', ''));
}.bind(this));
this.asset.setStyle('display', 'none').inject(this.content);
return false;
}
return this.asset;
},
string: function(str) {
return str;
}
});
SqueezeBox.handlers.url = SqueezeBox.handlers.ajax;
SqueezeBox.parsers.url = SqueezeBox.parsers.ajax;
SqueezeBox.parsers.adopt = SqueezeBox.parsers.clone;
| luizwbr/MoIP-VirtueMart-3 | assets/js/SqueezeBox.js | JavaScript | gpl-3.0 | 12,254 |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// AlipayOpenPublicInfoModifyResponse.
/// </summary>
public class AlipayOpenPublicInfoModifyResponse : AopResponse
{
/// <summary>
/// 服务窗审核状态描述,如果审核驳回则有相关的驳回理由
/// </summary>
[XmlElement("audit_desc")]
public string AuditDesc { get; set; }
/// <summary>
/// 服务窗审核状态,对于系统商而言,只有三个状态,AUDITING:审核中,AUDIT_FAILED:审核驳回,AUDIT_SUCCESS:审核通过。
/// </summary>
[XmlElement("audit_status")]
public string AuditStatus { get; set; }
}
}
| ColgateKas/cms | source/BaiRong.Core/ThirdParty/Alipay/openapi/Response/AlipayOpenPublicInfoModifyResponse.cs | C# | gpl-3.0 | 748 |
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2014 Uwe Hermann <uwe@hermann-uwe.de>
##
## 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 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##
#
# Chip specific properties:
#
# - vendor: chip manufacturer
# - model: chip model
# - size: total EEPROM size (in number of bytes)
# - page_size: page size (in number of bytes)
# - page_wraparound: Whether writes wrap-around at page boundaries
# - addr_bytes: number of EEPROM address bytes used
# - addr_pins: number of address pins (A0/A1/A2) on this chip
# - max_speed: max. supported I²C speed (in kHz)
#
chips = {
# Generic chip (128 bytes, 8 bytes page size)
'generic': {
'vendor': '',
'model': 'Generic',
'size': 128,
'page_size': 8,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 3,
'max_speed': 400,
},
# Microchip
'microchip_24aa65': {
'vendor': 'Microchip',
'model': '24AA65',
'size': 8 * 1024,
'page_size': 64, # Actually 8, but there are 8 pages of "input cache"
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3,
'max_speed': 400,
},
'microchip_24lc65': {
'vendor': 'Microchip',
'model': '24LC65',
'size': 8 * 1024,
'page_size': 64, # Actually 8, but there are 8 pages of "input cache"
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3,
'max_speed': 400,
},
'microchip_24c65': {
'vendor': 'Microchip',
'model': '24C65',
'size': 8 * 1024,
'page_size': 64, # Actually 8, but there are 8 pages of "input cache"
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3,
'max_speed': 400,
},
'microchip_24aa64': {
'vendor': 'Microchip',
'model': '24AA64',
'size': 8 * 1024,
'page_size': 32,
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3,
'max_speed': 400, # 100 for VCC < 2.5V
},
'microchip_24lc64': {
'vendor': 'Microchip',
'model': '24LC64',
'size': 8 * 1024,
'page_size': 32,
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3,
'max_speed': 400,
},
'microchip_24aa02uid': {
'vendor': 'Microchip',
'model': '24AA02UID',
'size': 256,
'page_size': 8,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 0, # Pins A0, A1, A2 not used
'max_speed': 400,
},
'microchip_24aa025uid': {
'vendor': 'Microchip',
'model': '24AA025UID',
'size': 256,
'page_size': 16,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 3,
'max_speed': 400,
},
'microchip_24aa025uid_sot23': {
'vendor': 'Microchip',
'model': '24AA025UID (SOT-23)',
'size': 256,
'page_size': 16,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 2, # SOT-23 package: A2 not available
'max_speed': 400,
},
# ON Semiconductor
'onsemi_cat24c256': {
'vendor': 'ON Semiconductor',
'model': 'CAT24C256',
'size': 32 * 1024,
'page_size': 64,
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3,
'max_speed': 1000,
},
'onsemi_cat24m01': {
'vendor': 'ON Semiconductor',
'model': 'CAT24M01',
'size': 128 * 1024,
'page_size': 256,
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 2, # Pin A0 not connected
'max_speed': 1000,
},
# Siemens
'siemens_slx_24c01': {
'vendor': 'Siemens',
'model': 'SLx 24C01',
'size': 128,
'page_size': 8,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 0, # Pins A0, A1, A2 are not connected (NC)
'max_speed': 400,
},
'siemens_slx_24c02': {
'vendor': 'Siemens',
'model': 'SLx 24C02',
'size': 256,
'page_size': 8,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 0, # Pins A0, A1, A2 are not connected (NC)
'max_speed': 400,
},
# ST
'st_m24c01': {
'vendor': 'ST',
'model': 'M24C01',
'size': 128,
'page_size': 16,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 3, # Called E0, E1, E2 on this chip.
'max_speed': 400,
},
'st_m24c02': {
'vendor': 'ST',
'model': 'M24C02',
'size': 256,
'page_size': 16,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 3, # Called E0, E1, E2 on this chip.
'max_speed': 400,
},
'st_m24c32': {
'vendor': 'ST',
'model': 'M24C32',
'size': 4 * 1024,
'page_size': 32,
'page_wraparound': True,
'addr_bytes': 2,
'addr_pins': 3, # Called E0, E1, E2 on this chip.
'max_speed': 1000,
},
# Xicor
'xicor_x24c02': {
'vendor': 'Xicor',
'model': 'X24C02',
'size': 256,
'page_size': 4,
'page_wraparound': True,
'addr_bytes': 1,
'addr_pins': 3,
'max_speed': 100,
},
}
| sigrokproject/libsigrokdecode | decoders/eeprom24xx/lists.py | Python | gpl-3.0 | 5,965 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by texinfo, http://www.gnu.org/software/texinfo/ -->
<head>
<title>File used for navigation testing: 1.1 Section in chapter</title>
<meta name="description" content="File used for navigation testing: 1.1 Section in chapter">
<meta name="keywords" content="File used for navigation testing: 1.1 Section in chapter">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2any">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="section"></a>
<table border="0" cellpadding="0" cellspacing="0">
<tr valign="top">
<td align="left">
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr valign="top" align="left">
<td valign="middle" align="left">[<a href="chapter.html#chapter" title="Beginning of this chapter or previous chapter"> << </a>]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[<a href="chapter.html#chapter" title="Previous section in reading order"> < </a>]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[<a href="chapter.html#chapter" title="Up section"> Up </a>]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[<a href="#subsection" title="Next section in reading order"> > </a>]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[ >> ]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"> </td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"> </td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"> </td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"> </td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[<a href="index.html#Top" title="Cover (top) of document">Top</a>]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[<a href="navigation_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[Index]</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left">[<a href="navigation_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr>
</table>
</td>
<td align="left">
<a name="Section-in-chapter"></a>
<h2 class="section">1.1 Section in chapter</h2>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>AAAA
</p>
<p>b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b
b b b b b b b b b b b b b b b b b b b b b bb b b b b b b bb b bb.
</p>
<table class="menu" border="0" cellspacing="0">
<tr><td align="left" valign="top"><a href="#subsection">1.1.1 Sub section in section</a></td><td> </td><td align="left" valign="top">
</td></tr>
</table>
<hr>
<a name="subsection"></a>
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="chapter.html#chapter" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="#section" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="#section" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[ > ]</td>
<td valign="middle" align="left">[ >> ]</td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left"> </td>
<td valign="middle" align="left">[<a href="index.html#Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="navigation_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[Index]</td>
<td valign="middle" align="left">[<a href="navigation_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<a name="Sub-section-in-section"></a>
<h3 class="subsection">1.1.1 Sub section in section</h3>
</td>
</tr>
</table>
<hr>
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="chapter.html#chapter" title="Beginning of this chapter or previous chapter"> << </a>]</td>
<td valign="middle" align="left">[<a href="#section" title="Previous section in reading order"> < </a>]</td>
<td valign="middle" align="left">[<a href="#section" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[ > ]</td>
<td valign="middle" align="left">[ >> ]</td>
</tr></table>
<p><font size="-1">
This document was generated on <em>a sunny day</em> using <a href="http://www.gnu.org/software/texinfo/"><em>texi2any</em></a>.
</font></p>
</body>
</html>
| cfx-next/toolchain_texinfo | tp/tests/layout/res_parser/navigation_section_vertical/section.html | HTML | gpl-3.0 | 6,107 |
use vars qw(%result_texis %result_texts %result_trees %result_errors
%result_indices %result_sectioning %result_nodes %result_menus
%result_floats %result_converted %result_converted_errors
%result_elements %result_directions_text);
use utf8;
$result_trees{'implicit_quoting_recursion'} = {
'contents' => [
{
'args' => [
{
'parent' => {},
'text' => 'cat',
'type' => 'macro_name'
},
{
'parent' => {},
'text' => 'a',
'type' => 'macro_arg'
},
{
'parent' => {},
'text' => 'b',
'type' => 'macro_arg'
}
],
'cmdname' => 'rmacro',
'contents' => [
{
'parent' => {},
'text' => '\\a\\\\b\\',
'type' => 'raw'
},
{
'parent' => {},
'text' => '
',
'type' => 'last_raw_newline'
}
],
'extra' => {
'arg_line' => ' cat{a,b}
',
'args_index' => {
'a' => 0,
'b' => 1
},
'macrobody' => '\\a\\\\b\\
',
'spaces_after_command' => {
'extra' => {
'command' => {}
},
'parent' => {},
'text' => '
',
'type' => 'empty_line_after_command'
}
},
'line_nr' => {
'file_name' => '',
'line_nr' => 1,
'macro' => ''
},
'parent' => {}
},
{},
{
'parent' => {},
'text' => '
',
'type' => 'empty_line'
},
{
'contents' => [
{
'parent' => {},
'text' => 'natopocotuototam
'
}
],
'parent' => {},
'type' => 'paragraph'
}
],
'type' => 'text_root'
};
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'args'}[0]{'parent'} = $result_trees{'implicit_quoting_recursion'}{'contents'}[0];
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'args'}[1]{'parent'} = $result_trees{'implicit_quoting_recursion'}{'contents'}[0];
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'args'}[2]{'parent'} = $result_trees{'implicit_quoting_recursion'}{'contents'}[0];
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'contents'}[0]{'parent'} = $result_trees{'implicit_quoting_recursion'}{'contents'}[0];
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'contents'}[1]{'parent'} = $result_trees{'implicit_quoting_recursion'}{'contents'}[0];
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'extra'}{'spaces_after_command'}{'extra'}{'command'} = $result_trees{'implicit_quoting_recursion'}{'contents'}[0];
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'extra'}{'spaces_after_command'}{'parent'} = $result_trees{'implicit_quoting_recursion'};
$result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'parent'} = $result_trees{'implicit_quoting_recursion'};
$result_trees{'implicit_quoting_recursion'}{'contents'}[1] = $result_trees{'implicit_quoting_recursion'}{'contents'}[0]{'extra'}{'spaces_after_command'};
$result_trees{'implicit_quoting_recursion'}{'contents'}[2]{'parent'} = $result_trees{'implicit_quoting_recursion'};
$result_trees{'implicit_quoting_recursion'}{'contents'}[3]{'contents'}[0]{'parent'} = $result_trees{'implicit_quoting_recursion'}{'contents'}[3];
$result_trees{'implicit_quoting_recursion'}{'contents'}[3]{'parent'} = $result_trees{'implicit_quoting_recursion'};
$result_texis{'implicit_quoting_recursion'} = '@rmacro cat{a,b}
\\a\\\\b\\
@end rmacro
natopocotuototam
';
$result_texts{'implicit_quoting_recursion'} = '
natopocotuototam
';
$result_errors{'implicit_quoting_recursion'} = [];
1;
| cfx-next/toolchain_texinfo | tp/t/results/macro/implicit_quoting_recursion.pl | Perl | gpl-3.0 | 3,692 |
<?php
/**
* PHPUnit
*
* Copyright (c) 2002-2011, Sebastian Bergmann <sebastian@phpunit.de>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package PHPUnit
* @subpackage Extensions
* @author Sebastian Bergmann <sebastian@phpunit.de>
* @copyright 2002-2011 Sebastian Bergmann <sebastian@phpunit.de>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://www.phpunit.de/
* @since File available since Release 2.0.0
*/
/**
* A Decorator for Tests.
*
* Use TestDecorator as the base class for defining new
* test decorators. Test decorator subclasses can be introduced
* to add behaviour before or after a test is run.
*
* @package PHPUnit
* @subpackage Extensions
* @author Sebastian Bergmann <sebastian@phpunit.de>
* @copyright 2002-2011 Sebastian Bergmann <sebastian@phpunit.de>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://www.phpunit.de/
* @since Class available since Release 2.0.0
*/
class PHPUnit_Extensions_TestDecorator extends PHPUnit_Framework_Assert implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing
{
/**
* The Test to be decorated.
*
* @var object
*/
protected $test = NULL;
/**
* Constructor.
*
* @param PHPUnit_Framework_Test $test
*/
public function __construct(PHPUnit_Framework_Test $test)
{
$this->test = $test;
}
/**
* Returns a string representation of the test.
*
* @return string
*/
public function toString()
{
return $this->test->toString();
}
/**
* Runs the test and collects the
* result in a TestResult.
*
* @param PHPUnit_Framework_TestResult $result
*/
public function basicRun(PHPUnit_Framework_TestResult $result)
{
$this->test->run($result);
}
/**
* Counts the number of test cases that
* will be run by this test.
*
* @return integer
*/
public function count()
{
return count($this->test);
}
/**
* Creates a default TestResult object.
*
* @return PHPUnit_Framework_TestResult
*/
protected function createResult()
{
return new PHPUnit_Framework_TestResult;
}
/**
* Returns the test to be run.
*
* @return PHPUnit_Framework_Test
*/
public function getTest()
{
return $this->test;
}
/**
* Runs the decorated test and collects the
* result in a TestResult.
*
* @param PHPUnit_Framework_TestResult $result
* @return PHPUnit_Framework_TestResult
* @throws InvalidArgumentException
*/
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
if ($result === NULL) {
$result = $this->createResult();
}
$this->basicRun($result);
return $result;
}
}
| seiyar81/phpui | tests/library/PHPUnit/Extensions/TestDecorator_1.php | PHP | gpl-3.0 | 4,521 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd">
<HTML style="overflow:auto;">
<HEAD>
<meta name="generator" content="JDiff v1.1.0">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
Constructor Changes Index
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
<style type="text/css">
</style>
</HEAD>
<BODY class="gc-documentation" style="padding:12px;">
<a NAME="topheader"></a>
<table summary="Index for Constructors" width="100%" class="jdiffIndex" border="0" cellspacing="0" cellpadding="0" style="padding-bottom:0;margin-bottom:0;">
<tr>
<th class="indexHeader">
Filter the Index:
</th>
</tr>
<tr>
<td class="indexText" style="line-height:1.3em;padding-left:2em;">
<a href="constructors_index_all.html" class="staysblack">All Constructors</a>
<br>
<font color="#999999">Removals</font>
<br>
<font color="#999999">Additions</font>
<br>
<font color="#999999">Changes</font>
</td>
</tr>
</table>
<div id="indexTableCaption" style="background-color:#eee;padding:0 4px 0 4px;font-size:11px;margin-bottom:1em;">
Listed as: <span style="color:#069"><strong>Added</strong></span>, <span style="color:#069"><strike>Removed</strike></span>, <span style="color:#069">Changed</span></font>
</div>
<script src="//www.google-analytics.com/ga.js" type="text/javascript">
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._setAllowAnchor(true);
pageTracker._initData();
pageTracker._trackPageview();
} catch(e) {}
</script>
</BODY>
</HTML>
| s20121035/rk3288_android5.1_repo | frameworks/base/docs/html/sdk/api_diff/20/changes/constructors_index_changes.html | HTML | gpl-3.0 | 2,458 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TemplateSmarty.class.php 2730 2012-02-12 04:45:34Z liu21st $
/**
+-------------------------------------
* Smarty模板引擎驱动类
+-------------------------------------
*/
class TemplateSmarty {
/**
+----------------------------------------------------------
* 渲染模板输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
* @param array $var 模板变量
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function fetch($templateFile,$var) {
$templateFile=substr($templateFile,strlen(TMPL_PATH));
vendor('Smarty.Smarty#class');
$tpl = new Smarty();
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
foreach ($config as $key=>$val){
$tpl->{$key} = $val;
}
}else{
$tpl->caching = C('TMPL_CACHE_ON');
$tpl->template_dir = TMPL_PATH;
$tpl->compile_dir = CACHE_PATH ;
$tpl->cache_dir = TEMP_PATH ;
}
$tpl->assign($var);
$tpl->display($templateFile);
}
} | zning1994/newscentersystem | ThinkPHP/Extend/Driver/Template/TemplateSmarty.class.php | PHP | gpl-3.0 | 1,999 |
package edu.dfci.cccb.mev.annotation.elasticsearch.perf.alltypes;
public class PerfTestNumerify_AllTypes_100Krows_10cols extends PerfTestNumerify_AllTypes_Base {
// run 1 each index about 45M
// samples: 3
// max: 17080
// average: 14201.333333333334
// median: 10171
@Override
protected long getNUMCOLS () {
return 10;
}
@Override
protected int getNUMROWS () {
return 100*1000;
}
}
| apartensky/mev | annotation/elasticsearch/src/test/java/edu/dfci/cccb/mev/annotation/elasticsearch/perf/alltypes/PerfTestNumerify_AllTypes_100Krows_10cols.java | Java | gpl-3.0 | 419 |
//
// C++ Implementation: stopwatch
//
// Description:
//
//
// Author: Lorenzo Bettini <http://www.lorenzobettini.it>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "stopwatch.h"
#include <iostream>
using namespace std;
namespace srchilite {
StopWatch::~StopWatch()
{
clock_t total = clock() - start;
cout << "elapsed time (secs): " << double(total) / CLOCKS_PER_SEC << endl;
}
}
| lizh06/src-highlite | lib/srchilite/stopwatch.cpp | C++ | gpl-3.0 | 486 |
/*
* Copyright (c) 2010, SQL Power Group Inc.
*
* This file is part of Wabit.
*
* Wabit 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.
*
* Wabit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ca.sqlpower.wabit.rs;
public interface ResultSetProducerStatusInformant {
boolean isRunning();
}
| SQLPower/wabit | src/main/java/ca/sqlpower/wabit/rs/ResultSetProducerStatusInformant.java | Java | gpl-3.0 | 853 |
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_VERSION_')) {
exit;
}
function upgrade_module_2_5_8($module)
{
$hook_to_remove_id = Hook::getIdByName('advancedPaymentApi');
if ($hook_to_remove_id) {
$module->unregisterHook((int)$hook_to_remove_id);
}
return true;
}
| rjpalermo1/paymentsandbox_ps | src/modules/ps_checkpayment/upgrade/upgrade-2.5.8.php | PHP | gpl-3.0 | 1,241 |
#!/usr/bin/env /usr/bin/python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
from gnuradio import gr, filter
from . import dtv_python as dtv
# FIXME move these into separate constants module
ATSC_CHANNEL_BW = 6.0e6
ATSC_SYMBOL_RATE = 4.5e6/286*684 # ~10.76 Mbaud
ATSC_RRC_SYMS = 8 # filter kernel extends over 2N+1 symbols
class atsc_rx_filter(gr.hier_block2):
def __init__(self, input_rate, sps):
gr.hier_block2.__init__(self, "atsc_rx_filter",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
# Create matched RX filter with RRC response for fractional
# interpolator.
nfilts = 16
output_rate = ATSC_SYMBOL_RATE*sps # Desired oversampled sample rate
filter_rate = input_rate*nfilts
symbol_rate = ATSC_SYMBOL_RATE / 2.0 # One-sided bandwidth of sideband
excess_bw = 0.1152 #1.0-(0.5*ATSC_SYMBOL_RATE/ATSC_CHANNEL_BW) # ~10.3%
ntaps = int((2*ATSC_RRC_SYMS+1)*sps*nfilts)
interp = output_rate / input_rate
gain = nfilts*symbol_rate/filter_rate
rrc_taps = filter.firdes.root_raised_cosine(gain, # Filter gain
filter_rate, # PFB filter prototype rate
symbol_rate, # ATSC symbol rate
excess_bw, # ATSC RRC excess bandwidth
ntaps) # Length of filter
pfb = filter.pfb_arb_resampler_ccf(interp, rrc_taps, nfilts)
# Connect pipeline
self.connect(self, pfb, self)
| mrjacobagilbert/gnuradio | gr-dtv/python/dtv/atsc_rx_filter.py | Python | gpl-3.0 | 2,537 |
<?php
echo("Processors : ");
// Include all discovery modules
$include_dir = "includes/discovery/processors";
include("includes/include-dir.inc.php");
// Last-resort discovery here
include("processors-ucd-old.inc.php");
// Remove processors which weren't redetected here
$sql = "SELECT * FROM `processors` WHERE `device_id` = '".$device['device_id']."'";
if ($debug) { print_r ($valid['processor']); }
foreach (dbFetchRows($sql) as $test_processor)
{
$processor_index = $test_processor['processor_index'];
$processor_type = $test_processor['processor_type'];
if ($debug) { echo($processor_index . " -> " . $processor_type . "\n"); }
if (!$valid['processor'][$processor_type][$processor_index])
{
echo("-");
dbDelete('Processors', '`processor_id` = ?', array($test_processor['processor_id']));
log_event("Processor removed: type ".$processor_type." index ".$processor_index." descr ". $test_processor['processor_descr'], $device, 'processor', $test_processor['processor_id']);
}
unset($processor_oid); unset($processor_type);
}
echo("\n");
?>
| wojons/librenms | includes/discovery/processors.inc.php | PHP | gpl-3.0 | 1,080 |
##
## This file is part of the libsigrok project.
##
## Copyright (C) 2014 Martin Ling <martin-sigrok@earth.li>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
from __future__ import print_function
from xml.etree import ElementTree
import sys, os
language, input_file = sys.argv[1:3]
if len(sys.argv) == 4:
mode = sys.argv[3]
input_dir = os.path.dirname(input_file)
index = ElementTree.parse(input_file)
def get_text(node):
paras = node.findall('para')
return str.join('\n\n', [p.text.rstrip() for p in paras if p.text])
for compound in index.findall('compound'):
if compound.attrib['kind'] != 'class':
continue
class_name = compound.find('name').text
if not class_name.startswith('sigrok::'):
continue
trimmed_name = class_name.split('::')[1]
doc = ElementTree.parse("%s/%s.xml" % (input_dir, compound.attrib['refid']))
cls = doc.find('compounddef')
brief = get_text(cls.find('briefdescription'))
if brief:
if language == 'python':
print('%%feature("docstring") %s "%s";' % (class_name, brief))
elif language == 'java':
print('%%typemap(javaclassmodifiers) %s "/** %s */\npublic class"' % (
class_name, brief))
constants = []
for section in cls.findall('sectiondef'):
kind = section.attrib['kind']
if kind not in ('public-func', 'public-static-attrib'):
continue
for member in section.findall('memberdef'):
member_name = member.find('name').text
brief = get_text(member.find('briefdescription')).replace('"', '\\"')
parameters = {}
for para in member.find('detaileddescription').findall('para'):
paramlist = para.find('parameterlist')
if paramlist is not None:
for param in paramlist.findall('parameteritem'):
namelist = param.find('parameternamelist')
name = namelist.find('parametername').text
description = get_text(param.find('parameterdescription'))
if description:
parameters[name] = description
if brief:
if language == 'python' and kind == 'public-func':
print(str.join('\n', [
'%%feature("docstring") %s::%s "%s' % (
class_name, member_name, brief)] + [
'@param %s %s' % (name, desc)
for name, desc in parameters.items()]) + '";')
elif language == 'java' and kind == 'public-func':
print(str.join('\n', [
'%%javamethodmodifiers %s::%s "/** %s' % (
class_name, member_name, brief)] + [
' * @param %s %s' % (name, desc)
for name, desc in parameters.items()])
+ ' */\npublic"')
elif kind == 'public-static-attrib':
constants.append((member_name, brief))
if language == 'java' and constants:
print('%%typemap(javacode) %s %%{' % class_name)
for member_name, brief in constants:
print(' /** %s */\n public static final %s %s = new %s(classesJNI.%s_%s_get(), false);\n' % (
brief, trimmed_name, member_name, trimmed_name,
trimmed_name, member_name))
print('%}')
elif language == 'python' and constants:
if mode == 'start':
print('%%extend %s {\n%%pythoncode %%{' % class_name)
for member_name, brief in constants:
print(' ## @brief %s\n %s = None' % (brief, member_name))
print('%}\n}')
elif mode == 'end':
print('%pythoncode %{')
for member_name, brief in constants:
print('%s.%s.__doc__ = """%s"""' % (
trimmed_name, member_name, brief))
print('%}')
| mtitinger/libsigrok | bindings/swig/doc.py | Python | gpl-3.0 | 4,655 |
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_ARM_MACRO_ASSEMBLER_ARM_H_
#define V8_ARM_MACRO_ASSEMBLER_ARM_H_
#include "src/assembler.h"
#include "src/bailout-reason.h"
#include "src/frames.h"
#include "src/globals.h"
namespace v8 {
namespace internal {
// ----------------------------------------------------------------------------
// Static helper functions
// Generate a MemOperand for loading a field from an object.
inline MemOperand FieldMemOperand(Register object, int offset) {
return MemOperand(object, offset - kHeapObjectTag);
}
// Give alias names to registers
const Register cp = { kRegister_r7_Code }; // JavaScript context pointer.
const Register pp = { kRegister_r8_Code }; // Constant pool pointer.
const Register kRootRegister = { kRegister_r10_Code }; // Roots array pointer.
// Flags used for AllocateHeapNumber
enum TaggingMode {
// Tag the result.
TAG_RESULT,
// Don't tag
DONT_TAG_RESULT
};
enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
enum PointersToHereCheck {
kPointersToHereMaybeInteresting,
kPointersToHereAreAlwaysInteresting
};
enum LinkRegisterStatus { kLRHasNotBeenSaved, kLRHasBeenSaved };
Register GetRegisterThatIsNotOneOf(Register reg1,
Register reg2 = no_reg,
Register reg3 = no_reg,
Register reg4 = no_reg,
Register reg5 = no_reg,
Register reg6 = no_reg);
#ifdef DEBUG
bool AreAliased(Register reg1,
Register reg2,
Register reg3 = no_reg,
Register reg4 = no_reg,
Register reg5 = no_reg,
Register reg6 = no_reg,
Register reg7 = no_reg,
Register reg8 = no_reg);
#endif
enum TargetAddressStorageMode {
CAN_INLINE_TARGET_ADDRESS,
NEVER_INLINE_TARGET_ADDRESS
};
// MacroAssembler implements a collection of frequently used macros.
class MacroAssembler: public Assembler {
public:
// The isolate parameter can be NULL if the macro assembler should
// not use isolate-dependent functionality. In this case, it's the
// responsibility of the caller to never invoke such function on the
// macro assembler.
MacroAssembler(Isolate* isolate, void* buffer, int size);
// Returns the size of a call in instructions. Note, the value returned is
// only valid as long as no entries are added to the constant pool between
// checking the call size and emitting the actual call.
static int CallSize(Register target, Condition cond = al);
int CallSize(Address target, RelocInfo::Mode rmode, Condition cond = al);
int CallStubSize(CodeStub* stub,
TypeFeedbackId ast_id = TypeFeedbackId::None(),
Condition cond = al);
static int CallSizeNotPredictableCodeSize(Isolate* isolate,
Address target,
RelocInfo::Mode rmode,
Condition cond = al);
// Jump, Call, and Ret pseudo instructions implementing inter-working.
void Jump(Register target, Condition cond = al);
void Jump(Address target, RelocInfo::Mode rmode, Condition cond = al);
void Jump(Handle<Code> code, RelocInfo::Mode rmode, Condition cond = al);
void Call(Register target, Condition cond = al);
void Call(Address target, RelocInfo::Mode rmode,
Condition cond = al,
TargetAddressStorageMode mode = CAN_INLINE_TARGET_ADDRESS);
int CallSize(Handle<Code> code,
RelocInfo::Mode rmode = RelocInfo::CODE_TARGET,
TypeFeedbackId ast_id = TypeFeedbackId::None(),
Condition cond = al);
void Call(Handle<Code> code,
RelocInfo::Mode rmode = RelocInfo::CODE_TARGET,
TypeFeedbackId ast_id = TypeFeedbackId::None(),
Condition cond = al,
TargetAddressStorageMode mode = CAN_INLINE_TARGET_ADDRESS);
void Ret(Condition cond = al);
// Emit code to discard a non-negative number of pointer-sized elements
// from the stack, clobbering only the sp register.
void Drop(int count, Condition cond = al);
void Ret(int drop, Condition cond = al);
// Swap two registers. If the scratch register is omitted then a slightly
// less efficient form using xor instead of mov is emitted.
void Swap(Register reg1,
Register reg2,
Register scratch = no_reg,
Condition cond = al);
void Mls(Register dst, Register src1, Register src2, Register srcA,
Condition cond = al);
void And(Register dst, Register src1, const Operand& src2,
Condition cond = al);
void Ubfx(Register dst, Register src, int lsb, int width,
Condition cond = al);
void Sbfx(Register dst, Register src, int lsb, int width,
Condition cond = al);
// The scratch register is not used for ARMv7.
// scratch can be the same register as src (in which case it is trashed), but
// not the same as dst.
void Bfi(Register dst,
Register src,
Register scratch,
int lsb,
int width,
Condition cond = al);
void Bfc(Register dst, Register src, int lsb, int width, Condition cond = al);
void Usat(Register dst, int satpos, const Operand& src,
Condition cond = al);
void Call(Label* target);
void Push(Register src) { push(src); }
void Pop(Register dst) { pop(dst); }
// Register move. May do nothing if the registers are identical.
void Move(Register dst, Handle<Object> value);
void Move(Register dst, Register src, Condition cond = al);
void Move(Register dst, const Operand& src, SBit sbit = LeaveCC,
Condition cond = al) {
if (!src.is_reg() || !src.rm().is(dst) || sbit != LeaveCC) {
mov(dst, src, sbit, cond);
}
}
void Move(DwVfpRegister dst, DwVfpRegister src);
void Load(Register dst, const MemOperand& src, Representation r);
void Store(Register src, const MemOperand& dst, Representation r);
// Load an object from the root table.
void LoadRoot(Register destination,
Heap::RootListIndex index,
Condition cond = al);
// Store an object to the root table.
void StoreRoot(Register source,
Heap::RootListIndex index,
Condition cond = al);
// ---------------------------------------------------------------------------
// GC Support
void IncrementalMarkingRecordWriteHelper(Register object,
Register value,
Register address);
enum RememberedSetFinalAction {
kReturnAtEnd,
kFallThroughAtEnd
};
// Record in the remembered set the fact that we have a pointer to new space
// at the address pointed to by the addr register. Only works if addr is not
// in new space.
void RememberedSetHelper(Register object, // Used for debug code.
Register addr,
Register scratch,
SaveFPRegsMode save_fp,
RememberedSetFinalAction and_then);
void CheckPageFlag(Register object,
Register scratch,
int mask,
Condition cc,
Label* condition_met);
// Check if object is in new space. Jumps if the object is not in new space.
// The register scratch can be object itself, but scratch will be clobbered.
void JumpIfNotInNewSpace(Register object,
Register scratch,
Label* branch) {
InNewSpace(object, scratch, ne, branch);
}
// Check if object is in new space. Jumps if the object is in new space.
// The register scratch can be object itself, but it will be clobbered.
void JumpIfInNewSpace(Register object,
Register scratch,
Label* branch) {
InNewSpace(object, scratch, eq, branch);
}
// Check if an object has a given incremental marking color.
void HasColor(Register object,
Register scratch0,
Register scratch1,
Label* has_color,
int first_bit,
int second_bit);
void JumpIfBlack(Register object,
Register scratch0,
Register scratch1,
Label* on_black);
// Checks the color of an object. If the object is already grey or black
// then we just fall through, since it is already live. If it is white and
// we can determine that it doesn't need to be scanned, then we just mark it
// black and fall through. For the rest we jump to the label so the
// incremental marker can fix its assumptions.
void EnsureNotWhite(Register object,
Register scratch1,
Register scratch2,
Register scratch3,
Label* object_is_white_and_not_data);
// Detects conservatively whether an object is data-only, i.e. it does need to
// be scanned by the garbage collector.
void JumpIfDataObject(Register value,
Register scratch,
Label* not_data_object);
// Notify the garbage collector that we wrote a pointer into an object.
// |object| is the object being stored into, |value| is the object being
// stored. value and scratch registers are clobbered by the operation.
// The offset is the offset from the start of the object, not the offset from
// the tagged HeapObject pointer. For use with FieldOperand(reg, off).
void RecordWriteField(
Register object,
int offset,
Register value,
Register scratch,
LinkRegisterStatus lr_status,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
SmiCheck smi_check = INLINE_SMI_CHECK,
PointersToHereCheck pointers_to_here_check_for_value =
kPointersToHereMaybeInteresting);
// As above, but the offset has the tag presubtracted. For use with
// MemOperand(reg, off).
inline void RecordWriteContextSlot(
Register context,
int offset,
Register value,
Register scratch,
LinkRegisterStatus lr_status,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
SmiCheck smi_check = INLINE_SMI_CHECK,
PointersToHereCheck pointers_to_here_check_for_value =
kPointersToHereMaybeInteresting) {
RecordWriteField(context,
offset + kHeapObjectTag,
value,
scratch,
lr_status,
save_fp,
remembered_set_action,
smi_check,
pointers_to_here_check_for_value);
}
void RecordWriteForMap(
Register object,
Register map,
Register dst,
LinkRegisterStatus lr_status,
SaveFPRegsMode save_fp);
// For a given |object| notify the garbage collector that the slot |address|
// has been written. |value| is the object being stored. The value and
// address registers are clobbered by the operation.
void RecordWrite(
Register object,
Register address,
Register value,
LinkRegisterStatus lr_status,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
SmiCheck smi_check = INLINE_SMI_CHECK,
PointersToHereCheck pointers_to_here_check_for_value =
kPointersToHereMaybeInteresting);
// Push a handle.
void Push(Handle<Object> handle);
void Push(Smi* smi) { Push(Handle<Smi>(smi, isolate())); }
// Push two registers. Pushes leftmost register first (to highest address).
void Push(Register src1, Register src2, Condition cond = al) {
DCHECK(!src1.is(src2));
if (src1.code() > src2.code()) {
stm(db_w, sp, src1.bit() | src2.bit(), cond);
} else {
str(src1, MemOperand(sp, 4, NegPreIndex), cond);
str(src2, MemOperand(sp, 4, NegPreIndex), cond);
}
}
// Push three registers. Pushes leftmost register first (to highest address).
void Push(Register src1, Register src2, Register src3, Condition cond = al) {
DCHECK(!src1.is(src2));
DCHECK(!src2.is(src3));
DCHECK(!src1.is(src3));
if (src1.code() > src2.code()) {
if (src2.code() > src3.code()) {
stm(db_w, sp, src1.bit() | src2.bit() | src3.bit(), cond);
} else {
stm(db_w, sp, src1.bit() | src2.bit(), cond);
str(src3, MemOperand(sp, 4, NegPreIndex), cond);
}
} else {
str(src1, MemOperand(sp, 4, NegPreIndex), cond);
Push(src2, src3, cond);
}
}
// Push four registers. Pushes leftmost register first (to highest address).
void Push(Register src1,
Register src2,
Register src3,
Register src4,
Condition cond = al) {
DCHECK(!src1.is(src2));
DCHECK(!src2.is(src3));
DCHECK(!src1.is(src3));
DCHECK(!src1.is(src4));
DCHECK(!src2.is(src4));
DCHECK(!src3.is(src4));
if (src1.code() > src2.code()) {
if (src2.code() > src3.code()) {
if (src3.code() > src4.code()) {
stm(db_w,
sp,
src1.bit() | src2.bit() | src3.bit() | src4.bit(),
cond);
} else {
stm(db_w, sp, src1.bit() | src2.bit() | src3.bit(), cond);
str(src4, MemOperand(sp, 4, NegPreIndex), cond);
}
} else {
stm(db_w, sp, src1.bit() | src2.bit(), cond);
Push(src3, src4, cond);
}
} else {
str(src1, MemOperand(sp, 4, NegPreIndex), cond);
Push(src2, src3, src4, cond);
}
}
// Pop two registers. Pops rightmost register first (from lower address).
void Pop(Register src1, Register src2, Condition cond = al) {
DCHECK(!src1.is(src2));
if (src1.code() > src2.code()) {
ldm(ia_w, sp, src1.bit() | src2.bit(), cond);
} else {
ldr(src2, MemOperand(sp, 4, PostIndex), cond);
ldr(src1, MemOperand(sp, 4, PostIndex), cond);
}
}
// Pop three registers. Pops rightmost register first (from lower address).
void Pop(Register src1, Register src2, Register src3, Condition cond = al) {
DCHECK(!src1.is(src2));
DCHECK(!src2.is(src3));
DCHECK(!src1.is(src3));
if (src1.code() > src2.code()) {
if (src2.code() > src3.code()) {
ldm(ia_w, sp, src1.bit() | src2.bit() | src3.bit(), cond);
} else {
ldr(src3, MemOperand(sp, 4, PostIndex), cond);
ldm(ia_w, sp, src1.bit() | src2.bit(), cond);
}
} else {
Pop(src2, src3, cond);
ldr(src1, MemOperand(sp, 4, PostIndex), cond);
}
}
// Pop four registers. Pops rightmost register first (from lower address).
void Pop(Register src1,
Register src2,
Register src3,
Register src4,
Condition cond = al) {
DCHECK(!src1.is(src2));
DCHECK(!src2.is(src3));
DCHECK(!src1.is(src3));
DCHECK(!src1.is(src4));
DCHECK(!src2.is(src4));
DCHECK(!src3.is(src4));
if (src1.code() > src2.code()) {
if (src2.code() > src3.code()) {
if (src3.code() > src4.code()) {
ldm(ia_w,
sp,
src1.bit() | src2.bit() | src3.bit() | src4.bit(),
cond);
} else {
ldr(src4, MemOperand(sp, 4, PostIndex), cond);
ldm(ia_w, sp, src1.bit() | src2.bit() | src3.bit(), cond);
}
} else {
Pop(src3, src4, cond);
ldm(ia_w, sp, src1.bit() | src2.bit(), cond);
}
} else {
Pop(src2, src3, src4, cond);
ldr(src1, MemOperand(sp, 4, PostIndex), cond);
}
}
// Push a fixed frame, consisting of lr, fp, constant pool (if
// FLAG_enable_ool_constant_pool), context and JS function / marker id if
// marker_reg is a valid register.
void PushFixedFrame(Register marker_reg = no_reg);
void PopFixedFrame(Register marker_reg = no_reg);
// Push and pop the registers that can hold pointers, as defined by the
// RegList constant kSafepointSavedRegisters.
void PushSafepointRegisters();
void PopSafepointRegisters();
// Store value in register src in the safepoint stack slot for
// register dst.
void StoreToSafepointRegisterSlot(Register src, Register dst);
// Load the value of the src register from its safepoint stack slot
// into register dst.
void LoadFromSafepointRegisterSlot(Register dst, Register src);
// Load two consecutive registers with two consecutive memory locations.
void Ldrd(Register dst1,
Register dst2,
const MemOperand& src,
Condition cond = al);
// Store two consecutive registers to two consecutive memory locations.
void Strd(Register src1,
Register src2,
const MemOperand& dst,
Condition cond = al);
// Ensure that FPSCR contains values needed by JavaScript.
// We need the NaNModeControlBit to be sure that operations like
// vadd and vsub generate the Canonical NaN (if a NaN must be generated).
// In VFP3 it will be always the Canonical NaN.
// In VFP2 it will be either the Canonical NaN or the negative version
// of the Canonical NaN. It doesn't matter if we have two values. The aim
// is to be sure to never generate the hole NaN.
void VFPEnsureFPSCRState(Register scratch);
// If the value is a NaN, canonicalize the value else, do nothing.
void VFPCanonicalizeNaN(const DwVfpRegister dst,
const DwVfpRegister src,
const Condition cond = al);
void VFPCanonicalizeNaN(const DwVfpRegister value,
const Condition cond = al) {
VFPCanonicalizeNaN(value, value, cond);
}
// Compare single values and move the result to the normal condition flags.
void VFPCompareAndSetFlags(const SwVfpRegister src1, const SwVfpRegister src2,
const Condition cond = al);
void VFPCompareAndSetFlags(const SwVfpRegister src1, const float src2,
const Condition cond = al);
// Compare double values and move the result to the normal condition flags.
void VFPCompareAndSetFlags(const DwVfpRegister src1,
const DwVfpRegister src2,
const Condition cond = al);
void VFPCompareAndSetFlags(const DwVfpRegister src1,
const double src2,
const Condition cond = al);
// Compare single values and then load the fpscr flags to a register.
void VFPCompareAndLoadFlags(const SwVfpRegister src1,
const SwVfpRegister src2,
const Register fpscr_flags,
const Condition cond = al);
void VFPCompareAndLoadFlags(const SwVfpRegister src1, const float src2,
const Register fpscr_flags,
const Condition cond = al);
// Compare double values and then load the fpscr flags to a register.
void VFPCompareAndLoadFlags(const DwVfpRegister src1,
const DwVfpRegister src2,
const Register fpscr_flags,
const Condition cond = al);
void VFPCompareAndLoadFlags(const DwVfpRegister src1,
const double src2,
const Register fpscr_flags,
const Condition cond = al);
void Vmov(const DwVfpRegister dst,
const double imm,
const Register scratch = no_reg);
void VmovHigh(Register dst, DwVfpRegister src);
void VmovHigh(DwVfpRegister dst, Register src);
void VmovLow(Register dst, DwVfpRegister src);
void VmovLow(DwVfpRegister dst, Register src);
// Loads the number from object into dst register.
// If |object| is neither smi nor heap number, |not_number| is jumped to
// with |object| still intact.
void LoadNumber(Register object,
LowDwVfpRegister dst,
Register heap_number_map,
Register scratch,
Label* not_number);
// Loads the number from object into double_dst in the double format.
// Control will jump to not_int32 if the value cannot be exactly represented
// by a 32-bit integer.
// Floating point value in the 32-bit integer range that are not exact integer
// won't be loaded.
void LoadNumberAsInt32Double(Register object,
DwVfpRegister double_dst,
Register heap_number_map,
Register scratch,
LowDwVfpRegister double_scratch,
Label* not_int32);
// Loads the number from object into dst as a 32-bit integer.
// Control will jump to not_int32 if the object cannot be exactly represented
// by a 32-bit integer.
// Floating point value in the 32-bit integer range that are not exact integer
// won't be converted.
void LoadNumberAsInt32(Register object,
Register dst,
Register heap_number_map,
Register scratch,
DwVfpRegister double_scratch0,
LowDwVfpRegister double_scratch1,
Label* not_int32);
// Generates function and stub prologue code.
void StubPrologue();
void Prologue(bool code_pre_aging);
// Enter exit frame.
// stack_space - extra stack space, used for alignment before call to C.
void EnterExitFrame(bool save_doubles, int stack_space = 0);
// Leave the current exit frame. Expects the return value in r0.
// Expect the number of values, pushed prior to the exit frame, to
// remove in a register (or no_reg, if there is nothing to remove).
void LeaveExitFrame(bool save_doubles, Register argument_count,
bool restore_context,
bool argument_count_is_length = false);
// Get the actual activation frame alignment for target environment.
static int ActivationFrameAlignment();
void LoadContext(Register dst, int context_chain_length);
// Conditionally load the cached Array transitioned map of type
// transitioned_kind from the native context if the map in register
// map_in_out is the cached Array map in the native context of
// expected_kind.
void LoadTransitionedArrayMapConditional(
ElementsKind expected_kind,
ElementsKind transitioned_kind,
Register map_in_out,
Register scratch,
Label* no_map_match);
void LoadGlobalFunction(int index, Register function);
// Load the initial map from the global function. The registers
// function and map can be the same, function is then overwritten.
void LoadGlobalFunctionInitialMap(Register function,
Register map,
Register scratch);
void InitializeRootRegister() {
ExternalReference roots_array_start =
ExternalReference::roots_array_start(isolate());
mov(kRootRegister, Operand(roots_array_start));
}
// ---------------------------------------------------------------------------
// JavaScript invokes
// Invoke the JavaScript function code by either calling or jumping.
void InvokeCode(Register code,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper);
// Invoke the JavaScript function in the given register. Changes the
// current context to the context in the function before invoking.
void InvokeFunction(Register function,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper);
void InvokeFunction(Register function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper);
void InvokeFunction(Handle<JSFunction> function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper);
void IsObjectJSObjectType(Register heap_object,
Register map,
Register scratch,
Label* fail);
void IsInstanceJSObjectType(Register map,
Register scratch,
Label* fail);
void IsObjectJSStringType(Register object,
Register scratch,
Label* fail);
void IsObjectNameType(Register object,
Register scratch,
Label* fail);
// ---------------------------------------------------------------------------
// Debugger Support
void DebugBreak();
// ---------------------------------------------------------------------------
// Exception handling
// Push a new stack handler and link into stack handler chain.
void PushStackHandler();
// Unlink the stack handler on top of the stack from the stack handler chain.
// Must preserve the result register.
void PopStackHandler();
// ---------------------------------------------------------------------------
// Inline caching support
// Generate code for checking access rights - used for security checks
// on access to global objects across environments. The holder register
// is left untouched, whereas both scratch registers are clobbered.
void CheckAccessGlobalProxy(Register holder_reg,
Register scratch,
Label* miss);
void GetNumberHash(Register t0, Register scratch);
void LoadFromNumberDictionary(Label* miss,
Register elements,
Register key,
Register result,
Register t0,
Register t1,
Register t2);
inline void MarkCode(NopMarkerTypes type) {
nop(type);
}
// Check if the given instruction is a 'type' marker.
// i.e. check if is is a mov r<type>, r<type> (referenced as nop(type))
// These instructions are generated to mark special location in the code,
// like some special IC code.
static inline bool IsMarkedCode(Instr instr, int type) {
DCHECK((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER));
return IsNop(instr, type);
}
static inline int GetCodeMarker(Instr instr) {
int dst_reg_offset = 12;
int dst_mask = 0xf << dst_reg_offset;
int src_mask = 0xf;
int dst_reg = (instr & dst_mask) >> dst_reg_offset;
int src_reg = instr & src_mask;
uint32_t non_register_mask = ~(dst_mask | src_mask);
uint32_t mov_mask = al | 13 << 21;
// Return <n> if we have a mov rn rn, else return -1.
int type = ((instr & non_register_mask) == mov_mask) &&
(dst_reg == src_reg) &&
(FIRST_IC_MARKER <= dst_reg) && (dst_reg < LAST_CODE_MARKER)
? src_reg
: -1;
DCHECK((type == -1) ||
((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER)));
return type;
}
// ---------------------------------------------------------------------------
// Allocation support
// Allocate an object in new space or old space. The object_size is
// specified either in bytes or in words if the allocation flag SIZE_IN_WORDS
// is passed. If the space is exhausted control continues at the gc_required
// label. The allocated object is returned in result. If the flag
// tag_allocated_object is true the result is tagged as as a heap object.
// All registers are clobbered also when control continues at the gc_required
// label.
void Allocate(int object_size,
Register result,
Register scratch1,
Register scratch2,
Label* gc_required,
AllocationFlags flags);
void Allocate(Register object_size,
Register result,
Register scratch1,
Register scratch2,
Label* gc_required,
AllocationFlags flags);
// Undo allocation in new space. The object passed and objects allocated after
// it will no longer be allocated. The caller must make sure that no pointers
// are left to the object(s) no longer allocated as they would be invalid when
// allocation is undone.
void UndoAllocationInNewSpace(Register object, Register scratch);
void AllocateTwoByteString(Register result,
Register length,
Register scratch1,
Register scratch2,
Register scratch3,
Label* gc_required);
void AllocateOneByteString(Register result, Register length,
Register scratch1, Register scratch2,
Register scratch3, Label* gc_required);
void AllocateTwoByteConsString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required);
void AllocateOneByteConsString(Register result, Register length,
Register scratch1, Register scratch2,
Label* gc_required);
void AllocateTwoByteSlicedString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required);
void AllocateOneByteSlicedString(Register result, Register length,
Register scratch1, Register scratch2,
Label* gc_required);
// Allocates a heap number or jumps to the gc_required label if the young
// space is full and a scavenge is needed. All registers are clobbered also
// when control continues at the gc_required label.
void AllocateHeapNumber(Register result,
Register scratch1,
Register scratch2,
Register heap_number_map,
Label* gc_required,
TaggingMode tagging_mode = TAG_RESULT,
MutableMode mode = IMMUTABLE);
void AllocateHeapNumberWithValue(Register result,
DwVfpRegister value,
Register scratch1,
Register scratch2,
Register heap_number_map,
Label* gc_required);
// Copies a fixed number of fields of heap objects from src to dst.
void CopyFields(Register dst,
Register src,
LowDwVfpRegister double_scratch,
int field_count);
// Copies a number of bytes from src to dst. All registers are clobbered. On
// exit src and dst will point to the place just after where the last byte was
// read or written and length will be zero.
void CopyBytes(Register src,
Register dst,
Register length,
Register scratch);
// Initialize fields with filler values. Fields starting at |start_offset|
// not including end_offset are overwritten with the value in |filler|. At
// the end the loop, |start_offset| takes the value of |end_offset|.
void InitializeFieldsWithFiller(Register start_offset,
Register end_offset,
Register filler);
// ---------------------------------------------------------------------------
// Support functions.
// Machine code version of Map::GetConstructor().
// |temp| holds |result|'s map when done, and |temp2| its instance type.
void GetMapConstructor(Register result, Register map, Register temp,
Register temp2);
// Try to get function prototype of a function and puts the value in
// the result register. Checks that the function really is a
// function and jumps to the miss label if the fast checks fail. The
// function register will be untouched; the other registers may be
// clobbered.
void TryGetFunctionPrototype(Register function,
Register result,
Register scratch,
Label* miss,
bool miss_on_bound_function = false);
// Compare object type for heap object. heap_object contains a non-Smi
// whose object type should be compared with the given type. This both
// sets the flags and leaves the object type in the type_reg register.
// It leaves the map in the map register (unless the type_reg and map register
// are the same register). It leaves the heap object in the heap_object
// register unless the heap_object register is the same register as one of the
// other registers.
// Type_reg can be no_reg. In that case ip is used.
void CompareObjectType(Register heap_object,
Register map,
Register type_reg,
InstanceType type);
// Compare object type for heap object. Branch to false_label if type
// is lower than min_type or greater than max_type.
// Load map into the register map.
void CheckObjectTypeRange(Register heap_object,
Register map,
InstanceType min_type,
InstanceType max_type,
Label* false_label);
// Compare instance type in a map. map contains a valid map object whose
// object type should be compared with the given type. This both
// sets the flags and leaves the object type in the type_reg register.
void CompareInstanceType(Register map,
Register type_reg,
InstanceType type);
// Check if a map for a JSObject indicates that the object has fast elements.
// Jump to the specified label if it does not.
void CheckFastElements(Register map,
Register scratch,
Label* fail);
// Check if a map for a JSObject indicates that the object can have both smi
// and HeapObject elements. Jump to the specified label if it does not.
void CheckFastObjectElements(Register map,
Register scratch,
Label* fail);
// Check if a map for a JSObject indicates that the object has fast smi only
// elements. Jump to the specified label if it does not.
void CheckFastSmiElements(Register map,
Register scratch,
Label* fail);
// Check to see if maybe_number can be stored as a double in
// FastDoubleElements. If it can, store it at the index specified by key in
// the FastDoubleElements array elements. Otherwise jump to fail.
void StoreNumberToDoubleElements(Register value_reg,
Register key_reg,
Register elements_reg,
Register scratch1,
LowDwVfpRegister double_scratch,
Label* fail,
int elements_offset = 0);
// Compare an object's map with the specified map and its transitioned
// elements maps if mode is ALLOW_ELEMENT_TRANSITION_MAPS. Condition flags are
// set with result of map compare. If multiple map compares are required, the
// compare sequences branches to early_success.
void CompareMap(Register obj,
Register scratch,
Handle<Map> map,
Label* early_success);
// As above, but the map of the object is already loaded into the register
// which is preserved by the code generated.
void CompareMap(Register obj_map,
Handle<Map> map,
Label* early_success);
// Check if the map of an object is equal to a specified map and branch to
// label if not. Skip the smi check if not required (object is known to be a
// heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
// against maps that are ElementsKind transition maps of the specified map.
void CheckMap(Register obj,
Register scratch,
Handle<Map> map,
Label* fail,
SmiCheckType smi_check_type);
void CheckMap(Register obj,
Register scratch,
Heap::RootListIndex index,
Label* fail,
SmiCheckType smi_check_type);
// Check if the map of an object is equal to a specified weak map and branch
// to a specified target if equal. Skip the smi check if not required
// (object is known to be a heap object)
void DispatchWeakMap(Register obj, Register scratch1, Register scratch2,
Handle<WeakCell> cell, Handle<Code> success,
SmiCheckType smi_check_type);
// Compare the given value and the value of weak cell.
void CmpWeakValue(Register value, Handle<WeakCell> cell, Register scratch);
void GetWeakValue(Register value, Handle<WeakCell> cell);
// Load the value of the weak cell in the value register. Branch to the given
// miss label if the weak cell was cleared.
void LoadWeakValue(Register value, Handle<WeakCell> cell, Label* miss);
// Compare the object in a register to a value from the root list.
// Uses the ip register as scratch.
void CompareRoot(Register obj, Heap::RootListIndex index);
// Load and check the instance type of an object for being a string.
// Loads the type into the second argument register.
// Returns a condition that will be enabled if the object was a string
// and the passed-in condition passed. If the passed-in condition failed
// then flags remain unchanged.
Condition IsObjectStringType(Register obj,
Register type,
Condition cond = al) {
ldr(type, FieldMemOperand(obj, HeapObject::kMapOffset), cond);
ldrb(type, FieldMemOperand(type, Map::kInstanceTypeOffset), cond);
tst(type, Operand(kIsNotStringMask), cond);
DCHECK_EQ(0u, kStringTag);
return eq;
}
// Picks out an array index from the hash field.
// Register use:
// hash - holds the index's hash. Clobbered.
// index - holds the overwritten index on exit.
void IndexFromHash(Register hash, Register index);
// Get the number of least significant bits from a register
void GetLeastBitsFromSmi(Register dst, Register src, int num_least_bits);
void GetLeastBitsFromInt32(Register dst, Register src, int mun_least_bits);
// Load the value of a smi object into a double register.
// The register value must be between d0 and d15.
void SmiToDouble(LowDwVfpRegister value, Register smi);
// Check if a double can be exactly represented as a signed 32-bit integer.
// Z flag set to one if true.
void TestDoubleIsInt32(DwVfpRegister double_input,
LowDwVfpRegister double_scratch);
// Try to convert a double to a signed 32-bit integer.
// Z flag set to one and result assigned if the conversion is exact.
void TryDoubleToInt32Exact(Register result,
DwVfpRegister double_input,
LowDwVfpRegister double_scratch);
// Floor a double and writes the value to the result register.
// Go to exact if the conversion is exact (to be able to test -0),
// fall through calling code if an overflow occurred, else go to done.
// In return, input_high is loaded with high bits of input.
void TryInt32Floor(Register result,
DwVfpRegister double_input,
Register input_high,
LowDwVfpRegister double_scratch,
Label* done,
Label* exact);
// Performs a truncating conversion of a floating point number as used by
// the JS bitwise operations. See ECMA-262 9.5: ToInt32. Goes to 'done' if it
// succeeds, otherwise falls through if result is saturated. On return
// 'result' either holds answer, or is clobbered on fall through.
//
// Only public for the test code in test-code-stubs-arm.cc.
void TryInlineTruncateDoubleToI(Register result,
DwVfpRegister input,
Label* done);
// Performs a truncating conversion of a floating point number as used by
// the JS bitwise operations. See ECMA-262 9.5: ToInt32.
// Exits with 'result' holding the answer.
void TruncateDoubleToI(Register result, DwVfpRegister double_input);
// Performs a truncating conversion of a heap number as used by
// the JS bitwise operations. See ECMA-262 9.5: ToInt32. 'result' and 'input'
// must be different registers. Exits with 'result' holding the answer.
void TruncateHeapNumberToI(Register result, Register object);
// Converts the smi or heap number in object to an int32 using the rules
// for ToInt32 as described in ECMAScript 9.5.: the value is truncated
// and brought into the range -2^31 .. +2^31 - 1. 'result' and 'input' must be
// different registers.
void TruncateNumberToI(Register object,
Register result,
Register heap_number_map,
Register scratch1,
Label* not_int32);
// Check whether d16-d31 are available on the CPU. The result is given by the
// Z condition flag: Z==0 if d16-d31 available, Z==1 otherwise.
void CheckFor32DRegs(Register scratch);
// Does a runtime check for 16/32 FP registers. Either way, pushes 32 double
// values to location, saving [d0..(d15|d31)].
void SaveFPRegs(Register location, Register scratch);
// Does a runtime check for 16/32 FP registers. Either way, pops 32 double
// values to location, restoring [d0..(d15|d31)].
void RestoreFPRegs(Register location, Register scratch);
// ---------------------------------------------------------------------------
// Runtime calls
// Call a code stub.
void CallStub(CodeStub* stub,
TypeFeedbackId ast_id = TypeFeedbackId::None(),
Condition cond = al);
// Call a code stub.
void TailCallStub(CodeStub* stub, Condition cond = al);
// Call a runtime routine.
void CallRuntime(const Runtime::Function* f,
int num_arguments,
SaveFPRegsMode save_doubles = kDontSaveFPRegs);
void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
const Runtime::Function* function = Runtime::FunctionForId(id);
CallRuntime(function, function->nargs, kSaveFPRegs);
}
// Convenience function: Same as above, but takes the fid instead.
void CallRuntime(Runtime::FunctionId id,
int num_arguments,
SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
}
// Convenience function: call an external reference.
void CallExternalReference(const ExternalReference& ext,
int num_arguments);
// Tail call of a runtime routine (jump).
// Like JumpToExternalReference, but also takes care of passing the number
// of parameters.
void TailCallExternalReference(const ExternalReference& ext,
int num_arguments,
int result_size);
// Convenience function: tail call a runtime routine (jump).
void TailCallRuntime(Runtime::FunctionId fid,
int num_arguments,
int result_size);
int CalculateStackPassedWords(int num_reg_arguments,
int num_double_arguments);
// Before calling a C-function from generated code, align arguments on stack.
// After aligning the frame, non-register arguments must be stored in
// sp[0], sp[4], etc., not pushed. The argument count assumes all arguments
// are word sized. If double arguments are used, this function assumes that
// all double arguments are stored before core registers; otherwise the
// correct alignment of the double values is not guaranteed.
// Some compilers/platforms require the stack to be aligned when calling
// C++ code.
// Needs a scratch register to do some arithmetic. This register will be
// trashed.
void PrepareCallCFunction(int num_reg_arguments,
int num_double_registers,
Register scratch);
void PrepareCallCFunction(int num_reg_arguments,
Register scratch);
// There are two ways of passing double arguments on ARM, depending on
// whether soft or hard floating point ABI is used. These functions
// abstract parameter passing for the three different ways we call
// C functions from generated code.
void MovToFloatParameter(DwVfpRegister src);
void MovToFloatParameters(DwVfpRegister src1, DwVfpRegister src2);
void MovToFloatResult(DwVfpRegister src);
// Calls a C function and cleans up the space for arguments allocated
// by PrepareCallCFunction. The called function is not allowed to trigger a
// garbage collection, since that might move the code and invalidate the
// return address (unless this is somehow accounted for by the called
// function).
void CallCFunction(ExternalReference function, int num_arguments);
void CallCFunction(Register function, int num_arguments);
void CallCFunction(ExternalReference function,
int num_reg_arguments,
int num_double_arguments);
void CallCFunction(Register function,
int num_reg_arguments,
int num_double_arguments);
void MovFromFloatParameter(DwVfpRegister dst);
void MovFromFloatResult(DwVfpRegister dst);
// Jump to a runtime routine.
void JumpToExternalReference(const ExternalReference& builtin);
// Invoke specified builtin JavaScript function. Adds an entry to
// the unresolved list if the name does not resolve.
void InvokeBuiltin(Builtins::JavaScript id,
InvokeFlag flag,
const CallWrapper& call_wrapper = NullCallWrapper());
// Store the code object for the given builtin in the target register and
// setup the function in r1.
void GetBuiltinEntry(Register target, Builtins::JavaScript id);
// Store the function for the given builtin in the target register.
void GetBuiltinFunction(Register target, Builtins::JavaScript id);
Handle<Object> CodeObject() {
DCHECK(!code_object_.is_null());
return code_object_;
}
// Emit code for a truncating division by a constant. The dividend register is
// unchanged and ip gets clobbered. Dividend and result must be different.
void TruncatingDiv(Register result, Register dividend, int32_t divisor);
// ---------------------------------------------------------------------------
// StatsCounter support
void SetCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2);
void IncrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2);
void DecrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2);
// ---------------------------------------------------------------------------
// Debugging
// Calls Abort(msg) if the condition cond is not satisfied.
// Use --debug_code to enable.
void Assert(Condition cond, BailoutReason reason);
void AssertFastElements(Register elements);
// Like Assert(), but always enabled.
void Check(Condition cond, BailoutReason reason);
// Print a message to stdout and abort execution.
void Abort(BailoutReason msg);
// Verify restrictions about code generated in stubs.
void set_generating_stub(bool value) { generating_stub_ = value; }
bool generating_stub() { return generating_stub_; }
void set_has_frame(bool value) { has_frame_ = value; }
bool has_frame() { return has_frame_; }
inline bool AllowThisStubCall(CodeStub* stub);
// EABI variant for double arguments in use.
bool use_eabi_hardfloat() {
#ifdef __arm__
return base::OS::ArmUsingHardFloat();
#elif USE_EABI_HARDFLOAT
return true;
#else
return false;
#endif
}
// ---------------------------------------------------------------------------
// Number utilities
// Check whether the value of reg is a power of two and not zero. If not
// control continues at the label not_power_of_two. If reg is a power of two
// the register scratch contains the value of (reg - 1) when control falls
// through.
void JumpIfNotPowerOfTwoOrZero(Register reg,
Register scratch,
Label* not_power_of_two_or_zero);
// Check whether the value of reg is a power of two and not zero.
// Control falls through if it is, with scratch containing the mask
// value (reg - 1).
// Otherwise control jumps to the 'zero_and_neg' label if the value of reg is
// zero or negative, or jumps to the 'not_power_of_two' label if the value is
// strictly positive but not a power of two.
void JumpIfNotPowerOfTwoOrZeroAndNeg(Register reg,
Register scratch,
Label* zero_and_neg,
Label* not_power_of_two);
// ---------------------------------------------------------------------------
// Smi utilities
void SmiTag(Register reg, SBit s = LeaveCC) {
add(reg, reg, Operand(reg), s);
}
void SmiTag(Register dst, Register src, SBit s = LeaveCC) {
add(dst, src, Operand(src), s);
}
// Try to convert int32 to smi. If the value is to large, preserve
// the original value and jump to not_a_smi. Destroys scratch and
// sets flags.
void TrySmiTag(Register reg, Label* not_a_smi) {
TrySmiTag(reg, reg, not_a_smi);
}
void TrySmiTag(Register reg, Register src, Label* not_a_smi) {
SmiTag(ip, src, SetCC);
b(vs, not_a_smi);
mov(reg, ip);
}
void SmiUntag(Register reg, SBit s = LeaveCC) {
mov(reg, Operand::SmiUntag(reg), s);
}
void SmiUntag(Register dst, Register src, SBit s = LeaveCC) {
mov(dst, Operand::SmiUntag(src), s);
}
// Untag the source value into destination and jump if source is a smi.
// Souce and destination can be the same register.
void UntagAndJumpIfSmi(Register dst, Register src, Label* smi_case);
// Untag the source value into destination and jump if source is not a smi.
// Souce and destination can be the same register.
void UntagAndJumpIfNotSmi(Register dst, Register src, Label* non_smi_case);
// Test if the register contains a smi (Z == 0 (eq) if true).
inline void SmiTst(Register value) {
tst(value, Operand(kSmiTagMask));
}
inline void NonNegativeSmiTst(Register value) {
tst(value, Operand(kSmiTagMask | kSmiSignMask));
}
// Jump if the register contains a smi.
inline void JumpIfSmi(Register value, Label* smi_label) {
tst(value, Operand(kSmiTagMask));
b(eq, smi_label);
}
// Jump if either of the registers contain a non-smi.
inline void JumpIfNotSmi(Register value, Label* not_smi_label) {
tst(value, Operand(kSmiTagMask));
b(ne, not_smi_label);
}
// Jump if either of the registers contain a non-smi.
void JumpIfNotBothSmi(Register reg1, Register reg2, Label* on_not_both_smi);
// Jump if either of the registers contain a smi.
void JumpIfEitherSmi(Register reg1, Register reg2, Label* on_either_smi);
// Abort execution if argument is a smi, enabled via --debug-code.
void AssertNotSmi(Register object);
void AssertSmi(Register object);
// Abort execution if argument is not a string, enabled via --debug-code.
void AssertString(Register object);
// Abort execution if argument is not a name, enabled via --debug-code.
void AssertName(Register object);
// Abort execution if argument is not undefined or an AllocationSite, enabled
// via --debug-code.
void AssertUndefinedOrAllocationSite(Register object, Register scratch);
// Abort execution if reg is not the root value with the given index,
// enabled via --debug-code.
void AssertIsRoot(Register reg, Heap::RootListIndex index);
// ---------------------------------------------------------------------------
// HeapNumber utilities
void JumpIfNotHeapNumber(Register object,
Register heap_number_map,
Register scratch,
Label* on_not_heap_number);
// ---------------------------------------------------------------------------
// String utilities
// Generate code to do a lookup in the number string cache. If the number in
// the register object is found in the cache the generated code falls through
// with the result in the result register. The object and the result register
// can be the same. If the number is not found in the cache the code jumps to
// the label not_found with only the content of register object unchanged.
void LookupNumberStringCache(Register object,
Register result,
Register scratch1,
Register scratch2,
Register scratch3,
Label* not_found);
// Checks if both objects are sequential one-byte strings and jumps to label
// if either is not. Assumes that neither object is a smi.
void JumpIfNonSmisNotBothSequentialOneByteStrings(Register object1,
Register object2,
Register scratch1,
Register scratch2,
Label* failure);
// Checks if both objects are sequential one-byte strings and jumps to label
// if either is not.
void JumpIfNotBothSequentialOneByteStrings(Register first, Register second,
Register scratch1,
Register scratch2,
Label* not_flat_one_byte_strings);
// Checks if both instance types are sequential one-byte strings and jumps to
// label if either is not.
void JumpIfBothInstanceTypesAreNotSequentialOneByte(
Register first_object_instance_type, Register second_object_instance_type,
Register scratch1, Register scratch2, Label* failure);
// Check if instance type is sequential one-byte string and jump to label if
// it is not.
void JumpIfInstanceTypeIsNotSequentialOneByte(Register type, Register scratch,
Label* failure);
void JumpIfNotUniqueNameInstanceType(Register reg, Label* not_unique_name);
void EmitSeqStringSetCharCheck(Register string,
Register index,
Register value,
uint32_t encoding_mask);
// ---------------------------------------------------------------------------
// Patching helpers.
// Get the location of a relocated constant (its address in the constant pool)
// from its load site.
void GetRelocatedValueLocation(Register ldr_location, Register result,
Register scratch);
void ClampUint8(Register output_reg, Register input_reg);
void ClampDoubleToUint8(Register result_reg,
DwVfpRegister input_reg,
LowDwVfpRegister double_scratch);
void LoadInstanceDescriptors(Register map, Register descriptors);
void EnumLength(Register dst, Register map);
void NumberOfOwnDescriptors(Register dst, Register map);
void LoadAccessor(Register dst, Register holder, int accessor_index,
AccessorComponent accessor);
template<typename Field>
void DecodeField(Register dst, Register src) {
Ubfx(dst, src, Field::kShift, Field::kSize);
}
template<typename Field>
void DecodeField(Register reg) {
DecodeField<Field>(reg, reg);
}
template<typename Field>
void DecodeFieldToSmi(Register dst, Register src) {
static const int shift = Field::kShift;
static const int mask = Field::kMask >> shift << kSmiTagSize;
STATIC_ASSERT((mask & (0x80000000u >> (kSmiTagSize - 1))) == 0);
STATIC_ASSERT(kSmiTag == 0);
if (shift < kSmiTagSize) {
mov(dst, Operand(src, LSL, kSmiTagSize - shift));
and_(dst, dst, Operand(mask));
} else if (shift > kSmiTagSize) {
mov(dst, Operand(src, LSR, shift - kSmiTagSize));
and_(dst, dst, Operand(mask));
} else {
and_(dst, src, Operand(mask));
}
}
template<typename Field>
void DecodeFieldToSmi(Register reg) {
DecodeField<Field>(reg, reg);
}
// Activation support.
void EnterFrame(StackFrame::Type type,
bool load_constant_pool_pointer_reg = false);
// Returns the pc offset at which the frame ends.
int LeaveFrame(StackFrame::Type type);
// Expects object in r0 and returns map with validated enum cache
// in r0. Assumes that any other register can be used as a scratch.
void CheckEnumCache(Register null_value, Label* call_runtime);
// AllocationMemento support. Arrays may have an associated
// AllocationMemento object that can be checked for in order to pretransition
// to another type.
// On entry, receiver_reg should point to the array object.
// scratch_reg gets clobbered.
// If allocation info is present, condition flags are set to eq.
void TestJSArrayForAllocationMemento(Register receiver_reg,
Register scratch_reg,
Label* no_memento_found);
void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
Register scratch_reg,
Label* memento_found) {
Label no_memento_found;
TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
&no_memento_found);
b(eq, memento_found);
bind(&no_memento_found);
}
// Jumps to found label if a prototype map has dictionary elements.
void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
Register scratch1, Label* found);
private:
void CallCFunctionHelper(Register function,
int num_reg_arguments,
int num_double_arguments);
void Jump(intptr_t target, RelocInfo::Mode rmode, Condition cond = al);
// Helper functions for generating invokes.
void InvokePrologue(const ParameterCount& expected,
const ParameterCount& actual,
Handle<Code> code_constant,
Register code_reg,
Label* done,
bool* definitely_mismatches,
InvokeFlag flag,
const CallWrapper& call_wrapper);
void InitializeNewString(Register string,
Register length,
Heap::RootListIndex map_index,
Register scratch1,
Register scratch2);
// Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
void InNewSpace(Register object,
Register scratch,
Condition cond, // eq for new space, ne otherwise.
Label* branch);
// Helper for finding the mark bits for an address. Afterwards, the
// bitmap register points at the word with the mark bits and the mask
// the position of the first bit. Leaves addr_reg unchanged.
inline void GetMarkBits(Register addr_reg,
Register bitmap_reg,
Register mask_reg);
// Compute memory operands for safepoint stack slots.
static int SafepointRegisterStackIndex(int reg_code);
MemOperand SafepointRegisterSlot(Register reg);
MemOperand SafepointRegistersAndDoublesSlot(Register reg);
// Loads the constant pool pointer (pp) register.
void LoadConstantPoolPointerRegister();
bool generating_stub_;
bool has_frame_;
// This handle will be patched with the code object on installation.
Handle<Object> code_object_;
// Needs access to SafepointRegisterStackIndex for compiled frame
// traversal.
friend class StandardFrame;
};
// The code patcher is used to patch (typically) small parts of code e.g. for
// debugging and other types of instrumentation. When using the code patcher
// the exact number of bytes specified must be emitted. It is not legal to emit
// relocation information. If any of these constraints are violated it causes
// an assertion to fail.
class CodePatcher {
public:
enum FlushICache {
FLUSH,
DONT_FLUSH
};
CodePatcher(byte* address,
int instructions,
FlushICache flush_cache = FLUSH);
virtual ~CodePatcher();
// Macro assembler to emit code.
MacroAssembler* masm() { return &masm_; }
// Emit an instruction directly.
void Emit(Instr instr);
// Emit an address directly.
void Emit(Address addr);
// Emit the condition part of an instruction leaving the rest of the current
// instruction unchanged.
void EmitCondition(Condition cond);
private:
byte* address_; // The address of the code being patched.
int size_; // Number of bytes of the expected patch size.
MacroAssembler masm_; // Macro assembler used to generate the code.
FlushICache flush_cache_; // Whether to flush the I cache after patching.
};
// -----------------------------------------------------------------------------
// Static helper functions.
inline MemOperand ContextOperand(Register context, int index) {
return MemOperand(context, Context::SlotOffset(index));
}
inline MemOperand GlobalObjectOperand() {
return ContextOperand(cp, Context::GLOBAL_OBJECT_INDEX);
}
#ifdef GENERATED_CODE_COVERAGE
#define CODE_COVERAGE_STRINGIFY(x) #x
#define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
#define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
#define ACCESS_MASM(masm) masm->stop(__FILE_LINE__); masm->
#else
#define ACCESS_MASM(masm) masm->
#endif
} } // namespace v8::internal
#endif // V8_ARM_MACRO_ASSEMBLER_ARM_H_
| zhangf911/fibjs | vender/v8/src/arm/macro-assembler-arm.h | C | gpl-3.0 | 63,551 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "addarraymembervisitor.h"
#include <qmljs/parser/qmljsast_p.h>
using namespace QmlDesigner;
using namespace QmlDesigner::Internal;
AddArrayMemberVisitor::AddArrayMemberVisitor(TextModifier &modifier,
quint32 parentLocation,
const QString &propertyName,
const QString &content):
QMLRewriter(modifier),
m_parentLocation(parentLocation),
m_propertyName(propertyName),
m_content(content),
m_convertObjectBindingIntoArrayBinding(false)
{
}
void AddArrayMemberVisitor::findArrayBindingAndInsert(const QString &propertyName, QmlJS::AST::UiObjectMemberList *ast)
{
for (QmlJS::AST::UiObjectMemberList *iter = ast; iter; iter = iter->next) {
if (auto arrayBinding = QmlJS::AST::cast<QmlJS::AST::UiArrayBinding*>(iter->member)) {
if (toString(arrayBinding->qualifiedId) == propertyName)
insertInto(arrayBinding);
} else if (auto objectBinding = QmlJS::AST::cast<QmlJS::AST::UiObjectBinding*>(iter->member)) {
if (toString(objectBinding->qualifiedId) == propertyName && willConvertObjectBindingIntoArrayBinding())
convertAndAdd(objectBinding);
}
}
}
bool AddArrayMemberVisitor::visit(QmlJS::AST::UiObjectBinding *ast)
{
if (didRewriting())
return false;
if (ast->firstSourceLocation().offset == m_parentLocation)
findArrayBindingAndInsert(m_propertyName, ast->initializer->members);
return !didRewriting();
}
bool AddArrayMemberVisitor::visit(QmlJS::AST::UiObjectDefinition *ast)
{
if (didRewriting())
return false;
if (ast->firstSourceLocation().offset == m_parentLocation)
findArrayBindingAndInsert(m_propertyName, ast->initializer->members);
return !didRewriting();
}
// FIXME: duplicate code in the QmlJS::Rewriter class, remove this
void AddArrayMemberVisitor::insertInto(QmlJS::AST::UiArrayBinding *arrayBinding)
{
QmlJS::AST::UiObjectMember *lastMember = nullptr;
for (QmlJS::AST::UiArrayMemberList *iter = arrayBinding->members; iter; iter = iter->next)
if (iter->member)
lastMember = iter->member;
if (!lastMember)
return; // an array binding cannot be empty, so there will (or should) always be a last member.
const int insertionPoint = lastMember->lastSourceLocation().end();
const int indentDepth = calculateIndentDepth(lastMember->firstSourceLocation());
replace(insertionPoint, 0, QStringLiteral(",\n") + addIndentation(m_content, indentDepth));
setDidRewriting(true);
}
void AddArrayMemberVisitor::convertAndAdd(QmlJS::AST::UiObjectBinding *objectBinding)
{
const int indentDepth = calculateIndentDepth(objectBinding->firstSourceLocation());
const QString arrayPrefix = QStringLiteral("[\n") + addIndentation(QString(), indentDepth);
replace(objectBinding->qualifiedTypeNameId->identifierToken.offset, 0, arrayPrefix);
const int insertionPoint = objectBinding->lastSourceLocation().end();
replace(insertionPoint, 0,
QStringLiteral(",\n")
+ addIndentation(m_content, indentDepth) + QLatin1Char('\n')
+ addIndentation(QStringLiteral("]"), indentDepth)
);
setDidRewriting(true);
}
| qtproject/qt-creator | src/plugins/qmldesigner/designercore/filemanager/addarraymembervisitor.cpp | C++ | gpl-3.0 | 4,529 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.commons.codec Class Hierarchy (Apache Commons Codec 1.9 API)</title>
<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="org.apache.commons.codec Class Hierarchy (Apache Commons Codec 1.9 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<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</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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>Prev</li>
<li><a href="../../../../org/apache/commons/codec/binary/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/commons/codec/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.apache.commons.codec</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a>
<ul>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/CharEncoding.html" title="class in org.apache.commons.codec"><span class="strong">CharEncoding</span></a></li>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/Charsets.html" title="class in org.apache.commons.codec"><span class="strong">Charsets</span></a></li>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/StringEncoderComparator.html" title="class in org.apache.commons.codec"><span class="strong">StringEncoderComparator</span></a> (implements java.util.<a href="http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html?is-external=true" title="class or interface in java.util">Comparator</a><T>)</li>
<li type="circle">java.lang.<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html?is-external=true" title="class or interface in java.lang"><span class="strong">Throwable</span></a> (implements java.io.<a href="http://download.oracle.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>)
<ul>
<li type="circle">java.lang.<a href="http://download.oracle.com/javase/6/docs/api/java/lang/Exception.html?is-external=true" title="class or interface in java.lang"><span class="strong">Exception</span></a>
<ul>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/DecoderException.html" title="class in org.apache.commons.codec"><span class="strong">DecoderException</span></a></li>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/EncoderException.html" title="class in org.apache.commons.codec"><span class="strong">EncoderException</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/Decoder.html" title="interface in org.apache.commons.codec"><span class="strong">Decoder</span></a>
<ul>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/BinaryDecoder.html" title="interface in org.apache.commons.codec"><span class="strong">BinaryDecoder</span></a></li>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/StringDecoder.html" title="interface in org.apache.commons.codec"><span class="strong">StringDecoder</span></a></li>
</ul>
</li>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/Encoder.html" title="interface in org.apache.commons.codec"><span class="strong">Encoder</span></a>
<ul>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/BinaryEncoder.html" title="interface in org.apache.commons.codec"><span class="strong">BinaryEncoder</span></a></li>
<li type="circle">org.apache.commons.codec.<a href="../../../../org/apache/commons/codec/StringEncoder.html" title="interface in org.apache.commons.codec"><span class="strong">StringEncoder</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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>Prev</li>
<li><a href="../../../../org/apache/commons/codec/binary/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/commons/codec/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2002–2013 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| LordTerbium/Ampl | libs/commons-codec-1.9/apidocs/org/apache/commons/codec/package-tree.html | HTML | gpl-3.0 | 7,521 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Mtf\Client\Element;
use Magento\Mtf\Client\Locator;
use Magento\Mtf\Client\ElementInterface;
/**
* Class MultiselectgrouplistElement
* Typified element class for multiselect with group
*/
class MultiselectgrouplistElement extends MultiselectElement
{
/**
* Indent length
*/
const INDENT_LENGTH = 4;
/**
* Locator for search optgroup by label
*
* @var string
*/
protected $optgroupByLabel = './/optgroup[@label="%s"]';
/**
* Locator for search optgroup by number
*
* @var string
*/
protected $optgroupByNumber = './/optgroup[%d]';
/**
* Locator for search next optgroup
*
* @var string
*/
protected $nextOptgroup = './/following-sibling::optgroup[%d]';
/**
* Locator for search child optgroup
*
* @var string
*/
protected $childOptgroup = ".//following-sibling::optgroup[%d][@label='%s']";
/**
* Locator for search parent optgroup
*
* @var string
*/
protected $parentOptgroup = 'optgroup[option[text()="%s"]]';
/**
* Locator for search preceding sibling optgroup
*
* @var string
*/
protected $precedingOptgroup = '/preceding-sibling::optgroup[1][substring(@label,1,%d)="%s"]';
/**
* Locator for option
*
* @var string
*/
protected $option = './/option[text()="%s"]';
/**
* Locator search for option by number
*
* @var string
*/
protected $childOptionByNumber = './/optgroup[%d]/option[%d]';
/**
* Locator search for option by data-text attribute
*
* @var string
*/
protected $uiOptionText = './/option[@data-title="%s"]';
/**
* Locator for search parent option
*
* @var string
*/
protected $optionByNumber = './option[%d]';
/**
* Indent, four symbols non breaking space
*
* @var string
*/
protected $indent = "\xC2\xA0\xC2\xA0\xC2\xA0\xC2\xA0";
/**
* Trim symbols
*
* @var string
*/
protected $trim = "\xC2\xA0 ";
/**
* Set values
*
* @param array|string $values
* @return void
*/
public function setValue($values)
{
$this->deselectAll();
$values = is_array($values) ? $values : [$values];
foreach ($values as $value) {
$this->selectOption($value);
}
}
/**
* Select option
*
* @param string $option
* @return void
* @throws \Exception
*/
protected function selectOption($option)
{
$optionElement = $this->find(sprintf($this->uiOptionText, $option), Locator::SELECTOR_XPATH);
if ($optionElement->isVisible()) {
if (!$optionElement->isSelected()) {
$optionElement->click();
}
return;
}
$isOptgroup = false;
$optgroupIndent = '';
$values = explode('/', $option);
$context = $this;
foreach ($values as $value) {
$optionIndent = $isOptgroup ? $this->indent : '';
$optionElement = $context->find(sprintf($this->option, $optionIndent . $value), Locator::SELECTOR_XPATH);
if ($optionElement->isVisible()) {
if (!$optionElement->isSelected()) {
$optionElement->click();
}
return;
}
$value = $optgroupIndent . $value;
$optgroupIndent .= $this->indent;
if ($isOptgroup) {
$context = $this->getChildOptgroup($value, $context);
} else {
$context = $this->getOptgroup($value, $context);
$isOptgroup = true;
}
}
throw new \Exception("Can't find option \"{$option}\".");
}
/**
* Get optgroup
*
* @param string $value
* @param ElementInterface $context
* @return ElementInterface
* @throws \Exception
*/
protected function getOptgroup($value, ElementInterface $context)
{
$optgroup = $context->find(sprintf($this->optgroupByLabel, $value), Locator::SELECTOR_XPATH);
if (!$optgroup->isVisible()) {
throw new \Exception("Can't find group \"{$value}\".");
}
return $optgroup;
}
/**
* Get child optgroup
*
* @param string $value
* @param ElementInterface $context
* @return ElementInterface
* @throws \Exception
*/
protected function getChildOptgroup($value, ElementInterface $context)
{
$childOptgroup = null;
$count = 1;
while (!$childOptgroup) {
$optgroup = $context->find(sprintf($this->nextOptgroup, $count), Locator::SELECTOR_XPATH);
if (!$optgroup->isVisible()) {
throw new \Exception("Can't find child group \"{$value}\"");
}
$childOptgroup = $context->find(
sprintf($this->childOptgroup, $count, $value),
Locator::SELECTOR_XPATH
);
if (!$childOptgroup->isVisible()) {
$childOptgroup = null;
}
++$count;
}
return $childOptgroup;
}
/**
* Get value
*
* @return array
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getValue()
{
$values = [];
$indentOption = str_repeat(' ', self::INDENT_LENGTH);
foreach ($this->getSelectedOptions() as $option) {
$value = [];
/** @var ElementInterface $option */
$optionText = $option->getText();
$optionValue = trim($optionText, $this->trim);
$value[] = $optionValue;
if (0 !== strpos($optionText, $indentOption)) {
$values[] = implode('/', $value);
continue;
}
$pathOptgroup = sprintf($this->parentOptgroup, $this->indent . $optionValue);
$optgroup = $this->find($pathOptgroup, Locator::SELECTOR_XPATH);
$optgroupText = $optgroup->getAttribute('label');
$optgroupValue = trim($optgroupText, $this->trim);
$amountIndent = strlen($optgroupText) - strlen($optgroupValue);
$amountIndent = $amountIndent ? ($amountIndent / strlen($this->indent)) : 0;
$value[] = $optgroupValue;
if (0 == $amountIndent) {
$values[] = implode('/', $value);
continue;
}
--$amountIndent;
$indent = $amountIndent ? str_repeat($this->indent, $amountIndent) : '';
$pathOptgroup .= sprintf($this->precedingOptgroup, $amountIndent * self::INDENT_LENGTH, $indent);
while (0 <= $amountIndent && $this->find($pathOptgroup, Locator::SELECTOR_XPATH)->isVisible()) {
$optgroup = $this->find($pathOptgroup, Locator::SELECTOR_XPATH);
$optgroupText = $optgroup->getAttribute('label');
$optgroupValue = trim($optgroupText, $this->trim);
$value[] = $optgroupValue;
--$amountIndent;
$indent = (0 < $amountIndent) ? str_repeat($this->indent, $amountIndent) : '';
$pathOptgroup .= sprintf($this->precedingOptgroup, $amountIndent * self::INDENT_LENGTH, $indent);
}
$values[] = implode('/', array_reverse($value));
}
return $values;
}
/**
* Get options
*
* @return ElementInterface[]
*/
protected function getOptions()
{
$options = [];
$countOption = 1;
$option = $this->find(sprintf($this->optionByNumber, $countOption), Locator::SELECTOR_XPATH);
while ($option->isVisible()) {
$options[] = $option;
++$countOption;
$option = $this->find(sprintf($this->optionByNumber, $countOption), Locator::SELECTOR_XPATH);
}
$countOptgroup = 1;
$optgroup = $this->find(sprintf($this->optgroupByNumber, $countOptgroup), Locator::SELECTOR_XPATH);
while ($optgroup->isVisible()) {
$countOption = 1;
$option = $this->find(
sprintf($this->childOptionByNumber, $countOptgroup, $countOption),
Locator::SELECTOR_XPATH
);
while ($option->isVisible()) {
$options[] = $option;
++$countOption;
$option = $this->find(
sprintf($this->childOptionByNumber, $countOptgroup, $countOption),
Locator::SELECTOR_XPATH
);
}
++$countOptgroup;
$optgroup = $this->find(sprintf($this->optgroupByNumber, $countOptgroup), Locator::SELECTOR_XPATH);
}
return $options;
}
/**
* Get selected options
*
* @return array
*/
protected function getSelectedOptions()
{
$options = [];
foreach ($this->getOptions() as $option) {
if ($option->isSelected()) {
$options[] = $option;
}
}
return $options;
}
}
| rajmahesh/magento2-master | vendor/magento/magento2-base/dev/tests/functional/lib/Magento/Mtf/Client/Element/MultiselectgrouplistElement.php | PHP | gpl-3.0 | 9,293 |
/*++ BUILD Version: 0001 // Increment this if a change has global effects
Copyright (c) Microsoft Corporation. All rights reserved.
Module Name:
ntddstor.h
Abstract:
This is the include file that defines all common constants and types
accessing the storage class drivers
Author:
Peter Wieland 19-Jun-1996
Revision History:
--*/
//
// Interface GUIDs
//
// need these GUIDs outside conditional includes so that user can
// #include <ntddstor.h> in precompiled header
// #include <initguid.h> in a single source file
// #include <ntddstor.h> in that source file a second time to instantiate the GUIDs
//
#ifdef DEFINE_GUID
//
// Make sure FAR is defined...
//
#ifndef FAR
#ifdef _WIN32
#define FAR
#else
#define FAR _far
#endif
#endif
// begin_wioctlguids
DEFINE_GUID(GUID_DEVINTERFACE_DISK, 0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_CDROM, 0x53f56308L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_PARTITION, 0x53f5630aL, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_TAPE, 0x53f5630bL, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_WRITEONCEDISK, 0x53f5630cL, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_VOLUME, 0x53f5630dL, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_MEDIUMCHANGER, 0x53f56310L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_FLOPPY, 0x53f56311L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_CDCHANGER, 0x53f56312L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT, 0x2accfe60L, 0xc130, 0x11d2, 0xb0, 0x82, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
// end_wioctlguids
// begin_wioctlobsoleteguids
#define DiskClassGuid GUID_DEVINTERFACE_DISK
#define CdRomClassGuid GUID_DEVINTERFACE_CDROM
#define PartitionClassGuid GUID_DEVINTERFACE_PARTITION
#define TapeClassGuid GUID_DEVINTERFACE_TAPE
#define WriteOnceDiskClassGuid GUID_DEVINTERFACE_WRITEONCEDISK
#define VolumeClassGuid GUID_DEVINTERFACE_VOLUME
#define MediumChangerClassGuid GUID_DEVINTERFACE_MEDIUMCHANGER
#define FloppyClassGuid GUID_DEVINTERFACE_FLOPPY
#define CdChangerClassGuid GUID_DEVINTERFACE_CDCHANGER
#define StoragePortClassGuid GUID_DEVINTERFACE_STORAGEPORT
// end_wioctlobsoleteguids
#endif
// begin_winioctl
#ifndef _NTDDSTOR_H_
#define _NTDDSTOR_H_
#ifdef __cplusplus
extern "C" {
#endif
//
// IoControlCode values for storage devices
//
#define IOCTL_STORAGE_BASE FILE_DEVICE_MASS_STORAGE
//
// The following device control codes are common for all class drivers. They
// should be used in place of the older IOCTL_DISK, IOCTL_CDROM and IOCTL_TAPE
// common codes
//
#define IOCTL_STORAGE_CHECK_VERIFY CTL_CODE(IOCTL_STORAGE_BASE, 0x0200, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_CHECK_VERIFY2 CTL_CODE(IOCTL_STORAGE_BASE, 0x0200, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_MEDIA_REMOVAL CTL_CODE(IOCTL_STORAGE_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_EJECT_MEDIA CTL_CODE(IOCTL_STORAGE_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_LOAD_MEDIA CTL_CODE(IOCTL_STORAGE_BASE, 0x0203, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_LOAD_MEDIA2 CTL_CODE(IOCTL_STORAGE_BASE, 0x0203, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_RESERVE CTL_CODE(IOCTL_STORAGE_BASE, 0x0204, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_RELEASE CTL_CODE(IOCTL_STORAGE_BASE, 0x0205, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_FIND_NEW_DEVICES CTL_CODE(IOCTL_STORAGE_BASE, 0x0206, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_EJECTION_CONTROL CTL_CODE(IOCTL_STORAGE_BASE, 0x0250, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_MCN_CONTROL CTL_CODE(IOCTL_STORAGE_BASE, 0x0251, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_GET_MEDIA_TYPES CTL_CODE(IOCTL_STORAGE_BASE, 0x0300, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_GET_MEDIA_TYPES_EX CTL_CODE(IOCTL_STORAGE_BASE, 0x0301, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER CTL_CODE(IOCTL_STORAGE_BASE, 0x0304, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_GET_HOTPLUG_INFO CTL_CODE(IOCTL_STORAGE_BASE, 0x0305, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_SET_HOTPLUG_INFO CTL_CODE(IOCTL_STORAGE_BASE, 0x0306, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_STORAGE_RESET_BUS CTL_CODE(IOCTL_STORAGE_BASE, 0x0400, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_RESET_DEVICE CTL_CODE(IOCTL_STORAGE_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_BREAK_RESERVATION CTL_CODE(IOCTL_STORAGE_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_STORAGE_GET_DEVICE_NUMBER CTL_CODE(IOCTL_STORAGE_BASE, 0x0420, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_STORAGE_PREDICT_FAILURE CTL_CODE(IOCTL_STORAGE_BASE, 0x0440, METHOD_BUFFERED, FILE_ANY_ACCESS)
// end_winioctl
#define IOCTL_STORAGE_QUERY_PROPERTY CTL_CODE(IOCTL_STORAGE_BASE, 0x0500, METHOD_BUFFERED, FILE_ANY_ACCESS)
// begin_winioctl
//
// These ioctl codes are obsolete. They are defined here to avoid resuing them
// and to allow class drivers to respond to them more easily.
//
#define OBSOLETE_IOCTL_STORAGE_RESET_BUS CTL_CODE(IOCTL_STORAGE_BASE, 0x0400, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define OBSOLETE_IOCTL_STORAGE_RESET_DEVICE CTL_CODE(IOCTL_STORAGE_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
//
// IOCTL_STORAGE_GET_HOTPLUG_INFO
//
typedef struct _STORAGE_HOTPLUG_INFO {
ULONG Size; // version
BOOLEAN MediaRemovable; // ie. zip, jaz, cdrom, mo, etc. vs hdd
BOOLEAN MediaHotplug; // ie. does the device succeed a lock even though its not lockable media?
BOOLEAN DeviceHotplug; // ie. 1394, USB, etc.
BOOLEAN WriteCacheEnableOverride; // This field should not be relied upon because it is no longer used
} STORAGE_HOTPLUG_INFO, *PSTORAGE_HOTPLUG_INFO;
//
// IOCTL_STORAGE_GET_DEVICE_NUMBER
//
// input - none
//
// output - STORAGE_DEVICE_NUMBER structure
// The values in the STORAGE_DEVICE_NUMBER structure are guaranteed
// to remain unchanged until the system is rebooted. They are not
// guaranteed to be persistant across boots.
//
typedef struct _STORAGE_DEVICE_NUMBER {
//
// The FILE_DEVICE_XXX type for this device.
//
DWORD DeviceType;
//
// The number of this device
//
ULONG DeviceNumber;
//
// If the device is partitionable, the partition number of the device.
// Otherwise -1
//
ULONG PartitionNumber;
} STORAGE_DEVICE_NUMBER, *PSTORAGE_DEVICE_NUMBER;
//
// Define the structures for scsi resets
//
typedef struct _STORAGE_BUS_RESET_REQUEST {
UCHAR PathId;
} STORAGE_BUS_RESET_REQUEST, *PSTORAGE_BUS_RESET_REQUEST;
//
// IOCTL_STORAGE_MEDIA_REMOVAL disables the mechanism
// on a storage device that ejects media. This function
// may or may not be supported on storage devices that
// support removable media.
//
// TRUE means prevent media from being removed.
// FALSE means allow media removal.
//
typedef struct _PREVENT_MEDIA_REMOVAL {
BOOLEAN PreventMediaRemoval;
} PREVENT_MEDIA_REMOVAL, *PPREVENT_MEDIA_REMOVAL;
// begin_ntminitape
typedef struct _TAPE_STATISTICS {
ULONG Version;
ULONG Flags;
LARGE_INTEGER RecoveredWrites;
LARGE_INTEGER UnrecoveredWrites;
LARGE_INTEGER RecoveredReads;
LARGE_INTEGER UnrecoveredReads;
UCHAR CompressionRatioReads;
UCHAR CompressionRatioWrites;
} TAPE_STATISTICS, *PTAPE_STATISTICS;
#define RECOVERED_WRITES_VALID 0x00000001
#define UNRECOVERED_WRITES_VALID 0x00000002
#define RECOVERED_READS_VALID 0x00000004
#define UNRECOVERED_READS_VALID 0x00000008
#define WRITE_COMPRESSION_INFO_VALID 0x00000010
#define READ_COMPRESSION_INFO_VALID 0x00000020
typedef struct _TAPE_GET_STATISTICS {
ULONG Operation;
} TAPE_GET_STATISTICS, *PTAPE_GET_STATISTICS;
#define TAPE_RETURN_STATISTICS 0L
#define TAPE_RETURN_ENV_INFO 1L
#define TAPE_RESET_STATISTICS 2L
//
// IOCTL_STORAGE_GET_MEDIA_TYPES_EX will return an array of DEVICE_MEDIA_INFO
// structures, one per supported type, embedded in the GET_MEDIA_TYPES struct.
//
typedef enum _STORAGE_MEDIA_TYPE {
//
// Following are defined in ntdddisk.h in the MEDIA_TYPE enum
//
// Unknown, // Format is unknown
// F5_1Pt2_512, // 5.25", 1.2MB, 512 bytes/sector
// F3_1Pt44_512, // 3.5", 1.44MB, 512 bytes/sector
// F3_2Pt88_512, // 3.5", 2.88MB, 512 bytes/sector
// F3_20Pt8_512, // 3.5", 20.8MB, 512 bytes/sector
// F3_720_512, // 3.5", 720KB, 512 bytes/sector
// F5_360_512, // 5.25", 360KB, 512 bytes/sector
// F5_320_512, // 5.25", 320KB, 512 bytes/sector
// F5_320_1024, // 5.25", 320KB, 1024 bytes/sector
// F5_180_512, // 5.25", 180KB, 512 bytes/sector
// F5_160_512, // 5.25", 160KB, 512 bytes/sector
// RemovableMedia, // Removable media other than floppy
// FixedMedia, // Fixed hard disk media
// F3_120M_512, // 3.5", 120M Floppy
// F3_640_512, // 3.5" , 640KB, 512 bytes/sector
// F5_640_512, // 5.25", 640KB, 512 bytes/sector
// F5_720_512, // 5.25", 720KB, 512 bytes/sector
// F3_1Pt2_512, // 3.5" , 1.2Mb, 512 bytes/sector
// F3_1Pt23_1024, // 3.5" , 1.23Mb, 1024 bytes/sector
// F5_1Pt23_1024, // 5.25", 1.23MB, 1024 bytes/sector
// F3_128Mb_512, // 3.5" MO 128Mb 512 bytes/sector
// F3_230Mb_512, // 3.5" MO 230Mb 512 bytes/sector
// F8_256_128, // 8", 256KB, 128 bytes/sector
// F3_200Mb_512, // 3.5", 200M Floppy (HiFD)
//
DDS_4mm = 0x20, // Tape - DAT DDS1,2,... (all vendors)
MiniQic, // Tape - miniQIC Tape
Travan, // Tape - Travan TR-1,2,3,...
QIC, // Tape - QIC
MP_8mm, // Tape - 8mm Exabyte Metal Particle
AME_8mm, // Tape - 8mm Exabyte Advanced Metal Evap
AIT1_8mm, // Tape - 8mm Sony AIT
DLT, // Tape - DLT Compact IIIxt, IV
NCTP, // Tape - Philips NCTP
IBM_3480, // Tape - IBM 3480
IBM_3490E, // Tape - IBM 3490E
IBM_Magstar_3590, // Tape - IBM Magstar 3590
IBM_Magstar_MP, // Tape - IBM Magstar MP
STK_DATA_D3, // Tape - STK Data D3
SONY_DTF, // Tape - Sony DTF
DV_6mm, // Tape - 6mm Digital Video
DMI, // Tape - Exabyte DMI and compatibles
SONY_D2, // Tape - Sony D2S and D2L
CLEANER_CARTRIDGE, // Cleaner - All Drive types that support Drive Cleaners
CD_ROM, // Opt_Disk - CD
CD_R, // Opt_Disk - CD-Recordable (Write Once)
CD_RW, // Opt_Disk - CD-Rewriteable
DVD_ROM, // Opt_Disk - DVD-ROM
DVD_R, // Opt_Disk - DVD-Recordable (Write Once)
DVD_RW, // Opt_Disk - DVD-Rewriteable
MO_3_RW, // Opt_Disk - 3.5" Rewriteable MO Disk
MO_5_WO, // Opt_Disk - MO 5.25" Write Once
MO_5_RW, // Opt_Disk - MO 5.25" Rewriteable (not LIMDOW)
MO_5_LIMDOW, // Opt_Disk - MO 5.25" Rewriteable (LIMDOW)
PC_5_WO, // Opt_Disk - Phase Change 5.25" Write Once Optical
PC_5_RW, // Opt_Disk - Phase Change 5.25" Rewriteable
PD_5_RW, // Opt_Disk - PhaseChange Dual Rewriteable
ABL_5_WO, // Opt_Disk - Ablative 5.25" Write Once Optical
PINNACLE_APEX_5_RW, // Opt_Disk - Pinnacle Apex 4.6GB Rewriteable Optical
SONY_12_WO, // Opt_Disk - Sony 12" Write Once
PHILIPS_12_WO, // Opt_Disk - Philips/LMS 12" Write Once
HITACHI_12_WO, // Opt_Disk - Hitachi 12" Write Once
CYGNET_12_WO, // Opt_Disk - Cygnet/ATG 12" Write Once
KODAK_14_WO, // Opt_Disk - Kodak 14" Write Once
MO_NFR_525, // Opt_Disk - Near Field Recording (Terastor)
NIKON_12_RW, // Opt_Disk - Nikon 12" Rewriteable
IOMEGA_ZIP, // Mag_Disk - Iomega Zip
IOMEGA_JAZ, // Mag_Disk - Iomega Jaz
SYQUEST_EZ135, // Mag_Disk - Syquest EZ135
SYQUEST_EZFLYER, // Mag_Disk - Syquest EzFlyer
SYQUEST_SYJET, // Mag_Disk - Syquest SyJet
AVATAR_F2, // Mag_Disk - 2.5" Floppy
MP2_8mm, // Tape - 8mm Hitachi
DST_S, // Ampex DST Small Tapes
DST_M, // Ampex DST Medium Tapes
DST_L, // Ampex DST Large Tapes
VXATape_1, // Ecrix 8mm Tape
VXATape_2, // Ecrix 8mm Tape
STK_9840, // STK 9840
LTO_Ultrium, // IBM, HP, Seagate LTO Ultrium
LTO_Accelis, // IBM, HP, Seagate LTO Accelis
DVD_RAM, // Opt_Disk - DVD-RAM
AIT_8mm, // AIT2 or higher
ADR_1, // OnStream ADR Mediatypes
ADR_2,
STK_9940, // STK 9940
SAIT // SAIT Tapes
} STORAGE_MEDIA_TYPE, *PSTORAGE_MEDIA_TYPE;
#define MEDIA_ERASEABLE 0x00000001
#define MEDIA_WRITE_ONCE 0x00000002
#define MEDIA_READ_ONLY 0x00000004
#define MEDIA_READ_WRITE 0x00000008
#define MEDIA_WRITE_PROTECTED 0x00000100
#define MEDIA_CURRENTLY_MOUNTED 0x80000000
//
// Define the different storage bus types
// Bus types below 128 (0x80) are reserved for Microsoft use
//
typedef enum _STORAGE_BUS_TYPE {
BusTypeUnknown = 0x00,
BusTypeScsi,
BusTypeAtapi,
BusTypeAta,
BusType1394,
BusTypeSsa,
BusTypeFibre,
BusTypeUsb,
BusTypeRAID,
BusTypeMaxReserved = 0x7F
} STORAGE_BUS_TYPE, *PSTORAGE_BUS_TYPE;
typedef struct _DEVICE_MEDIA_INFO {
union {
struct {
LARGE_INTEGER Cylinders;
STORAGE_MEDIA_TYPE MediaType;
ULONG TracksPerCylinder;
ULONG SectorsPerTrack;
ULONG BytesPerSector;
ULONG NumberMediaSides;
ULONG MediaCharacteristics; // Bitmask of MEDIA_XXX values.
} DiskInfo;
struct {
LARGE_INTEGER Cylinders;
STORAGE_MEDIA_TYPE MediaType;
ULONG TracksPerCylinder;
ULONG SectorsPerTrack;
ULONG BytesPerSector;
ULONG NumberMediaSides;
ULONG MediaCharacteristics; // Bitmask of MEDIA_XXX values.
} RemovableDiskInfo;
struct {
STORAGE_MEDIA_TYPE MediaType;
ULONG MediaCharacteristics; // Bitmask of MEDIA_XXX values.
ULONG CurrentBlockSize;
STORAGE_BUS_TYPE BusType;
//
// Bus specific information describing the medium supported.
//
union {
struct {
UCHAR MediumType;
UCHAR DensityCode;
} ScsiInformation;
} BusSpecificData;
} TapeInfo;
} DeviceSpecific;
} DEVICE_MEDIA_INFO, *PDEVICE_MEDIA_INFO;
typedef struct _GET_MEDIA_TYPES {
ULONG DeviceType; // FILE_DEVICE_XXX values
ULONG MediaInfoCount;
DEVICE_MEDIA_INFO MediaInfo[1];
} GET_MEDIA_TYPES, *PGET_MEDIA_TYPES;
//
// IOCTL_STORAGE_PREDICT_FAILURE
//
// input - none
//
// output - STORAGE_PREDICT_FAILURE structure
// PredictFailure returns zero if no failure predicted and non zero
// if a failure is predicted.
//
// VendorSpecific returns 512 bytes of vendor specific information
// if a failure is predicted
//
typedef struct _STORAGE_PREDICT_FAILURE
{
ULONG PredictFailure;
UCHAR VendorSpecific[512];
} STORAGE_PREDICT_FAILURE, *PSTORAGE_PREDICT_FAILURE;
// end_ntminitape
// end_winioctl
//
// Property Query Structures
//
//
// IOCTL_STORAGE_QUERY_PROPERTY
//
// Input Buffer:
// a STORAGE_PROPERTY_QUERY structure which describes what type of query
// is being done, what property is being queried for, and any additional
// parameters which a particular property query requires.
//
// Output Buffer:
// Contains a buffer to place the results of the query into. Since all
// property descriptors can be cast into a STORAGE_DESCRIPTOR_HEADER,
// the IOCTL can be called once with a small buffer then again using
// a buffer as large as the header reports is necessary.
//
//
// Types of queries
//
typedef enum _STORAGE_QUERY_TYPE {
PropertyStandardQuery = 0, // Retrieves the descriptor
PropertyExistsQuery, // Used to test whether the descriptor is supported
PropertyMaskQuery, // Used to retrieve a mask of writeable fields in the descriptor
PropertyQueryMaxDefined // use to validate the value
} STORAGE_QUERY_TYPE, *PSTORAGE_QUERY_TYPE;
//
// define some initial property id's
//
typedef enum _STORAGE_PROPERTY_ID {
StorageDeviceProperty = 0,
StorageAdapterProperty,
StorageDeviceIdProperty
} STORAGE_PROPERTY_ID, *PSTORAGE_PROPERTY_ID;
//
// Query structure - additional parameters for specific queries can follow
// the header
//
typedef struct _STORAGE_PROPERTY_QUERY {
//
// ID of the property being retrieved
//
STORAGE_PROPERTY_ID PropertyId;
//
// Flags indicating the type of query being performed
//
STORAGE_QUERY_TYPE QueryType;
//
// Space for additional parameters if necessary
//
UCHAR AdditionalParameters[1];
} STORAGE_PROPERTY_QUERY, *PSTORAGE_PROPERTY_QUERY;
//
// Standard property descriptor header. All property pages should use this
// as their first element or should contain these two elements
//
typedef struct _STORAGE_DESCRIPTOR_HEADER {
ULONG Version;
ULONG Size;
} STORAGE_DESCRIPTOR_HEADER, *PSTORAGE_DESCRIPTOR_HEADER;
//
// Device property descriptor - this is really just a rehash of the inquiry
// data retrieved from a scsi device
//
// This may only be retrieved from a target device. Sending this to the bus
// will result in an error
//
typedef struct _STORAGE_DEVICE_DESCRIPTOR {
//
// Sizeof(STORAGE_DEVICE_DESCRIPTOR)
//
ULONG Version;
//
// Total size of the descriptor, including the space for additional
// data and id strings
//
ULONG Size;
//
// The SCSI-2 device type
//
UCHAR DeviceType;
//
// The SCSI-2 device type modifier (if any) - this may be zero
//
UCHAR DeviceTypeModifier;
//
// Flag indicating whether the device's media (if any) is removable. This
// field should be ignored for media-less devices
//
BOOLEAN RemovableMedia;
//
// Flag indicating whether the device can support mulitple outstanding
// commands. The actual synchronization in this case is the responsibility
// of the port driver.
//
BOOLEAN CommandQueueing;
//
// Byte offset to the zero-terminated ascii string containing the device's
// vendor id string. For devices with no such ID this will be zero
//
ULONG VendorIdOffset;
//
// Byte offset to the zero-terminated ascii string containing the device's
// product id string. For devices with no such ID this will be zero
//
ULONG ProductIdOffset;
//
// Byte offset to the zero-terminated ascii string containing the device's
// product revision string. For devices with no such string this will be
// zero
//
ULONG ProductRevisionOffset;
//
// Byte offset to the zero-terminated ascii string containing the device's
// serial number. For devices with no serial number this will be zero
//
ULONG SerialNumberOffset;
//
// Contains the bus type (as defined above) of the device. It should be
// used to interpret the raw device properties at the end of this structure
// (if any)
//
STORAGE_BUS_TYPE BusType;
//
// The number of bytes of bus-specific data which have been appended to
// this descriptor
//
ULONG RawPropertiesLength;
//
// Place holder for the first byte of the bus specific property data
//
UCHAR RawDeviceProperties[1];
} STORAGE_DEVICE_DESCRIPTOR, *PSTORAGE_DEVICE_DESCRIPTOR;
//
// Adapter properties
//
// This descriptor can be retrieved from a target device object of from the
// device object for the bus. Retrieving from the target device object will
// forward the request to the underlying bus
//
typedef struct _STORAGE_ADAPTER_DESCRIPTOR {
ULONG Version;
ULONG Size;
ULONG MaximumTransferLength;
ULONG MaximumPhysicalPages;
ULONG AlignmentMask;
BOOLEAN AdapterUsesPio;
BOOLEAN AdapterScansDown;
BOOLEAN CommandQueueing;
BOOLEAN AcceleratedTransfer;
UCHAR BusType;
USHORT BusMajorVersion;
USHORT BusMinorVersion;
} STORAGE_ADAPTER_DESCRIPTOR, *PSTORAGE_ADAPTER_DESCRIPTOR;
//
// Storage identification descriptor.
// The definitions here are based on the SCSI/SBP vital product data
// device identifier page.
//
typedef enum _STORAGE_IDENTIFIER_CODE_SET {
StorageIdCodeSetReserved = 0,
StorageIdCodeSetBinary = 1,
StorageIdCodeSetAscii = 2
} STORAGE_IDENTIFIER_CODE_SET, *PSTORAGE_IDENTIFIER_CODE_SET;
typedef enum _STORAGE_IDENTIFIER_TYPE {
StorageIdTypeVendorSpecific = 0,
StorageIdTypeVendorId = 1,
StorageIdTypeEUI64 = 2,
StorageIdTypeFCPHName = 3,
StorageIdTypePortRelative = 4
} STORAGE_IDENTIFIER_TYPE, *PSTORAGE_IDENTIFIER_TYPE;
typedef enum _STORAGE_ASSOCIATION_TYPE {
StorageIdAssocDevice = 0,
StorageIdAssocPort = 1
} STORAGE_ASSOCIATION_TYPE, *PSTORAGE_ASSOCIATION_TYPE;
typedef struct _STORAGE_IDENTIFIER {
STORAGE_IDENTIFIER_CODE_SET CodeSet;
STORAGE_IDENTIFIER_TYPE Type;
USHORT IdentifierSize;
USHORT NextOffset;
//
// Add new fields here since existing code depends on
// the above layout not changing.
//
STORAGE_ASSOCIATION_TYPE Association;
//
// The identifier is a variable length array of bytes.
//
UCHAR Identifier[1];
} STORAGE_IDENTIFIER, *PSTORAGE_IDENTIFIER;
typedef struct _STORAGE_DEVICE_ID_DESCRIPTOR {
ULONG Version;
ULONG Size;
//
// The number of identifiers reported by the device.
//
ULONG NumberOfIdentifiers;
//
// The following field is actually a variable length array of identification
// descriptors. Unfortunately there's no C notation for an array of
// variable length structures so we're forced to just pretend.
//
UCHAR Identifiers[1];
} STORAGE_DEVICE_ID_DESCRIPTOR, *PSTORAGE_DEVICE_ID_DESCRIPTOR;
#pragma warning(push)
#pragma warning(disable:4200)
typedef struct _STORAGE_MEDIA_SERIAL_NUMBER_DATA {
USHORT Reserved;
//
// the SerialNumberLength will be set to zero
// if the command is supported and the media
// does not have a valid serial number.
//
USHORT SerialNumberLength;
//
// the following data is binary, and is not guaranteed
// to be NULL terminated. this is an excercise for the
// caller.
//
UCHAR SerialNumber[0];
} STORAGE_MEDIA_SERIAL_NUMBER_DATA, *PSTORAGE_MEDIA_SERIAL_NUMBER_DATA;
#pragma warning(push)
// begin_winioctl
#ifdef __cplusplus
}
#endif
#endif // _NTDDSTOR_H_
// end_winioctl
| vldbhw/sector_level_mapping_FTL | installer/ntddstor.h | C | gpl-3.0 | 24,817 |
<?php
/**
* @package WPSEO\Admin
*/
/**
* Represents the values for a single Yoast Premium extension plugin.
*/
class WPSEO_License_Page_Manager implements WPSEO_WordPress_Integration {
const VERSION_LEGACY = '1';
const VERSION_BACKWARDS_COMPATIBILITY = '2';
/**
* Registers all hooks to WordPress.
*/
public function register_hooks() {
add_filter( 'http_response', array( $this, 'handle_response' ), 10, 3 );
if ( $this->get_version() === self::VERSION_BACKWARDS_COMPATIBILITY ) {
add_filter( 'yoast-license-valid', '__return_true' );
add_filter( 'yoast-show-license-notice', '__return_false' );
add_action( 'admin_init', array( $this, 'validate_extensions' ), 15 );
}
else {
add_action( 'admin_init', array( $this, 'remove_faulty_notifications' ), 15 );
}
}
/**
* Validates the extensions and show a notice for the invalid extensions.
*/
public function validate_extensions() {
if ( filter_input( INPUT_GET, 'page' ) === WPSEO_Admin::PAGE_IDENTIFIER ) {
/**
* Filter: 'yoast-active-extensions' - Collects all active extensions. This hook is implemented in the
* license manager.
*
* @api array $extensions The array with extensions.
*/
apply_filters( 'yoast-active-extensions', array() );
}
$extension_list = new WPSEO_Extensions();
$extensions = $extension_list->get();
$notification_center = Yoast_Notification_Center::get();
foreach ( $extensions as $product_name ) {
$notification = $this->create_notification( $product_name );
// Add a notification when the installed plugin isn't activated in My Yoast.
if ( $extension_list->is_installed( $product_name ) && ! $extension_list->is_valid( $product_name ) ) {
$notification_center->add_notification( $notification );
continue;
}
$notification_center->remove_notification( $notification );
}
}
/**
* Removes the faulty set notifications.
*/
public function remove_faulty_notifications() {
$extension_list = new WPSEO_Extensions();
$extensions = $extension_list->get();
$notification_center = Yoast_Notification_Center::get();
foreach ( $extensions as $product_name ) {
$notification = $this->create_notification( $product_name );
$notification_center->remove_notification( $notification );
}
}
/**
* Handles the response.
*
* @param array $response HTTP response.
* @param array $request_arguments HTTP request arguments. Unused.
* @param string $url The request URL.
*
* @return array The response array.
*/
public function handle_response( array $response, $request_arguments, $url ) {
$response_code = wp_remote_retrieve_response_code( $response );
if ( $response_code === 200 && $this->is_expected_endpoint( $url ) ) {
$response_data = $this->parse_response( $response );
$this->detect_version( $response_data );
}
return $response;
}
/**
* Returns the license page to use based on the version number.
*
* @return string The page to use.
*/
public function get_license_page() {
return 'licenses';
}
/**
* Returns the version number of the license server.
*
* @return int The version number
*/
protected function get_version() {
return get_option( $this->get_option_name(), self::VERSION_BACKWARDS_COMPATIBILITY );
}
/**
* Returns the option name.
*
* @return string The option name.
*/
protected function get_option_name() {
return 'wpseo_license_server_version';
}
/**
* Sets the version when there is a value in the response.
*
* @param array $response The response to extract the version from.
*/
protected function detect_version( $response ) {
if ( ! empty( $response['serverVersion'] ) ) {
$this->set_version( $response['serverVersion'] );
}
}
/**
* Sets the version.
*
* @param string $server_version The version number to save.
*/
protected function set_version( $server_version ) {
update_option( $this->get_option_name(), $server_version );
}
/**
* Parses the response by getting its body and do a unserialize of it.
*
* @param array $response The response to parse.
*
* @return mixed|string|false The parsed response.
*/
protected function parse_response( $response ) {
$response = json_decode( wp_remote_retrieve_body( $response ), true );
$response = maybe_unserialize( $response );
return $response;
}
/**
* Checks if the given url matches the expected endpoint.
*
* @param string $url The url to check.
*
* @return bool True when url matches the endpoint.
*/
protected function is_expected_endpoint( $url ) {
$url_parts = wp_parse_url( $url );
$is_yoast_com = ( in_array( $url_parts['host'], array( 'yoast.com', 'my.yoast.com' ), true ) );
$is_edd_api = ( isset( $url_parts['path'] ) && $url_parts['path'] === '/edd-sl-api' );
return $is_yoast_com && $is_edd_api;
}
/**
* Creates an instance of Yoast_Notification
*
* @param string $product_name The product to create the notification for.
*
* @return Yoast_Notification The created notification.
*/
protected function create_notification( $product_name ) {
$notification_options = array(
'type' => Yoast_Notification::ERROR,
'id' => 'wpseo-dismiss-' . sanitize_title_with_dashes( $product_name, null, 'save' ),
'capabilities' => 'wpseo_manage_options',
);
$notification = new Yoast_Notification(
sprintf(
/* translators: %1$s expands to the product name. %2$s expands to a link to My Yoast */
__( 'You are not receiving updates or support! Fix this problem by adding this site and enabling %1$s for it in %2$s.', 'wordpress-seo' ),
$product_name,
'<a href="' . WPSEO_Shortlinker::get( 'https://yoa.st/13j' ) . '" target="_blank">My Yoast</a>'
),
$notification_options
);
return $notification;
}
}
| WordBenchNagoya/WordFes2017 | wp/wp-content/plugins/wordpress-seo/admin/class-license-page-manager.php | PHP | gpl-3.0 | 5,869 |
-----------------------------------
--
-- Zone: Windurst_Walls (239)
--
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -2,-17,140, 2,-16,142);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
-- MOG HOUSE EXIT
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
position = math.random(1,5) - 123;
player:setPos(-257.5,-5.05,position,0);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
elseif(ENABLE_ASA == 1 and player:getCurrentMission(ASA) == A_SHANTOTTO_ASCENSION
and (prevZone == 238 or prevZone == 241) and player:getMainLvl()>=10) then
cs = 0x01fe;
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x) -- Heaven's Tower enter portal
player:startEvent(0x56);
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x56) then
player:setPos(0,0,-22.40,192,242);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif(csid == 0x01fe) then
player:startEvent(0x0202);
elseif (csid == 0x0202) then
player:completeMission(ASA,A_SHANTOTTO_ASCENSION);
player:addMission(ASA,BURGEONING_DREAD);
player:setVar("ASA_Status",0);
end
end;
| FFXIOrgins/FFXIOrgins | scripts/zones/Windurst_Walls/Zone.lua | Lua | gpl-3.0 | 2,810 |
#!/bin/env ruby
require 'xml'
resolutions = {
'mdpi' => 1,
'hdpi' => 1.5,
'xhdpi' => 2,
'xxhdpi' => 3,
'xxxhdpi' => 4,
}
images = {
'main_logo.svg' => ['conversations/main_logo', 200],
'quicksy_main_logo.svg' => ['quicksy/main_logo', 200],
'splash_logo.svg' => ['conversations/splash_logo', 144],
'quicksy_splash_logo.svg' => ['quicksy/splash_logo', 144],
'ic_search_black.svg' => ['ic_search_background_black', 144],
'ic_search_white.svg' => ['ic_search_background_white', 144],
'ic_no_results_white.svg' => ['ic_no_results_background_white', 144],
'ic_no_results_black.svg' => ['ic_no_results_background_black', 144],
'play_video_white.svg' => ['play_video_white', 128],
'play_gif_white.svg' => ['play_gif_white', 128],
'play_video_black.svg' => ['play_video_black', 128],
'play_gif_black.svg' => ['play_gif_black', 128],
'conversations_mono.svg' => ['conversations/ic_notification', 24],
'quicksy_mono.svg' => ['quicksy/ic_notification', 24],
'ic_received_indicator.svg' => ['ic_received_indicator', 12],
'ic_send_text_offline.svg' => ['ic_send_text_offline', 36],
'ic_send_text_offline_white.svg' => ['ic_send_text_offline_white', 36],
'ic_send_text_online.svg' => ['ic_send_text_online', 36],
'ic_send_text_away.svg' => ['ic_send_text_away', 36],
'ic_send_text_dnd.svg' => ['ic_send_text_dnd', 36],
'ic_send_photo_online.svg' => ['ic_send_photo_online', 36],
'ic_send_photo_offline.svg' => ['ic_send_photo_offline', 36],
'ic_send_photo_offline_white.svg' => ['ic_send_photo_offline_white', 36],
'ic_send_photo_away.svg' => ['ic_send_photo_away', 36],
'ic_send_photo_dnd.svg' => ['ic_send_photo_dnd', 36],
'ic_send_location_online.svg' => ['ic_send_location_online', 36],
'ic_send_location_offline.svg' => ['ic_send_location_offline', 36],
'ic_send_location_offline_white.svg' => ['ic_send_location_offline_white', 36],
'ic_send_location_away.svg' => ['ic_send_location_away', 36],
'ic_send_location_dnd.svg' => ['ic_send_location_dnd', 36],
'ic_send_voice_online.svg' => ['ic_send_voice_online', 36],
'ic_send_voice_offline.svg' => ['ic_send_voice_offline', 36],
'ic_send_voice_offline_white.svg' => ['ic_send_voice_offline_white', 36],
'ic_send_voice_away.svg' => ['ic_send_voice_away', 36],
'ic_send_voice_dnd.svg' => ['ic_send_voice_dnd', 36],
'ic_send_cancel_online.svg' => ['ic_send_cancel_online', 36],
'ic_send_cancel_offline.svg' => ['ic_send_cancel_offline', 36],
'ic_send_cancel_offline_white.svg' => ['ic_send_cancel_offline_white', 36],
'ic_send_cancel_away.svg' => ['ic_send_cancel_away', 36],
'ic_send_cancel_dnd.svg' => ['ic_send_cancel_dnd', 36],
'ic_send_picture_online.svg' => ['ic_send_picture_online', 36],
'ic_send_picture_offline.svg' => ['ic_send_picture_offline', 36],
'ic_send_picture_offline_white.svg' => ['ic_send_picture_offline_white', 36],
'ic_send_picture_away.svg' => ['ic_send_picture_away', 36],
'ic_send_picture_dnd.svg' => ['ic_send_picture_dnd', 36],
'ic_send_videocam_online.svg' => ['ic_send_videocam_online', 36],
'ic_send_videocam_offline.svg' => ['ic_send_videocam_offline', 36],
'ic_send_videocam_offline_white.svg' => ['ic_send_videocam_offline_white', 36],
'ic_send_videocam_away.svg' => ['ic_send_videocam_away', 36],
'ic_send_videocam_dnd.svg' => ['ic_send_videocam_dnd', 36],
'ic_notifications_none_white80.svg' => ['ic_notifications_none_white80', 24],
'ic_notifications_off_white80.svg' => ['ic_notifications_off_white80', 24],
'ic_notifications_paused_white80.svg' => ['ic_notifications_paused_white80', 24],
'ic_notifications_white80.svg' => ['ic_notifications_white80', 24],
'ic_verified_fingerprint.svg' => ['ic_verified_fingerprint', 36],
'qrcode-scan.svg' => ['ic_qr_code_scan_white_24dp', 24],
'message_bubble_received.svg' => ['message_bubble_received.9', 0],
'message_bubble_received_grey.svg' => ['message_bubble_received_grey.9', 0],
'message_bubble_received_dark.svg' => ['message_bubble_received_dark.9', 0],
'message_bubble_received_warning.svg' => ['message_bubble_received_warning.9', 0],
'message_bubble_received_white.svg' => ['message_bubble_received_white.9', 0],
'message_bubble_sent.svg' => ['message_bubble_sent.9', 0],
'message_bubble_sent_grey.svg' => ['message_bubble_sent_grey.9', 0],
'date_bubble_white.svg' => ['date_bubble_white.9', 0],
'date_bubble_grey.svg' => ['date_bubble_grey.9', 0],
'marker.svg' => ['marker', 0]
}
# Executable paths for Mac OSX
# "/Applications/Inkscape.app/Contents/Resources/bin/inkscape"
inkscape = "inkscape"
imagemagick = "magick"
def execute_cmd(cmd)
puts cmd
system cmd
end
images.each do |source_filename, settings|
svg_content = File.read(source_filename)
svg = XML::Document.string(svg_content)
base_width = svg.root["width"].to_i
base_height = svg.root["height"].to_i
guides = svg.find(".//sodipodi:guide","sodipodi:http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd")
resolutions.each do |resolution, factor|
output_filename, base_size = settings
if base_size > 0
width = factor * base_size
height = factor * base_size
else
width = factor * base_width
height = factor * base_height
end
output_parts = output_filename.split('/')
if output_parts.count != 2
path = "../src/main/res/drawable-#{resolution}/#{output_filename}.png"
else
path = "../src/#{output_parts[0]}/res/drawable-#{resolution}/#{output_parts[1]}.png"
end
execute_cmd "#{inkscape} -f #{source_filename} -z -C -w #{width} -h #{height} -e #{path}"
top = []
right = []
bottom = []
left = []
guides.each do |guide|
orientation = guide["orientation"]
x, y = guide["position"].split(",")
x, y = x.to_i, y.to_i
if orientation == "1,0" and y == base_height
top.push(x * factor)
end
if orientation == "0,1" and x == base_width
right.push((base_height - y) * factor)
end
if orientation == "1,0" and y == 0
bottom.push(x * factor)
end
if orientation == "0,1" and x == 0
left.push((base_height - y) * factor)
end
end
next if top.length != 2
next if right.length != 2
next if bottom.length != 2
next if left.length != 2
execute_cmd "#{imagemagick} -background none PNG32:#{path} -gravity center -extent #{width+2}x#{height+2} PNG32:#{path}"
draw_format = "-draw \"line %d,%d %d,%d\""
top_line = draw_format % [top.min + 1, 0, top.max, 0]
right_line = draw_format % [width + 1, right.min + 1, width + 1, right.max]
bottom_line = draw_format % [bottom.min + 1, height + 1, bottom.max, height + 1]
left_line = draw_format % [0, left.min + 1, 0, left.max]
draws = "#{top_line} #{right_line} #{bottom_line} #{left_line}"
execute_cmd "#{imagemagick} -background none PNG32:#{path} -fill black -stroke none #{draws} PNG32:#{path}"
end
end
| cijo7/Conversations | art/render.rb | Ruby | gpl-3.0 | 6,801 |
<style>
.blinking_alarm {
-webkit-animation-name: blinker;
-webkit-animation-duration: 0.7s;
-webkit-animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
-moz-animation-name: blinker;
-moz-animation-duration: 0.7s;
-moz-animation-timing-function: linear;
-moz-animation-iteration-count: infinite;
animation-name: blinker;
animation-duration: 0.7s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
@-moz-keyframes blinker {
0% { opacity: 1.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}
@-webkit-keyframes blinker {
0% { opacity: 1.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}
@keyframes blinker {
0% { opacity: 1.0; }
50% { opacity: 0.5; }
100% { opacity: 1.0; }
}
</style>
<div data-ui-field="widget" class="ui-overlay-shadow ui-corner-all ui-body-inherit hg-widget-b" style="width:320px;height:290px;position:relative;z-index:10;background:none">
<div class="ui-body-inherit ui-corner-all" style="position:absolute;opacity:0.8;z-index:-1;left:0;top:0;right:0;bottom:0"></div>
<div class="ui-header" style="padding-left:5px;padding-right:5px;font-weight:normal;border-top:0">
<img data-ui-field="icon" style="height:36px;margin:2px;margin-right:4px" align="left" src="pages/control/widgets/homegenie/generic/images/securitysystem.png" />
<div data-ui-field="name" style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width:236px;font-size:16pt;font-weight:bold;padding:6px;float:left;">Alarm System</div>
<a data-ui-field="settings" data-role="button" data-icon="gear" data-iconshadow="false" data-iconpos="notext" class="ui-btn-right">Configuration</a>
</div>
<div data-ui-field="status-container" align="center" style="background:rgba(100,255,100,0.45);margin:0;padding:0;margin-bottom:10px">
<h3 data-ui-field="description" style="padding:6px;margin:0;font-weight:bold">...</h3>
</div>
<div data-ui-field="arm_group" data-role="controlgroup" data-type="horizontal" align="center" data-mini="true">
<a data-ui-field="btn_armhome" href="#" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
<a data-ui-field="btn_armaway" href="#" class="ui-btn ui-icon-lock ui-btn-icon-right">Away</a>
</div>
<div data-ui-field="disarm_group" data-role="controlgroup" data-type="horizontal" align="center" data-mini="true" style="display:none">
<a data-ui-field="btn_disarm" href="#" class="ui-btn ui-icon-forbidden ui-btn-icon-left">Disarm</a>
</div>
<div style="position:absolute;bottom:10px;right:5px;left:5px;height:148px;overflow-y:auto;font-size:10pt">
<div data-ui-field="activity-log" class="ui-grid-a" style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;padding-right:4px">
</div>
</div>
<div class="ui-footer ui-bar-inherit hg-widget-footer" align="right" style="display:none">
<div data-ui-field="status" style="font-size:11pt;display: table-cell;"> </div>
</div>
</div>
| davidwallis3101/HomeGenie | BaseFiles/Common/html/pages/control/widgets/homegenie/generic/securitysystem.html | HTML | gpl-3.0 | 3,055 |
package chat.tox.antox.utils
import java.io.File
import java.sql.Timestamp
import chat.tox.antox.fragments.ContactItemType.ContactItemType
import chat.tox.antox.wrapper.ContactKey
import im.tox.tox4j.core.enums.ToxUserStatus
class LeftPaneItem(
val viewType: ContactItemType,
val key: ContactKey,
val image: Option[File],
val first: String, // name
val second: String, // status message, last message or call info depending on which tab
val secondImage: Option[Int],
val isOnline: Boolean,
val status: ToxUserStatus,
val favorite: Boolean,
val count: Int,
val timestamp: Timestamp, // if call is active this is start time
val activeCall: Boolean) {
def this(viewType: ContactItemType, key: ContactKey, message: String) =
this(viewType, key, None, key.toString, message, None, false, null, false, 0, null, false)
} | wiiam/Antox | app/src/main/scala/chat/tox/antox/utils/LeftPaneItem.scala | Scala | gpl-3.0 | 1,064 |
/* Copyright 2014 the SumatraPDF project authors (see AUTHORS file).
License: Simplified BSD */
/* Wrappers around dbghelp.dll that load it on demand and provide
utility functions related to debugging like getting callstacs etc.
This module is carefully written to not allocate memory as it
can be used from crash handler.
*/
#include "BaseUtil.h"
#include "DbgHelpDyn.h"
#include "FileUtil.h"
#include "WinUtil.h"
/* Hard won wisdom: changing symbol path with SymSetSearchPath() after modules
have been loaded (invideProcess=TRUE in SymInitialize() or SymRefreshModuleList())
doesn't work.
I had to provide symbol path in SymInitialize() (and either invideProcess=TRUE
or invideProcess=FALSE and call SymRefreshModuleList()). There's probably
a way to force it, but I'm happy I found a way that works.
*/
// all of these symbols may not be available under Win2000
typedef BOOL WINAPI MiniDumpWriteDumpProc(
HANDLE hProcess,
DWORD ProcessId,
HANDLE hFile,
LONG DumpType,
PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
typedef BOOL _stdcall SymInitializeWProc(
HANDLE hProcess,
PCWSTR UserSearchPath,
BOOL fInvadeProcess);
typedef BOOL _stdcall SymInitializeProc(
HANDLE hProcess,
PCSTR UserSearchPath,
BOOL fInvadeProcess);
typedef BOOL _stdcall SymCleanupProc(
HANDLE hProcess);
typedef DWORD _stdcall SymGetOptionsProc();
typedef DWORD _stdcall SymSetOptionsProc(DWORD SymOptions);
typedef BOOL _stdcall StackWalk64Proc(
DWORD MachineType,
HANDLE hProcess,
HANDLE hThread,
LPSTACKFRAME64 StackFrame,
PVOID ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
typedef BOOL _stdcall SymFromAddrProc(
HANDLE hProcess,
DWORD64 Address,
PDWORD64 Displacement,
PSYMBOL_INFO Symbol);
typedef PVOID _stdcall SymFunctionTableAccess64Proc(
HANDLE hProcess,
DWORD64 AddrBase);
typedef DWORD64 _stdcall SymGetModuleBase64Proc(
HANDLE hProcess,
DWORD64 qwAddr);
typedef BOOL _stdcall SymSetSearchPathWProc(
HANDLE hProcess,
PCWSTR SearchPath);
typedef BOOL _stdcall SymSetSearchPathProc(
HANDLE hProcess,
PCSTR SearchPath);
typedef BOOL _stdcall SymRefreshModuleListProc(
HANDLE hProcess);
typedef BOOL _stdcall SymGetLineFromAddr64Proc(
HANDLE hProcess,
DWORD64 dwAddr,
PDWORD pdwDisplacement,
PIMAGEHLP_LINE64 Line);
namespace dbghelp {
static MiniDumpWriteDumpProc * _MiniDumpWriteDump;
static SymInitializeWProc * _SymInitializeW;
static SymInitializeProc * _SymInitialize;
static SymCleanupProc * _SymCleanup;
static SymGetOptionsProc * _SymGetOptions;
static SymSetOptionsProc * _SymSetOptions;
static SymSetSearchPathWProc * _SymSetSearchPathW;
static SymSetSearchPathProc * _SymSetSearchPath;
static StackWalk64Proc * _StackWalk64;
static SymFunctionTableAccess64Proc * _SymFunctionTableAccess64;
static SymGetModuleBase64Proc * _SymGetModuleBase64;
static SymFromAddrProc * _SymFromAddr;
static SymRefreshModuleListProc * _SymRefreshModuleList;
static SymGetLineFromAddr64Proc * _SymGetLineFromAddr64;
static BOOL gSymInitializeOk = FALSE;
static char *ExceptionNameFromCode(DWORD excCode)
{
#define EXC(x) case EXCEPTION_##x: return #x;
switch (excCode)
{
EXC(ACCESS_VIOLATION)
EXC(DATATYPE_MISALIGNMENT)
EXC(BREAKPOINT)
EXC(SINGLE_STEP)
EXC(ARRAY_BOUNDS_EXCEEDED)
EXC(FLT_DENORMAL_OPERAND)
EXC(FLT_DIVIDE_BY_ZERO)
EXC(FLT_INEXACT_RESULT)
EXC(FLT_INVALID_OPERATION)
EXC(FLT_OVERFLOW)
EXC(FLT_STACK_CHECK)
EXC(FLT_UNDERFLOW)
EXC(INT_DIVIDE_BY_ZERO)
EXC(INT_OVERFLOW)
EXC(PRIV_INSTRUCTION)
EXC(IN_PAGE_ERROR)
EXC(ILLEGAL_INSTRUCTION)
EXC(NONCONTINUABLE_EXCEPTION)
EXC(STACK_OVERFLOW)
EXC(INVALID_DISPOSITION)
EXC(GUARD_PAGE)
EXC(INVALID_HANDLE)
}
#undef EXC
static char buf[512] = { 0 };
FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandleA("ntdll.dll"),
excCode, 0, buf, sizeof(buf), 0);
return buf;
}
// It only loads dbghelp.dll and gets its functions.
// It can (but doesn't have to) be called before Initialize().
bool Load()
{
if (_MiniDumpWriteDump)
return true;
#if 0
WCHAR *dbghelpPath = L"C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\dbghelp.dll";
HMODULE h = LoadLibrary(dbghelpPath);
#else
HMODULE h = SafeLoadLibrary(L"dbghelp.dll");
#endif
#define Load(func) _ ## func = (func ## Proc *)GetProcAddress(h, #func)
Load(MiniDumpWriteDump);
Load(SymInitializeW);
Load(SymInitialize);
Load(SymCleanup);
Load(SymGetOptions);
Load(SymSetOptions);
Load(SymSetSearchPathW);
Load(SymSetSearchPath);
Load(StackWalk64);
Load(SymFunctionTableAccess64);
Load(SymGetModuleBase64);
Load(SymFromAddr);
Load(SymRefreshModuleList);
Load(SymGetLineFromAddr64);
#undef Load
bool ok = (NULL != _StackWalk64);
//if (!ok)
// plog("dbghelp::Load(): _StackWalk64 not present in dbghelp.dll");
return ok;
}
#if 0
static bool SetupSymbolPath()
{
if (!_SymSetSearchPathW && !_SymSetSearchPath) {
plog("SetupSymbolPath(): _SymSetSearchPathW and _SymSetSearchPath missing");
return false;
}
ScopedMem<WCHAR> path(GetSymbolPath());
if (!path) {
plog("SetupSymbolPath(): GetSymbolPath() returned NULL");
return false;
}
BOOL ok = FALSE;
ScopedMem<WCHAR> tpath(str::conv::FromWStr(path));
if (_SymSetSearchPathW) {
ok = _SymSetSearchPathW(GetCurrentProcess(), path);
if (!ok)
plog("_SymSetSearchPathW() failed");
} else {
ScopedMem<char> tmp(str::conv::ToAnsi(tpath));
ok = SymSetSearchPath(GetCurrentProcess(), tmp);
if (!ok)
plog("_SymSetSearchPath() failed");
}
_SymRefreshModuleList(GetCurrentProcess());
return ok;
}
#endif
static bool CanStackWalk()
{
bool ok = gSymInitializeOk && _SymCleanup && _SymGetOptions &&
_SymSetOptions && _StackWalk64 && _SymFunctionTableAccess64 &&
_SymGetModuleBase64 && _SymFromAddr;
//if (!ok)
// plog("dbghelp::CanStackWalk(): no");
return ok;
}
__declspec(noinline) bool CanSymbolizeAddress(DWORD64 addr)
{
static const int MAX_SYM_LEN = 512;
char buf[sizeof(SYMBOL_INFO) + MAX_SYM_LEN * sizeof(char)];
SYMBOL_INFO *symInfo = (SYMBOL_INFO*)buf;
memset(buf, 0, sizeof(buf));
symInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
symInfo->MaxNameLen = MAX_SYM_LEN;
DWORD64 symDisp = 0;
BOOL ok = _SymFromAddr(GetCurrentProcess(), addr, &symDisp, symInfo);
return ok && symInfo->Name[0];
}
// a heuristic to test if we have symbols for our own binaries by testing if
// we can get symbol for any of our functions.
bool HasSymbols()
{
DWORD64 addr = (DWORD64)&CanSymbolizeAddress;
return CanSymbolizeAddress(addr);
}
// Load and initialize dbghelp.dll. Returns false if failed.
// To simplify callers, it can be called multiple times - it only does the
// work the first time, unless force is true, in which case we re-initialize
// the library (needed in crash dump where we re-initialize dbghelp.dll after
// downloading symbols)
bool Initialize(const WCHAR *symPathW, bool force)
{
if (gSymInitializeOk && !force)
return true;
bool needsCleanup = gSymInitializeOk;
if (!Load())
return false;
if (!_SymInitializeW && !_SymInitialize) {
//plog("dbghelp::Initialize(): SymInitializeW() and SymInitialize() not present in dbghelp.dll");
return false;
}
if (needsCleanup)
_SymCleanup(GetCurrentProcess());
if (_SymInitializeW) {
gSymInitializeOk = _SymInitializeW(GetCurrentProcess(), symPathW, TRUE);
} else {
// SymInitializeW() is not present on some XP systems
char symPathA[MAX_PATH];
if (0 != str::conv::ToCodePageBuf(symPathA, dimof(symPathA), symPathW, CP_ACP))
gSymInitializeOk = _SymInitialize(GetCurrentProcess(), symPathA, TRUE);
}
if (!gSymInitializeOk) {
//plog("dbghelp::Initialize(): _SymInitialize() failed");
return false;
}
DWORD symOptions = _SymGetOptions();
symOptions |= (SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME);
symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS; // don't show system msg box on errors
_SymSetOptions(symOptions);
//SetupSymbolPath();
return true;
}
static BOOL CALLBACK OpenMiniDumpCallback(void *param, PMINIDUMP_CALLBACK_INPUT input, PMINIDUMP_CALLBACK_OUTPUT output)
{
if (!input || !output)
return FALSE;
switch (input->CallbackType) {
case ModuleCallback:
if (!(output->ModuleWriteFlags & ModuleReferencedByMemory))
output->ModuleWriteFlags &= ~ModuleWriteModule;
return TRUE;
case IncludeModuleCallback:
case IncludeThreadCallback:
case ThreadCallback:
case ThreadExCallback:
return TRUE;
default:
return FALSE;
}
}
void WriteMiniDump(const WCHAR *crashDumpFilePath, MINIDUMP_EXCEPTION_INFORMATION* mei, bool fullDump)
{
if (!Initialize(NULL) || !_MiniDumpWriteDump)
return;
HANDLE hFile = CreateFile(crashDumpFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
if (INVALID_HANDLE_VALUE == hFile)
return;
MINIDUMP_TYPE type = (MINIDUMP_TYPE)(MiniDumpNormal | MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory);
if (fullDump)
type = (MINIDUMP_TYPE)(type | MiniDumpWithDataSegs | MiniDumpWithHandleData | MiniDumpWithPrivateReadWriteMemory);
MINIDUMP_CALLBACK_INFORMATION mci = { OpenMiniDumpCallback, NULL };
_MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, type, mei, NULL, &mci);
CloseHandle(hFile);
}
// TODO: should offsetOut be DWORD_PTR for 64-bit compat?
static bool GetAddrInfo(void *addr, char *module, DWORD moduleLen, DWORD& sectionOut, DWORD& offsetOut)
{
MEMORY_BASIC_INFORMATION mbi;
if (0 == VirtualQuery(addr, &mbi, sizeof(mbi)))
return false;
HMODULE hMod = (HMODULE)mbi.AllocationBase;
if (0 == hMod)
return false;
if (!GetModuleFileNameA(hMod, module, moduleLen))
return false;
module[moduleLen - 1] = '\0';
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)mbi.AllocationBase;
PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((BYTE *)dosHeader + dosHeader->e_lfanew);
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNtHeader);
DWORD lAddr = (DWORD)addr - (DWORD)hMod;
for (unsigned int i = 0; i < pNtHeader->FileHeader.NumberOfSections; i++) {
DWORD startAddr = section->VirtualAddress;
DWORD endAddr = startAddr;
if (section->SizeOfRawData > section->Misc.VirtualSize)
endAddr += section->SizeOfRawData;
else
section->Misc.VirtualSize;
if (lAddr >= startAddr && lAddr <= endAddr) {
sectionOut = i+1;
offsetOut = lAddr - startAddr;
return true;
}
section++;
}
return false;
}
static void AppendAddress(str::Str<char>& s, DWORD64 addr)
{
#ifdef _WIN64
s.AppendFmt("%016I64X", addr);
#else
s.AppendFmt("%08X", (DWORD)addr);
#endif
}
static void GetAddressInfo(str::Str<char>& s, DWORD64 addr)
{
static const int MAX_SYM_LEN = 512;
char buf[sizeof(SYMBOL_INFO) + MAX_SYM_LEN * sizeof(char)];
SYMBOL_INFO *symInfo = (SYMBOL_INFO*)buf;
memset(buf, 0, sizeof(buf));
symInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
symInfo->MaxNameLen = MAX_SYM_LEN;
DWORD64 symDisp = 0;
char *symName = NULL;
BOOL ok = _SymFromAddr(GetCurrentProcess(), addr, &symDisp, symInfo);
if (ok)
symName = &(symInfo->Name[0]);
char module[MAX_PATH] = { 0 };
DWORD section, offset;
if (GetAddrInfo((void*)addr, module, sizeof(module), section, offset)) {
str::ToLower(module);
const char *moduleShort = path::GetBaseName(module);
AppendAddress(s, addr);
s.AppendFmt(" %02X:", section);
AppendAddress(s, offset);
s.AppendFmt(" %s", moduleShort);
if (symName) {
s.AppendFmt("!%s+0x%x", symName, (int)symDisp);
} else if (symDisp != 0) {
s.AppendFmt("+0x%x", (int)symDisp);
}
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
DWORD disp;
if (_SymGetLineFromAddr64(GetCurrentProcess(), addr, &disp, &line)) {
s.AppendFmt(" %s+%d", line.FileName, line.LineNumber);
}
} else {
AppendAddress(s, addr);
}
s.Append("\r\n");
}
static bool GetStackFrameInfo(str::Str<char>& s, STACKFRAME64 *stackFrame,
CONTEXT *ctx, HANDLE hThread)
{
#if defined(_WIN64)
int machineType = IMAGE_FILE_MACHINE_AMD64;
#else
int machineType = IMAGE_FILE_MACHINE_I386;
#endif
BOOL ok = _StackWalk64(machineType, GetCurrentProcess(), hThread,
stackFrame, ctx, NULL, _SymFunctionTableAccess64,
_SymGetModuleBase64, NULL);
if (!ok)
return false;
DWORD64 addr = stackFrame->AddrPC.Offset;
if (0 == addr)
return true;
if (addr == stackFrame->AddrReturn.Offset) {
s.Append("GetStackFrameInfo(): addr == stackFrame->AddrReturn.Offset");
return false;
}
GetAddressInfo(s, addr);
return true;
}
static bool GetCallstack(str::Str<char>& s, CONTEXT& ctx, HANDLE hThread)
{
if (!CanStackWalk()) {
s.Append("GetCallstack(): CanStackWalk() returned false");
return false;
}
STACKFRAME64 stackFrame;
memset(&stackFrame, 0, sizeof(stackFrame));
#ifdef _WIN64
stackFrame.AddrPC.Offset = ctx.Rip;
stackFrame.AddrFrame.Offset = ctx.Rbp;
stackFrame.AddrStack.Offset = ctx.Rsp;
#else
stackFrame.AddrPC.Offset = ctx.Eip;
stackFrame.AddrFrame.Offset = ctx.Ebp;
stackFrame.AddrStack.Offset = ctx.Esp;
#endif
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrFrame.Mode = AddrModeFlat;
stackFrame.AddrStack.Mode = AddrModeFlat;
int framesCount = 0;
static const int maxFrames = 32;
while (framesCount < maxFrames)
{
if (!GetStackFrameInfo(s, &stackFrame, &ctx, hThread))
break;
framesCount++;
}
if (0 == framesCount) {
s.Append("StackWalk64() couldn't get even the first stack frame info");
return false;
}
return true;
}
void GetThreadCallstack(str::Str<char>& s, DWORD threadId)
{
if (threadId == GetCurrentThreadId())
return;
s.AppendFmt("\r\nThread: %x\r\n", threadId);
DWORD access = THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SUSPEND_RESUME;
HANDLE hThread = OpenThread(access, false, threadId);
if (!hThread) {
s.Append("Failed to OpenThread()\r\n");
return;
}
DWORD res = SuspendThread(hThread);
if (-1 == res) {
s.Append("Failed to SuspendThread()\r\n");
} else {
CONTEXT ctx = { 0 };
ctx.ContextFlags = CONTEXT_FULL;
BOOL ok = GetThreadContext(hThread, &ctx);
if (ok)
GetCallstack(s, ctx, hThread);
else
s.Append("Failed to GetThreadContext()\r\n");
ResumeThread(hThread);
}
CloseHandle(hThread);
}
// we disable optimizations for this function as it calls RtlCaptureContext()
// which cannot deal with Omit Frame Pointers optimization (/Oy explicitly, turned
// implicitly by e.g. /O2)
// http://www.bytetalk.net/2011/06/why-rtlcapturecontext-crashes-on.html
#pragma optimize( "", off )
// we also need to disable warning 4748 "/GS can not protect parameters and local variables
// from local buffer overrun because optimizations are disabled in function)"
#pragma warning(push)
#pragma warning(disable : 4748)
typedef VOID WINAPI RtlCaptureContextProc(PCONTEXT ContextRecord);
__declspec(noinline) bool GetCurrentThreadCallstack(str::Str<char>& s)
{
if (!Initialize(NULL))
return false;
CONTEXT ctx;
// not available under Win2000
RtlCaptureContextProc *MyRtlCaptureContext = (RtlCaptureContextProc *)LoadDllFunc(L"kernel32.dll", "RtlCaptureContext");
if (!MyRtlCaptureContext)
return false;
MyRtlCaptureContext(&ctx);
return GetCallstack(s, ctx, GetCurrentThread());
}
#pragma optimize("", off )
str::Str<char> *gCallstackLogs = NULL;
// start remembering callstack logs done with LogCallstack()
void RememberCallstackLogs()
{
CrashIf(gCallstackLogs);
gCallstackLogs = new str::Str<char>();
}
void FreeCallstackLogs()
{
delete gCallstackLogs;
gCallstackLogs = NULL;
}
char *GetCallstacks()
{
if (!gCallstackLogs)
return NULL;
return str::Dup(gCallstackLogs->Get());
}
void LogCallstack()
{
str::Str<char> s(2048);
if (!GetCurrentThreadCallstack(s))
return;
s.Append("\n");
plog(s.Get());
if (gCallstackLogs)
gCallstackLogs->Append(s.Get());
}
void GetAllThreadsCallstacks(str::Str<char>& s)
{
HANDLE threadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (threadSnap == INVALID_HANDLE_VALUE)
return;
THREADENTRY32 te32;
te32.dwSize = sizeof(THREADENTRY32);
DWORD pid = GetCurrentProcessId();
BOOL ok = Thread32First(threadSnap, &te32);
while (ok) {
if (te32.th32OwnerProcessID == pid)
GetThreadCallstack(s, te32.th32ThreadID);
ok = Thread32Next(threadSnap, &te32);
}
CloseHandle(threadSnap);
}
#pragma warning(pop)
void GetExceptionInfo(str::Str<char>& s, EXCEPTION_POINTERS *excPointers)
{
if (!excPointers)
return;
EXCEPTION_RECORD *excRecord = excPointers->ExceptionRecord;
DWORD excCode = excRecord->ExceptionCode;
s.AppendFmt("Exception: %08X %s\r\n", (int)excCode, ExceptionNameFromCode(excCode));
s.AppendFmt("Faulting IP: ");
GetAddressInfo(s, (DWORD64)excRecord->ExceptionAddress);
if ((EXCEPTION_ACCESS_VIOLATION == excCode) ||
(EXCEPTION_IN_PAGE_ERROR == excCode))
{
int readWriteFlag = (int)excRecord->ExceptionInformation[0];
DWORD64 dataVirtAddr = (DWORD64)excRecord->ExceptionInformation[1];
if (0 == readWriteFlag) {
s.Append("Fault reading address "); AppendAddress(s, dataVirtAddr);
} else if (1 == readWriteFlag) {
s.Append("Fault writing address "); AppendAddress(s, dataVirtAddr);
} else if (8 == readWriteFlag) {
s.Append("DEP violation at address "); AppendAddress(s, dataVirtAddr);
} else {
s.Append("unknown readWriteFlag: %d", readWriteFlag);
}
s.Append("\r\n");
}
PCONTEXT ctx = excPointers->ContextRecord;
s.AppendFmt("\r\nRegisters:\r\n");
#ifdef _WIN64
s.AppendFmt("RAX:%016I64X RBX:%016I64X RCX:%016I64X\r\nRDX:%016I64X RSI:%016I64X RDI:%016I64X\r\n"
"R8: %016I64X\r\nR9: %016I64X\r\nR10:%016I64X\r\nR11:%016I64X\r\nR12:%016I64X\r\nR13:%016I64X\r\nR14:%016I64X\r\nR15:%016I64X\r\n",
ctx->Rax, ctx->Rbx, ctx->Rcx, ctx->Rdx, ctx->Rsi, ctx->Rdi,
ctx->R9,ctx->R10,ctx->R11,ctx->R12,ctx->R13,ctx->R14,ctx->R15);
s.AppendFmt("CS:RIP:%04X:%016I64X\r\n", ctx->SegCs, ctx->Rip);
s.AppendFmt("SS:RSP:%04X:%016X RBP:%08X\r\n", ctx->SegSs, ctx->Rsp, ctx->Rbp);
s.AppendFmt("DS:%04X ES:%04X FS:%04X GS:%04X\r\n", ctx->SegDs, ctx->SegEs, ctx->SegFs, ctx->SegGs);
s.AppendFmt("Flags:%08X\r\n", ctx->EFlags);
#else
s.AppendFmt("EAX:%08X EBX:%08X ECX:%08X\r\nEDX:%08X ESI:%08X EDI:%08X\r\n",
ctx->Eax, ctx->Ebx, ctx->Ecx, ctx->Edx, ctx->Esi, ctx->Edi);
s.AppendFmt("CS:EIP:%04X:%08X\r\n", ctx->SegCs, ctx->Eip);
s.AppendFmt("SS:ESP:%04X:%08X EBP:%08X\r\n", ctx->SegSs, ctx->Esp, ctx->Ebp);
s.AppendFmt("DS:%04X ES:%04X FS:%04X GS:%04X\r\n", ctx->SegDs, ctx->SegEs, ctx->SegFs, ctx->SegGs);
s.AppendFmt("Flags:%08X\r\n", ctx->EFlags);
#endif
s.Append("\r\nCrashed thread:\r\n");
// it's not really for current thread, but it seems to work
GetCallstack(s, *ctx, GetCurrentThread());
}
}
| ibb-zimmers/betsynetpdf | sumatrapdf/src/utils/DbgHelpDyn.cpp | C++ | gpl-3.0 | 21,447 |
"use strict";
/*global define, ajaxify, app, socket, utils, bootbox, RELATIVE_PATH*/
define('admin/general/dashboard', ['semver', 'Chart'], function(semver, Chart) {
var Admin = {},
intervals = {
rooms: false,
graphs: false
},
isMobile = false,
isPrerelease = /^v?\d+\.\d+\.\d+-.+$/,
graphData = {
rooms: {},
traffic: {}
},
currentGraph = {
units: 'hours',
until: undefined
};
var DEFAULTS = {
roomInterval: 10000,
graphInterval: 15000,
realtimeInterval: 1500
};
$(window).on('action:ajaxify.start', function(ev, data) {
clearInterval(intervals.rooms);
clearInterval(intervals.graphs);
intervals.rooms = null;
intervals.graphs = null;
graphData.rooms = null;
graphData.traffic = null;
usedTopicColors.length = 0;
});
Admin.init = function() {
app.enterRoom('admin');
socket.emit('admin.rooms.getAll', Admin.updateRoomUsage);
isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
$.get('https://api.github.com/repos/NodeBB/NodeBB/tags', function(releases) {
// Re-sort the releases, as they do not follow Semver (wrt pre-releases)
releases = releases.sort(function(a, b) {
a = a.name.replace(/^v/, '');
b = b.name.replace(/^v/, '');
return semver.lt(a, b) ? 1 : -1;
}).filter(function(version) {
return !isPrerelease.test(version.name); // filter out automated prerelease versions
});
var version = $('#version').html(),
latestVersion = releases[0].name.slice(1),
checkEl = $('.version-check');
// Alter box colour accordingly
if (semver.eq(latestVersion, version)) {
checkEl.removeClass('alert-info').addClass('alert-success');
checkEl.append('<p>You are <strong>up-to-date</strong> <i class="fa fa-check"></i></p>');
} else if (semver.gt(latestVersion, version)) {
checkEl.removeClass('alert-info').addClass('alert-warning');
if (!isPrerelease.test(version)) {
checkEl.append('<p>A new version (v' + latestVersion + ') has been released. Consider <a href="https://docs.nodebb.org/en/latest/upgrading/index.html">upgrading your NodeBB</a>.</p>');
} else {
checkEl.append('<p>This is an outdated pre-release version of NodeBB. A new version (v' + latestVersion + ') has been released. Consider <a href="https://docs.nodebb.org/en/latest/upgrading/index.html">upgrading your NodeBB</a>.</p>');
}
} else if (isPrerelease.test(version)) {
checkEl.removeClass('alert-info').addClass('alert-info');
checkEl.append('<p>This is a <strong>pre-release</strong> version of NodeBB. Unintended bugs may occur. <i class="fa fa-exclamation-triangle"></i>.</p>');
}
});
$('[data-toggle="tooltip"]').tooltip();
setupRealtimeButton();
setupGraphs();
initiateDashboard();
};
Admin.updateRoomUsage = function(err, data) {
if (err) {
return app.alertError(err.message);
}
if (JSON.stringify(graphData.rooms) === JSON.stringify(data)) {
return;
}
graphData.rooms = data;
var html = '<div class="text-center pull-left">' +
'<div>'+ data.onlineRegisteredCount +'</div>' +
'<div>Users</div>' +
'</div>' +
'<div class="text-center pull-left">' +
'<div>'+ data.onlineGuestCount +'</div>' +
'<div>Guests</div>' +
'</div>' +
'<div class="text-center pull-left">' +
'<div>'+ (data.onlineRegisteredCount + data.onlineGuestCount) +'</div>' +
'<div>Total</div>' +
'</div>' +
'<div class="text-center pull-left">' +
'<div>'+ data.socketCount +'</div>' +
'<div>Connections</div>' +
'</div>';
updateRegisteredGraph(data.onlineRegisteredCount, data.onlineGuestCount);
updatePresenceGraph(data.users);
updateTopicsGraph(data.topics);
$('#active-users').html(html);
};
var graphs = {
traffic: null,
registered: null,
presence: null,
topics: null
};
var topicColors = ["#bf616a","#5B90BF","#d08770","#ebcb8b","#a3be8c","#96b5b4","#8fa1b3","#b48ead","#ab7967","#46BFBD"],
usedTopicColors = [];
// from chartjs.org
function lighten(col, amt) {
var usePound = false;
if (col[0] == "#") {
col = col.slice(1);
usePound = true;
}
var num = parseInt(col,16);
var r = (num >> 16) + amt;
if (r > 255) r = 255;
else if (r < 0) r = 0;
var b = ((num >> 8) & 0x00FF) + amt;
if (b > 255) b = 255;
else if (b < 0) b = 0;
var g = (num & 0x0000FF) + amt;
if (g > 255) g = 255;
else if (g < 0) g = 0;
return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
}
function setupGraphs() {
var trafficCanvas = document.getElementById('analytics-traffic'),
registeredCanvas = document.getElementById('analytics-registered'),
presenceCanvas = document.getElementById('analytics-presence'),
topicsCanvas = document.getElementById('analytics-topics'),
trafficCtx = trafficCanvas.getContext('2d'),
registeredCtx = registeredCanvas.getContext('2d'),
presenceCtx = presenceCanvas.getContext('2d'),
topicsCtx = topicsCanvas.getContext('2d'),
trafficLabels = utils.getHoursArray();
if (isMobile) {
Chart.defaults.global.showTooltips = false;
Chart.defaults.global.animation = false;
}
var data = {
labels: trafficLabels,
datasets: [
{
label: "Page Views",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
},
{
label: "Unique Visitors",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
}
]
};
trafficCanvas.width = $(trafficCanvas).parent().width();
graphs.traffic = new Chart(trafficCtx).Line(data, {
responsive: true
});
graphs.registered = new Chart(registeredCtx).Doughnut([{
value: 1,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Registered Users"
},
{
value: 1,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Anonymous Users"
}], {
responsive: true
});
graphs.presence = new Chart(presenceCtx).Doughnut([{
value: 1,
color:"#F7464A",
highlight: "#FF5A5E",
label: "On categories list"
},
{
value: 1,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Reading posts"
},
{
value: 1,
color: "#FDB45C",
highlight: "#FFC870",
label: "Browsing topics"
},
{
value: 1,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Recent"
},
{
value: 1,
color: "#9FB194",
highlight: "#A8B3C5",
label: "Unread"
}
], {
responsive: true
});
graphs.topics = new Chart(topicsCtx).Doughnut([], {responsive: true});
topicsCanvas.onclick = function(evt){
var obj = graphs.topics.getSegmentsAtEvent(evt);
if (obj && obj[0]) {
window.open(RELATIVE_PATH + '/topic/' + obj[0].tid);
}
};
updateTrafficGraph();
$(window).on('resize', adjustPieCharts);
adjustPieCharts();
$('[data-action="updateGraph"]').on('click', function() {
var until = undefined;
switch($(this).attr('data-until')) {
case 'last-month':
var lastMonth = new Date();
lastMonth.setDate(lastMonth.getDate()-30);
until = lastMonth.getTime();
}
updateTrafficGraph($(this).attr('data-units'), until);
});
}
function adjustPieCharts() {
$('.pie-chart.legend-up').each(function() {
var $this = $(this);
if ($this.width() < 320) {
$this.addClass('compact');
} else {
$this.removeClass('compact');
}
});
}
function updateTrafficGraph(units, until) {
if (!app.isFocused) {
return;
}
socket.emit('admin.analytics.get', {
graph: 'traffic',
units: units || 'hours',
until: until
}, function (err, data) {
if (JSON.stringify(graphData.traffic) === JSON.stringify(data)) {
return;
}
graphData.traffic = data;
// If new data set contains fewer points than currently shown, truncate
while(graphs.traffic.datasets[0].points.length > data.pageviews.length) {
graphs.traffic.removeData();
}
if (units === 'days') {
graphs.traffic.scale.xLabels = utils.getDaysArray(until);
} else {
graphs.traffic.scale.xLabels = utils.getHoursArray();
$('#pageViewsThisMonth').html(data.monthlyPageViews.thisMonth);
$('#pageViewsLastMonth').html(data.monthlyPageViews.lastMonth);
$('#pageViewsPastDay').html(data.pastDay);
utils.addCommasToNumbers($('#pageViewsThisMonth'));
utils.addCommasToNumbers($('#pageViewsLastMonth'));
utils.addCommasToNumbers($('#pageViewsPastDay'));
}
for (var i = 0, ii = data.pageviews.length; i < ii; i++) {
if (graphs.traffic.datasets[0].points[i]) {
graphs.traffic.datasets[0].points[i].value = data.pageviews[i];
graphs.traffic.datasets[0].points[i].label = graphs.traffic.scale.xLabels[i];
graphs.traffic.datasets[1].points[i].value = data.uniqueVisitors[i];
graphs.traffic.datasets[1].points[i].label = graphs.traffic.scale.xLabels[i];
} else {
// No points to replace? Add data.
graphs.traffic.addData([data.pageviews[i], data.uniqueVisitors[i]], graphs.traffic.scale.xLabels[i]);
}
}
graphs.traffic.update();
currentGraph.units = units;
currentGraph.until = until;
});
}
function updateRegisteredGraph(registered, anonymous) {
graphs.registered.segments[0].value = registered;
graphs.registered.segments[1].value = anonymous;
graphs.registered.update();
}
function updatePresenceGraph(users) {
graphs.presence.segments[0].value = users.categories;
graphs.presence.segments[1].value = users.topics;
graphs.presence.segments[2].value = users.category;
graphs.presence.segments[3].value = users.recent;
graphs.presence.segments[4].value = users.unread;
graphs.presence.update();
}
function updateTopicsGraph(topics) {
if (!Object.keys(topics).length) {
topics = {"0": {
title: "No users browsing",
value: 1
}};
}
var tids = Object.keys(topics),
segments = graphs.topics.segments;
function reassignExistingTopics() {
for (var i = segments.length - 1; i >= 0; i--) {
if (!segments[i]) {
continue;
}
var tid = segments[i].tid;
if ($.inArray(tid, tids) === -1) {
usedTopicColors.splice($.inArray(segments[i].fillColor, usedTopicColors), 1);
graphs.topics.removeData(i);
} else {
graphs.topics.segments[i].value = topics[tid].value;
delete topics[tid];
}
}
}
function assignNewTopics() {
while (segments.length < 10 && tids.length > 0) {
var tid = tids.pop(),
data = topics[tid],
color = null;
if (!data) {
continue;
}
if (tid === '0') {
color = '#4D5360';
} else {
do {
for (var i = 0, ii = topicColors.length; i < ii; i++) {
var chosenColor = topicColors[i];
if ($.inArray(chosenColor, usedTopicColors) === -1) {
color = chosenColor;
usedTopicColors.push(color);
break;
}
}
} while (color === null && usedTopicColors.length < topicColors.length);
}
if (color) {
graphs.topics.addData({
value: data.value,
color: color,
highlight: lighten(color, 10),
label: data.title
});
segments[segments.length - 1].tid = tid;
}
}
}
function buildTopicsLegend() {
var legend = $('#topics-legend').html('');
segments.sort(function(a, b) {
return b.value - a.value;
});
for (var i = 0, ii = segments.length; i < ii; i++) {
var topic = segments[i],
label = topic.tid === '0' ? topic.label : '<a title="' + topic.label + '"href="' + RELATIVE_PATH + '/topic/' + topic.tid + '" target="_blank"> ' + topic.label + '</a>';
legend.append(
'<li>' +
'<div style="background-color: ' + topic.highlightColor + '; border-color: ' + topic.strokeColor + '"></div>' +
'<span>' + label + '</span>' +
'</li>');
}
}
reassignExistingTopics();
assignNewTopics();
buildTopicsLegend();
graphs.topics.update();
}
function setupRealtimeButton() {
$('#toggle-realtime .fa').on('click', function() {
var $this = $(this);
if ($this.hasClass('fa-toggle-on')) {
$this.removeClass('fa-toggle-on').addClass('fa-toggle-off');
$this.parent().find('strong').html('OFF');
initiateDashboard(false);
} else {
$this.removeClass('fa-toggle-off').addClass('fa-toggle-on');
$this.parent().find('strong').html('ON');
initiateDashboard(true);
}
});
}
function initiateDashboard(realtime) {
clearInterval(intervals.rooms);
clearInterval(intervals.graphs);
intervals.rooms = setInterval(function() {
if (app.isFocused && app.isConnected) {
socket.emit('admin.rooms.getAll', Admin.updateRoomUsage);
}
}, realtime ? DEFAULTS.realtimeInterval : DEFAULTS.roomInterval);
intervals.graphs = setInterval(function() {
updateTrafficGraph(currentGraph.units, currentGraph.until);
}, realtime ? DEFAULTS.realtimeInterval : DEFAULTS.graphInterval);
}
return Admin;
});
| rockq-org/cnodebb | public/src/admin/general/dashboard.js | JavaScript | gpl-3.0 | 13,348 |
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
/*
* AP_EPM.h
*
* Created on: DEC 06, 2013
* Author: Andreas Jochum
*
* Set-up Wiki: http://copter.ardupilot.com/wiki/common-electro-permanent-magnet-gripper/
*/
/// @file AP_EPM.h
/// @brief AP_EPM control class
#pragma once
#include <AP_Math/AP_Math.h>
#include <AP_Common/AP_Common.h>
#include <RC_Channel/RC_Channel.h>
// EPM PWM definitions
#define EPM_GRAB_PWM_DEFAULT 1900
#define EPM_RELEASE_PWM_DEFAULT 1100
#define EPM_NEUTRAL_PWM_DEFAULT 1500
#define EPM_RETURN_TO_NEUTRAL_MS 500 // EPM PWM returns to neutral position this many milliseconds after grab or release
#define EPM_REGRAB_DEFAULT 0 // default re-grab interval (in seconds) to ensure cargo is securely held
/// @class AP_EPM
/// @brief Class to manage the EPM_CargoGripper
class AP_EPM {
public:
AP_EPM();
// initialise the EPM
void init();
// enabled - true if the EPM is enabled
bool enabled() { return _enabled; }
// grab - move the EPM pwm output to the grab position
void grab();
// release - move the EPM pwm output to the release position
void release();
// update - moves the pwm back to neutral after the timeout has passed
// should be called at at least 10hz
void update();
static const struct AP_Param::GroupInfo var_info[];
private:
// neutral - return the EPM pwm output to the neutral position
void neutral();
// EPM flags
struct EPM_Flags {
uint8_t grab : 1; // true if we think we have grabbed onto cargo, false if we think we've released it
uint8_t active : 1; // true if we are actively sending grab or release PWM to EPM to activate grabbing or releasing, false if we are sending neutral pwm
} _flags;
// parameters
AP_Int8 _enabled; // EPM enable/disable
AP_Int16 _grab_pwm; // PWM value sent to EPM to initiate grabbing the cargo
AP_Int16 _release_pwm; // PWM value sent to EPM to release the cargo
AP_Int16 _neutral_pwm; // PWM value sent to EPM when not grabbing or releasing
AP_Int8 _regrab_interval; // Time in seconds that gripper will regrab the cargo to ensure grip has not weakend
// internal variables
uint32_t _last_grab_or_release;
};
| busyStone/ardupilot | libraries/AP_EPM/AP_EPM.h | C | gpl-3.0 | 2,448 |
//===- llvm/Pass.h - Base class for Passes ----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a base class that indicates that a specified class is a
// transformation pass implementation.
//
// Passes are designed this way so that it is possible to run passes in a cache
// and organizationally optimal order without having to specify it at the front
// end. This allows arbitrary passes to be strung together and have them
// executed as efficiently as possible.
//
// Passes should extend one of the classes below, depending on the guarantees
// that it can make about what will be modified as it is run. For example, most
// global optimizations should derive from FunctionPass, because they do not add
// or delete functions, they operate on the internals of the function.
//
// Note that this file #includes PassSupport.h and PassAnalysisSupport.h (at the
// bottom), so the APIs exposed by these files are also automatically available
// to all users of this file.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_PASS_H
#define LLVM_PASS_H
#include <string>
namespace llvm {
class BasicBlock;
class Function;
class Module;
class AnalysisUsage;
class PassInfo;
class ImmutablePass;
class PMStack;
class AnalysisResolver;
class PMDataManager;
class raw_ostream;
class StringRef;
// AnalysisID - Use the PassInfo to identify a pass...
typedef const void* AnalysisID;
/// Different types of internal pass managers. External pass managers
/// (PassManager and FunctionPassManager) are not represented here.
/// Ordering of pass manager types is important here.
enum PassManagerType {
PMT_Unknown = 0,
PMT_ModulePassManager = 1, ///< MPPassManager
PMT_CallGraphPassManager, ///< CGPassManager
PMT_FunctionPassManager, ///< FPPassManager
PMT_LoopPassManager, ///< LPPassManager
PMT_RegionPassManager, ///< RGPassManager
PMT_BasicBlockPassManager, ///< BBPassManager
PMT_Last
};
// Different types of passes.
enum PassKind {
PT_BasicBlock,
PT_Region,
PT_Loop,
PT_Function,
PT_CallGraphSCC,
PT_Module,
PT_PassManager
};
//===----------------------------------------------------------------------===//
/// Pass interface - Implemented by all 'passes'. Subclass this if you are an
/// interprocedural optimization or you do not fit into any of the more
/// constrained passes described below.
///
class Pass {
AnalysisResolver *Resolver; // Used to resolve analysis
const void *PassID;
PassKind Kind;
void operator=(const Pass&); // DO NOT IMPLEMENT
Pass(const Pass &); // DO NOT IMPLEMENT
public:
explicit Pass(PassKind K, char &pid);
virtual ~Pass();
PassKind getPassKind() const { return Kind; }
/// getPassName - Return a nice clean name for a pass. This usually
/// implemented in terms of the name that is registered by one of the
/// Registration templates, but can be overloaded directly.
///
virtual const char *getPassName() const;
/// getPassID - Return the PassID number that corresponds to this pass.
virtual AnalysisID getPassID() const {
return PassID;
}
/// print - Print out the internal state of the pass. This is called by
/// Analyze to print out the contents of an analysis. Otherwise it is not
/// necessary to implement this method. Beware that the module pointer MAY be
/// null. This automatically forwards to a virtual function that does not
/// provide the Module* in case the analysis doesn't need it it can just be
/// ignored.
///
virtual void print(raw_ostream &O, const Module *M) const;
void dump() const; // dump - Print to stderr.
/// createPrinterPass - Get a Pass appropriate to print the IR this
/// pass operates on (Module, Function or MachineFunction).
virtual Pass *createPrinterPass(raw_ostream &O,
const std::string &Banner) const = 0;
/// Each pass is responsible for assigning a pass manager to itself.
/// PMS is the stack of available pass manager.
virtual void assignPassManager(PMStack &,
PassManagerType) {}
/// Check if available pass managers are suitable for this pass or not.
virtual void preparePassManager(PMStack &);
/// Return what kind of Pass Manager can manage this pass.
virtual PassManagerType getPotentialPassManagerType() const;
// Access AnalysisResolver
void setResolver(AnalysisResolver *AR);
AnalysisResolver *getResolver() const { return Resolver; }
/// getAnalysisUsage - This function should be overriden by passes that need
/// analysis information to do their job. If a pass specifies that it uses a
/// particular analysis result to this function, it can then use the
/// getAnalysis<AnalysisType>() function, below.
///
virtual void getAnalysisUsage(AnalysisUsage &) const;
/// releaseMemory() - This member can be implemented by a pass if it wants to
/// be able to release its memory when it is no longer needed. The default
/// behavior of passes is to hold onto memory for the entire duration of their
/// lifetime (which is the entire compile time). For pipelined passes, this
/// is not a big deal because that memory gets recycled every time the pass is
/// invoked on another program unit. For IP passes, it is more important to
/// free memory when it is unused.
///
/// Optionally implement this function to release pass memory when it is no
/// longer used.
///
virtual void releaseMemory();
/// getAdjustedAnalysisPointer - This method is used when a pass implements
/// an analysis interface through multiple inheritance. If needed, it should
/// override this to adjust the this pointer as needed for the specified pass
/// info.
virtual void *getAdjustedAnalysisPointer(AnalysisID ID);
virtual ImmutablePass *getAsImmutablePass();
virtual PMDataManager *getAsPMDataManager();
/// verifyAnalysis() - This member can be implemented by a analysis pass to
/// check state of analysis information.
virtual void verifyAnalysis() const;
// dumpPassStructure - Implement the -debug-passes=PassStructure option
virtual void dumpPassStructure(unsigned Offset = 0);
// lookupPassInfo - Return the pass info object for the specified pass class,
// or null if it is not known.
static const PassInfo *lookupPassInfo(const void *TI);
// lookupPassInfo - Return the pass info object for the pass with the given
// argument string, or null if it is not known.
static const PassInfo *lookupPassInfo(StringRef Arg);
/// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to
/// get analysis information that might be around, for example to update it.
/// This is different than getAnalysis in that it can fail (if the analysis
/// results haven't been computed), so should only be used if you can handle
/// the case when the analysis is not available. This method is often used by
/// transformation APIs to update analysis results for a pass automatically as
/// the transform is performed.
///
template<typename AnalysisType> AnalysisType *
getAnalysisIfAvailable() const; // Defined in PassAnalysisSupport.h
/// mustPreserveAnalysisID - This method serves the same function as
/// getAnalysisIfAvailable, but works if you just have an AnalysisID. This
/// obviously cannot give you a properly typed instance of the class if you
/// don't have the class name available (use getAnalysisIfAvailable if you
/// do), but it can tell you if you need to preserve the pass at least.
///
bool mustPreserveAnalysisID(char &AID) const;
/// getAnalysis<AnalysisType>() - This function is used by subclasses to get
/// to the analysis information that they claim to use by overriding the
/// getAnalysisUsage function.
///
template<typename AnalysisType>
AnalysisType &getAnalysis() const; // Defined in PassAnalysisSupport.h
template<typename AnalysisType>
AnalysisType &getAnalysis(Function &F); // Defined in PassAnalysisSupport.h
template<typename AnalysisType>
AnalysisType &getAnalysisID(AnalysisID PI) const;
template<typename AnalysisType>
AnalysisType &getAnalysisID(AnalysisID PI, Function &F);
};
//===----------------------------------------------------------------------===//
/// ModulePass class - This class is used to implement unstructured
/// interprocedural optimizations and analyses. ModulePasses may do anything
/// they want to the program.
///
class ModulePass : public Pass {
public:
/// createPrinterPass - Get a module printer pass.
Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
/// runOnModule - Virtual method overriden by subclasses to process the module
/// being operated on.
virtual bool runOnModule(Module &M) = 0;
virtual void assignPassManager(PMStack &PMS,
PassManagerType T);
/// Return what kind of Pass Manager can manage this pass.
virtual PassManagerType getPotentialPassManagerType() const;
explicit ModulePass(char &pid) : Pass(PT_Module, pid) {}
// Force out-of-line virtual method.
virtual ~ModulePass();
};
//===----------------------------------------------------------------------===//
/// ImmutablePass class - This class is used to provide information that does
/// not need to be run. This is useful for things like target information and
/// "basic" versions of AnalysisGroups.
///
class ImmutablePass : public ModulePass {
public:
/// initializePass - This method may be overriden by immutable passes to allow
/// them to perform various initialization actions they require. This is
/// primarily because an ImmutablePass can "require" another ImmutablePass,
/// and if it does, the overloaded version of initializePass may get access to
/// these passes with getAnalysis<>.
///
virtual void initializePass();
virtual ImmutablePass *getAsImmutablePass() { return this; }
/// ImmutablePasses are never run.
///
bool runOnModule(Module &) { return false; }
explicit ImmutablePass(char &pid)
: ModulePass(pid) {}
// Force out-of-line virtual method.
virtual ~ImmutablePass();
};
//===----------------------------------------------------------------------===//
/// FunctionPass class - This class is used to implement most global
/// optimizations. Optimizations should subclass this class if they meet the
/// following constraints:
///
/// 1. Optimizations are organized globally, i.e., a function at a time
/// 2. Optimizing a function does not cause the addition or removal of any
/// functions in the module
///
class FunctionPass : public Pass {
public:
explicit FunctionPass(char &pid) : Pass(PT_Function, pid) {}
/// createPrinterPass - Get a function printer pass.
Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
/// doInitialization - Virtual method overridden by subclasses to do
/// any necessary per-module initialization.
///
virtual bool doInitialization(Module &);
/// runOnFunction - Virtual method overriden by subclasses to do the
/// per-function processing of the pass.
///
virtual bool runOnFunction(Function &F) = 0;
/// doFinalization - Virtual method overriden by subclasses to do any post
/// processing needed after all passes have run.
///
virtual bool doFinalization(Module &);
virtual void assignPassManager(PMStack &PMS,
PassManagerType T);
/// Return what kind of Pass Manager can manage this pass.
virtual PassManagerType getPotentialPassManagerType() const;
};
//===----------------------------------------------------------------------===//
/// BasicBlockPass class - This class is used to implement most local
/// optimizations. Optimizations should subclass this class if they
/// meet the following constraints:
/// 1. Optimizations are local, operating on either a basic block or
/// instruction at a time.
/// 2. Optimizations do not modify the CFG of the contained function, or any
/// other basic block in the function.
/// 3. Optimizations conform to all of the constraints of FunctionPasses.
///
class BasicBlockPass : public Pass {
public:
explicit BasicBlockPass(char &pid) : Pass(PT_BasicBlock, pid) {}
/// createPrinterPass - Get a basic block printer pass.
Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const;
/// doInitialization - Virtual method overridden by subclasses to do
/// any necessary per-module initialization.
///
virtual bool doInitialization(Module &);
/// doInitialization - Virtual method overridden by BasicBlockPass subclasses
/// to do any necessary per-function initialization.
///
virtual bool doInitialization(Function &);
/// runOnBasicBlock - Virtual method overriden by subclasses to do the
/// per-basicblock processing of the pass.
///
virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
/// doFinalization - Virtual method overriden by BasicBlockPass subclasses to
/// do any post processing needed after all passes have run.
///
virtual bool doFinalization(Function &);
/// doFinalization - Virtual method overriden by subclasses to do any post
/// processing needed after all passes have run.
///
virtual bool doFinalization(Module &);
virtual void assignPassManager(PMStack &PMS,
PassManagerType T);
/// Return what kind of Pass Manager can manage this pass.
virtual PassManagerType getPotentialPassManagerType() const;
};
/// If the user specifies the -time-passes argument on an LLVM tool command line
/// then the value of this boolean will be true, otherwise false.
/// @brief This is the storage for the -time-passes option.
extern bool TimePassesIsEnabled;
} // End llvm namespace
// Include support files that contain important APIs commonly used by Passes,
// but that we want to separate out to make it easier to read the header files.
//
#include "llvm/PassSupport.h"
#include "llvm/PassAnalysisSupport.h"
#endif
| reinhrst/panda | usr/lib/llvm-3.0/include/llvm/Pass.h | C | gpl-3.0 | 14,333 |
// Copyright (c) Aura development team - Licensed under GNU GPL
// For more information, see license file in the main folder
using Aura.Mabi.Const;
using Aura.Shared.Database;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
namespace Aura.Msgr.Database
{
public class MsgrDb : AuraDb
{
/// <summary>
/// Returns a user for the given values, either from the db,
/// or by creating a new one.
/// </summary>
/// <param name="accountId"></param>
/// <param name="characterEntityId"></param>
/// <param name="characterName"></param>
/// <param name="server"></param>
/// <param name="channelName"></param>
/// <returns></returns>
public User GetOrCreateContact(string accountId, long characterEntityId, string characterName, string server, string channelName)
{
using (var conn = this.Connection)
{
var user = new User();
user.AccountId = accountId;
user.CharacterId = characterEntityId;
user.Name = characterName;
user.Server = server;
user.ChannelName = channelName;
user.Status = ContactStatus.Online;
user.ChatOptions = ChatOptions.NotifyOnFriendLogIn;
user.LastLogin = DateTime.Now;
// Try to get contact from db
using (var mc = new MySqlCommand("SELECT * FROM `contacts` WHERE `characterEntityId` = @characterEntityId", conn))
{
mc.Parameters.AddWithValue("@characterEntityId", characterEntityId);
using (var reader = mc.ExecuteReader())
{
if (reader.Read())
{
user.Id = reader.GetInt32("contactId");
user.Status = (ContactStatus)reader.GetByte("status");
user.ChatOptions = (ChatOptions)reader.GetUInt32("chatOptions");
user.Nickname = reader.GetStringSafe("nickname") ?? "";
user.LastLogin = reader.GetDateTimeSafe("lastLogin");
if (!Enum.IsDefined(typeof(ContactStatus), user.Status) || user.Status == ContactStatus.None)
user.Status = ContactStatus.Online;
this.UpdateLastLogin(user);
return user;
}
}
}
// Create new contact
using (var cmd = new InsertCommand("INSERT INTO `contacts` {0}", conn))
{
cmd.Set("accountId", accountId);
cmd.Set("characterEntityId", characterEntityId);
cmd.Set("characterName", characterName);
cmd.Set("server", server);
cmd.Set("status", (byte)user.Status);
cmd.Set("chatOptions", (uint)user.ChatOptions);
cmd.Set("nickname", "");
cmd.Set("lastLogin", user.LastLogin);
cmd.Execute();
user.Id = (int)cmd.LastId;
return user;
}
}
}
/// <summary>
/// Updates contact's last login time.
/// </summary>
/// <param name="contact"></param>
private void UpdateLastLogin(Contact contact)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `contacts` SET {0} WHERE `contactId` = @contactId", conn))
{
cmd.AddParameter("@contactId", contact.Id);
cmd.Set("lastLogin", contact.LastLogin);
cmd.Execute();
}
}
/// <summary>
/// Returns contact with the given character id from the database
/// or null if it wasn't found.
/// </summary>
/// <param name="characterEntityId"></param>
/// <returns></returns>
public User GetUserByCharacterId(long characterEntityId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `contacts` WHERE `characterEntityId` = @characterEntityId", conn))
{
mc.Parameters.AddWithValue("@characterEntityId", characterEntityId);
using (var reader = mc.ExecuteReader())
{
if (!reader.Read())
return null;
var user = new User();
user.Id = reader.GetInt32("contactId");
user.AccountId = reader.GetString("accountId");
user.CharacterId = characterEntityId;
user.Name = reader.GetString("characterName");
user.Server = reader.GetString("server");
user.Status = (ContactStatus)reader.GetByte("status");
user.ChatOptions = (ChatOptions)reader.GetUInt32("chatOptions");
user.Nickname = reader.GetStringSafe("nickname") ?? "";
user.LastLogin = reader.GetDateTimeSafe("lastLogin");
if (!Enum.IsDefined(typeof(ContactStatus), user.Status) || user.Status == ContactStatus.None)
user.Status = ContactStatus.Online;
return user;
}
}
}
/// <summary>
/// Returns friend for invitation, or null if the user doesn't exist.
/// </summary>
/// <param name="characterName"></param>
/// <param name="server"></param>
/// <returns></returns>
public Friend GetFriendFromUser(string characterName, string server)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `contacts` WHERE `characterName` = @characterName AND `server` = @server", conn))
{
mc.Parameters.AddWithValue("@characterName", characterName);
mc.Parameters.AddWithValue("@server", server);
using (var reader = mc.ExecuteReader())
{
if (!reader.Read())
return null;
var friend = new Friend();
friend.AccountId = reader.GetString("accountId");
friend.Name = characterName;
friend.Server = server;
friend.Id = reader.GetInt32("contactId");
friend.Status = (ContactStatus)reader.GetByte("status");
return friend;
}
}
}
/// <summary>
/// Returns all notes for user.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public List<Note> GetNotes(User user)
{
var result = new List<Note>();
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `notes` WHERE `receiver` = @receiver", conn))
{
mc.Parameters.AddWithValue("@receiver", user.FullName);
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var note = this.ReadNote(reader);
if (note == null)
continue;
result.Add(note);
}
}
}
return result;
}
/// <summary>
/// Returns note with given id, or null on error.
/// </summary>
/// <param name="noteId"></param>
/// <returns></returns>
public Note GetNote(long noteId)
{
Note note = null;
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `notes` WHERE `noteId` = @noteId", conn))
{
mc.Parameters.AddWithValue("@noteId", noteId);
using (var reader = mc.ExecuteReader())
{
if (reader.Read())
note = this.ReadNote(reader);
}
}
return note;
}
/// <summary>
/// Reads note from reader, returns null on error.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private Note ReadNote(MySqlDataReader reader)
{
var note = new Note();
note.Id = reader.GetInt64("noteId");
note.Sender = reader.GetStringSafe("sender");
note.Receiver = reader.GetStringSafe("receiver");
note.Message = reader.GetStringSafe("message");
note.Time = reader.GetDateTimeSafe("time");
note.Read = reader.GetBoolean("read");
var split = note.Sender.Split('@');
if (split.Length != 2)
return null;
note.FromCharacterName = split[0];
note.FromServer = split[1];
return note;
}
/// <summary>
/// Sets read flag for given note.
/// </summary>
/// <param name="noteId"></param>
public void SetNoteRead(long noteId)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `notes` SET {0} WHERE `noteId` = @noteId", conn))
{
cmd.Set("read", true);
cmd.AddParameter("@noteId", noteId);
cmd.Execute();
}
}
/// <summary>
/// Adds note to database.
/// </summary>
/// <param name="noteId"></param>
public void AddNote(string sender, string receiver, string message)
{
using (var conn = this.Connection)
using (var cmd = new InsertCommand("INSERT INTO `notes` {0}", conn))
{
cmd.Set("sender", sender);
cmd.Set("receiver", receiver);
cmd.Set("message", message);
cmd.Set("time", DateTime.Now);
cmd.Execute();
}
}
/// <summary>
/// Deletes note from database.
/// </summary>
/// <param name="receiver"></param>
/// <param name="noteId"></param>
public void DeleteNote(string receiver, long noteId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("DELETE FROM `notes` WHERE `receiver` = @receiver AND `noteId` = @noteId", conn))
{
mc.Parameters.AddWithValue("@receiver", receiver);
mc.Parameters.AddWithValue("@noteId", noteId);
mc.ExecuteNonQuery();
}
}
/// <summary>
/// Returns first note with an id higher than the given one,
/// or null if none exist.
/// </summary>
/// <param name="receiver"></param>
/// <param name="noteId"></param>
/// <returns></returns>
public Note GetLatestUnreadNote(string receiver, long noteId)
{
Note note = null;
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `notes` WHERE `receiver` = @receiver AND `noteId` > @noteId AND `read` = 0 ORDER BY `noteId` DESC LIMIT 1", conn))
{
mc.Parameters.AddWithValue("@receiver", receiver);
mc.Parameters.AddWithValue("@noteId", noteId);
using (var reader = mc.ExecuteReader())
{
if (reader.Read())
note = this.ReadNote(reader);
}
}
return note;
}
/// <summary>
/// Saves user's options to database.
/// </summary>
/// <param name="user"></param>
public void SaveOptions(User user)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `contacts` SET {0} WHERE `contactId` = @contactId", conn))
{
cmd.Set("status", (byte)user.Status);
cmd.Set("chatOptions", (uint)user.ChatOptions);
cmd.Set("nickname", user.Nickname ?? "");
cmd.AddParameter("@contactId", user.Id);
cmd.Execute();
}
}
/// <summary>
/// Returns list of all groups in user's friend list.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public ICollection<Group> GetGroups(User user)
{
var result = new Dictionary<int, Group>();
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT * FROM `groups` WHERE `contactId` = @contactId", conn))
{
mc.Parameters.AddWithValue("@contactId", user.Id);
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var group = new Group();
group.Id = reader.GetInt32("groupId");
group.Name = reader.GetStringSafe("name");
// Override duplicate ids
result[group.Id] = group;
}
}
}
return result.Values;
}
/// <summary>
/// Adds group to database.
/// </summary>
/// <param name="user"></param>
/// <param name="groupId"></param>
/// <param name="groupName"></param>
public void AddGroup(User user, Group group)
{
using (var conn = this.Connection)
using (var cmd = new InsertCommand("INSERT INTO `groups` {0}", conn))
{
cmd.Set("groupId", group.Id);
cmd.Set("contactId", user.Id);
cmd.Set("name", group.Name);
cmd.Execute();
}
}
/// <summary>
/// Renames group in database.
/// </summary>
/// <param name="user"></param>
/// <param name="groupId"></param>
/// <param name="groupName"></param>
public void RenameGroup(User user, int groupId, string groupName)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `groups` SET {0} WHERE `groupId` = @groupId AND `contactId` = @contactId", conn))
{
cmd.Set("name", groupName);
cmd.AddParameter("@groupId", groupId);
cmd.AddParameter("@contactId", user.Id);
cmd.Execute();
}
}
/// <summary>
/// Changes group the friend is in in the database.
/// </summary>
/// <param name="user"></param>
/// <param name="friendContactId"></param>
/// <param name="groupId"></param>
public void ChangeGroup(User user, int friendContactId, int groupId)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `friends` SET {0} WHERE `userId1` = @userId1 AND `userId2` = @userId2", conn))
{
cmd.Set("groupId", groupId);
cmd.AddParameter("@userId1", user.Id);
cmd.AddParameter("@userId2", friendContactId);
cmd.Execute();
}
}
/// <summary>
/// Deletes group from database and moves friends in that group to ETC.
/// </summary>
/// <param name="user"></param>
/// <param name="groupId"></param>
public void DeleteGroup(User user, int groupId)
{
using (var conn = this.Connection)
{
// Move friends
using (var cmd = new UpdateCommand("UPDATE `friends` SET {0} WHERE `userId1` = @userId1 AND `groupId` = @oldGroupId", conn))
{
cmd.Set("groupId", -1);
cmd.AddParameter("@userId1", user.Id);
cmd.AddParameter("@oldGroupId", groupId);
cmd.Execute();
}
// Delete group
using (var mc = new MySqlCommand("DELETE FROM `groups` WHERE `contactId` = @contactId AND `groupId` = @groupId", conn))
{
mc.Parameters.AddWithValue("@contactId", user.Id);
mc.Parameters.AddWithValue("@groupId", groupId);
mc.ExecuteNonQuery();
}
}
}
/// <summary>
/// Returns list of friends for user.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public List<Friend> GetFriends(User user)
{
var result = new List<Friend>();
using (var conn = this.Connection)
using (var mc = new MySqlCommand(
"SELECT f.userId2 AS friendId, c.characterName AS friendName, c.server AS friendServer, f.groupId AS groupId, f.status AS status " +
"FROM `friends` AS f " +
"INNER JOIN `contacts` AS c ON `f`.`userId2` = `c`.`contactId` " +
"WHERE `f`.`userId1` = @userId", conn))
{
mc.Parameters.AddWithValue("@userId", user.Id);
using (var reader = mc.ExecuteReader())
{
while (reader.Read())
{
var friend = new Friend();
friend.Id = reader.GetInt32("friendId");
friend.Name = reader.GetStringSafe("friendName");
friend.Server = reader.GetStringSafe("friendServer");
friend.GroupId = reader.GetInt32("groupId");
friend.FriendshipStatus = (FriendshipStatus)reader.GetByte("status");
result.Add(friend);
}
}
}
return result;
}
/// <summary>
/// Creates friend entries for user and friend with status inviting/invited.
/// </summary>
/// <param name="userId"></param>
/// <param name="friendId"></param>
public void InviteFriend(int userId, int friendId)
{
using (var conn = this.Connection)
using (var transaction = conn.BeginTransaction())
{
using (var cmd = new InsertCommand("INSERT INTO `friends` {0}", conn, transaction))
{
cmd.Set("userId1", userId);
cmd.Set("userId2", friendId);
cmd.Set("groupId", -1);
cmd.Set("status", (byte)FriendshipStatus.Inviting);
cmd.Execute();
}
using (var cmd = new InsertCommand("INSERT INTO `friends` {0}", conn, transaction))
{
cmd.Set("userId1", friendId);
cmd.Set("userId2", userId);
cmd.Set("groupId", -1);
cmd.Set("status", (byte)FriendshipStatus.Invited);
cmd.Execute();
}
transaction.Commit();
}
}
/// <summary>
/// Creates friend entry for contact on user with the blacklist status.
/// </summary>
/// <param name="userId"></param>
/// <param name="contactId"></param>
public void Blacklist(int userId, int contactId)
{
using (var conn = this.Connection)
using (var cmd = new InsertCommand("INSERT INTO `friends` {0}", conn))
{
cmd.Set("userId1", userId);
cmd.Set("userId2", contactId);
cmd.Set("groupId", -4);
cmd.Set("status", (byte)FriendshipStatus.Blacklist);
cmd.Execute();
}
}
/// <summary>
/// Returns true if user blacklisted contact.
/// </summary>
/// <param name="userId"></param>
/// <param name="contactId"></param>
public bool IsBlacklisted(int userId, int contactId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT `friendId` FROM `friends` WHERE `userId1` = @userId1 AND `userId2` = @userId2 AND `status` = 7", conn))
{
mc.Parameters.AddWithValue("@userId1", userId);
mc.Parameters.AddWithValue("@userId2", contactId);
using (var reader = mc.ExecuteReader())
return reader.HasRows;
}
}
/// <summary>
/// Returns the amount of friends the given contact has.
/// </summary>
/// <param name="contactId"></param>
/// <returns></returns>
public long CountFriends(int contactId)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("SELECT COUNT(`friendId`) FROM `friends` WHERE `userId1` = @userId", conn))
{
mc.Parameters.AddWithValue("@userId", contactId);
return (long)mc.ExecuteScalar();
}
}
/// <summary>
/// Deletes friend entries between the two users.
/// </summary>
/// <param name="contactId"></param>
/// <returns></returns>
public void DeleteFriend(int contactId1, int contactId2)
{
using (var conn = this.Connection)
using (var mc = new MySqlCommand("DELETE FROM `friends` WHERE (`userId1` = @userId1 AND `userId2` = @userId2) OR (`userId2` = @userId1 AND `userId1` = @userId2)", conn))
{
mc.Parameters.AddWithValue("@userId1", contactId1);
mc.Parameters.AddWithValue("@userId2", contactId2);
mc.ExecuteNonQuery();
}
}
/// <summary>
/// Updates friendship status between the two users.
/// </summary>
/// <param name="contactId"></param>
/// <returns></returns>
public void SetFriendshipStatus(int contactId1, int contactId2, FriendshipStatus status)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `friends` SET {0} WHERE (`userId1` = @userId1 AND `userId2` = @userId2) OR (`userId2` = @userId1 AND `userId1` = @userId2)", conn))
{
cmd.Set("status", (byte)status);
cmd.AddParameter("@userId1", contactId1);
cmd.AddParameter("@userId2", contactId2);
cmd.Execute();
}
}
/// <summary>
/// Updates friendship status for contact 1.
/// </summary>
/// <param name="contactId"></param>
/// <returns></returns>
public void SetFriendshipStatusOneSided(int contactId1, int contactId2, FriendshipStatus status)
{
using (var conn = this.Connection)
using (var cmd = new UpdateCommand("UPDATE `friends` SET {0} WHERE (`userId1` = @userId1 AND `userId2` = @userId2)", conn))
{
cmd.Set("status", (byte)status);
cmd.AddParameter("@userId1", contactId1);
cmd.AddParameter("@userId2", contactId2);
cmd.Execute();
}
}
}
}
| xeroplz/aura | src/MsgrServer/Database/MsgrDb.cs | C# | gpl-3.0 | 18,465 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "testutil.h"
#include "apr_shm.h"
#include "apr_errno.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_thread_proc.h"
#include "apr_time.h"
#include "testshm.h"
#include "apr.h"
#if APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if APR_HAS_SHARED_MEMORY
#if APR_HAS_FORK
static int msgwait(int sleep_sec, int first_box, int last_box)
{
int i;
int recvd = 0;
apr_time_t start = apr_time_now();
apr_interval_time_t sleep_duration = apr_time_from_sec(sleep_sec);
while (apr_time_now() - start < sleep_duration) {
for (i = first_box; i < last_box; i++) {
if (boxes[i].msgavail && !strcmp(boxes[i].msg, MSG)) {
recvd++;
boxes[i].msgavail = 0; /* reset back to 0 */
/* reset the msg field. 1024 is a magic number and it should
* be a macro, but I am being lazy.
*/
memset(boxes[i].msg, 0, 1024);
}
}
apr_sleep(apr_time_make(0, 10000)); /* 10ms */
}
return recvd;
}
static void msgput(int boxnum, char *msg)
{
apr_cpystrn(boxes[boxnum].msg, msg, strlen(msg) + 1);
boxes[boxnum].msgavail = 1;
}
#endif /* APR_HAS_FORK */
static void test_anon_create(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
static void test_check_size(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
apr_size_t retsize;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
retsize = apr_shm_size_get(shm);
ABTS_SIZE_EQUAL(tc, SHARED_SIZE, retsize);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
static void test_shm_allocate(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
boxes = apr_shm_baseaddr_get(shm);
ABTS_PTR_NOTNULL(tc, boxes);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
#if APR_HAS_FORK
static void test_anon(abts_case *tc, void *data)
{
apr_proc_t proc;
apr_status_t rv;
apr_shm_t *shm;
apr_size_t retsize;
int cnt, i;
int recvd;
rv = apr_shm_create(&shm, SHARED_SIZE, NULL, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
ABTS_PTR_NOTNULL(tc, shm);
retsize = apr_shm_size_get(shm);
ABTS_INT_EQUAL(tc, SHARED_SIZE, retsize);
boxes = apr_shm_baseaddr_get(shm);
ABTS_PTR_NOTNULL(tc, boxes);
rv = apr_proc_fork(&proc, p);
if (rv == APR_INCHILD) { /* child */
int num = msgwait(5, 0, N_BOXES);
/* exit with the number of messages received so that the parent
* can check that all messages were received.
*/
exit(num);
}
else if (rv == APR_INPARENT) { /* parent */
i = N_BOXES;
cnt = 0;
while (cnt++ < N_MESSAGES) {
if ((i-=3) < 0) {
i += N_BOXES; /* start over at the top */
}
msgput(i, MSG);
apr_sleep(apr_time_make(0, 10000));
}
}
else {
ABTS_FAIL(tc, "apr_proc_fork failed");
}
/* wait for the child */
rv = apr_proc_wait(&proc, &recvd, NULL, APR_WAIT);
ABTS_INT_EQUAL(tc, N_MESSAGES, recvd);
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
#endif
static void test_named(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm = NULL;
apr_size_t retsize;
apr_proc_t pidproducer, pidconsumer;
apr_procattr_t *attr1 = NULL, *attr2 = NULL;
int sent, received;
apr_exit_why_e why;
const char *args[4];
apr_shm_remove(SHARED_FILENAME, p);
rv = apr_shm_create(&shm, SHARED_SIZE, SHARED_FILENAME, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
if (rv != APR_SUCCESS) {
return;
}
ABTS_PTR_NOTNULL(tc, shm);
retsize = apr_shm_size_get(shm);
ABTS_SIZE_EQUAL(tc, SHARED_SIZE, retsize);
boxes = apr_shm_baseaddr_get(shm);
ABTS_PTR_NOTNULL(tc, boxes);
rv = apr_procattr_create(&attr1, p);
ABTS_PTR_NOTNULL(tc, attr1);
APR_ASSERT_SUCCESS(tc, "Couldn't create attr1", rv);
rv = apr_procattr_cmdtype_set(attr1, APR_PROGRAM_ENV);
APR_ASSERT_SUCCESS(tc, "Couldn't set copy environment", rv);
args[0] = apr_pstrdup(p, "testshmproducer" EXTENSION);
args[1] = NULL;
rv = apr_proc_create(&pidproducer, TESTBINPATH "testshmproducer" EXTENSION, args,
NULL, attr1, p);
APR_ASSERT_SUCCESS(tc, "Couldn't launch producer", rv);
rv = apr_procattr_create(&attr2, p);
ABTS_PTR_NOTNULL(tc, attr2);
APR_ASSERT_SUCCESS(tc, "Couldn't create attr2", rv);
rv = apr_procattr_cmdtype_set(attr2, APR_PROGRAM_ENV);
APR_ASSERT_SUCCESS(tc, "Couldn't set copy environment", rv);
args[0] = apr_pstrdup(p, "testshmconsumer" EXTENSION);
rv = apr_proc_create(&pidconsumer, TESTBINPATH "testshmconsumer" EXTENSION, args,
NULL, attr2, p);
APR_ASSERT_SUCCESS(tc, "Couldn't launch consumer", rv);
rv = apr_proc_wait(&pidconsumer, &received, &why, APR_WAIT);
ABTS_INT_EQUAL(tc, APR_CHILD_DONE, rv);
ABTS_INT_EQUAL(tc, APR_PROC_EXIT, why);
rv = apr_proc_wait(&pidproducer, &sent, &why, APR_WAIT);
ABTS_INT_EQUAL(tc, APR_CHILD_DONE, rv);
ABTS_INT_EQUAL(tc, APR_PROC_EXIT, why);
/* Cleanup before testing that producer and consumer worked correctly.
* This way, if they didn't succeed, we can just run this test again
* without having to cleanup manually.
*/
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory",
apr_shm_destroy(shm));
ABTS_INT_EQUAL(tc, sent, received);
}
static void test_named_remove(abts_case *tc, void *data)
{
apr_status_t rv;
apr_shm_t *shm, *shm2;
apr_shm_remove(SHARED_FILENAME, p);
rv = apr_shm_create(&shm, SHARED_SIZE, SHARED_FILENAME, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
if (rv != APR_SUCCESS) {
return;
}
ABTS_PTR_NOTNULL(tc, shm);
rv = apr_shm_remove(SHARED_FILENAME, p);
/* On platforms which acknowledge the removal of the shared resource,
* ensure another of the same name may be created after removal;
*/
if (rv == APR_SUCCESS)
{
rv = apr_shm_create(&shm2, SHARED_SIZE, SHARED_FILENAME, p);
APR_ASSERT_SUCCESS(tc, "Error allocating shared memory block", rv);
if (rv != APR_SUCCESS) {
return;
}
ABTS_PTR_NOTNULL(tc, shm2);
rv = apr_shm_destroy(shm2);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
}
rv = apr_shm_destroy(shm);
APR_ASSERT_SUCCESS(tc, "Error destroying shared memory block", rv);
/* Now ensure no named resource remains which we may attach to */
rv = apr_shm_attach(&shm, SHARED_FILENAME, p);
ABTS_TRUE(tc, rv != 0);
}
#endif
abts_suite *testshm(abts_suite *suite)
{
suite = ADD_SUITE(suite)
#if APR_HAS_SHARED_MEMORY
abts_run_test(suite, test_anon_create, NULL);
abts_run_test(suite, test_check_size, NULL);
abts_run_test(suite, test_shm_allocate, NULL);
#if APR_HAS_FORK
abts_run_test(suite, test_anon, NULL);
#endif
abts_run_test(suite, test_named, NULL);
abts_run_test(suite, test_named_remove, NULL);
#endif
return suite;
}
| Kiddinglife/gecoengine | thirdparty/apr/test/testshm.c | C | gpl-3.0 | 9,081 |
package org.impact2585.lib2585;
/**
* SAM interface with a destroy() method
*/
@FunctionalInterface
public interface Destroyable{
/**
* destroy object
*/
public void destroy();
}
| 2585Robophiles/Lib2585 | src/org/impact2585/lib2585/Destroyable.java | Java | gpl-3.0 | 205 |
/*
===========================================================================
ARX FATALIS GPL Source Code
Copyright (C) 1999-2010 Arkane Studios SA, a ZeniMax Media company.
This file is part of the Arx Fatalis GPL Source Code ('Arx Fatalis Source Code').
Arx Fatalis Source Code 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.
Arx Fatalis Source Code 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 Arx Fatalis Source Code. If not, see
<http://www.gnu.org/licenses/>.
In addition, the Arx Fatalis Source Code is also subject to certain additional terms. You should have received a copy of these
additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Arx
Fatalis Source Code. If not, please request a copy in writing from Arkane Studios at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing Arkane Studios, c/o
ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
//////////////////////////////////////////////////////////////////////////////////////
// @@ @@@ @@@ @@ @@@@@ //
// @@@ @@@@@@ @@@ @@ @@@@ @@@ @@@ //
// @@@ @@@@@@@ @@@ @@@@ @@@@ @@ @@@@ //
// @@@ @@ @@@@ @@@ @@@@@ @@@@@@ @@@ @@@ //
// @@@@@ @@ @@@@ @@@ @@@@@ @@@@@@@ @@@ @ @@@ //
// @@@@@ @@ @@@@ @@@@@@@@ @@@@ @@@ @@@@@ @@ @@@@@@@ //
// @@ @@@ @@ @@@@ @@@@@@@ @@@ @@@ @@@@@@ @@ @@@@ //
// @@@ @@@ @@@ @@@@ @@@@@ @@@@@@@@@ @@@@@@@ @@@ @@@@ //
// @@@ @@@@ @@@@@@@ @@@@@@ @@@ @@@@ @@@ @@@ @@@ @@@@ //
// @@@@@@@@ @@@@@ @@@@@@@@@@ @@@ @@@ @@@ @@@ @@@ @@@@@ //
// @@@ @@@@ @@@@ @@@ @@@@@@@ @@@ @@@ @@@@ @@@ @@@@ @@@@@ //
//@@@ @@@@ @@@@@ @@@ @@@@@@ @@ @@@ @@@@ @@@@@@@ @@@@@ @@@@@ //
//@@@ @@@@@ @@@@@ @@@@ @@@ @@ @@ @@@@ @@@@@@@ @@@@@@@@@ //
//@@@ @@@@ @@@@@@@ @@@@ @@ @@ @@@@ @@@@@ @@@@@ //
//@@@ @@@@ @@@@@@@ @@@@ @@ @@ @@@@ @@@@@ @@ //
//@@@ @@@ @@@ @@@@@ @@ @@@ //
// @@@ @@@ @@ @@ STUDIOS //
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// CSpellFx_Lvl04.h
//////////////////////////////////////////////////////////////////////////////////////
//
// Description:
// ARX Spells FX Level 04
//
// Updates: (date) (person) (update)
//////////////////////////////////////////////////////////////////////////////////////
// Refer to CSpellFx.h for details
//
// Copyright (c) 1999-2001 ARKANE Studios SA. All rights reserved
//////////////////////////////////////////////////////////////////////////////////////
#ifndef ARX_CSPELLFX_LVL04_H
#define ARX_CSPELLFX_LVL04_H
#include "ARX_CParticles.h"
class CParticleSystem;
class CSpellFx;
//-----------------------------------------------------------------------------
// Done By : Didier Pédreno
// Status :
//-----------------------------------------------------------------------------
class CBless: public CSpellFx
{
public:
bool bDone;
int iNumber;
EERIE_3D eSrc;
EERIE_3D eTarget;
TextureContainer * tex_p1;
TextureContainer * tex_sol;
float fRot;
float fRotPerMSec;
int iNbPS;
CParticleSystem psTab[256];
int iNpcTab[256];
int iMax;
float fSize;
CParticleSystem pPS;
public:
CBless(LPDIRECT3DDEVICE7 m_pd3dDevice);
// accesseurs
public:
void SetPos(EERIE_3D);
void Set_Angle(EERIE_3D);
// surcharge
public:
void Create(EERIE_3D, float afBeta = 0);
void Update(unsigned long);
float Render(LPDIRECT3DDEVICE7);
void Kill();
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Done By : Didier Pédreno
// Status :
//-----------------------------------------------------------------------------
class CDispellField: public CSpellFx
{
public:
bool bDone;
int iNumber;
EERIE_3D eSrc;
EERIE_3D eTarget;
TextureContainer * tex_p1;
TextureContainer * tex_p2;
int iMax;
float fSize;
public:
// accesseurs
public:
void SetPos(EERIE_3D);
// surcharge
public:
void Create(EERIE_3D, float afBeta = 0);
void Kill();
void Update(unsigned long);
float Render(LPDIRECT3DDEVICE7);
};
//-----------------------------------------------------------------------------
class CFireProtection: public CSpellFx
{
private:
int iNpc;
public:
CFireProtection();
~CFireProtection();
// surcharge
void Create(long, int);
void Update(unsigned long);
float Render(LPDIRECT3DDEVICE7);
};
//-----------------------------------------------------------------------------
class CColdProtection: public CSpellFx
{
private:
int iNpc;
public:
CColdProtection();
~CColdProtection();
// surcharge
void Create(long, int);
void Update(unsigned long);
float Render(LPDIRECT3DDEVICE7);
};
//-----------------------------------------------------------------------------
// Done By :
// Status :
//-----------------------------------------------------------------------------
class CTelekinesis: public CSpellFx
{
public:
bool bDone;
int iNumber;
EERIE_3D eSrc;
EERIE_3D eTarget;
TextureContainer * tex_p1;
TextureContainer * tex_p2;
int iMax;
float fSize;
public:
~CTelekinesis();
// accesseurs
public:
void SetPos(EERIE_3D);
// surcharge
public:
void Create(EERIE_3D, float afBeta = 0);
void Kill();
void Update(unsigned long);
float Render(LPDIRECT3DDEVICE7);
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Done By :
// Status :
//-----------------------------------------------------------------------------
class CCurse: public CSpellFx
{
public:
bool bDone;
int iNumber;
EERIE_3D eSrc;
EERIE_3D eTarget;
TextureContainer * tex_p1;
TextureContainer * tex_p2;
float fRot;
float fRotPerMSec;
public:
CCurse(LPDIRECT3DDEVICE7 m_pd3dDevice);
~CCurse();
// accesseurs
public:
void SetPos(EERIE_3D);
// surcharge
public:
void Create(EERIE_3D, float afBeta = 0);
void Kill();
void Update(unsigned long);
float Render(LPDIRECT3DDEVICE7, EERIE_3D * pos);
};
//-----------------------------------------------------------------------------
#endif
| johndrinkwater/arx-fatalis | src/DANAE/ARX_SpellFx_Lvl04.h | C | gpl-3.0 | 7,681 |
# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.exceptions import UserError
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT
class MaintenanceStage(models.Model):
""" Model for case stages. This models the main stages of a Maintenance Request management flow. """
_name = 'maintenance.stage'
_description = 'Maintenance Stage'
_order = 'sequence, id'
name = fields.Char('Name', required=True, translate=True)
sequence = fields.Integer('Sequence', default=20)
fold = fields.Boolean('Folded in Maintenance Pipe')
done = fields.Boolean('Request Done')
class MaintenanceEquipmentCategory(models.Model):
_name = 'maintenance.equipment.category'
_inherit = ['mail.alias.mixin', 'mail.thread']
_description = 'Asset Category'
@api.one
@api.depends('equipment_ids')
def _compute_fold(self):
self.fold = False if self.equipment_count else True
name = fields.Char('Category Name', required=True, translate=True)
technician_user_id = fields.Many2one('res.users', 'Responsible', track_visibility='onchange', default=lambda self: self.env.uid, oldname='user_id')
color = fields.Integer('Color Index')
note = fields.Text('Comments', translate=True)
equipment_ids = fields.One2many('maintenance.equipment', 'category_id', string='Equipments', copy=False)
equipment_count = fields.Integer(string="Equipment", compute='_compute_equipment_count')
maintenance_ids = fields.One2many('maintenance.request', 'category_id', copy=False)
maintenance_count = fields.Integer(string="Maintenance", compute='_compute_maintenance_count')
alias_id = fields.Many2one(
'mail.alias', 'Alias', ondelete='restrict', required=True,
help="Email alias for this equipment category. New emails will automatically "
"create new maintenance request for this equipment category.")
fold = fields.Boolean(string='Folded in Maintenance Pipe', compute='_compute_fold', store=True)
@api.multi
def _compute_equipment_count(self):
equipment_data = self.env['maintenance.equipment'].read_group([('category_id', 'in', self.ids)], ['category_id'], ['category_id'])
mapped_data = dict([(m['category_id'][0], m['category_id_count']) for m in equipment_data])
for category in self:
category.equipment_count = mapped_data.get(category.id, 0)
@api.multi
def _compute_maintenance_count(self):
maintenance_data = self.env['maintenance.request'].read_group([('category_id', 'in', self.ids)], ['category_id'], ['category_id'])
mapped_data = dict([(m['category_id'][0], m['category_id_count']) for m in maintenance_data])
for category in self:
category.maintenance_count = mapped_data.get(category.id, 0)
@api.model
def create(self, vals):
self = self.with_context(alias_model_name='maintenance.request', alias_parent_model_name=self._name)
if not vals.get('alias_name'):
vals['alias_name'] = vals.get('name')
category_id = super(MaintenanceEquipmentCategory, self).create(vals)
category_id.alias_id.write({'alias_parent_thread_id': category_id.id, 'alias_defaults': {'category_id': category_id.id}})
return category_id
@api.multi
def unlink(self):
MailAlias = self.env['mail.alias']
for category in self:
if category.equipment_ids or category.maintenance_ids:
raise UserError(_("You cannot delete an equipment category containing equipments or maintenance requests."))
MailAlias += category.alias_id
res = super(MaintenanceEquipmentCategory, self).unlink()
MailAlias.unlink()
return res
def get_alias_model_name(self, vals):
return vals.get('alias_model', 'maintenance.equipment')
def get_alias_values(self):
values = super(MaintenanceEquipmentCategory, self).get_alias_values()
values['alias_defaults'] = {'category_id': self.id}
return values
class MaintenanceEquipment(models.Model):
_name = 'maintenance.equipment'
_inherit = ['mail.thread', 'mail.activity.mixin']
_description = 'Equipment'
@api.multi
def _track_subtype(self, init_values):
self.ensure_one()
if 'owner_user_id' in init_values and self.owner_user_id:
return 'maintenance.mt_mat_assign'
return super(MaintenanceEquipment, self)._track_subtype(init_values)
@api.multi
def name_get(self):
result = []
for record in self:
if record.name and record.serial_no:
result.append((record.id, record.name + '/' + record.serial_no))
if record.name and not record.serial_no:
result.append((record.id, record.name))
return result
@api.model
def name_search(self, name, args=None, operator='ilike', limit=100):
args = args or []
recs = self.browse()
if name:
recs = self.search([('name', '=', name)] + args, limit=limit)
if not recs:
recs = self.search([('name', operator, name)] + args, limit=limit)
return recs.name_get()
name = fields.Char('Equipment Name', required=True, translate=True)
active = fields.Boolean(default=True)
technician_user_id = fields.Many2one('res.users', string='Technician', track_visibility='onchange', oldname='user_id')
owner_user_id = fields.Many2one('res.users', string='Owner', track_visibility='onchange')
category_id = fields.Many2one('maintenance.equipment.category', string='Equipment Category',
track_visibility='onchange', group_expand='_read_group_category_ids')
partner_id = fields.Many2one('res.partner', string='Vendor', domain="[('supplier', '=', 1)]")
partner_ref = fields.Char('Vendor Reference')
location = fields.Char('Location')
model = fields.Char('Model')
serial_no = fields.Char('Serial Number', copy=False)
assign_date = fields.Date('Assigned Date', track_visibility='onchange')
cost = fields.Float('Cost')
note = fields.Text('Note')
warranty = fields.Date('Warranty')
color = fields.Integer('Color Index')
scrap_date = fields.Date('Scrap Date')
maintenance_ids = fields.One2many('maintenance.request', 'equipment_id')
maintenance_count = fields.Integer(compute='_compute_maintenance_count', string="Maintenance", store=True)
maintenance_open_count = fields.Integer(compute='_compute_maintenance_count', string="Current Maintenance", store=True)
period = fields.Integer('Days between each preventive maintenance')
next_action_date = fields.Date(compute='_compute_next_maintenance', string='Date of the next preventive maintenance', store=True)
maintenance_team_id = fields.Many2one('maintenance.team', string='Maintenance Team')
maintenance_duration = fields.Float(help="Maintenance Duration in hours.")
@api.depends('period', 'maintenance_ids.request_date', 'maintenance_ids.close_date')
def _compute_next_maintenance(self):
date_now = fields.Date.context_today(self)
for equipment in self.filtered(lambda x: x.period > 0):
next_maintenance_todo = self.env['maintenance.request'].search([
('equipment_id', '=', equipment.id),
('maintenance_type', '=', 'preventive'),
('stage_id.done', '!=', True),
('close_date', '=', False)], order="request_date asc", limit=1)
last_maintenance_done = self.env['maintenance.request'].search([
('equipment_id', '=', equipment.id),
('maintenance_type', '=', 'preventive'),
('stage_id.done', '=', True),
('close_date', '!=', False)], order="close_date desc", limit=1)
if next_maintenance_todo and last_maintenance_done:
next_date = next_maintenance_todo.request_date
date_gap = fields.Date.from_string(next_maintenance_todo.request_date) - fields.Date.from_string(last_maintenance_done.close_date)
# If the gap between the last_maintenance_done and the next_maintenance_todo one is bigger than 2 times the period and next request is in the future
# We use 2 times the period to avoid creation too closed request from a manually one created
if date_gap > timedelta(0) and date_gap > timedelta(days=equipment.period) * 2 and fields.Date.from_string(next_maintenance_todo.request_date) > fields.Date.from_string(date_now):
# If the new date still in the past, we set it for today
if fields.Date.from_string(last_maintenance_done.close_date) + timedelta(days=equipment.period) < fields.Date.from_string(date_now):
next_date = date_now
else:
next_date = fields.Date.to_string(fields.Date.from_string(last_maintenance_done.close_date) + timedelta(days=equipment.period))
elif next_maintenance_todo:
next_date = next_maintenance_todo.request_date
date_gap = fields.Date.from_string(next_maintenance_todo.request_date) - fields.Date.from_string(date_now)
# If next maintenance to do is in the future, and in more than 2 times the period, we insert an new request
# We use 2 times the period to avoid creation too closed request from a manually one created
if date_gap > timedelta(0) and date_gap > timedelta(days=equipment.period) * 2:
next_date = fields.Date.to_string(fields.Date.from_string(date_now)+timedelta(days=equipment.period))
elif last_maintenance_done:
next_date = fields.Date.from_string(last_maintenance_done.close_date)+timedelta(days=equipment.period)
# If when we add the period to the last maintenance done and we still in past, we plan it for today
if next_date < fields.Date.from_string(date_now):
next_date = date_now
else:
next_date = fields.Date.to_string(fields.Date.from_string(date_now) + timedelta(days=equipment.period))
equipment.next_action_date = next_date
@api.one
@api.depends('maintenance_ids.stage_id.done')
def _compute_maintenance_count(self):
self.maintenance_count = len(self.maintenance_ids)
self.maintenance_open_count = len(self.maintenance_ids.filtered(lambda x: not x.stage_id.done))
@api.onchange('category_id')
def _onchange_category_id(self):
self.technician_user_id = self.category_id.technician_user_id
_sql_constraints = [
('serial_no', 'unique(serial_no)', "Another asset already exists with this serial number!"),
]
@api.model
def create(self, vals):
equipment = super(MaintenanceEquipment, self).create(vals)
if equipment.owner_user_id:
equipment.message_subscribe_users(user_ids=[equipment.owner_user_id.id])
return equipment
@api.multi
def write(self, vals):
if vals.get('owner_user_id'):
self.message_subscribe_users(user_ids=[vals['owner_user_id']])
return super(MaintenanceEquipment, self).write(vals)
@api.model
def _read_group_category_ids(self, categories, domain, order):
""" Read group customization in order to display all the categories in
the kanban view, even if they are empty.
"""
category_ids = categories._search([], order=order, access_rights_uid=SUPERUSER_ID)
return categories.browse(category_ids)
def _create_new_request(self, date):
self.ensure_one()
self.env['maintenance.request'].create({
'name': _('Preventive Maintenance - %s') % self.name,
'request_date': date,
'schedule_date': date,
'category_id': self.category_id.id,
'equipment_id': self.id,
'maintenance_type': 'preventive',
'owner_user_id': self.owner_user_id.id,
'technician_user_id': self.technician_user_id.id,
'maintenance_team_id': self.maintenance_team_id.id,
'duration': self.maintenance_duration,
})
@api.model
def _cron_generate_requests(self):
"""
Generates maintenance request on the next_action_date or today if none exists
"""
for equipment in self.search([('period', '>', 0)]):
next_requests = self.env['maintenance.request'].search([('stage_id.done', '=', False),
('equipment_id', '=', equipment.id),
('maintenance_type', '=', 'preventive'),
('request_date', '=', equipment.next_action_date)])
if not next_requests:
equipment._create_new_request(equipment.next_action_date)
class MaintenanceRequest(models.Model):
_name = 'maintenance.request'
_inherit = ['mail.thread', 'mail.activity.mixin']
_description = 'Maintenance Requests'
_order = "id desc"
@api.returns('self')
def _default_stage(self):
return self.env['maintenance.stage'].search([], limit=1)
@api.multi
def _track_subtype(self, init_values):
self.ensure_one()
if 'stage_id' in init_values and self.stage_id.sequence <= 1:
return 'maintenance.mt_req_created'
elif 'stage_id' in init_values and self.stage_id.sequence > 1:
return 'maintenance.mt_req_status'
return super(MaintenanceRequest, self)._track_subtype(init_values)
def _get_default_team_id(self):
return self.env.ref('maintenance.equipment_team_maintenance', raise_if_not_found=False)
name = fields.Char('Subjects', required=True)
description = fields.Text('Description')
request_date = fields.Date('Request Date', track_visibility='onchange', default=fields.Date.context_today,
help="Date requested for the maintenance to happen")
owner_user_id = fields.Many2one('res.users', string='Created by', default=lambda s: s.env.uid)
category_id = fields.Many2one('maintenance.equipment.category', related='equipment_id.category_id', string='Category', store=True, readonly=True)
equipment_id = fields.Many2one('maintenance.equipment', string='Equipment', index=True)
technician_user_id = fields.Many2one('res.users', string='Owner', track_visibility='onchange', oldname='user_id')
stage_id = fields.Many2one('maintenance.stage', string='Stage', track_visibility='onchange',
group_expand='_read_group_stage_ids', default=_default_stage)
priority = fields.Selection([('0', 'Very Low'), ('1', 'Low'), ('2', 'Normal'), ('3', 'High')], string='Priority')
color = fields.Integer('Color Index')
close_date = fields.Date('Close Date', help="Date the maintenance was finished. ")
kanban_state = fields.Selection([('normal', 'In Progress'), ('blocked', 'Blocked'), ('done', 'Ready for next stage')],
string='Kanban State', required=True, default='normal', track_visibility='onchange')
# active = fields.Boolean(default=True, help="Set active to false to hide the maintenance request without deleting it.")
archive = fields.Boolean(default=False, help="Set archive to true to hide the maintenance request without deleting it.")
maintenance_type = fields.Selection([('corrective', 'Corrective'), ('preventive', 'Preventive')], string='Maintenance Type', default="corrective")
schedule_date = fields.Datetime('Scheduled Date', help="Date the maintenance team plans the maintenance. It should not differ much from the Request Date. ")
maintenance_team_id = fields.Many2one('maintenance.team', string='Team', required=True, default=_get_default_team_id)
duration = fields.Float(help="Duration in minutes and seconds.")
@api.multi
def archive_equipment_request(self):
self.write({'archive': True})
@api.multi
def reset_equipment_request(self):
""" Reinsert the maintenance request into the maintenance pipe in the first stage"""
first_stage_obj = self.env['maintenance.stage'].search([], order="sequence asc", limit=1)
# self.write({'active': True, 'stage_id': first_stage_obj.id})
self.write({'archive': False, 'stage_id': first_stage_obj.id})
@api.onchange('equipment_id')
def onchange_equipment_id(self):
if self.equipment_id:
self.technician_user_id = self.equipment_id.technician_user_id if self.equipment_id.technician_user_id else self.equipment_id.category_id.technician_user_id
self.category_id = self.equipment_id.category_id
if self.equipment_id.maintenance_team_id:
self.maintenance_team_id = self.equipment_id.maintenance_team_id.id
@api.onchange('category_id')
def onchange_category_id(self):
if not self.technician_user_id or not self.equipment_id or (self.technician_user_id and not self.equipment_id.technician_user_id):
self.technician_user_id = self.category_id.technician_user_id
@api.model
def create(self, vals):
# context: no_log, because subtype already handle this
self = self.with_context(mail_create_nolog=True)
request = super(MaintenanceRequest, self).create(vals)
if request.owner_user_id or request.technician_user_id:
request._add_followers()
if request.equipment_id and not request.maintenance_team_id:
request.maintenance_team_id = request.equipment_id.maintenance_team_id
return request
@api.multi
def write(self, vals):
# Overridden to reset the kanban_state to normal whenever
# the stage (stage_id) of the Maintenance Request changes.
if vals and 'kanban_state' not in vals and 'stage_id' in vals:
vals['kanban_state'] = 'normal'
res = super(MaintenanceRequest, self).write(vals)
if vals.get('owner_user_id') or vals.get('technician_user_id'):
self._add_followers()
if self.stage_id.done and 'stage_id' in vals:
self.write({'close_date': fields.Date.today()})
return res
def _add_followers(self):
for request in self:
user_ids = (request.owner_user_id + request.technician_user_id).ids
request.message_subscribe_users(user_ids=user_ids)
@api.model
def _read_group_stage_ids(self, stages, domain, order):
""" Read group customization in order to display all the stages in the
kanban view, even if they are empty
"""
stage_ids = stages._search([], order=order, access_rights_uid=SUPERUSER_ID)
return stages.browse(stage_ids)
class MaintenanceTeam(models.Model):
_name = 'maintenance.team'
_description = 'Maintenance Teams'
name = fields.Char(required=True)
member_ids = fields.Many2many('res.users', 'maintenance_team_users_rel', string="Team Members")
color = fields.Integer("Color Index", default=1)
request_ids = fields.One2many('maintenance.request', 'maintenance_team_id', copy=False)
equipment_ids = fields.One2many('maintenance.equipment', 'maintenance_team_id', copy=False)
# For the dashboard only
todo_request_ids = fields.One2many('maintenance.request', copy=False, compute='_compute_todo_requests')
todo_request_count = fields.Integer(compute='_compute_todo_requests')
todo_request_count_date = fields.Integer(compute='_compute_todo_requests')
todo_request_count_high_priority = fields.Integer(compute='_compute_todo_requests')
todo_request_count_block = fields.Integer(compute='_compute_todo_requests')
todo_request_count_unscheduled = fields.Integer(compute='_compute_todo_requests')
@api.one
@api.depends('request_ids.stage_id.done')
def _compute_todo_requests(self):
self.todo_request_ids = self.request_ids.filtered(lambda e: e.stage_id.done==False)
self.todo_request_count = len(self.todo_request_ids)
self.todo_request_count_date = len(self.todo_request_ids.filtered(lambda e: e.schedule_date != False))
self.todo_request_count_high_priority = len(self.todo_request_ids.filtered(lambda e: e.priority == '3'))
self.todo_request_count_block = len(self.todo_request_ids.filtered(lambda e: e.kanban_state == 'blocked'))
self.todo_request_count_unscheduled = len(self.todo_request_ids.filtered(lambda e: not e.schedule_date))
@api.one
@api.depends('equipment_ids')
def _compute_equipment(self):
self.equipment_count = len(self.equipment_ids)
| richard-willowit/odoo | addons/maintenance/models/maintenance.py | Python | gpl-3.0 | 20,858 |
package command
import (
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
"time"
getter "github.com/hashicorp/go-getter"
"github.com/hashicorp/nomad/helper/discover"
)
// fetchBinary fetches the nomad binary and returns the temporary directory where it exists
func fetchBinary(bin string) (string, error) {
nomadBinaryDir, err := ioutil.TempDir("", "")
if err != nil {
return "", fmt.Errorf("failed to create temp dir: %v", err)
}
if bin == "" {
bin, err = discover.NomadExecutable()
if err != nil {
return "", fmt.Errorf("failed to discover nomad binary: %v", err)
}
}
dest := path.Join(nomadBinaryDir, "nomad")
if runtime.GOOS == "windows" {
dest = dest + ".exe"
}
if err = getter.GetFile(dest, bin); err != nil {
return "", fmt.Errorf("failed to get nomad binary: %v", err)
}
return nomadBinaryDir, nil
}
func procWaitTimeout(p *os.Process, d time.Duration) error {
stop := make(chan struct{})
go func() {
p.Wait()
stop <- struct{}{}
}()
select {
case <-stop:
return nil
case <-time.NewTimer(d).C:
return fmt.Errorf("timeout waiting for process %d to exit", p.Pid)
}
}
| nak3/nomad | e2e/cli/command/util.go | GO | mpl-2.0 | 1,122 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use CompositorProxy;
use compositor_task;
use devtools_traits::{DevtoolsControlMsg, ScriptToDevtoolsControlMsg};
use euclid::rect::{TypedRect};
use euclid::scale_factor::ScaleFactor;
use gfx::font_cache_task::FontCacheTask;
use gfx::paint_task::{ChromeToPaintMsg, LayoutToPaintMsg, PaintTask};
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use layers::geometry::DevicePixel;
use layout_traits::{LayoutControlChan, LayoutTaskFactory};
use msg::constellation_msg::{ConstellationChan, Failure, FrameId, PipelineId, SubpageId};
use msg::constellation_msg::{LoadData, MozBrowserEvent, PipelineExitType, WindowSizeData};
use net_traits::ResourceTask;
use net_traits::image_cache_task::ImageCacheTask;
use net_traits::storage_task::StorageTask;
use profile_traits::mem as profile_mem;
use profile_traits::time;
use script_traits::{ConstellationControlMsg, InitialScriptState};
use script_traits::{LayoutControlMsg, NewLayoutInfo, ScriptTaskFactory};
use std::any::Any;
use std::mem;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread;
use url::Url;
use util;
use util::geometry::{PagePx, ViewportPx};
use util::ipc::OptionalIpcSender;
use util::prefs;
/// A uniquely-identifiable pipeline of script task, layout task, and paint task.
pub struct Pipeline {
pub id: PipelineId,
pub parent_info: Option<(PipelineId, SubpageId)>,
pub script_chan: Sender<ConstellationControlMsg>,
/// A channel to layout, for performing reflows and shutdown.
pub layout_chan: LayoutControlChan,
pub chrome_to_paint_chan: Sender<ChromeToPaintMsg>,
pub layout_shutdown_port: Receiver<()>,
pub paint_shutdown_port: Receiver<()>,
/// URL corresponding to the most recently-loaded page.
pub url: Url,
/// The title of the most recently-loaded page.
pub title: Option<String>,
pub rect: Option<TypedRect<PagePx, f32>>,
/// Whether this pipeline is currently running animations. Pipelines that are running
/// animations cause composites to be continually scheduled.
pub running_animations: bool,
pub children: Vec<FrameId>,
}
/// The subset of the pipeline that is needed for layer composition.
#[derive(Clone)]
pub struct CompositionPipeline {
pub id: PipelineId,
pub script_chan: Sender<ConstellationControlMsg>,
pub layout_chan: LayoutControlChan,
pub chrome_to_paint_chan: Sender<ChromeToPaintMsg>,
}
/// Initial setup data needed to construct a pipeline.
pub struct InitialPipelineState {
/// The ID of the pipeline to create.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<(PipelineId, SubpageId)>,
/// A channel to the associated constellation.
pub constellation_chan: ConstellationChan,
/// A channel to the compositor.
pub compositor_proxy: Box<CompositorProxy + 'static + Send>,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<Sender<DevtoolsControlMsg>>,
/// A channel to the image cache task.
pub image_cache_task: ImageCacheTask,
/// A channel to the font cache task.
pub font_cache_task: FontCacheTask,
/// A channel to the resource task.
pub resource_task: ResourceTask,
/// A channel to the storage task.
pub storage_task: StorageTask,
/// A channel to the time profiler thread.
pub time_profiler_chan: time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: profile_mem::ProfilerChan,
/// Information about the initial window size.
pub window_rect: Option<TypedRect<PagePx, f32>>,
/// Information about the device pixel ratio.
pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>,
/// A channel to the script thread, if applicable. If this is `Some`,
/// then `parent_info` must also be `Some`.
pub script_chan: Option<Sender<ConstellationControlMsg>>,
/// Information about the page to load.
pub load_data: LoadData,
}
impl Pipeline {
/// Starts a paint task, layout task, and possibly a script task.
/// Returns the channels wrapped in a struct.
pub fn create<LTF, STF>(state: InitialPipelineState)
-> (Pipeline, PipelineContent)
where LTF: LayoutTaskFactory, STF: ScriptTaskFactory {
let (layout_to_paint_chan, layout_to_paint_port) = util::ipc::optional_ipc_channel();
let (chrome_to_paint_chan, chrome_to_paint_port) = channel();
let (paint_shutdown_chan, paint_shutdown_port) = channel();
let (layout_shutdown_chan, layout_shutdown_port) = channel();
let (pipeline_chan, pipeline_port) = ipc::channel().unwrap();
let mut pipeline_port = Some(pipeline_port);
let failure = Failure {
pipeline_id: state.id,
parent_info: state.parent_info,
};
let window_size = state.window_rect.map(|rect| {
WindowSizeData {
visible_viewport: rect.size,
initial_viewport: rect.size * ScaleFactor::new(1.0),
device_pixel_ratio: state.device_pixel_ratio,
}
});
// Route messages coming from content to devtools as appropriate.
let script_to_devtools_chan = state.devtools_chan.as_ref().map(|devtools_chan| {
let (script_to_devtools_chan, script_to_devtools_port) = ipc::channel().unwrap();
let devtools_chan = (*devtools_chan).clone();
ROUTER.add_route(script_to_devtools_port.to_opaque(), box move |message| {
let message: ScriptToDevtoolsControlMsg = message.to().unwrap();
devtools_chan.send(DevtoolsControlMsg::FromScript(message)).unwrap()
});
script_to_devtools_chan
});
let (script_chan, script_port) = match state.script_chan {
Some(script_chan) => {
let (containing_pipeline_id, subpage_id) =
state.parent_info.expect("script_pipeline != None but subpage_id == None");
let new_layout_info = NewLayoutInfo {
containing_pipeline_id: containing_pipeline_id,
new_pipeline_id: state.id,
subpage_id: subpage_id,
load_data: state.load_data.clone(),
paint_chan: box layout_to_paint_chan.clone() as Box<Any + Send>,
failure: failure,
pipeline_port: mem::replace(&mut pipeline_port, None).unwrap(),
layout_shutdown_chan: layout_shutdown_chan.clone(),
};
script_chan.send(ConstellationControlMsg::AttachLayout(new_layout_info))
.unwrap();
(script_chan, None)
}
None => {
let (script_chan, script_port) = channel();
(script_chan, Some(script_port))
}
};
let pipeline = Pipeline::new(state.id,
state.parent_info,
script_chan.clone(),
LayoutControlChan(pipeline_chan),
chrome_to_paint_chan.clone(),
layout_shutdown_port,
paint_shutdown_port,
state.load_data.url.clone(),
state.window_rect);
let pipeline_content = PipelineContent {
id: state.id,
parent_info: state.parent_info,
constellation_chan: state.constellation_chan,
compositor_proxy: state.compositor_proxy,
devtools_chan: script_to_devtools_chan,
image_cache_task: state.image_cache_task,
font_cache_task: state.font_cache_task,
resource_task: state.resource_task,
storage_task: state.storage_task,
time_profiler_chan: state.time_profiler_chan,
mem_profiler_chan: state.mem_profiler_chan,
window_size: window_size,
script_chan: script_chan,
load_data: state.load_data,
failure: failure,
script_port: script_port,
layout_to_paint_chan: layout_to_paint_chan,
chrome_to_paint_chan: chrome_to_paint_chan,
layout_to_paint_port: Some(layout_to_paint_port),
chrome_to_paint_port: Some(chrome_to_paint_port),
pipeline_port: pipeline_port,
paint_shutdown_chan: paint_shutdown_chan,
layout_shutdown_chan: layout_shutdown_chan,
};
(pipeline, pipeline_content)
}
pub fn new(id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>,
script_chan: Sender<ConstellationControlMsg>,
layout_chan: LayoutControlChan,
chrome_to_paint_chan: Sender<ChromeToPaintMsg>,
layout_shutdown_port: Receiver<()>,
paint_shutdown_port: Receiver<()>,
url: Url,
rect: Option<TypedRect<PagePx, f32>>)
-> Pipeline {
Pipeline {
id: id,
parent_info: parent_info,
script_chan: script_chan,
layout_chan: layout_chan,
chrome_to_paint_chan: chrome_to_paint_chan,
layout_shutdown_port: layout_shutdown_port,
paint_shutdown_port: paint_shutdown_port,
url: url,
title: None,
children: vec!(),
rect: rect,
running_animations: false,
}
}
pub fn grant_paint_permission(&self) {
let _ = self.chrome_to_paint_chan.send(ChromeToPaintMsg::PaintPermissionGranted);
}
pub fn revoke_paint_permission(&self) {
debug!("pipeline revoking paint channel paint permission");
let _ = self.chrome_to_paint_chan.send(ChromeToPaintMsg::PaintPermissionRevoked);
}
pub fn exit(&self, exit_type: PipelineExitType) {
debug!("pipeline {:?} exiting", self.id);
// Script task handles shutting down layout, and layout handles shutting down the painter.
// For now, if the script task has failed, we give up on clean shutdown.
if self.script_chan.send(ConstellationControlMsg::ExitPipeline(self.id, exit_type)).is_ok() {
// Wait until all slave tasks have terminated and run destructors
// NOTE: We don't wait for script task as we don't always own it
let _ = self.paint_shutdown_port.recv();
let _ = self.layout_shutdown_port.recv();
}
}
pub fn freeze(&self) {
let _ = self.script_chan.send(ConstellationControlMsg::Freeze(self.id)).unwrap();
}
pub fn thaw(&self) {
let _ = self.script_chan.send(ConstellationControlMsg::Thaw(self.id)).unwrap();
}
pub fn force_exit(&self) {
let _ = self.script_chan.send(
ConstellationControlMsg::ExitPipeline(self.id,
PipelineExitType::PipelineOnly)).unwrap();
let _ = self.chrome_to_paint_chan.send(ChromeToPaintMsg::Exit(
None,
PipelineExitType::PipelineOnly));
let LayoutControlChan(ref layout_channel) = self.layout_chan;
let _ = layout_channel.send(
LayoutControlMsg::ExitNow(PipelineExitType::PipelineOnly)).unwrap();
}
pub fn to_sendable(&self) -> CompositionPipeline {
CompositionPipeline {
id: self.id.clone(),
script_chan: self.script_chan.clone(),
layout_chan: self.layout_chan.clone(),
chrome_to_paint_chan: self.chrome_to_paint_chan.clone(),
}
}
pub fn add_child(&mut self, frame_id: FrameId) {
self.children.push(frame_id);
}
pub fn remove_child(&mut self, frame_id: FrameId) {
let index = self.children.iter().position(|id| *id == frame_id).unwrap();
self.children.remove(index);
}
pub fn trigger_mozbrowser_event(&self,
subpage_id: SubpageId,
event: MozBrowserEvent) {
assert!(prefs::get_pref("dom.mozbrowser.enabled").as_boolean().unwrap_or(false));
let event = ConstellationControlMsg::MozBrowserEvent(self.id,
subpage_id,
event);
self.script_chan.send(event).unwrap();
}
}
pub struct PipelineContent {
id: PipelineId,
parent_info: Option<(PipelineId, SubpageId)>,
constellation_chan: ConstellationChan,
compositor_proxy: Box<CompositorProxy + Send + 'static>,
devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
image_cache_task: ImageCacheTask,
font_cache_task: FontCacheTask,
resource_task: ResourceTask,
storage_task: StorageTask,
time_profiler_chan: time::ProfilerChan,
mem_profiler_chan: profile_mem::ProfilerChan,
window_size: Option<WindowSizeData>,
script_chan: Sender<ConstellationControlMsg>,
load_data: LoadData,
failure: Failure,
script_port: Option<Receiver<ConstellationControlMsg>>,
layout_to_paint_chan: OptionalIpcSender<LayoutToPaintMsg>,
chrome_to_paint_chan: Sender<ChromeToPaintMsg>,
layout_to_paint_port: Option<Receiver<LayoutToPaintMsg>>,
chrome_to_paint_port: Option<Receiver<ChromeToPaintMsg>>,
paint_shutdown_chan: Sender<()>,
pipeline_port: Option<IpcReceiver<LayoutControlMsg>>,
layout_shutdown_chan: Sender<()>,
}
impl PipelineContent {
pub fn start_all<LTF, STF>(mut self) where LTF: LayoutTaskFactory, STF: ScriptTaskFactory {
let layout_pair = ScriptTaskFactory::create_layout_channel(None::<&mut STF>);
let (script_to_compositor_chan, script_to_compositor_port) = ipc::channel().unwrap();
self.start_paint_task();
let compositor_proxy_for_script_listener_thread =
self.compositor_proxy.clone_compositor_proxy();
thread::spawn(move || {
compositor_task::run_script_listener_thread(
compositor_proxy_for_script_listener_thread,
script_to_compositor_port)
});
ScriptTaskFactory::create(None::<&mut STF>, InitialScriptState {
id: self.id,
parent_info: self.parent_info,
compositor: script_to_compositor_chan,
control_chan: self.script_chan.clone(),
control_port: mem::replace(&mut self.script_port, None).unwrap(),
constellation_chan: self.constellation_chan.clone(),
failure_info: self.failure.clone(),
resource_task: self.resource_task,
storage_task: self.storage_task.clone(),
image_cache_task: self.image_cache_task.clone(),
time_profiler_chan: self.time_profiler_chan.clone(),
mem_profiler_chan: self.mem_profiler_chan.clone(),
devtools_chan: self.devtools_chan,
window_size: self.window_size,
}, &layout_pair, self.load_data.clone());
LayoutTaskFactory::create(None::<&mut LTF>,
self.id,
self.load_data.url.clone(),
self.parent_info.is_some(),
layout_pair,
self.pipeline_port.unwrap(),
self.constellation_chan,
self.failure,
self.script_chan.clone(),
self.layout_to_paint_chan.clone(),
self.image_cache_task,
self.font_cache_task,
self.time_profiler_chan,
self.mem_profiler_chan,
self.layout_shutdown_chan);
}
pub fn start_paint_task(&mut self) {
PaintTask::create(self.id,
self.load_data.url.clone(),
self.chrome_to_paint_chan.clone(),
mem::replace(&mut self.layout_to_paint_port, None).unwrap(),
mem::replace(&mut self.chrome_to_paint_port, None).unwrap(),
self.compositor_proxy.clone_compositor_proxy(),
self.constellation_chan.clone(),
self.font_cache_task.clone(),
self.failure.clone(),
self.time_profiler_chan.clone(),
self.mem_profiler_chan.clone(),
self.paint_shutdown_chan.clone());
}
}
| RenaudParis/servo | components/compositing/pipeline.rs | Rust | mpl-2.0 | 17,123 |
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Object Storage Service API
//
// Common set of Object Storage and Archive Storage APIs for managing buckets, objects, and related resources.
//
package objectstorage
import (
"github.com/oracle/oci-go-sdk/common"
)
// WorkRequestLogEntry The representation of WorkRequestLogEntry
type WorkRequestLogEntry struct {
// Human-readable log message.
Message *string `mandatory:"false" json:"message"`
// The date and time the log message was written, as described in
// RFC 3339 (https://tools.ietf.org/rfc/rfc3339), section 14.29.
Timestamp *common.SDKTime `mandatory:"false" json:"timestamp"`
}
func (m WorkRequestLogEntry) String() string {
return common.PointerString(m)
}
| joelthompson/vault | vendor/github.com/oracle/oci-go-sdk/objectstorage/work_request_log_entry.go | GO | mpl-2.0 | 807 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = '1.0.0'
README = open('README.rst').read()
setup(
name='mach',
description='Generic command line command dispatching framework.',
long_description=README,
license='MPL 2.0',
author='Gregory Szorc',
author_email='gregory.szorc@gmail.com',
url='https://developer.mozilla.org/en-US/docs/Developer_Guide/mach',
packages=['mach', 'mach.mixin'],
version=VERSION,
classifiers=[
'Environment :: Console',
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
],
install_requires=[
'blessings',
'mozfile',
'mozprocess',
'six',
],
tests_require=['mock'],
)
| CYBAI/servo | python/mach/setup.py | Python | mpl-2.0 | 1,204 |
{# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/. -#}
{% extends "firefox/whatsnew/whatsnew-base-42.html" %}
{% add_lang_files "firefox/whatsnew_42" %}
{% block page_css %}
{% stylesheet 'firefox_whatsnew_zh_tw_49' %}
{% endblock %}
{% block body_class %}firefox-up-to-date{% endblock %}
{% block content %}
<main role="main" class="container" id="main-container" data-version="{{ version }}" data-geoKey="{{ settings.MOZILLA_LOCATION_SERVICES_KEY }}">
<div id="default-content" class="js-hidden">
<header class="main-header">
<h1 data-alt="{{ _('The world’s most private browsing. Only from Firefox.') }}">{{ self.page_title() }}</h1>
{% block main_subhead %}
<a class="button button-dark" href="{{ url('firefox.private-browsing') }}" data-highlight="privateWindow" role="button" data-link-type="button" data-link-name="Try the new Private Browsing">{{ _('Try the new Private Browsing') }}</a>
{% endblock %}
</header>
{% block private_browsing_cta %}
{% include 'firefox/includes/tracking-protection-animation.html' %}
{% endblock %}
</div>
<div id="special-content" class="hidden js-hidden">
<h1>智慧搜尋</h1>
<p class="hidden" id="copy-tw">
現在起,Firefox 使用 Yahoo 奇摩為您搜尋解答,快試試看!
</p>
<p class="hidden" id="copy-hk">
現在起,Firefox 使用 Yahoo 為您搜尋解答,快試試看!
</p>
<div id="image-frame">
<img src="{{ static('img/firefox/whatsnew_42/tw-poi.jpg') }}" alt="" id="image-tw" class="hidden">
<img src="{{ static('img/firefox/whatsnew_42/hk-astronomy.jpg') }}" alt="" id="image-hk" class="hidden">
</div>
</div>
</main>
{% endblock %}
{% block js %}
{% javascript 'firefox_whatsnew_zh_tw_49' %}
{% endblock %}
| glogiotatidis/bedrock | bedrock/firefox/templates/firefox/whatsnew/whatsnew-zh-tw-49.html | HTML | mpl-2.0 | 1,952 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Copyright 2013, Schmidt and Chen
#include "pblas.h"
// R.h and Rinternals.h needs to be included after Rconfig.h
#include "pbdBASE.h"
#include <RNACI.h>
// Transpose
SEXP R_PDTRAN(SEXP M, SEXP N, SEXP A, SEXP DESCA, SEXP CLDIM, SEXP DESCC)
{
R_INIT;
int IJ = 1;
double one = 1.0;
double zero = 0.0;
SEXP C;
newRmat(C, INT(CLDIM, 0), INT(CLDIM, 1), "dbl");
pdtran_(INTP(M), INTP(N), &one,
DBLP(A), &IJ, &IJ, INTP(DESCA), &zero,
DBLP(C), &IJ, &IJ, INTP(DESCC));
R_END;
return C;
}
// Mat-Mat-Mult
SEXP R_PDGEMM(SEXP TRANSA, SEXP TRANSB, SEXP M, SEXP N, SEXP K,
SEXP A, SEXP DESCA, SEXP B, SEXP DESCB, SEXP CLDIM, SEXP DESCC)
{
R_INIT;
double alpha = 1.0;
double beta = 0.0;
int IJ = 1;
SEXP C;
newRmat(C, INT(CLDIM, 0), INT(CLDIM, 1), "dbl");
#ifdef FC_LEN_T
pdgemm_(STR(TRANSA, 0), STR(TRANSB, 0),
INTP(M), INTP(N), INTP(K), &alpha,
DBLP(A), &IJ, &IJ, INTP(DESCA),
DBLP(B), &IJ, &IJ, INTP(DESCB), &beta,
DBLP(C), &IJ, &IJ, INTP(DESCC),
(FC_LEN_T) strlen(STR(TRANSA, 0)), (FC_LEN_T) strlen(STR(TRANSB, 0)));
#else
pdgemm_(STR(TRANSA, 0), STR(TRANSB, 0),
INTP(M), INTP(N), INTP(K), &alpha,
DBLP(A), &IJ, &IJ, INTP(DESCA),
DBLP(B), &IJ, &IJ, INTP(DESCB), &beta,
DBLP(C), &IJ, &IJ, INTP(DESCC));
#endif
R_END;
return C;
}
| cran/pbdBASE | src/base_pblas_level3.c | C | mpl-2.0 | 1,581 |
"""add timezone to each station
Revision ID: 4d0be367f095
Revises: 6722b0ef4e1
Create Date: 2014-03-19 16:43:00.326820
"""
# revision identifiers, used by Alembic.
revision = '4d0be367f095'
down_revision = '6722b0ef4e1'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('radio_station', sa.Column('timezone', sa.String(length=32), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('radio_station', 'timezone')
### end Alembic commands ###
| rootio/rootio_web | alembic/versions/4d0be367f095_station_timezone.py | Python | agpl-3.0 | 644 |
<?php
/**
* $Id: ml.php,v 1.3 2005/10/03 15:07:27 mike Exp $
*/
$this->codes = array(
'ADP' => 'Andorran Peseta',
'AED' => 'United Arab Emirates Dirham',
'AFA' => 'Afghani (1927-2002)',
'AFN' => 'Afghani',
'ALL' => 'Albanian Lek',
'AMD' => 'Armenian Dram',
'ANG' => 'Netherlands Antillan Guilder',
'AOA' => 'Angolan Kwanza',
'AOK' => 'Angolan Kwanza (1977-1990)',
'AON' => 'Angolan New Kwanza (1990-2000)',
'AOR' => 'Angolan Kwanza Reajustado (1995-1999)',
'ARA' => 'Argentine Austral',
'ARP' => 'Argentine Peso (1983-1985)',
'ARS' => 'Argentine Peso',
'ATS' => 'Austrian Schilling',
'AUD' => 'Australian Dollar',
'AWG' => 'Aruban Guilder',
'AZM' => 'Azerbaijanian Manat',
'BAD' => 'Bosnia-Herzegovina Dinar',
'BAM' => 'Bosnia-Herzegovina Convertible Mark',
'BBD' => 'Barbados Dollar',
'BDT' => 'Bangladesh Taka',
'BEC' => 'Belgian Franc (convertible)',
'BEF' => 'Belgian Franc',
'BEL' => 'Belgian Franc (financial)',
'BGL' => 'Bulgarian Hard Lev',
'BGN' => 'Bulgarian New Lev',
'BHD' => 'Bahraini Dinar',
'BIF' => 'Burundi Franc',
'BMD' => 'Bermudan Dollar',
'BND' => 'Brunei Dollar',
'BOB' => 'Boliviano',
'BOP' => 'Bolivian Peso',
'BOV' => 'Bolivian Mvdol',
'BRB' => 'Brazilian Cruzeiro Novo (1967-1986)',
'BRC' => 'Brazilian Cruzado',
'BRE' => 'Brazilian Cruzeiro (1990-1993)',
'BRL' => 'Brazilian Real',
'BRN' => 'Brazilian Cruzado Novo',
'BRR' => 'Brazilian Cruzeiro',
'BSD' => 'Bahamian Dollar',
'BTN' => 'Bhutan Ngultrum',
'BUK' => 'Burmese Kyat',
'BWP' => 'Botswanan Pula',
'BYB' => 'Belarussian New Ruble (1994-1999)',
'BYR' => 'Belarussian Ruble',
'BZD' => 'Belize Dollar',
'CAD' => 'Canadian Dollar',
'CDF' => 'Congolese Franc Congolais',
'CHE' => 'WIR Euro',
'CHF' => 'Swiss Franc',
'CHW' => 'WIR Franc',
'CLF' => 'Chilean Unidades de Fomento',
'CLP' => 'Chilean Peso',
'CNY' => 'Chinese Yuan Renminbi',
'COP' => 'Colombian Peso',
'COU' => 'Unidad de Valor Real',
'CRC' => 'Costa Rican Colon',
'CSD' => 'Serbian Dinar',
'CSK' => 'Czechoslovak Hard Koruna',
'CUP' => 'Cuban Peso',
'CVE' => 'Cape Verde Escudo',
'CYP' => 'Cyprus Pound',
'CZK' => 'Czech Republic Koruna',
'DDM' => 'East German Ostmark',
'DEM' => 'Deutsche Mark',
'DJF' => 'Djibouti Franc',
'DKK' => 'Danish Krone',
'DOP' => 'Dominican Peso',
'DZD' => 'Algerian Dinar',
'ECS' => 'Ecuador Sucre',
'ECV' => 'Ecuador Unidad de Valor Constante (UVC)',
'EEK' => 'Estonian Kroon',
'EGP' => 'Egyptian Pound',
'EQE' => 'Ekwele',
'ERN' => 'Eritrean Nakfa',
'ESA' => 'Spanish Peseta (A account)',
'ESB' => 'Spanish Peseta (convertible account)',
'ESP' => 'Spanish Peseta',
'ETB' => 'Ethiopian Birr',
'EUR' => 'Euro',
'FIM' => 'Finnish Markka',
'FJD' => 'Fiji Dollar',
'FKP' => 'Falkland Islands Pound',
'FRF' => 'French Franc',
'GBP' => 'British Pound Sterling',
'GEK' => 'Georgian Kupon Larit',
'GEL' => 'Georgian Lari',
'GHC' => 'Ghana Cedi',
'GIP' => 'Gibraltar Pound',
'GMD' => 'Gambia Dalasi',
'GNF' => 'Guinea Franc',
'GNS' => 'Guinea Syli',
'GQE' => 'Equatorial Guinea Ekwele Guineana',
'GRD' => 'Greek Drachma',
'GTQ' => 'Guatemala Quetzal',
'GWE' => 'Portuguese Guinea Escudo',
'GWP' => 'Guinea-Bissau Peso',
'GYD' => 'Guyana Dollar',
'HKD' => 'Hong Kong Dollar',
'HNL' => 'Hoduras Lempira',
'HRD' => 'Croatian Dinar',
'HRK' => 'Croatian Kuna',
'HTG' => 'Haitian Gourde',
'HUF' => 'Hungarian Forint',
'IDR' => 'Indonesian Rupiah',
'IEP' => 'Irish Pound',
'ILP' => 'Israeli Pound',
'ILS' => 'Israeli New Sheqel',
'INR' => 'Indian Rupee',
'IQD' => 'Iraqi Dinar',
'IRR' => 'Iranian Rial',
'ISK' => 'Icelandic Krona',
'ITL' => 'Italian Lira',
'JMD' => 'Jamaican Dollar',
'JOD' => 'Jordanian Dinar',
'JPY' => 'Japanese Yen',
'KES' => 'Kenyan Shilling',
'KGS' => 'Kyrgystan Som',
'KHR' => 'Cambodian Riel',
'KMF' => 'Comoro Franc',
'KPW' => 'North Korean Won',
'KRW' => 'South Korean Won',
'KWD' => 'Kuwaiti Dinar',
'KYD' => 'Cayman Islands Dollar',
'KZT' => 'Kazakhstan Tenge',
'LAK' => 'Laotian Kip',
'LBP' => 'Lebanese Pound',
'LKR' => 'Sri Lanka Rupee',
'LRD' => 'Liberian Dollar',
'LSL' => 'Lesotho Loti',
'LSM' => 'Maloti',
'LTL' => 'Lithuanian Lita',
'LTT' => 'Lithuanian Talonas',
'LUC' => 'Luxembourg Convertible Franc',
'LUF' => 'Luxembourg Franc',
'LUL' => 'Luxembourg Financial Franc',
'LVL' => 'Latvian Lats',
'LVR' => 'Latvian Ruble',
'LYD' => 'Libyan Dinar',
'MAD' => 'Moroccan Dirham',
'MAF' => 'Moroccan Franc',
'MDL' => 'Moldovan Leu',
'MGA' => 'Madagascar Ariary',
'MGF' => 'Madagascar Franc',
'MKD' => 'Macedonian Denar',
'MLF' => 'Mali Franc',
'MMK' => 'Myanmar Kyat',
'MNT' => 'Mongolian Tugrik',
'MOP' => 'Macao Pataca',
'MRO' => 'Mauritania Ouguiya',
'MTL' => 'Maltese Lira',
'MTP' => 'Maltese Pound',
'MUR' => 'Mauritius Rupee',
'MVR' => 'Maldive Islands Rufiyaa',
'MWK' => 'Malawi Kwacha',
'MXN' => 'Mexican Peso',
'MXP' => 'Mexican Silver Peso (1861-1992)',
'MXV' => 'Mexican Unidad de Inversion (UDI)',
'MYR' => 'Malaysian Ringgit',
'MZE' => 'Mozambique Escudo',
'MZM' => 'Mozambique Metical',
'NAD' => 'Namibia Dollar',
'NGN' => 'Nigerian Naira',
'NIC' => 'Nicaraguan Cordoba',
'NIO' => 'Nicaraguan Cordoba Oro',
'NLG' => 'Netherlands Guilder',
'NOK' => 'Norwegian Krone',
'NPR' => 'Nepalese Rupee',
'NZD' => 'New Zealand Dollar',
'OMR' => 'Oman Rial',
'PAB' => 'Panamanian Balboa',
'PEI' => 'Peruvian Inti',
'PEN' => 'Peruvian Sol Nuevo',
'PES' => 'Peruvian Sol',
'PGK' => 'Papua New Guinea Kina',
'PHP' => 'Philippine Peso',
'PKR' => 'Pakistan Rupee',
'PLN' => 'Polish Zloty',
'PLZ' => 'Polish Zloty (1950-1995)',
'PTE' => 'Portuguese Escudo',
'PYG' => 'Paraguay Guarani',
'QAR' => 'Qatari Rial',
'RHD' => 'Rhodesian Dollar',
'ROL' => 'Romanian Leu',
'RON' => 'Romanian Leu',
'RUB' => 'Russian Ruble',
'RUR' => 'Russian Ruble (1991-1998)',
'RWF' => 'Rwandan Franc',
'SAR' => 'Saudi Riyal',
'SBD' => 'Solomon Islands Dollar',
'SCR' => 'Seychelles Rupee',
'SDD' => 'Sudanese Dinar',
'SDP' => 'Sudanese Pound',
'SEK' => 'Swedish Krona',
'SGD' => 'Singapore Dollar',
'SHP' => 'Saint Helena Pound',
'SIT' => 'Slovenia Tolar',
'SKK' => 'Slovak Koruna',
'SLL' => 'Sierra Leone Leone',
'SOS' => 'Somali Shilling',
'SRD' => 'Surinam Dollar',
'SRG' => 'Suriname Guilder',
'STD' => 'Sao Tome and Principe Dobra',
'SUR' => 'Soviet Rouble',
'SVC' => 'El Salvador Colon',
'SYP' => 'Syrian Pound',
'SZL' => 'Swaziland Lilangeni',
'THB' => 'Thai Baht',
'TJR' => 'Tajikistan Ruble',
'TJS' => 'Tajikistan Somoni',
'TMM' => 'Turkmenistan Manat',
'TND' => 'Tunisian Dinar',
'TOP' => 'Tonga Paʻanga',
'TPE' => 'Timor Escudo',
'TRL' => 'Turkish Lira',
'TRY' => 'New Turkish Lira',
'TTD' => 'Trinidad and Tobago Dollar',
'TWD' => 'Taiwan New Dollar',
'TZS' => 'Tanzanian Shilling',
'UAH' => 'Ukrainian Hryvnia',
'UAK' => 'Ukrainian Karbovanetz',
'UGS' => 'Ugandan Shilling (1966-1987)',
'UGX' => 'Ugandan Shilling',
'USD' => 'US Dollar',
'USN' => 'US Dollar (Next day)',
'USS' => 'US Dollar (Same day)',
'UYP' => 'Uruguay Peso (1975-1993)',
'UYU' => 'Uruguay Peso Uruguayo',
'UZS' => 'Uzbekistan Sum',
'VEB' => 'Venezuelan Bolivar',
'VND' => 'Vietnamese Dong',
'VUV' => 'Vanuatu Vatu',
'WST' => 'Western Samoa Tala',
'XAF' => 'CFA Franc BEAC',
'XAG' => 'Silver',
'XAU' => 'Gold',
'XBA' => 'European Composite Unit',
'XBB' => 'European Monetary Unit',
'XBC' => 'European Unit of Account (XBC)',
'XBD' => 'European Unit of Account (XBD)',
'XCD' => 'East Caribbean Dollar',
'XDR' => 'Special Drawing Rights',
'XEU' => 'European Currency Unit',
'XFO' => 'French Gold Franc',
'XFU' => 'French UIC-Franc',
'XOF' => 'CFA Franc BCEAO',
'XPD' => 'Palladium',
'XPF' => 'CFP Franc',
'XPT' => 'Platinum',
'XRE' => 'RINET Funds',
'XTS' => 'Testing Currency Code',
'XXX' => 'No Currency',
'YDD' => 'Yemeni Dinar',
'YER' => 'Yemeni Rial',
'YUD' => 'Yugoslavian Hard Dinar',
'YUM' => 'Yugoslavian Noviy Dinar',
'YUN' => 'Yugoslavian Convertible Dinar',
'ZAL' => 'South African Rand (financial)',
'ZAR' => 'South African Rand',
'ZMK' => 'Zambian Kwacha',
'ZMW' => 'Zambian Kwacha',
'ZRN' => 'Zairean New Zaire',
'ZRZ' => 'Zairean Zaire',
'ZWD' => 'Zimbabwe Dollar',
);
?>
| alachaum/timetrex | classes/pear/I18Nv2/Currency/ml.php | PHP | agpl-3.0 | 8,992 |
<?php
/*********************************************************************************
* TimeTrex is a Payroll and Time Management program developed by
* TimeTrex Software Inc. Copyright (C) 2003 - 2014 TimeTrex Software Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY TIMETREX, TIMETREX DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact TimeTrex headquarters at Unit 22 - 2475 Dobbin Rd. Suite
* #292 Westbank, BC V4T 2E9, Canada or at email address info@timetrex.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by TimeTrex" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by TimeTrex".
********************************************************************************/
/**
* @package Core
*/
class LogDetailListFactory extends LogDetailFactory implements IteratorAggregate {
function getAll($limit = NULL, $page = NULL, $where = NULL, $order = NULL) {
$query = '
select *
from '. $this->getTable() .'
';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, NULL, $limit, $page );
return $this;
}
function getById($id, $where = NULL, $order = NULL) {
if ( $id == '') {
return FALSE;
}
$ph = array(
'id' => $id,
);
$query = '
select *
from '. $this->getTable() .'
where id = ?
';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
return $this;
}
function getByIdAndCompanyId($id, $company_id, $where = NULL, $order = NULL) {
if ( $id == '') {
return FALSE;
}
if ( $company_id == '') {
return FALSE;
}
$uf = new UserFactory();
$lf = new LogFactory();
$ph = array(
'id' => $id,
'company_id' => $company_id
);
$query = '
select a.*
from '. $this->getTable() .' as a
LEFT JOIN '. $lf->getTable() .' as lf on a.system_log_id = lf.id
LEFT JOIN '. $uf->getTable() .' as uf on lf.user_id = uf.id
where a.id = ?
AND uf.company_id = ?';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
return $this;
}
function getByCompanyId($company_id, $where = NULL, $order = NULL) {
if ( $company_id == '') {
return FALSE;
}
$uf = new UserFactory();
$lf = new LogFactory();
$ph = array(
'company_id' => $company_id
);
$query = '
select a.*
from '. $this->getTable() .' as a
LEFT JOIN '. $lf->getTable() .' as lf on a.system_log_id = lf.id
LEFT JOIN '. $uf->getTable() .' as uf on lf.user_id = uf.id
where uf.company_id = ?
AND ( uf.deleted = 0 )';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
return $this;
}
function getBySystemLogIdAndCompanyId($id, $company_id, $where = NULL, $order = NULL) {
if ( $id == '') {
return FALSE;
}
if ( $company_id == '') {
return FALSE;
}
if ( $order == NULL ) {
$order = array( 'a.field' => 'asc' );
$strict = FALSE;
} else {
$strict = TRUE;
}
$uf = new UserFactory();
$lf = new LogFactory();
$ph = array(
'id' => $id,
'company_id' => $company_id
);
$query = '
select a.*
from '. $this->getTable() .' as a
LEFT JOIN '. $lf->getTable() .' as lf on a.system_log_id = lf.id
LEFT JOIN '. $uf->getTable() .' as uf on lf.user_id = uf.id
where a.system_log_id = ?
AND uf.company_id = ?';
$query .= $this->getWhereSQL( $where );
$query .= $this->getSortSQL( $order );
$this->ExecuteSQL( $query, $ph );
return $this;
}
}
?>
| alachaum/timetrex | classes/modules/core/LogDetailListFactory.class.php | PHP | agpl-3.0 | 4,974 |
# Copyright (C) 2016 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
require 'spec_helper'
require_relative '../../lti_spec_helper'
RSpec.describe Lti::ContentMigrationService do
include WebMock::API
include LtiSpecHelper
describe '.begin_exports(course, options = {})' do
before do
# creates @course :-(
course_model
@root_account = @course.root_account
@root_account.ensure_defaults
@root_account.save!
@tool = @course.context_external_tools.build({
name: 'a',
domain: 'lti.example.com',
consumer_key: '12345',
shared_secret: 'secret',
})
@tool.settings = Importers::ContextExternalToolImporter.create_tool_settings({
settings: {
'custom_fields' => {
'course_id'=>'$Canvas.course.id',
},
'content_migration' => {
'export_start_url'=>'https://lti.example.com/begin_export',
'import_start_url'=>'https://lti.example.com/begin_import'
},
}
})
@tool.save!
response_body = {
status_url: 'https://lti.example.com/export/42/status',
fetch_url: 'https://lti.example.com/export/42',
}.to_json
stub_request(:post, 'https://lti.example.com/begin_export').
to_return(:status => 200, :body => response_body, :headers => {})
@return_value = Lti::ContentMigrationService.begin_exports(@course)
end
it 'must return a hash with the data returned by the tool for the next steps in the process' do
expect(@return_value).to include "lti_#{@tool.id}" => an_instance_of(Lti::ContentMigrationService::Exporter)
end
end
describe '.importer_for(key)' do
it 'must return an Importer with the original_tool_id set when the key is valid' do
importer = Lti::ContentMigrationService.importer_for('lti_42')
expect(importer).to be_an(Lti::ContentMigrationService::Importer)
expect(importer.original_tool_id).to eq 42
end
it "must return nil when the key doesn't include an id" do
importer = Lti::ContentMigrationService.importer_for('lti_')
expect(importer).to be_nil
end
it 'must return nil when the key has extra stuff at the end' do
importer = Lti::ContentMigrationService.importer_for('lti_23_foobar')
expect(importer).to be_nil
end
end
end
| matematikk-mooc/canvas-lms | spec/models/lti/content_migration_service_spec.rb | Ruby | agpl-3.0 | 2,970 |
# -*- coding: utf-8 -*-
from . import models
from .hooks import set_default_map_settings
| brain-tec/partner-contact | partner_external_map/__init__.py | Python | agpl-3.0 | 90 |
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Vaucher
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from lxml import etree
from openerp import models, fields, api
class PostlogisticsLicense(models.Model):
_name = 'postlogistics.license'
_description = 'PostLogistics Franking License'
_order = 'sequence'
name = fields.Char(string='Description',
translate=True,
required=True)
number = fields.Char(string='Number',
required=True)
company_id = fields.Many2one(comodel_name='res.company',
string='Company',
required=True)
sequence = fields.Integer(
string='Sequence',
help="Gives the sequence on company to define priority on license "
"when multiple licenses are available for the same group of "
"service."
)
class PostlogisticsServiceGroup(models.Model):
_name = 'postlogistics.service.group'
_description = 'PostLogistics Service Group'
name = fields.Char(string='Description', translate=True, required=True)
group_extid = fields.Integer(string='Group ID', required=True)
postlogistics_license_ids = fields.Many2many(
comodel_name='postlogistics.license',
relation='postlogistics_license_service_groups_rel',
column1='license_id',
column2='group_id',
string='PostLogistics Franking License')
_sql_constraints = [
('group_extid_uniq', 'unique(group_extid)',
"A service group ID must be unique.")
]
POSTLOGISTIC_TYPES = [
('label_layout', 'Label Layout'),
('output_format', 'Output Format'),
('resolution', 'Output Resolution'),
('basic', 'Basic Service'),
('additional', 'Additional Service'),
('delivery', 'Delivery Instructions')
]
class DeliveryCarrierTemplateOption(models.Model):
""" Set name translatable and add service group """
_inherit = 'delivery.carrier.template.option'
name = fields.Char(translate=True)
postlogistics_service_group_id = fields.Many2one(
comodel_name='postlogistics.service.group',
string='PostLogistics Service Group',
)
postlogistics_type = fields.Selection(
selection=POSTLOGISTIC_TYPES,
string="PostLogistics option type",
)
# relation tables to manage compatiblity between basic services
# and other services
postlogistics_basic_service_ids = fields.Many2many(
comodel_name='delivery.carrier.template.option',
relation='postlogistics_compatibility_service_rel',
column1='service_id',
column2='basic_service_id',
string="Basic Services",
domain=[('postlogistics_type', '=', 'basic')],
help="List of basic service for which this service is compatible",
)
postlogistics_additonial_service_ids = fields.Many2many(
comodel_name='delivery.carrier.template.option',
relation='postlogistics_compatibility_service_rel',
column1='basic_service_id',
column2='service_id',
string="Compatible Additional Services",
domain=[('postlogistics_type', '=', 'additional')],
)
postlogistics_delivery_instruction_ids = fields.Many2many(
comodel_name='delivery.carrier.template.option',
relation='postlogistics_compatibility_service_rel',
column1='basic_service_id',
column2='service_id',
string="Compatible Delivery Instructions",
domain=[('postlogistics_type', '=', 'delivery')],
)
class DeliveryCarrierOption(models.Model):
""" Set name translatable and add service group """
_inherit = 'delivery.carrier.option'
name = fields.Char(translate=True)
def fields_view_get(self, cr, uid, view_id=None, view_type='form',
context=None, toolbar=False, submenu=False):
_super = super(DeliveryCarrierOption, self)
result = _super.fields_view_get(cr, uid, view_id=view_id,
view_type=view_type, context=context,
toolbar=toolbar, submenu=submenu)
xmlid = 'delivery_carrier_label_postlogistics.postlogistics'
ref = self.pool['ir.model.data'].xmlid_to_object
postlogistics_partner = ref(cr, uid, xmlid, context=context)
if context.get('default_carrier_id'):
carrier_obj = self.pool['delivery.carrier']
carrier = carrier_obj.browse(cr, uid,
context['default_carrier_id'],
context=context)
if carrier.partner_id == postlogistics_partner:
arch = result['arch']
doc = etree.fromstring(arch)
for node in doc.xpath("//field[@name='tmpl_option_id']"):
node.set(
'domain',
"[('partner_id', '=', %s), "
" ('id', 'in', parent.allowed_option_ids[0][2])]" %
postlogistics_partner.id
)
result['arch'] = etree.tostring(doc)
return result
class DeliveryCarrier(models.Model):
""" Add service group """
_inherit = 'delivery.carrier'
@api.model
def _get_carrier_type_selection(self):
""" Add postlogistics carrier type """
res = super(DeliveryCarrier, self)._get_carrier_type_selection()
res.append(('postlogistics', 'Postlogistics'))
return res
@api.depends('partner_id',
'available_option_ids',
'available_option_ids.tmpl_option_id',
'available_option_ids.postlogistics_type',
)
def _get_basic_service_ids(self):
""" Search in all options for PostLogistics basic services if set """
xmlid = 'delivery_carrier_label_postlogistics.postlogistics'
postlogistics_partner = self.env.ref(xmlid)
for carrier in self:
if carrier.partner_id != postlogistics_partner:
continue
options = carrier.available_option_ids.filtered(
lambda option: option.postlogistics_type == 'basic'
).mapped('tmpl_option_id')
if not options:
continue
self.postlogistics_basic_service_ids = options
@api.depends('partner_id',
'postlogistics_service_group_id',
'postlogistics_basic_service_ids',
'postlogistics_basic_service_ids',
'available_option_ids',
'available_option_ids.postlogistics_type',
)
def _get_allowed_option_ids(self):
""" Return a list of possible options
A domain would be too complicated.
We do this to ensure the user first select a basic service. And
then he adds additional services.
"""
option_template_obj = self.env['delivery.carrier.template.option']
xmlid = 'delivery_carrier_label_postlogistics.postlogistics'
postlogistics_partner = self.env.ref(xmlid)
for carrier in self:
allowed = option_template_obj.browse()
if carrier.partner_id != postlogistics_partner:
continue
service_group = carrier.postlogistics_service_group_id
if service_group:
basic_services = carrier.postlogistics_basic_service_ids
services = option_template_obj.search(
[('postlogistics_service_group_id', '=', service_group.id)]
)
allowed |= services
if basic_services:
related_services = option_template_obj.search(
[('postlogistics_basic_service_ids', 'in',
basic_services.ids)]
)
allowed |= related_services
# Allows to set multiple optional single option in order to
# let the user select them
single_option_types = [
'label_layout',
'output_format',
'resolution',
]
selected_single_options = [
opt.tmpl_option_id.postlogistics_type
for opt in carrier.available_option_ids
if opt.postlogistics_type in single_option_types and
opt.mandatory]
if selected_single_options != single_option_types:
services = option_template_obj.search(
[('postlogistics_type', 'in', single_option_types),
('postlogistics_type', 'not in',
selected_single_options)],
)
allowed |= services
carrier.allowed_option_ids = allowed
postlogistics_license_id = fields.Many2one(
comodel_name='postlogistics.license',
string='PostLogistics Franking License',
)
postlogistics_service_group_id = fields.Many2one(
comodel_name='postlogistics.service.group',
string='PostLogistics Service Group',
help="Service group defines the available options for "
"this delivery method.",
)
postlogistics_basic_service_ids = fields.One2many(
comodel_name='delivery.carrier.template.option',
compute='_get_basic_service_ids',
string='PostLogistics Service Group',
help="Basic Service defines the available "
"additional options for this delivery method",
)
allowed_option_ids = fields.Many2many(
comodel_name='delivery.carrier.template.option',
compute='_get_allowed_option_ids',
string='Allowed options',
help="Compute allowed options according to selected options.",
)
| Antiun/carrier-delivery | delivery_carrier_label_postlogistics/delivery.py | Python | agpl-3.0 | 10,691 |
# Tableless model to handle updating multiple models at once from a single form
class ModelSet
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :collection
def initialize(klass, collection, attributes={}, reject_if=nil, delete_if=nil)
@klass, @collection, @reject_if, @delete_if = klass, collection, reject_if, delete_if
# Set here first, to ensure that we apply collection_attributes to the right collection
@collection = attributes[:collection] if attributes[:collection]
attributes.each do |name, value|
send("#{name}=", value)
end
end
def collection_attributes=(collection_attributes)
collection_attributes.each do |k, attributes|
# attributes == {:id => 123, :next_collection_at => '...'}
e = @collection.detect { |e| e.id.to_s == attributes[:id].to_s && !e.id.nil? }
if e.nil?
@collection << @klass.new(attributes) unless @reject_if.andand.call(attributes)
else
e.assign_attributes(attributes.except(:id))
end
end
end
def errors
errors = ActiveModel::Errors.new self
full_messages = @collection.map { |ef| ef.errors.full_messages }.flatten
full_messages.each { |fm| errors.add(:base, fm) }
errors
end
def save
collection_to_delete.each &:destroy
collection_to_keep.all? &:save
end
def collection_to_delete
# Remove all elements to be deleted from collection and return them
# Allows us to render @model_set.collection without deleted elements
deleted = []
collection.delete_if { |e| deleted << e if @delete_if.andand.call(e.attributes) }
deleted
end
def collection_to_keep
collection.reject { |e| @delete_if.andand.call(e.attributes) }
end
def persisted?
false
end
end
| levent/openfoodnetwork | app/models/model_set.rb | Ruby | agpl-3.0 | 1,775 |
/*
* Copyright 2010-2012 Fabric Engine Inc. All rights reserved.
*/
#ifndef _FABRIC_CG_SCOPE_H
#define _FABRIC_CG_SCOPE_H
#include <Fabric/Core/CG/BasicBlockBuilder.h>
#include <Fabric/Core/CG/ExprValue.h>
#include <Fabric/Core/CG/Adapter.h>
#include <Fabric/Core/CG/Error.h>
#include <Fabric/Core/CG/Location.h>
#include <Fabric/Core/CG/FunctionParam.h>
#include <Fabric/Core/CG/ReturnInfo.h>
#include <Fabric/Core/CG/Symbol.h>
#include <Fabric/Core/Util/UnorderedMap.h>
#include <Fabric/Base/Exception.h>
namespace Fabric
{
namespace CG
{
class Scope
{
public:
Scope( Scope const &parentScope )
: m_parentScope( &parentScope )
{
}
void put( RC::ConstHandle<Symbol> const &symbol )
{
m_symbols.push_back( symbol );
}
void put( std::string const &name, RC::ConstHandle<Symbol> const &symbol )
{
put( symbol );
m_namedSymbols.insert( StringToSymbolMap::value_type( name, symbol ) );
}
bool hasLocal( std::string const &name ) const
{
StringToSymbolMap::const_iterator it = m_namedSymbols.find(name);
return it != m_namedSymbols.end();
}
bool has( std::string const &name ) const
{
return hasLocal( name )
|| (m_parentScope && m_parentScope->has( name ));
}
RC::ConstHandle<Symbol> get( std::string const &name ) const
{
StringToSymbolMap::const_iterator it = m_namedSymbols.find(name);
if ( it != m_namedSymbols.end() )
return it->second;
else if ( m_parentScope )
return m_parentScope->get( name );
else return 0;
}
void llvmUnwind( BasicBlockBuilder &bbb ) const
{
for ( SymbolVector::const_iterator it=m_symbols.begin(); it!=m_symbols.end(); ++it )
{
RC::ConstHandle<Symbol> const &symbol = *it;
if ( symbol->isValue() )
{
RC::ConstHandle<ValueSymbol> valueSymbol = RC::ConstHandle<ValueSymbol>::StaticCast( symbol );
if ( valueSymbol->isVariable() )
{
RC::ConstHandle<VariableSymbol> variableSymbol = RC::ConstHandle<VariableSymbol>::StaticCast( valueSymbol );
ExprValue exprValue = variableSymbol->getExprValue();
llvm::Value *rValue = 0, *lValue = 0;
RC::ConstHandle<Adapter> adapter = exprValue.getAdapter();
switch ( exprValue.getUsage() )
{
case USAGE_RVALUE:
rValue = exprValue.getValue();
lValue = adapter->llvmRValueToLValue( bbb, rValue );
break;
case USAGE_LVALUE:
lValue = exprValue.getValue();
rValue = adapter->llvmLValueToRValue( bbb, lValue );
break;
default:
FABRIC_ASSERT( false );
break;
}
exprValue.getAdapter()->llvmDispose( bbb, lValue );
}
}
}
}
virtual void llvmBreak( BasicBlockBuilder &bbb, Location const &location ) const
{
llvmUnwind( bbb );
if ( !m_parentScope )
throw Error( location, "break outside of loop or switch statment" );
m_parentScope->llvmBreak( bbb, location );
}
virtual void llvmContinue( BasicBlockBuilder &bbb, Location const &location ) const
{
llvmUnwind( bbb );
if ( !m_parentScope )
throw Error( location, "continue outside of loop" );
m_parentScope->llvmContinue( bbb, location );
}
virtual ReturnInfo const &getReturnInfo() const
{
FABRIC_ASSERT( m_parentScope );
return m_parentScope->getReturnInfo();
}
virtual llvm::Value *llvmGetReturnLValue() const
{
FABRIC_ASSERT( m_parentScope );
return m_parentScope->llvmGetReturnLValue();
}
void llvmReturn( BasicBlockBuilder &bbb, ExprValue &exprValue ) const
{
ExprType const &returnExprType = getReturnInfo().getExprType();
if ( returnExprType )
{
FABRIC_ASSERT( exprValue );
RC::ConstHandle<Adapter> returnAdapter = returnExprType.getAdapter();
llvm::Value *returnRValue = returnAdapter->llvmCast( bbb, exprValue );
llvm::Value *returnLValue = llvmGetReturnLValue();
returnAdapter->llvmAssign( bbb, returnLValue, returnRValue );
}
else FABRIC_ASSERT( !exprValue );
llvmReturn( bbb );
}
protected:
Scope()
: m_parentScope( 0 )
{
}
virtual void llvmReturn( BasicBlockBuilder &bbb ) const
{
llvmUnwind( bbb );
FABRIC_ASSERT( m_parentScope );
m_parentScope->llvmReturn( bbb );
}
private:
typedef std::vector< RC::ConstHandle<Symbol> > SymbolVector;
typedef Util::UnorderedMap< std::string, RC::ConstHandle<Symbol> > StringToSymbolMap;
SymbolVector m_symbols;
StringToSymbolMap m_namedSymbols;
Scope const *m_parentScope;
};
class LoopScope : public Scope
{
public:
LoopScope( Scope const &parentScope, llvm::BasicBlock *doneBB, llvm::BasicBlock *nextBB )
: Scope( parentScope )
, m_doneBB( doneBB )
, m_nextBB( nextBB )
{
}
virtual void llvmBreak( BasicBlockBuilder &bbb, Location const &location ) const
{
bbb->CreateBr( m_doneBB );
}
virtual void llvmContinue( BasicBlockBuilder &bbb, Location const &location ) const
{
bbb->CreateBr( m_nextBB );
}
private:
llvm::BasicBlock *m_doneBB;
llvm::BasicBlock *m_nextBB;
};
class SwitchScope : public Scope
{
public:
SwitchScope( Scope const &parentScope, llvm::BasicBlock *breakBB )
: Scope( parentScope )
, m_breakBB( breakBB )
{
}
virtual void llvmBreak( BasicBlockBuilder &bbb, Location const &location ) const
{
bbb->CreateBr( m_breakBB );
}
private:
llvm::BasicBlock *m_breakBB;
};
class ModuleScope : public Scope
{
public:
ModuleScope()
: Scope()
{
}
};
class FunctionScope : public Scope
{
public:
FunctionScope( ModuleScope const &parentScope, ReturnInfo const &returnInfo )
: Scope( parentScope )
, m_returnInfo( returnInfo )
, m_returnLValue( 0 )
{
}
void llvmPrepareReturnLValue( BasicBlockBuilder &bbb )
{
RC::ConstHandle<Adapter> returnAdapter = m_returnInfo.getAdapter();
if ( returnAdapter )
{
if ( !m_returnInfo.usesReturnLValue() )
{
m_returnLValue = returnAdapter->llvmAlloca( bbb, "returnLValue" );
returnAdapter->llvmInit( bbb, m_returnLValue );
}
}
}
virtual llvm::Value *llvmGetReturnLValue() const
{
RC::ConstHandle<Adapter> returnAdapter = m_returnInfo.getAdapter();
if ( returnAdapter )
{
if ( !m_returnInfo.usesReturnLValue() )
{
FABRIC_ASSERT( m_returnLValue );
return m_returnLValue;
}
else return m_returnInfo.getReturnLValue();
}
else return 0;
}
virtual ReturnInfo const &getReturnInfo() const
{
return m_returnInfo;
}
protected:
virtual void llvmReturn( BasicBlockBuilder &bbb ) const
{
llvmUnwind( bbb );
RC::ConstHandle<Adapter> returnAdapter = m_returnInfo.getAdapter();
if ( returnAdapter )
{
if( m_returnInfo.usesReturnLValue() )
{
bbb->CreateRetVoid();
}
else
{
llvm::Value *returnRValue = returnAdapter->llvmLValueToRValue( bbb, llvmGetReturnLValue() );
bbb->CreateRet( returnRValue );
}
}
else bbb->CreateRetVoid();
}
private:
ReturnInfo m_returnInfo;
llvm::Value *m_returnLValue;
};
}
}
#endif //_FABRIC_CG_SCOPE_H
| chbfiv/fabric-engine-old | Native/Core/CG/Scope.h | C | agpl-3.0 | 8,376 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_balance_report(osv.osv_memory):
_inherit = "account.common.account.report"
_name = 'account.balance.report'
_description = 'Trial Balance Report'
_columns = {
'journal_ids': fields.many2many('account.journal', 'account_balance_report_journal_rel', 'account_id', 'journal_id', 'Journals', required=True),
}
_defaults = {
'journal_ids': [],
}
def _print_report(self, cr, uid, ids, data, context=None):
data = self.pre_print_report(cr, uid, ids, data, context=context)
return {'type': 'ir.actions.report.xml', 'report_name': 'account.account.balance', 'datas': data}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| jmesteve/saas3 | openerp/addons/account/wizard/account_report_account_balance.py | Python | agpl-3.0 | 1,729 |
class CreatePollWhiteResults < ActiveRecord::Migration[4.2]
def change
create_table :poll_white_results do |t|
t.integer :author_id
t.integer :amount
t.string :origin
t.date :date
t.integer :booth_assignment_id
t.integer :officer_assignment_id
t.text :amount_log, default: ""
t.text :officer_assignment_id_log, default: ""
t.text :author_id_log, default: ""
end
add_index :poll_white_results, :officer_assignment_id
add_index :poll_white_results, :booth_assignment_id
end
end
| AyuntamientoPuertoReal/decidePuertoReal | db/migrate/20170203163304_create_poll_white_results.rb | Ruby | agpl-3.0 | 591 |
<?php
/*********************************************************************************
* TimeTrex is a Payroll and Time Management program developed by
* TimeTrex Software Inc. Copyright (C) 2003 - 2014 TimeTrex Software Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY TIMETREX, TIMETREX DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact TimeTrex headquarters at Unit 22 - 2475 Dobbin Rd. Suite
* #292 Westbank, BC V4T 2E9, Canada or at email address info@timetrex.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by TimeTrex" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by TimeTrex".
********************************************************************************/
/**
* @package Modules\Install
*/
class InstallSchema extends Install {
protected $schema_version = NULL;
protected $obj = NULL;
function __construct( $database_type, $version, $db_conn, $is_upgrade = FALSE ) {
Debug::text('Database Type: '. $database_type .' Version: '. $version, __FILE__, __LINE__, __METHOD__, 10);
$this->database_type = $database_type;
$this->schema_version = $version;
if ( $database_type == '' ) {
return FALSE;
}
if ( $version == '' ) {
return FALSE;
}
$schema_class_file_name = Environment::getBasePath() . DIRECTORY_SEPARATOR .'classes'. DIRECTORY_SEPARATOR .'modules'. DIRECTORY_SEPARATOR .'install'. DIRECTORY_SEPARATOR .'InstallSchema_'. $version .'.class.php';
$schema_sql_file_name = $this->getSchemaSQLFilename( $version );
if ( file_exists($schema_class_file_name)
AND file_exists($schema_sql_file_name ) ) {
include_once( $schema_class_file_name );
$class_name = 'InstallSchema_'. $version;
$this->obj = new $class_name( $this ); //Pass current Install class object to the schema class, so we can call common functions.
$this->obj->setDatabaseConnection( $db_conn );
$this->obj->setIsUpgrade( $is_upgrade );
$this->obj->setVersion( $version );
$this->obj->setSchemaSQLFilename( $this->getSchemaSQLFilename() );
return TRUE;
} else {
Debug::text('Schema Install Class File DOES NOT Exists - File Name: '. $schema_class_file_name .' Schema SQL File: '. $schema_sql_file_name, __FILE__, __LINE__, __METHOD__, 10);
}
return FALSE;
}
function getSQLFileDirectory() {
return Environment::getBasePath() . DIRECTORY_SEPARATOR .'classes'. DIRECTORY_SEPARATOR .'modules'. DIRECTORY_SEPARATOR .'install'. DIRECTORY_SEPARATOR .'sql'. DIRECTORY_SEPARATOR . $this->database_type . DIRECTORY_SEPARATOR;
}
function getSchemaSQLFilename() {
return $this->getSQLFileDirectory() . $this->schema_version .'.sql';
}
//load Schema file data
function getSchemaSQLFileData() {
}
private function getObject() {
if ( is_object($this->obj) ) {
return $this->obj;
}
return FALSE;
}
function __call($function_name, $args = array() ) {
if ( $this->getObject() !== FALSE ) {
//Debug::text('Calling Sub-Class Function: '. $function_name, __FILE__, __LINE__, __METHOD__, 10);
if ( is_callable( array($this->getObject(), $function_name) ) ) {
$return = call_user_func_array(array($this->getObject(), $function_name), $args);
return $return;
}
}
Debug::text('Sub-Class Function Call FAILED!:'. $function_name, __FILE__, __LINE__, __METHOD__, 10);
return FALSE;
}
}
?>
| maestrano/timetrex | classes/modules/install/InstallSchema.class.php | PHP | agpl-3.0 | 4,618 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
# Jordi Esteve <jesteve@zikzakmedia.com>
# $Id$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
"""
Spanish Fiscal Year Closing Wizards
"""
import wizard_run
| jmesteve/saas3 | openerp/addons_extra/l10n_es_fiscal_year_closing/wizard/__init__.py | Python | agpl-3.0 | 1,141 |
// Sifer Aseph
// Empty
| Surufel/Personal | 1.sifer--/Out of Date/Empty.h | C | agpl-3.0 | 24 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2013-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.features.topology.plugins.browsers;
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.opennms.core.criteria.Criteria;
import org.opennms.netmgt.dao.api.AlarmDao;
import org.opennms.netmgt.dao.mock.MockTransactionTemplate;
import org.opennms.netmgt.model.OnmsAlarm;
public class OnmsDaoContainerTest {
@Test
public void testGetItemIdsWithOnlyOneItem() {
MockTransactionTemplate transactionTemplate = new MockTransactionTemplate();
transactionTemplate.afterPropertiesSet();
List<OnmsAlarm> alarmList = new ArrayList<>();
OnmsAlarm alarm = new OnmsAlarm();
alarm.setId(102);
alarmList.add(alarm);
final AlarmDao alarmDaoMock = EasyMock.createNiceMock(AlarmDao.class);
EasyMock.expect(alarmDaoMock.countMatching((Criteria)EasyMock.anyObject())).andReturn(1);
EasyMock.expect(alarmDaoMock.findMatching((Criteria)EasyMock.anyObject())).andReturn(alarmList);
EasyMock.replay(alarmDaoMock);
AlarmDaoContainer container = new AlarmDaoContainer(alarmDaoMock, transactionTemplate);
List<Integer> items = container.getItemIds(0, 1);
Assert.assertNotNull(items);
Assert.assertEquals(1, items.size());
}
}
| aihua/opennms | features/topology-map/plugins/org.opennms.features.topology.plugins.browsers/src/test/java/org/opennms/features/topology/plugins/browsers/OnmsDaoContainerTest.java | Java | agpl-3.0 | 2,542 |
class AddLastInlineViewToAttachments < ActiveRecord::Migration[4.2]
tag :predeploy
def self.up
add_column :attachments, :last_inline_view, :datetime
end
def self.down
remove_column :attachments, :last_inline_view
end
end
| matematikk-mooc/canvas-lms | db/migrate/20130521223335_add_last_inline_view_to_attachments.rb | Ruby | agpl-3.0 | 241 |
// Copyright 2012 Evrytania LLC (http://www.evrytania.com)
//
// Written by James Peroulas <james@evrytania.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Improved by Jiao Xianjun (putaoshu@gmail.com):
// 1. TD-LTE support
// 2. OpenCL to speedup
// 3. fast pre-search frequencies (external mixer/LNB support)
// 4. multiple tries at one frequency
// 5. .bin file recording and replaying
// 6. hackrf support
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <itpp/itbase.h>
#include <itpp/stat/misc_stat.h>
#include <boost/math/special_functions/gamma.hpp>
#include <list>
#include <sstream>
#include <curses.h>
#include <sys/time.h>
#include <signal.h>
#include "common.h"
#ifdef HAVE_RTLSDR
#include "rtl-sdr.h"
#endif
#ifdef HAVE_HACKRF
#include "hackrf.h"
#endif
#ifdef HAVE_BLADERF
#include <libbladeRF.h>
extern volatile bool do_exit;
#ifdef _MSC_VER
BOOL WINAPI
sighandler(int signum)
{
if (CTRL_C_EVENT == signum) {
fprintf(stdout, "Caught signal %d\n", signum);
do_exit = true;
return TRUE;
}
return FALSE;
}
#else
void sigint_callback_handler(int signum)
{
fprintf(stdout, "Caught signal %d\n", signum);
do_exit = true;
}
#endif
#endif // HAVE_BLADERF
#include "macros.h"
#include "lte_lib.h"
#include "constants.h"
#include "capbuf.h"
#include "filter_coef.h"
#include "itpp_ext.h"
#include "searcher.h"
#include "dsp.h"
using namespace itpp;
using namespace std;
uint8 verbosity=1;
// Simple usage screen.
void print_usage() {
cout << "LTE CellSearch (" << BUILD_TYPE << ") help. 1.0 to " << MAJOR_VERSION << "." << MINOR_VERSION << "." << PATCH_LEVEL << ": OpenCL/TDD/HACKRF/bladeRF/ext-LNB added by Jiao Xianjun(putaoshu@gmail.com)" << endl << endl;
cout << "CellSearch -s start_frequency [optional_parameters]" << endl;
cout << " Basic options" << endl;
cout << " -h --help" << endl;
cout << " print this help screen" << endl;
cout << " -v --verbose" << endl;
cout << " increase status messages from program" << endl;
cout << " -b --brief" << endl;
cout << " reduce status messages from program" << endl;
cout << " -i --device-index N" << endl;
cout << " specify which attached RTLSDR device to use" << endl;
cout << " -a --opencl-platform N" << endl;
cout << " specify which OpenCL platform to use (default: 0)" << endl;
cout << " -g --gain G" << endl;
cout << " specify gain to hardware (rtl default 0(auto); HACKRF default 40; bladeRF default LNA-MAX VGA-66)" << endl;
cout << " -j --opencl-device N" << endl;
cout << " specify which OpenCL device of selected platform to use (default: 0)" << endl;
cout << " -w --filter-workitem N" << endl;
cout << " specify how many OpenCL workitems are used for the 1st dim of 6RB filter (you'd better use values like 2^n)" << endl;
cout << " -u --xcorr-workitem N" << endl;
cout << " specify how many OpenCL workitems are used for the PSS xcorr (you'd better use values like 2^n)" << endl;
cout << " Frequency search options:" << endl;
cout << " -s --freq-start fs" << endl;
cout << " frequency where cell search should start" << endl;
cout << " -e --freq-end fe" << endl;
cout << " frequency where cell search should end" << endl;
cout << " -n --num-try nt" << endl;
cout << " number of tries at each frequency/file (default: 1)" << endl;
cout << " -m --num-reserve N" << endl;
cout << " number of reserved frequency-ppm peak pairs in pre-search phase (default: 1)" << endl;
cout << " Dongle LO correction options:" << endl;
cout << " -t --twisted" << endl;
cout << " enable original sampling-carrier-twisted mode (default is disable and using carrier&sampling isolated pre-search to support external mixer/LNB)" << endl;
cout << " -p --ppm ppm" << endl;
cout << " crystal remaining PPM error" << endl;
cout << " -c --correction c" << endl;
cout << " crystal correction factor" << endl;
cout << " Capture buffer save/ load options:" << endl;
cout << " -z --recbin" << endl;
cout << " save captured data in the bin file. (only supports single frequency scanning)" << endl;
cout << " -y --loadbin" << endl;
cout << " used data in captured bin file. (only supports single frequency scanning)" << endl;
cout << " -r --record" << endl;
cout << " save captured data in the files capbuf_XXXX.it" << endl;
cout << " -l --load" << endl;
cout << " used data in capbuf_XXXX.it files instead of live data" << endl;
cout << " -d --data-dir dir" << endl;
cout << " directory where capbuf_XXXX.it files are located" << endl << endl;
cout << "'c' is the correction factor to apply and indicates that if the desired" << endl;
cout << "center frequency is fc, the RTL-SDR dongle should be instructed to tune" << endl;
cout << "to freqency fc*c so that its true frequency shall be fc. Default: 1.0" << endl << endl;
cout << "'ppm' is the remaining frequency error of the crystal. Default: - (search -140kHz to 135kHz)" << endl;
cout << "" << endl;
cout << "If the crystal has not been used for a long time, use the default values for" << endl;
cout << "'ppm' and 'c' until a cell is successfully located. The program will return" << endl;
cout << "a 'c' value that can be used in the future, assuming that the crystal's" << endl;
cout << "frequency accuracy does not change significantly." << endl;
cout << "" << endl;
cout << "Even if a correction factor has been calculated, there is usually some" << endl;
cout << "remaining frequency error in the crystal. Thus, although after a c value is" << endl;
cout << "calculated the ppm value can be reduced, it can not be reduced to 0." << endl;
cout << "10.0 is a reasiable ppm value to use after a correction factor has been" << endl;
cout << "calculated." << endl;
}
// Parse the command line arguments and return optional parameters as
// variables.
// Also performs some basic sanity checks on the parameters.
void parse_commandline(
// Inputs
const int & argc,
char * const argv[],
// Outputs
double & freq_start,
double & freq_end,
uint16 & num_try,
bool & sampling_carrier_twist,
double & ppm,
double & correction,
bool & save_cap,
bool & use_recorded_data,
string & data_dir,
int & device_index,
char * record_bin_filename,
char * load_bin_filename,
uint16 & opencl_platform,
uint16 & opencl_device,
uint16 & filter_workitem,
uint16 & xcorr_workitem,
uint16 & num_reserve,
uint16 & num_loop,
int16 & gain
) {
// Default values
freq_start=-1;
freq_end=-1;
num_try=1; // default number
sampling_carrier_twist=false;
ppm=0;
correction=1;
save_cap=false;
use_recorded_data=false;
data_dir=".";
device_index=-1;
opencl_platform = 0;
opencl_device = 0;
filter_workitem = 32;
xcorr_workitem = 2;
num_reserve = 2;
num_loop = 0;
gain = -9999;
while (1) {
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"brief", no_argument, 0, 'b'},
{"freq-start", required_argument, 0, 's'},
{"freq-end", required_argument, 0, 'e'},
{"num-try", required_argument, 0, 'n'},
{"twisted", no_argument, 0, 't'},
{"ppm", required_argument, 0, 'p'},
{"correction", required_argument, 0, 'c'},
{"recbin", required_argument, 0, 'z'},
{"loadbin", required_argument, 0, 'y'},
{"record", no_argument, 0, 'r'},
{"load", no_argument, 0, 'l'},
{"data-dir", required_argument, 0, 'd'},
{"device-index", required_argument, 0, 'i'},
{"opencl-platform", required_argument, 0, 'a'},
{"gain", required_argument, 0, 'g'},
{"opencl-device", required_argument, 0, 'j'},
{"filter-workitem", required_argument, 0, 'w'},
{"xcorr-workitem", required_argument, 0, 'u'},
{"num-reserve", required_argument, 0, 'm'},
{"num-loop", required_argument, 0, 'k'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
int c = getopt_long (argc, argv, "hvbs:e:n:tp:c:z:y:rld:i:a:g:j:w:u:m:k:",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c) {
char * endp;
case 0:
// Code should only get here if a long option was given a non-null
// flag value.
cout << "Check code!" << endl;
ABORT(-1);
break;
case 'h':
print_usage();
ABORT(-1);
break;
case 'v':
verbosity=2;
break;
case 'b':
verbosity=0;
break;
case 's':
freq_start=strtod(optarg,&endp);
if ((optarg==endp)||(*endp!='\0')) {
cerr << "Error: could not parse start frequency" << endl;
ABORT(-1);
}
break;
case 'e':
freq_end=strtod(optarg,&endp);
if ((optarg==endp)||(*endp!='\0')) {
cerr << "Error: could not parse end frequency" << endl;
ABORT(-1);
}
break;
case 'n':
num_try=strtol(optarg,&endp,10);
if ((optarg==endp)||(*endp!='\0')) {
cerr << "Error: could not parse number of tries" << endl;
ABORT(-1);
}
break;
case 't':
sampling_carrier_twist=true;
break;
case 'p':
ppm=strtod(optarg,&endp);
if ((optarg==endp)||(*endp!='\0')) {
cerr << "Error: could not parse ppm value" << endl;
ABORT(-1);
}
break;
case 'c':
correction=strtod(optarg,&endp);
if ((optarg==endp)||(*endp!='\0')) {
cerr << "Error: could not parse correction factor" << endl;
ABORT(-1);
}
break;
case 'r':
save_cap=true;
break;
case 'l':
use_recorded_data=true;
break;
case 'z':
{
int len_str = strlen(optarg);
if (len_str<5)
{
cerr << "Error: record bin filename too short" << endl;
ABORT(-1);
}
if ( (len_str<1) || (strcmp(optarg+len_str-4, ".bin")) )
{
cerr << "Error: could not parse record bin filename (must be .bin file)" << endl;
ABORT(-1);
}
else
{
strcpy(record_bin_filename, optarg);
}
}
break;
case 'y':
{
int len_str = strlen(optarg);
if (len_str<5)
{
cerr << "Error: load bin filename too short" << endl;
ABORT(-1);
}
if ( (len_str<1) || (strcmp(optarg+len_str-4, ".bin")) )
{
cerr << "Error: could not parse load bin filename (must be .bin file)" << endl;
ABORT(-1);
}
else
{
strcpy(load_bin_filename, optarg);
//freq_start=9999e6; // fake
}
}
break;
case 'd':
data_dir=optarg;
break;
case 'i':
device_index=strtol(optarg,&endp,10);
if ((optarg==endp)||(*endp!='\0')) {
cerr << "Error: could not parse device index" << endl;
ABORT(-1);
}
if (device_index<0) {
cerr << "Error: device index cannot be negative" << endl;
ABORT(-1);
}
break;
case 'a':
opencl_platform=strtol(optarg,&endp,10);
break;
case 'g':
gain=strtol(optarg,&endp,10);
break;
case 'j':
opencl_device=strtol(optarg,&endp,10);
break;
case 'w':
filter_workitem=strtol(optarg,&endp,10);
case 'u':
xcorr_workitem=strtol(optarg,&endp,10);
break;
case 'm':
num_reserve=strtol(optarg,&endp,10);
break;
case 'k':
num_loop = strtol(optarg,&endp,10);
break;
case '?':
/* getopt_long already printed an error message. */
ABORT(-1);
default:
ABORT(-1);
}
}
// Error if extra arguments are found on the command line
if (optind < argc) {
cerr << "Error: unknown/extra arguments specified on command line" << endl;
ABORT(-1);
}
// Second order command line checking. Ensure that command line options
// are consistent.
if (freq_start==-1) {
// if (!sampling_carrier_twist) {
freq_start=9999e6; // fake
cout << "Warning: Frequency not specified. Make sure you are working on captured file.\n";
// } else {
// cerr << "Error: must specify a start frequency. (Try --help)" << endl;
// ABORT(-1);
// }
}
// Start and end frequencies should be on a 100kHz raster.
if (freq_start<1e6) {
cerr << "Error: start frequency must be greater than 1MHz" << endl;
ABORT(-1);
}
// Number of tries should be not less than 1.
if (num_try<1) {
cerr << "Error: number of tries at each frequency/file should be not less than 1" << endl;
ABORT(-1);
}
// if (freq_start/100e3!=itpp::round(freq_start/100e3)) {
// freq_start=itpp::round(freq_start/100e3)*100e3;
// cout << "Warning: start frequency has been rounded to the nearest multiple of 100kHz" << endl;
// }
if (freq_end==-1) {
freq_end=freq_start;
}
if (freq_end<freq_start) {
cerr << "Error: end frequency must be >= start frequency" << endl;
ABORT(-1);
}
// if (freq_end/100e3!=itpp::round(freq_end/100e3)) {
// freq_end=itpp::round(freq_end/100e3)*100e3;
// cout << "Warning: end frequency has been rounded to the nearest multiple of 100kHz" << endl;
// }
// PPM values should be positive an most likely less than 200 ppm.
if (ppm<0) {
cerr << "Error: ppm value must be positive" << endl;
ABORT(-1);
}
if (ppm>200) {
cout << "Warning: ppm value appears to be set unreasonably high" << endl;
}
// Warn if correction factor is greater than 1000 ppm.
if (abs(correction-1)>1000e-6) {
cout << "Warning: crystal correction factor appears to be unreasonable" << endl;
}
// Should never both read and write captured data from a file
if (save_cap&&use_recorded_data) {
cerr << "Error: cannot read and write captured data at the same time!" << endl;
ABORT(-1);
}
// Should never both read from .it and read from .bin file.
if ( use_recorded_data && (strlen(load_bin_filename)>4) ) {
cerr << "Error: cannot read from .it and .bin file at the same time!" << endl;
ABORT(-1);
}
if (verbosity>=1) {
cout << "LTE CellSearch (" << BUILD_TYPE << ") beginning. 1.0 to " << MAJOR_VERSION << "." << MINOR_VERSION << "." << PATCH_LEVEL << ": OpenCL/TDD/HACKRF/bladeRF/ext-LNB added by Jiao Xianjun(putaoshu@gmail.com)" << endl;
// // frequency information will be displayed in main() function.
// if (freq_start==freq_end) {
// cout << " Search frequency: " << freq_start/1e6 << " MHz" << endl;
// } else {
// cout << " Search frequency range: " << freq_start/1e6 << "-" << freq_end/1e6 << " MHz" << endl;
// }
// if (sampling_carrier_twist) {
cout << " PPM: " << ppm << endl;
stringstream temp;
temp << setprecision(20) << correction;
cout << " correction: " << temp.str() << endl;
// }
if (save_cap)
cout << " Captured data will be saved in capbufXXXX.it files" << endl;
if (use_recorded_data)
cout << " Captured data will be read from capbufXXXX.it files" << endl;
}
}
// In high SNR environments, a cell may be detected on different carrier
// frequencies and with different frequency offsets. Keep only the cell
// with the highest received power.
void dedup(
const vector < list<Cell> > & detected_cells,
list <Cell> & cells_final
) {
cells_final.clear();
for (uint16 t=0;t<detected_cells.size();t++) {
list <Cell>::const_iterator it_n=detected_cells[t].begin();
while (it_n!=detected_cells[t].end()) {
bool match=false;
list <Cell>::iterator it_f=cells_final.begin();
while (it_f!=cells_final.end()) {
// Do these detected cells match and are they close to each other
// in frequency?
if (
((*it_n).n_id_cell()==(*it_f).n_id_cell()) &&
(abs(((*it_n).fc_requested+(*it_n).freq_superfine)-((*it_f).fc_requested+(*it_f).freq_superfine))<1e6)
) {
match=true;
// Keep either the new cell or the old cell, but not both.
if ((*it_n).pss_pow>(*it_f).pss_pow) {
(*it_f)=(*it_n);
}
break;
}
++it_f;
}
if (!match) {
// This cell does not match any previous cells. Add this to the
// final list of cells.
cells_final.push_back((*it_n));
}
++it_n;
}
}
}
// Helper function to assist in formatting frequency offsets.
string freq_formatter(
const double & freq
) {
stringstream temp;
if (abs(freq)<998.0) {
temp << setw(5) << setprecision(3) << freq << "h";
} else if (abs(freq)<998000.0) {
temp << setw(5) << setprecision(3) << freq/1e3 << "k";
} else if (abs(freq)<998000000.0) {
temp << setw(5) << setprecision(3) << freq/1e6 << "m";
} else if (abs(freq)<998000000000.0) {
temp << setw(5) << setprecision(3) << freq/1e9 << "g";
} else if (abs(freq)<998000000000000.0) {
temp << setw(5) << setprecision(3) << freq/1e12 << "t";
} else {
temp << freq;
}
return temp.str();
}
#ifdef HAVE_RTLSDR
// Open the RTLSDR device
int config_rtlsdr(
const bool & sampling_carrier_twist,
const double & correction,
const int32 & device_index_cmdline,
const double & fc,
rtlsdr_device *& dev,
double & fs_programmed,
const int16 & gain
) {
int32 device_index=device_index_cmdline;
int8 n_rtlsdr=rtlsdr_get_device_count();
if (n_rtlsdr==0) {
cerr << "config_rtlsdr Error: no RTL-SDR USB devices found..." << endl;
// ABORT(-1);
return(1);
}
// Choose which device to use
if ((n_rtlsdr==1)&&(device_index==-1)) {
device_index=0;
}
if ((device_index<0)||(device_index>=n_rtlsdr)) {
cerr << "config_rtlsdr Error: must specify which USB device to use with --device-index" << endl;
cerr << "config_rtlsdr Found the following USB devices:" << endl;
char vendor[256],product[256],serial[256];
for (uint8 t=0;t<n_rtlsdr;t++) {
rtlsdr_get_device_usb_strings(t,vendor,product,serial);
cerr << "Device index " << t << ": [Vendor: " << vendor << "] [Product: " << product << "] [Serial#: " << serial << "]" << endl;
}
// ABORT(-1);
return(1);
}
// Open device
if (rtlsdr_open(&dev,device_index)<0) {
cerr << "config_rtlsdr Error: unable to open RTLSDR device" << endl;
// ABORT(-1);
return(1);
}
double sampling_rate = 0;
// if (sampling_carrier_twist)
sampling_rate = (FS_LTE/16)*correction;
// else
// sampling_rate = 1920000;
// Sampling frequency
if (rtlsdr_set_sample_rate(dev,itpp::round(sampling_rate))<0) {
cerr << "config_rtlsdr Error: unable to set sampling rate" << endl;
// ABORT(-1);
return(1);
}
// Calculate the actual fs that was programmed
fs_programmed=(double)rtlsdr_get_sample_rate(dev);
// Center frequency
uint8 n_fail=0;
while (rtlsdr_set_center_freq(dev,itpp::round(fc*correction))<0) {
n_fail++;
if (n_fail>=5) {
cerr << "config_rtlsdr Error: unable to set center frequency" << endl;
// ABORT(-1);
return(1);
}
cerr << "config_rtlsdr Unable to set center frequency... retrying..." << endl;
sleep(1);
}
int gain_tmp = gain;
if (gain == -9999)
gain_tmp = 0;
if (gain_tmp==0) {
// Turn on AGC
if (rtlsdr_set_tuner_gain_mode(dev,0)<0) {
cerr << "config_rtlsdr Error: unable to enter AGC mode" << endl;
// ABORT(-1);
return(1);
}
} else {
if (rtlsdr_set_tuner_gain_mode(dev,1)<0) {
cerr << "config_rtlsdr Error: unable to enter manual gain mode" << endl;
return(1);
}
if (rtlsdr_set_tuner_gain(dev, gain_tmp*10)<0) {
cerr << "config_rtlsdr Error: unable to rtlsdr_set_tuner_gain" << endl;
return(1);
}
}
// Reset the buffer
if (rtlsdr_reset_buffer(dev)<0) {
cerr << "config_rtlsdr Error: unable to reset RTLSDR buffer" << endl;
// ABORT(-1);
return(1);
}
// Discard about 1.5s worth of data to give the AGC time to converge
if (verbosity>=2) {
cout << "config_rtlsdr Waiting for AGC to converge..." << endl;
}
uint32 n_read=0;
int n_read_current;
#define BLOCK_SIZE 16*16384
uint8 * buffer=(uint8 *)malloc(BLOCK_SIZE*sizeof(uint8));
while (true) {
if (rtlsdr_read_sync(dev,buffer,BLOCK_SIZE,&n_read_current)<0) {
cerr << "config_rtlsdr Error: synchronous read failed" << endl;
// ABORT(-1);
return(1);
}
if (n_read_current<BLOCK_SIZE) {
cerr << "config_rtlsdr Error: short read; samples lost" << endl;
// ABORT(-1);
return(1);
}
n_read+=n_read_current;
if (n_read>2880000*2)
break;
}
free(buffer);
return(0);
}
#endif // HAVE_RTLSDR
#ifdef HAVE_HACKRF
// Open the HACKRF device
int config_hackrf(
const bool & sampling_carrier_twist,
const double & correction,
const int32 & device_index_cmdline,
const double & fc,
hackrf_device * & dev,
double & fs_programmed,
const int16 & gain
) {
unsigned int lna_gain=40; // default value
unsigned int vga_gain=40; // default value
if (gain!=-9999)
vga_gain = (gain/2)*2;
int result = hackrf_init();
if( result != HACKRF_SUCCESS ) {
printf("config_hackrf hackrf_init() failed: %s (%d)\n", hackrf_error_name((hackrf_error)result), result);
// ABORT(-1);
return(result);
}
result = hackrf_open(&dev);
if( result != HACKRF_SUCCESS ) {
printf("config_hackrf hackrf_open() failed: %s (%d)\n", hackrf_error_name((hackrf_error)result), result);
// ABORT(-1);
return(result);
}
double sampling_rate = (FS_LTE/16)*correction;
// Sampling frequency
result = hackrf_set_sample_rate_manual(dev, sampling_rate, 1);
if( result != HACKRF_SUCCESS ) {
printf("config_hackrf hackrf_sample_rate_set() failed: %s (%d)\n", hackrf_error_name((hackrf_error)result), result);
// ABORT(-1);
return(result);
}
// Need to handle in the future
fs_programmed=sampling_rate;
result = hackrf_set_baseband_filter_bandwidth(dev, 1.45e6);
if( result != HACKRF_SUCCESS ) {
printf("config_hackrf hackrf_baseband_filter_bandwidth_set() failed: %s (%d)\n", hackrf_error_name((hackrf_error)result), result);
// ABORT(-1);
return(result);
}
result = hackrf_set_vga_gain(dev, vga_gain);
result |= hackrf_set_lna_gain(dev, lna_gain);
if( result != HACKRF_SUCCESS ) {
printf("config_hackrf hackrf_set_vga_gain hackrf_set_lna_gain failed: %s (%d)\n", hackrf_error_name((hackrf_error)result), result);
// ABORT(-1);
return(result);
}
// Center frequency
result = hackrf_set_freq(dev, fc);
if( result != HACKRF_SUCCESS ) {
printf("config_hackrf hackrf_set_freq() failed: %s (%d)\n", hackrf_error_name((hackrf_error)result), result);
// ABORT(-1);
return(result);
}
// test read samples from dev
cvec capbuf(CAPLENGTH);
double fc_programmed;
rtlsdr_device *fake_rtlsdr_dev = NULL;
bladerf_device *fake_bladerf_dev = NULL;
capture_data(fc, 1, false, " ", false, " ", " ",fake_rtlsdr_dev,dev,fake_bladerf_dev,dev_type_t::HACKRF, capbuf, fc_programmed, fs_programmed,0);
return(result);
}
#endif
#ifdef HAVE_BLADERF
static inline const char *backend2str(bladerf_backend b)
{
switch (b) {
case BLADERF_BACKEND_LIBUSB:
return "libusb";
case BLADERF_BACKEND_LINUX:
return "Linux kernel driver";
default:
return "Unknown";
}
}
// Open the BLADERF device
int config_bladerf(
const bool & sampling_carrier_twist,
const double & correction,
const int32 & device_index_cmdline,
const double & fc,
bladerf_device * & dev,
double & fs_programmed,
const int16 & gain
) {
bladerf_devinfo *devices = NULL;
int n_devices = bladerf_get_device_list(&devices);
if (n_devices < 0) {
if (n_devices == BLADERF_ERR_NODEV) {
printf("config_bladerf bladerf_get_device_list: No bladeRF devices found.\n");
} else {
printf("config_bladerf bladerf_get_device_list: Failed to probe for bladeRF devices: %s\n", bladerf_strerror(n_devices));
}
return(-1);
}
printf("init_board: %d bladeRF devices found! The 1st one will be used:\n", n_devices);
printf(" Backend: %s\n", backend2str(devices[0].backend));
printf(" Serial: %s\n", devices[0].serial);
printf(" USB Bus: %d\n", devices[0].usb_bus);
printf(" USB Address: %d\n", devices[0].usb_addr);
int fpga_loaded;
int status = bladerf_open(&dev, NULL);
if (status != 0) {
printf("config_bladerf bladerf_open: Failed to open bladeRF device: %s\n",
bladerf_strerror(status));
return(-1);
}
fpga_loaded = bladerf_is_fpga_configured(dev);
if (fpga_loaded < 0) {
printf("config_bladerf bladerf_is_fpga_configured: Failed to check FPGA state: %s\n",
bladerf_strerror(fpga_loaded));
status = -1;
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
} else if (fpga_loaded == 0) {
printf("config_bladerf bladerf_is_fpga_configured: The device's FPGA is not loaded.\n");
status = -1;
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
double sampling_rate = (FS_LTE/16)*correction;
unsigned int actual_sample_rate;
status = bladerf_set_sample_rate(dev, BLADERF_MODULE_RX, (unsigned int)sampling_rate, &actual_sample_rate);
if (status != 0) {
printf("config_bladerf bladerf_set_sample_rate: Failed to set samplerate: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
fs_programmed = actual_sample_rate;
unsigned int actual_bw;
status = bladerf_set_bandwidth(dev, BLADERF_MODULE_RX, 1500000, &actual_bw);
if (status != 0) {
printf("config_bladerf bladerf_set_bandwidth: Failed to set bandwidth: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
int gian_set = (gain==-9999?66:gain);
status = bladerf_set_gain(dev, BLADERF_MODULE_RX, gian_set);
if (status != 0) {
printf("config_bladerf bladerf_set_gain: Failed to set gain: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
bladerf_lna_gain actual_lna_gain;
status = bladerf_get_lna_gain(dev, &actual_lna_gain);
if (status != 0) {
printf("config_bladerf bladerf_get_lna_gain: Failed to get lna gain: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
char *lna_gain_str = NULL;
if (actual_lna_gain == BLADERF_LNA_GAIN_BYPASS) {
lna_gain_str = (char *)"BLADERF_LNA_GAIN_BYPASS";
} else if (actual_lna_gain == BLADERF_LNA_GAIN_MAX) {
lna_gain_str = (char *)"BLADERF_LNA_GAIN_MAX";
} else if (actual_lna_gain == BLADERF_LNA_GAIN_MID) {
lna_gain_str = (char *)"BLADERF_LNA_GAIN_MID";
} else if (actual_lna_gain == BLADERF_LNA_GAIN_UNKNOWN) {
lna_gain_str = (char *)"BLADERF_LNA_GAIN_UNKNOWN";
} else {
lna_gain_str = (char *)"INVALID_BLADERF_LNA_GAIN";
}
int actual_vga1_gain;
status = bladerf_get_rxvga1(dev, &actual_vga1_gain);
if (status != 0) {
printf("config_bladerf bladerf_get_rxvga1: Failed to get rxvga1 gain: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
int actual_vga2_gain;
status = bladerf_get_rxvga2(dev, &actual_vga2_gain);
if (status != 0) {
printf("config_bladerf bladerf_get_rxvga2: Failed to get rxvga2 gain: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
int actual_total_vga_gain = actual_vga1_gain + actual_vga2_gain;
status = bladerf_set_frequency(dev, BLADERF_MODULE_RX, (unsigned int)fc);
if (status != 0) {
printf("config_bladerf bladerf_set_frequency: Failed to set frequency: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
unsigned int actual_frequency;
status = bladerf_get_frequency(dev, BLADERF_MODULE_RX, &actual_frequency);
if (status != 0) {
printf("config_bladerf bladerf_get_frequency: Failed to read back frequency: %s\n",
bladerf_strerror(status));
if (dev!=NULL) {bladerf_close(dev); dev = NULL; return(-1);}
}
#ifdef _MSC_VER
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
#else
signal(SIGINT, &sigint_callback_handler);
signal(SIGILL, &sigint_callback_handler);
signal(SIGFPE, &sigint_callback_handler);
signal(SIGSEGV, &sigint_callback_handler);
signal(SIGTERM, &sigint_callback_handler);
signal(SIGABRT, &sigint_callback_handler);
#endif
// test read samples from dev
cvec capbuf(CAPLENGTH);
double fc_programmed;
rtlsdr_device *fake_rtlsdr_dev = NULL;
hackrf_device *fake_hackrf_dev = NULL;
capture_data(fc, 1, false, " ", false, " ", " ",fake_rtlsdr_dev,fake_hackrf_dev,dev,dev_type_t::BLADERF, capbuf, fc_programmed, fs_programmed,0);
printf("config_bladerf: set bladeRF to %fMHz %fMsps BW %fMHz %s VGA_GAIN %ddB (%d+%d).\n", (float)actual_frequency/1000000.0f, (float)actual_sample_rate/1000000.0f, (float)actual_bw/1000000.0f, lna_gain_str, actual_total_vga_gain, actual_vga1_gain, actual_vga2_gain);
return(status);
}
#endif
// Main cell search routine.
int main(
const int argc,
char * const argv[]
) {
// Command line parameters are stored here.
double freq_start;
double freq_end;
uint16 num_try;
bool sampling_carrier_twist;
double ppm;
double correction;
bool save_cap;
bool use_recorded_data;
string data_dir;
int device_index;
char record_bin_filename[256] = {0};
char load_bin_filename[256] = {0};
int16 gain;
uint16 opencl_platform;
uint16 opencl_device;
uint16 filter_workitem;
uint16 xcorr_workitem;
uint16 num_reserve;
uint16 num_loop; // it is not so useful
// Get search parameters from user
parse_commandline(argc,argv,freq_start,freq_end,num_try,sampling_carrier_twist,ppm,correction,save_cap,use_recorded_data,data_dir,device_index, record_bin_filename, load_bin_filename,opencl_platform,opencl_device,filter_workitem,xcorr_workitem,num_reserve,num_loop,gain);
// Open the USB device (if necessary).
dev_type_t::dev_type_t dev_use = dev_type_t::UNKNOWN;
rtlsdr_device * rtlsdr_dev=NULL;
hackrf_device * hackrf_dev = NULL; // if HAVE_HACKRF isn't defined, hackrf_device will be asigned a fake type.
bladerf_device * bladerf_dev = NULL; // if HAVE_BLADERF isn't defined, bladerf_device will be asigned a fake type.
double fs_programmed = FS_LTE/16; // in case not initialized by config_rtlsdr
double fc_programmed; // for correction frequency calculation
double fc_requested, fc_requested_tmp, fc_programmed_tmp, fs_requested_tmp, fs_programmed_tmp;
bool dongle_used = (!use_recorded_data) && (strlen(load_bin_filename)==0);
if ( dongle_used && freq_start!=9999e6) {
#ifdef HAVE_RTLSDR
if ( config_rtlsdr(sampling_carrier_twist,correction,device_index,freq_start,rtlsdr_dev,fs_programmed,gain) == 0 ) {
dev_use = dev_type_t::RTLSDR;
cout << "RTLSDR device FOUND!\n";
} else {
cout << "RTLSDR device not FOUND!\n";
ABORT(-1);
}
#endif
#ifdef HAVE_HACKRF
if ( config_hackrf(sampling_carrier_twist,correction,device_index,freq_start,hackrf_dev,fs_programmed,gain) == 0 ) {
dev_use = dev_type_t::HACKRF;
cout << "HACKRF device FOUND!\n";
} else {
cout << "HACKRF device not FOUND!\n";
ABORT(-1);
}
#endif
#ifdef HAVE_BLADERF
if ( config_bladerf(sampling_carrier_twist,correction,device_index,freq_start,bladerf_dev,fs_programmed,gain) == 0 ) {
dev_use = dev_type_t::BLADERF;
cout << "BLADERF device FOUND!\n";
} else {
cout << "BLADERF device not FOUND!\n";
ABORT(-1);
}
#endif
if (dev_use == dev_type_t::RTLSDR) {
#ifdef HAVE_RTLSDR
fc_programmed_tmp = calculate_fc_programmed_in_context(freq_start, use_recorded_data, load_bin_filename, rtlsdr_dev);
#endif // HAVE_RTLSDR
} else if (dev_use == dev_type_t::HACKRF) {
fc_programmed_tmp = freq_start;
} else if (dev_use == dev_type_t::BLADERF) {
fc_programmed_tmp = freq_start;
} else {
cout << "No valid device present or configured.\n";
ABORT(-1);
}
cout << "Use HW begin with " << ( freq_start/1e6 ) << "MHz actual " << (fc_programmed_tmp/1e6) << "MHz " << fs_programmed << "MHz\n";
} else {
if (strlen(load_bin_filename)!=0) { // use captured bin file
if ( read_header_from_bin( load_bin_filename, fc_requested_tmp, fc_programmed_tmp, fs_requested_tmp, fs_programmed_tmp) ) {
cerr << "main: read_header_from_bin failed.\n";
ABORT(-1);
}
if (fc_requested_tmp==NAN) { // no valid header information is found
cerr << "Neither frequency nor valid bin file header information is specified!\n";
ABORT(-1);
}
} else if (use_recorded_data){ // use captured .it file
stringstream filename;
filename << data_dir << "/capbuf_" << setw(4) << setfill('0') << 0 << ".it";
it_ifile itf(filename.str());
itf.seek("fc");
ivec fc_v;
itf>>fc_v;
itf.seek("fcp");
ivec fc_p;
itf>>fc_p;
itf.seek("fsp");
ivec fs_p;
itf>>fs_p;
itf.close();
fc_requested_tmp = fc_v(0);
fc_programmed_tmp = fc_p(0);
fs_programmed_tmp = fs_p(0);
}
fs_programmed = fs_programmed_tmp;
cout << "Use file begin with " << ( fc_requested_tmp/1e6 ) << "MHz actual " << (fc_programmed_tmp/1e6) << "MHz " << fs_programmed_tmp << "MHz\n";
}
if (use_recorded_data)
num_try=1; // compatible to .it file case
// Generate a list of center frequencies that should be searched and also
// a list of frequency offsets that should be searched for each center
// frequency.
vec fc_search_set;
double freq_correction = 0;
if (freq_start!=9999e6) { // if frequency scanning range is specified
fc_search_set=itpp_ext::matlab_range(freq_start,100e3,freq_end);
} else { // if frequency scanning range is not specified. a file is as input
if (strlen(load_bin_filename)!=0 || use_recorded_data) { // use captured file
freq_start = fc_requested_tmp;
freq_end = freq_start;
fc_search_set.set_length(1, false);
fc_search_set[0] = fc_requested_tmp;
} else {
cerr << "Neither frequency nor captured file is specified!\n";
ABORT(-1);
}
}
freq_correction = fc_programmed_tmp*(correction-1)/correction;
cout << " Search frequency: " << fc_search_set(0)/1e6 << " to " << fc_search_set( length(fc_search_set)-1 )/1e6 << " MHz" << endl;
cout << "with freq correction: " << freq_correction/1e3 << " kHz" << endl;
cmat pss_fo_set;// pre-generate frequencies offseted pss time domain sequence
vec f_search_set;
if (sampling_carrier_twist) { // original mode
uint16 n_extra=0;
if (ppm!=0)
n_extra=floor_i((fc_search_set(0)*ppm/1e6+2.5e3)/5e3);
else
n_extra=28;
f_search_set=to_vec(itpp_ext::matlab_range( -n_extra*5000,5000, (n_extra-1)*5000));
// for graphic card which has limited mem, you should turn num_loop on if OpenCL reports -4: CL_MEM_OBJECT_ALLOCATION_FAILURE
// if (num_loop == 0) // it is not so useful
// num_loop = length(f_search_set)/2;
} else {
if (length(fc_search_set)==1) {//when only one frequency is specified, whole PPM range should be covered
uint16 n_extra=0;
if (ppm!=0)
n_extra=floor_i((fc_search_set(0)*ppm/1e6+2.5e3)/5e3);
else
n_extra=28; //-140kHz to 135kHz
f_search_set=to_vec(itpp_ext::matlab_range( -n_extra*5000,5000, (n_extra-1)*5000));
} else {
// since we have frequency step is 100e3, why not have sub search set limited by this regardless PPM?
f_search_set=to_vec(itpp_ext::matlab_range(-60000,5000,55000)); // 2*65kHz > 100kHz, overlap adjacent frequencies
// if (num_loop == 0) // it is not so useful
// num_loop = 36;
// f_search_set=to_vec(itpp_ext::matlab_range(-100000,5000,100000)); // align to matlab script
}
}
cout << " Search PSS at fo: " << f_search_set(0)/1e3 << " to " << f_search_set( length(f_search_set)-1 )/1e3 << " kHz" << endl;
pss_fo_set_gen(f_search_set, pss_fo_set);
// cout << "Search PSS fo(crect): " << f_search_set(0)/1e3 << " to " << f_search_set( length(f_search_set)-1 )/1e3 << " kHz" << endl;
const uint16 n_fc=length(fc_search_set);
// construct data for multiple tries
const uint32 n_fc_multi_try=n_fc*num_try;
vec fc_search_set_multi_try;
fc_search_set_multi_try.set_length(n_fc_multi_try, false);
for(uint32 i=0; i<n_fc; i++) {
uint32 sp = i*num_try;
uint32 ep = sp + num_try;
fc_search_set_multi_try.set_subvector(sp, ep-1, fc_search_set(i));
}
// get coefficients of 6 RB filter (to improve SNR)
// coef = fir1(46, (0.18e6*6+150e3)/sampling_rate);
vec coef(( sizeof( chn_6RB_filter_coef )/sizeof(float) ));
for (uint16 i=0; i<length(coef); i++) {
coef(i) = chn_6RB_filter_coef[i];
}
cvec capbuf;
lte_opencl_t lte_ocl(opencl_platform, opencl_device);
#ifdef USE_OPENCL
lte_ocl.setup_filter_my((string)"filter_my_kernels.cl", CAPLENGTH, filter_workitem);
// if ( (length(f_search_set)*3)%num_loop != 0 ){
// cerr << "length(f_search_set)*3 can not be divided by num_loop. " << (length(f_search_set)*3) << " " << num_loop << "\n";
// ABORT(-1);
// }
// lte_ocl.setup_filter_mchn((string)"filter_mchn_kernels.cl", CAPLENGTH, length(f_search_set)*3/num_loop, pss_fo_set.cols(), xcorr_workitem);
#ifdef FILTER_MCHN_SIMPLE_KERNEL
lte_ocl.setup_filter_mchn((string)"filter_mchn_simple_kernel.cl", CAPLENGTH, length(f_search_set)*3, pss_fo_set.cols(), xcorr_workitem);
#else
lte_ocl.setup_filter_mchn((string)"filter_mchn_kernels.cl", CAPLENGTH, length(f_search_set)*3, pss_fo_set.cols(), xcorr_workitem);
#endif
#endif
vec period_ppm;
vec k_factor_set;
// Calculate the threshold vector
const uint8 thresh1_n_nines=12;
double rx_cutoff=(6*12*15e3/2+4*15e3)/(FS_LTE/16/2);
// for PSS correlate
//cout << "DS_COMB_ARM override!!!" << endl;
#define DS_COMB_ARM 2
mat xc_incoherent_collapsed_pow;
imat xc_incoherent_collapsed_frq;
vector <mat> xc_incoherent_single(3);
vector <mat> xc_incoherent(3);
vector <mat> xc(3);
vec sp_incoherent;
vec sp;
// for SSS detection
#define THRESH2_N_SIGMA 3
vec sss_h1_np_est_meas;
vec sss_h2_np_est_meas;
cvec sss_h1_nrm_est_meas;
cvec sss_h2_nrm_est_meas;
cvec sss_h1_ext_est_meas;
cvec sss_h2_ext_est_meas;
mat log_lik_nrm;
mat log_lik_ext;
// for time frequency grid
// Extract time and frequency grid
cmat tfg;
vec tfg_timestamp;
// Compensate for time and frequency offsets
cmat tfg_comp;
vec tfg_comp_timestamp;
Real_Timer tt; // for profiling
// Each center frequency is searched independently. Results are stored in this vector.
vector < list<Cell> > detected_cells(n_fc);
// Loop for each center frequency.
for (uint32 fci=0;fci<n_fc_multi_try;fci++) {
fc_requested=fc_search_set_multi_try(fci);
uint32 fc_idx = fci/num_try;
uint32 try_idx = fci - fc_idx*num_try;
if (verbosity>=1) {
cout << "\nExamining center frequency " << fc_requested/1e6 << " MHz ... try " << try_idx << endl;
}
// Fill capture buffer
int run_out_of_data = capture_data(fc_requested,correction,save_cap,record_bin_filename,use_recorded_data,load_bin_filename,data_dir,rtlsdr_dev,hackrf_dev,bladerf_dev,dev_use,capbuf,fc_programmed, fs_programmed, false);
if (run_out_of_data){
fci = n_fc_multi_try; // end of loop
continue;
}
capbuf = capbuf - mean(capbuf); // remove DC
freq_correction = fc_programmed*(correction-1)/correction;
// if (!dongle_used) { // if dongle is not used, do correction explicitly. Because if dongle is used, the correction is done when tuning dongle's frequency.
capbuf = fshift(capbuf,-freq_correction,fs_programmed);
// }
// 6RB filter to improve SNR
// tt.tic();
#ifdef USE_OPENCL
// tt.tic();
lte_ocl.filter_my(capbuf); // be careful! capbuf.zeros() will slow down the xcorr part pretty much!
// cout << "1 cost " << tt.get_time() << "s\n";
//
// tt.tic();
// filter_my_fft(coef, capbuf);
// cout << "2 cost " << tt.get_time() << "s\n";
#else
filter_my(coef, capbuf);
#endif
// cout << "6RB filter cost " << tt.get_time() << "s\n";
vec dynamic_f_search_set = f_search_set; // don't touch the original
double xcorr_pss_time;
sampling_ppm_f_search_set_by_pss(lte_ocl, num_loop, capbuf, pss_fo_set, sampling_carrier_twist, num_reserve, dynamic_f_search_set, period_ppm, xc, xcorr_pss_time);
cout << "PSS XCORR cost " << xcorr_pss_time << "s\n";
list <Cell> peak_search_cells;
if (!sampling_carrier_twist) {
if ( isnan(period_ppm[0]) ) {
if (verbosity>=2) cout << "No valid PSS is found at pre-proc phase! Please try again.\n";
continue;
} else {
k_factor_set.set_length(length(period_ppm));
k_factor_set = 1 + period_ppm*1e-6;
}
vec tmp_f_search(1);
vector <mat> tmp_xc(3);
tmp_xc[0].set_size(1, length(capbuf)-136);
tmp_xc[1].set_size(1, length(capbuf)-136);
tmp_xc[2].set_size(1, length(capbuf)-136);
for (uint16 i=0; i<length(k_factor_set); i++) {
tmp_f_search(0) = dynamic_f_search_set(i);
tmp_xc[0].set_row(0, xc[0].get_row(i));
tmp_xc[1].set_row(0, xc[1].get_row(i));
tmp_xc[2].set_row(0, xc[2].get_row(i));
// Correlate
uint16 n_comb_xc;
uint16 n_comb_sp;
if (verbosity>=2) {
cout << " Calculating PSS correlations" << endl;
}
// tt.tic();
xcorr_pss(capbuf,tmp_f_search,DS_COMB_ARM,fc_requested,fc_programmed,fs_programmed,tmp_xc,xc_incoherent_collapsed_pow,xc_incoherent_collapsed_frq,xc_incoherent_single,xc_incoherent,sp_incoherent,sp,n_comb_xc,n_comb_sp,sampling_carrier_twist,(const double)k_factor_set[i]);
// cout << "PSS post cost " << tt.get_time() << "s\n";
// Calculate the threshold vector
double R_th1=chi2cdf_inv(1-pow(10.0,-thresh1_n_nines),2*n_comb_xc*(2*DS_COMB_ARM+1));
vec Z_th1=R_th1*sp_incoherent/rx_cutoff/137/n_comb_xc/(2*DS_COMB_ARM+1); // remove /2 to avoid many false alarm
// Search for the peaks
if (verbosity>=2) {
cout << " Searching for and examining correlation peaks..." << endl;
}
// tt.tic();
peak_search(xc_incoherent_collapsed_pow,xc_incoherent_collapsed_frq,Z_th1,tmp_f_search,fc_requested,fc_programmed,xc_incoherent_single,DS_COMB_ARM,sampling_carrier_twist,(const double)k_factor_set[i],peak_search_cells);
// cout << "peak_search cost " << tt.get_time() << "s\n";
}
} else {
// Correlate
uint16 n_comb_xc;
uint16 n_comb_sp;
if (verbosity>=2) {
cout << " Calculating PSS correlations" << endl;
}
// tt.tic();
xcorr_pss(capbuf,dynamic_f_search_set,DS_COMB_ARM,fc_requested,fc_programmed,fs_programmed,xc,xc_incoherent_collapsed_pow,xc_incoherent_collapsed_frq,xc_incoherent_single,xc_incoherent,sp_incoherent,sp,n_comb_xc,n_comb_sp,sampling_carrier_twist,NAN);
// cout << "PSS post cost " << tt.get_time() << "s\n";
// Calculate the threshold vector
double R_th1=chi2cdf_inv(1-pow(10.0,-thresh1_n_nines),2*n_comb_xc*(2*DS_COMB_ARM+1));
vec Z_th1=R_th1*sp_incoherent/rx_cutoff/137/n_comb_xc/(2*DS_COMB_ARM+1); // remove /2 to avoid many false alarm
// Search for the peaks
if (verbosity>=2) {
cout << " Searching for and examining correlation peaks..." << endl;
}
// tt.tic();
peak_search(xc_incoherent_collapsed_pow,xc_incoherent_collapsed_frq,Z_th1,dynamic_f_search_set,fc_requested,fc_programmed,xc_incoherent_single,DS_COMB_ARM,sampling_carrier_twist,NAN,peak_search_cells);
// cout << "peak_search cost " << tt.get_time() << "s\n";
}
detected_cells[fc_idx]=peak_search_cells;
cout << "Hit num peaks " << detected_cells[fc_idx].size()/2 << "\n";
// Loop and check each peak
list<Cell>::iterator iterator=detected_cells[fc_idx].begin();
int tdd_flag = 1;
uint16 tmp_count = 0;
while (iterator!=detected_cells[fc_idx].end()) {
tdd_flag = !tdd_flag;
cout << "try peak " << tmp_count/2 << " tdd_flag " << tdd_flag << "\n";
tmp_count++;
// cout << tdd_flag << "\n";
// cout << (*iterator).ind << "\n";
// Detect SSS if possible
(*iterator)=sss_detect((*iterator),capbuf,THRESH2_N_SIGMA,fc_requested,fc_programmed,fs_programmed,sss_h1_np_est_meas,sss_h2_np_est_meas,sss_h1_nrm_est_meas,sss_h2_nrm_est_meas,sss_h1_ext_est_meas,sss_h2_ext_est_meas,log_lik_nrm,log_lik_ext,sampling_carrier_twist,tdd_flag);
if ((*iterator).n_id_1!=-1) {
// Fine FOE
(*iterator)=pss_sss_foe((*iterator),capbuf,fc_requested,fc_programmed,fs_programmed,sampling_carrier_twist,tdd_flag);
// Extract time and frequency grid
extract_tfg((*iterator),capbuf,fc_requested,fc_programmed,fs_programmed,tfg,tfg_timestamp,sampling_carrier_twist);
// Create object containing all RS
RS_DL rs_dl((*iterator).n_id_cell(),6,(*iterator).cp_type);
// Compensate for time and frequency offsets
(*iterator)=tfoec((*iterator),tfg,tfg_timestamp,fc_requested,fc_programmed,rs_dl,tfg_comp,tfg_comp_timestamp,sampling_carrier_twist);
// Finally, attempt to decode the MIB
(*iterator)=decode_mib((*iterator),tfg_comp,rs_dl);
if ((*iterator).n_rb_dl==-1) {
// No MIB could be successfully decoded.
iterator=detected_cells[fc_idx].erase(iterator);
continue;
}
if (verbosity>=1) {
if (tdd_flag==0)
cout << " Detected a FDD cell! At freqeuncy " << fc_requested/1e6 << "MHz, try " << try_idx << endl;
else
cout << " Detected a TDD cell! At freqeuncy " << fc_requested/1e6 << "MHz, try " << try_idx << endl;
cout << " cell ID: " << (*iterator).n_id_cell() << endl;
cout << " PSS ID: " << (*iterator).n_id_2 << endl;
cout << " RX power level: " << db10((*iterator).pss_pow) << " dB" << endl;
cout << " residual frequency offset: " << (*iterator).freq_superfine << " Hz" << endl;
cout << " k_factor: " << (*iterator).k_factor << endl;
}
++iterator;
} else {
iterator=detected_cells[fc_idx].erase(iterator);
}
// // Detect SSS if possible
// #define THRESH2_N_SIGMA 3
// cell_temp = (*iterator);
// for(tdd_flag=0;tdd_flag<2;tdd_flag++)
// {
//// tt.tic();
// (*iterator)=sss_detect(cell_temp,capbuf,THRESH2_N_SIGMA,fc_requested,fc_programmed,fs_programmed,sss_h1_np_est_meas,sss_h2_np_est_meas,sss_h1_nrm_est_meas,sss_h2_nrm_est_meas,sss_h1_ext_est_meas,sss_h2_ext_est_meas,log_lik_nrm,log_lik_ext,sampling_carrier_twist,tdd_flag);
//// cout << "sss_detect cost " << tt.get_time() << "s\n";
// if ((*iterator).n_id_1!=-1)
// break;
// }
// if ((*iterator).n_id_1==-1) {
// // No SSS detected.
//
// continue;
// }
// // Fine FOE
//// tt.tic();
// (*iterator)=pss_sss_foe((*iterator),capbuf,fc_requested,fc_programmed,fs_programmed,sampling_carrier_twist,tdd_flag);
//// cout << "pss_sss_foe cost " << tt.get_time() << "s\n";
//
// // Extract time and frequency grid
//// tt.tic();
// extract_tfg((*iterator),capbuf,fc_requested,fc_programmed,fs_programmed,tfg,tfg_timestamp,sampling_carrier_twist);
//// cout << "extract_tfg cost " << tt.get_time() << "s\n";
//
// // Create object containing all RS
// RS_DL rs_dl((*iterator).n_id_cell(),6,(*iterator).cp_type);
//
// // Compensate for time and frequency offsets
//// tt.tic();
// (*iterator)=tfoec((*iterator),tfg,tfg_timestamp,fc_requested,fc_programmed,rs_dl,tfg_comp,tfg_comp_timestamp,sampling_carrier_twist);
//// cout << "tfoec cost " << tt.get_time() << "s\n";
//
// // Finally, attempt to decode the MIB
//// tt.tic();
// (*iterator)=decode_mib((*iterator),tfg_comp,rs_dl);
//// cout << "decode_mib cost " << tt.get_time() << "s\n";
// if ((*iterator).n_rb_dl==-1) {
// // No MIB could be successfully decoded.
// iterator=detected_cells[fc_idx].erase(iterator);
// continue;
// }
//
// if (verbosity>=1) {
// if (tdd_flag==0)
// cout << " Detected a FDD cell! At freqeuncy " << fc_requested/1e6 << "MHz, try " << try_idx << endl;
// else
// cout << " Detected a TDD cell! At freqeuncy " << fc_requested/1e6 << "MHz, try " << try_idx << endl;
// cout << " cell ID: " << (*iterator).n_id_cell() << endl;
// cout << " PSS ID: " << (*iterator).n_id_2 << endl;
// cout << " RX power level: " << db10((*iterator).pss_pow) << " dB" << endl;
// cout << " residual frequency offset: " << (*iterator).freq_superfine << " Hz" << endl;
// cout << " k_factor: " << (*iterator).k_factor << endl;
// }
//
// ++iterator;
}
if (detected_cells[fc_idx].size() > 0){
fci = (fc_idx+1)*num_try - 1; // skip to next frequency
}
}
if (dev_use == dev_type_t::HACKRF) {
#ifdef HAVE_HACKRF
if (hackrf_dev != NULL) {
hackrf_close(hackrf_dev);
hackrf_dev = NULL;
hackrf_exit();
}
#endif
}
if (dev_use == dev_type_t::RTLSDR) {
#ifdef HAVE_RTLSDR
if (rtlsdr_dev != NULL) {
rtlsdr_close(rtlsdr_dev);
rtlsdr_dev = NULL;
}
#endif
}
if (dev_use == dev_type_t::BLADERF) {
#ifdef HAVE_BLADERF
if (bladerf_dev!=NULL) {
bladerf_close(bladerf_dev);
bladerf_dev = NULL;
}
#endif
}
// Generate final list of detected cells.
list <Cell> cells_final;
dedup(detected_cells,cells_final);
// Print out the final list of detected cells.
if (cells_final.size()==0) {
cout << "No LTE cells were found..." << endl;
} else {
cout << "Detected the following cells:" << endl;
cout << "DPX:TDD/FDD; A: #antenna ports C: CP type ; P: PHICH duration ; PR: PHICH resource type" << endl;
cout << "DPX CID A fc freq-offset RXPWR C nRB P PR CrystalCorrectionFactor" << endl;
list <Cell>::iterator it=cells_final.begin();
while (it!=cells_final.end()) {
// Use a stringstream to avoid polluting the iostream settings of cout.
stringstream ss;
if ((*it).duplex_mode == 1)
ss << "TDD ";
else
ss << "FDD ";
ss << setw(3) << (*it).n_id_cell();
ss << setw(2) << (*it).n_ports;
ss << " " << setw(6) << setprecision(5) << (*it).fc_requested/1e6 << "M";
ss << " " << setw(13) << freq_formatter((*it).freq_superfine);
ss << " " << setw(5) << setprecision(3) << db10((*it).pss_pow);
ss << " " << (((*it).cp_type==cp_type_t::NORMAL)?"N":(((*it).cp_type==cp_type_t::UNKNOWN)?"U":"E"));
ss << " " << setw(3) << (*it).n_rb_dl;
ss << " " << (((*it).phich_duration==phich_duration_t::NORMAL)?"N":(((*it).phich_duration==phich_duration_t::UNKNOWN)?"U":"E"));
switch ((*it).phich_resource) {
case phich_resource_t::UNKNOWN: ss << " UNK"; break;
case phich_resource_t::oneSixth: ss << " 1/6"; break;
case phich_resource_t::half: ss << " 1/2"; break;
case phich_resource_t::one: ss << " one"; break;
case phich_resource_t::two: ss << " two"; break;
}
// Calculate the correction factor.
// This is where we know the carrier is located
const double true_location=(*it).fc_programmed;
// We can calculate the RTLSDR's actualy frequency
const double crystal_freq_actual=(*it).fc_programmed-(*it).freq_superfine;
// Calculate correction factors
const double correction_residual=true_location/crystal_freq_actual;
double correction_new=correction*correction_residual;
// if (!sampling_carrier_twist) {
// correction_new = (*it).k_factor;
// }
ss << " " << setprecision(20) << correction_new;
cout << ss.str() << endl;
++it;
}
}
// Successful exit.
return 0;
}
| hongyunnchen/LTE-Cell-Scanner | src/CellSearch.cpp | C++ | agpl-3.0 | 53,734 |
/*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive_grid_cloud_portal.common;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.Callable;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MalformedObjectNameException;
import javax.management.ReflectionException;
import org.apache.log4j.Logger;
import org.ow2.proactive.scheduler.common.exception.NotConnectedException;
/**
* Simple cache for Statistic History
* <p>
* Fetching statistic history from the server can be costly,
* but customization of the time range per request make the response vary.
* <p>
* This class will store the result of the requests along with the parameter,
* so that future request matching the same parameter are directly retrieved from the cache.
*
* @author mschnoor
*
*/
public class StatHistoryCaching {
private static final Logger LOGGER = Logger.getLogger(StatHistoryCaching.class);
// invalidate entry after MAX_DURATION millis
private static final long MAX_DURATION = 5000;
public class StatHistoryCacheEntry {
private long timeStamp;
private String value;
public StatHistoryCacheEntry(String value, long timeStamp) {
this.timeStamp = timeStamp;
this.value = value;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
private HashMap<String, StatHistoryCacheEntry> statHistoryCache = null;
private static StatHistoryCaching instance = null;
private StatHistoryCaching() {
this.statHistoryCache = new HashMap<>();
}
public static synchronized StatHistoryCaching getInstance() {
if (instance == null)
instance = new StatHistoryCaching();
return instance;
}
/**
* @param key key of the cache element to retrieve
* @return the cache entry if it exists and has not expired, or null
*/
public synchronized StatHistoryCacheEntry getEntry(String key) {
StatHistoryCacheEntry entry = this.statHistoryCache.get(key);
if (entry == null)
return null;
if (System.currentTimeMillis() - entry.timeStamp > MAX_DURATION) {
this.statHistoryCache.remove(key);
return null;
}
return entry;
}
public synchronized StatHistoryCacheEntry getEntryOrCompute(String key, RestCallable<String> valueCreator)
throws ReflectionException, InterruptedException, NotConnectedException, IntrospectionException,
IOException, InstanceNotFoundException, MalformedObjectNameException {
StatHistoryCacheEntry entry = statHistoryCache.get(key);
if (entry == null || (System.currentTimeMillis() - entry.timeStamp) > MAX_DURATION) {
statHistoryCache.remove(key);
long timeStamp = System.currentTimeMillis();
String value = valueCreator.call();
entry = new StatHistoryCacheEntry(value, timeStamp);
statHistoryCache.put(key, entry);
}
return entry;
}
@FunctionalInterface
public interface RestCallable<V> {
V call() throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException,
MalformedObjectNameException, NullPointerException, InterruptedException, NotConnectedException;
}
public synchronized void addEntry(String key, long timeStamp, String value) {
StatHistoryCacheEntry entry = new StatHistoryCacheEntry(value, timeStamp);
this.statHistoryCache.put(key, entry);
}
}
| ShatalovYaroslav/scheduling | rest/rest-server/src/main/java/org/ow2/proactive_grid_cloud_portal/common/StatHistoryCaching.java | Java | agpl-3.0 | 4,896 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>strategy::transform::translate_transformer</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Geometry">
<link rel="up" href="../strategies.html" title="Strategies">
<link rel="prev" href="strategy_transform_scale_transformer.html" title="strategy::transform::scale_transformer">
<link rel="next" href="strategy_transform_ublas_transformer.html" title="strategy::transform::ublas_transformer">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="strategy_transform_scale_transformer.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_transform_ublas_transformer.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="geometry.reference.strategies.strategy_transform_translate_transformer"></a><a class="link" href="strategy_transform_translate_transformer.html" title="strategy::transform::translate_transformer">strategy::transform::translate_transformer</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idp141965584"></a><a class="indexterm" name="idp141966272"></a><a class="indexterm" name="idp141966960"></a>
Strategy of translate transformation in Cartesian system.
</p>
<h6>
<a name="geometry.reference.strategies.strategy_transform_translate_transformer.h0"></a>
<span class="phrase"><a name="geometry.reference.strategies.strategy_transform_translate_transformer.description"></a></span><a class="link" href="strategy_transform_translate_transformer.html#geometry.reference.strategies.strategy_transform_translate_transformer.description">Description</a>
</h6>
<p>
Translate moves a geometry a fixed distance in 2 or 3 dimensions.
</p>
<h6>
<a name="geometry.reference.strategies.strategy_transform_translate_transformer.h1"></a>
<span class="phrase"><a name="geometry.reference.strategies.strategy_transform_translate_transformer.synopsis"></a></span><a class="link" href="strategy_transform_translate_transformer.html#geometry.reference.strategies.strategy_transform_translate_transformer.synopsis">Synopsis</a>
</h6>
<p>
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> <span class="identifier">CalculationType</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">Dimension1</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">Dimension2</span><span class="special">></span>
<span class="keyword">class</span> <span class="identifier">strategy</span><span class="special">::</span><span class="identifier">transform</span><span class="special">::</span><span class="identifier">translate_transformer</span>
<span class="special">{</span>
<span class="comment">// ...</span>
<span class="special">};</span>
</pre>
<p>
</p>
<h6>
<a name="geometry.reference.strategies.strategy_transform_translate_transformer.h2"></a>
<span class="phrase"><a name="geometry.reference.strategies.strategy_transform_translate_transformer.template_parameter_s_"></a></span><a class="link" href="strategy_transform_translate_transformer.html#geometry.reference.strategies.strategy_transform_translate_transformer.template_parameter_s_">Template
parameter(s)</a>
</h6>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Parameter
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
typename CalculationType
</p>
</td>
<td>
</td>
</tr>
<tr>
<td>
<p>
std::size_t Dimension1
</p>
</td>
<td>
<p>
number of dimensions to transform from
</p>
</td>
</tr>
<tr>
<td>
<p>
std::size_t Dimension2
</p>
</td>
<td>
<p>
number of dimensions to transform to
</p>
</td>
</tr>
</tbody>
</table></div>
<h6>
<a name="geometry.reference.strategies.strategy_transform_translate_transformer.h3"></a>
<span class="phrase"><a name="geometry.reference.strategies.strategy_transform_translate_transformer.header"></a></span><a class="link" href="strategy_transform_translate_transformer.html#geometry.reference.strategies.strategy_transform_translate_transformer.header">Header</a>
</h6>
<p>
<code class="computeroutput"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">strategies</span><span class="special">/</span><span class="identifier">transform</span><span class="special">/</span><span class="identifier">matrix_transformers</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2009-2015 Barend Gehrels, Bruno Lalande,
Mateusz Loskot, Adam Wulkiewicz, Oracle and/or its affiliates<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="strategy_transform_scale_transformer.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_transform_ublas_transformer.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| ntonjeta/iidea-Docker | examples/sobel/src/boost_1_63_0/libs/geometry/doc/html/geometry/reference/strategies/strategy_transform_translate_transformer.html | HTML | agpl-3.0 | 7,837 |
--TEST--
package-validate command
--SKIPIF--
<?php
if (!getenv('PHP_PEAR_RUNTESTS')) {
echo 'skip';
}
?>
--FILE--
<?php
require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'setup.php.inc';
$savedir = getcwd();
chdir($temp_path);
copy(dirname(__FILE__) . '/packagefiles/validv1.xml', $temp_path . DIRECTORY_SEPARATOR . 'validv1.xml');
copy(dirname(__FILE__) . '/packagefiles/validfakebar.xml', $temp_path . DIRECTORY_SEPARATOR . 'validv2.xml');
copy(dirname(__FILE__) . '/packagefiles/validv1.xml', $temp_path . DIRECTORY_SEPARATOR . 'package.xml');
// 1.0
$ret = $command->run('package-validate', array(), array($temp_path . DIRECTORY_SEPARATOR . 'validv1.xml'));
$phpunit->assertErrors(array(
array('package' => 'PEAR_PackageFile_v1', 'message' => 'Channel validator error: field "date" - Release Date "2004-11-27" is not today'),
array('package' => 'PEAR_PackageFile_v1', 'message' => 'File "' . $temp_path . DIRECTORY_SEPARATOR .
'foo1.php" in package.xml does not exist'),
array('package' => 'PEAR_PackageFile_v1', 'message' => 'File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist'),
), 'ret 1');
$phpunit->assertEquals(array (
0 =>
array (
'info' => 'Error: File "' . $temp_path . DIRECTORY_SEPARATOR .
'foo1.php" in package.xml does not exist
Error: File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist
Warning: Channel validator error: field "date" - Release Date "2004-11-27" is not today
Validation: 2 error(s), 1 warning(s)
',
'cmd' => 'package-validate',
),
), $fakelog->getLog(), 'log 1');
$ret = $command->run('package-validate', array(), array());
$phpunit->assertErrors(array(
array('package' => 'PEAR_PackageFile_v1', 'message' => 'Channel validator error: field "date" - Release Date "2004-11-27" is not today'),
array('package' => 'PEAR_PackageFile_v1', 'message' => 'File "' . $temp_path . DIRECTORY_SEPARATOR .
'foo1.php" in package.xml does not exist'),
array('package' => 'PEAR_PackageFile_v1', 'message' => 'File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist'),
), 'ret 1.5');
$phpunit->assertEquals(array (
0 =>
array (
'info' => 'Error: File "' . $temp_path . DIRECTORY_SEPARATOR .
'foo1.php" in package.xml does not exist
Error: File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist
Warning: Channel validator error: field "date" - Release Date "2004-11-27" is not today
Validation: 2 error(s), 1 warning(s)
',
'cmd' => 'package-validate',
),
), $fakelog->getLog(), 'log 1.5');
// 2.0
$ret = $command->run('package-validate', array(), array($temp_path . DIRECTORY_SEPARATOR . 'validv2.xml'));
$phpunit->assertErrors(array(
array('package' => 'PEAR_PackageFile_v2', 'message' => 'Channel validator warning: field "date" - Release Date "2004-12-25" is not today'),
array('package' => 'PEAR_PackageFile_v2', 'message' => 'File "' . $temp_path . DIRECTORY_SEPARATOR .
'foo1.php" in package.xml does not exist'),
array('package' => 'PEAR_PackageFile_v2', 'message' => 'File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist'),
), 'ret 2');
$phpunit->assertEquals(array (
0 =>
array (
'info' => 'Error: File "' . $temp_path . DIRECTORY_SEPARATOR .
'foo1.php" in package.xml does not exist
Error: File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist
Warning: Channel validator warning: field "date" - Release Date "2004-12-25" is not today
Validation: 2 error(s), 1 warning(s)
',
'cmd' => 'package-validate',
),
), $fakelog->getLog(), 'log 2');
copy(dirname(__FILE__) . '/packagefiles/foo1.php', $temp_path . DIRECTORY_SEPARATOR . 'foo1.php');
$ret = $command->run('package-validate', array(), array($temp_path . DIRECTORY_SEPARATOR . 'validv2.xml'));
$phpunit->assertErrors(array(
array('package' => 'PEAR_PackageFile_v2', 'message' => 'Channel validator warning: field "date" - Release Date "2004-12-25" is not today'),
array('package' => 'PEAR_PackageFile_v2', 'message' => 'File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist'),
), 'ret 2.1');
$phpunit->assertEquals(array (
0 =>
array (
0 => 1,
1 => 'Analyzing foo1.php',
),
1 =>
array (
'info' => 'Error: File "' . $temp_path . DIRECTORY_SEPARATOR .
'sunger/foo.dat" in package.xml does not exist
Warning: Channel validator warning: field "date" - Release Date "2004-12-25" is not today
Validation: 1 error(s), 1 warning(s)
',
'cmd' => 'package-validate',
),
), $fakelog->getLog(), 'log 2.1');
mkdir($temp_path . DIRECTORY_SEPARATOR . 'sunger');
copy(dirname(__FILE__) . '/packagefiles/sunger/foo.dat', $temp_path . DIRECTORY_SEPARATOR .
'sunger' . DIRECTORY_SEPARATOR . 'foo.dat');
$contents = file_get_contents($temp_path . DIRECTORY_SEPARATOR . 'validv2.xml');
$contents = str_replace('2004-12-25', date('Y-m-d'), $contents);
$fp = fopen($temp_path . DIRECTORY_SEPARATOR . 'validv2.xml', 'wb');
fwrite($fp, $contents);
fclose($fp);
$ret = $command->run('package-validate', array(), array($temp_path . DIRECTORY_SEPARATOR . 'validv2.xml'));
$phpunit->assertNoErrors('ret success');
$phpunit->assertEquals(array (
0 =>
array (
0 => 1,
1 => 'Analyzing foo1.php',
),
1 =>
array (
'info' => 'Validation: 0 error(s), 0 warning(s)
',
'cmd' => 'package-validate',
),
), $fakelog->getLog(), 'log success');
chdir($savedir);
echo 'tests done';
?>
--CLEAN--
<?php
require_once dirname(dirname(__FILE__)) . '/teardown.php.inc';
?>
--EXPECT--
tests done
| aydancoskun/timetrex-community-edition | vendor/pear/pear/tests/PEAR_Command_Package/package-validate/test.phpt | PHP | agpl-3.0 | 5,778 |
<%inherit file="/template.html" />
<%namespace name="components" file="/components.html" />
<%namespace name="admin_tiles" file="/admin/tiles.html" />
<%def name="title()">${_("Site administration")}</%def>
<%block name="headline">
${admin_tiles.headline()}
</%block>
<%block name="main_content">
<dl>
<dt>Adhocracy version</dt>
<dd>${h.version.get_version()}</dd>
</dl>
</%block>
<%block name="sidebar">
${admin_tiles.navigation()}
</%block>
| phihag/adhocracy | src/adhocracy/templates/admin/index.html | HTML | agpl-3.0 | 454 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/s3/model/DefaultRetention.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace S3
{
namespace Model
{
DefaultRetention::DefaultRetention() :
m_mode(ObjectLockRetentionMode::NOT_SET),
m_modeHasBeenSet(false),
m_days(0),
m_daysHasBeenSet(false),
m_years(0),
m_yearsHasBeenSet(false)
{
}
DefaultRetention::DefaultRetention(const XmlNode& xmlNode) :
m_mode(ObjectLockRetentionMode::NOT_SET),
m_modeHasBeenSet(false),
m_days(0),
m_daysHasBeenSet(false),
m_years(0),
m_yearsHasBeenSet(false)
{
*this = xmlNode;
}
DefaultRetention& DefaultRetention::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode modeNode = resultNode.FirstChild("Mode");
if(!modeNode.IsNull())
{
m_mode = ObjectLockRetentionModeMapper::GetObjectLockRetentionModeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(modeNode.GetText()).c_str()).c_str());
m_modeHasBeenSet = true;
}
XmlNode daysNode = resultNode.FirstChild("Days");
if(!daysNode.IsNull())
{
m_days = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(daysNode.GetText()).c_str()).c_str());
m_daysHasBeenSet = true;
}
XmlNode yearsNode = resultNode.FirstChild("Years");
if(!yearsNode.IsNull())
{
m_years = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(yearsNode.GetText()).c_str()).c_str());
m_yearsHasBeenSet = true;
}
}
return *this;
}
void DefaultRetention::AddToNode(XmlNode& parentNode) const
{
Aws::StringStream ss;
if(m_modeHasBeenSet)
{
XmlNode modeNode = parentNode.CreateChildElement("Mode");
modeNode.SetText(ObjectLockRetentionModeMapper::GetNameForObjectLockRetentionMode(m_mode));
}
if(m_daysHasBeenSet)
{
XmlNode daysNode = parentNode.CreateChildElement("Days");
ss << m_days;
daysNode.SetText(ss.str());
ss.str("");
}
if(m_yearsHasBeenSet)
{
XmlNode yearsNode = parentNode.CreateChildElement("Years");
ss << m_years;
yearsNode.SetText(ss.str());
ss.str("");
}
}
} // namespace Model
} // namespace S3
} // namespace Aws
| uroni/urbackup_backend | external/aws-cpp-sdk/aws-cpp-sdk-s3/source/model/DefaultRetention.cpp | C++ | agpl-3.0 | 2,540 |
## mako
<%page expression_filter="h"/>
<%namespace name='static' file='../../static_content.html'/>
<%namespace file='../../main.html' import="login_query"/>
<%!
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
%>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
% if course:
<div class="course-header">
<span class="provider">${course.display_org_with_default}:</span>
<span class="course-number">${course.display_number_with_default}</span>
<%
display_name = course.display_name_with_default
if settings.FEATURES.get('CUSTOM_COURSES_EDX', False):
ccx = get_current_ccx(course.id)
if ccx:
display_name = ccx.display_name
%>
<span class="course-name">${display_name}</span>
</div>
% endif
% if settings.FEATURES.get('COURSES_ARE_BROWSABLE') and not show_program_listing:
<li class="nav-item mt-2 nav-item-open-collapsed">
<a class="nav-link" href="${marketing_link('COURSES')}">${_('Explore courses')}</a>
</li>
% endif
% if show_program_listing:
<li class="nav-item mt-2 nav-item-open-collapsed">
<a class="nav-link ${'active' if reverse('dashboard') == request.path else ''}" href="${reverse('dashboard')}">
${_("Courses")}
</a>
</li>
<li class="nav-item mt-2 nav-item-open-collapsed">
<a class="nav-link ${'active' if reverse('program_listing_view') in request.path else ''}" href="${reverse('program_listing_view')}">
${_("Programs")}
</a>
</li>
% endif
% if settings.FEATURES.get('ENABLE_SYSADMIN_DASHBOARD','') and user.is_staff:
<li class="nav-item mt-2 nav-item-open-collapsed">
## Translators: This is short for "System administration".
<a class="nav-link" href="${reverse('sysadmin')}">${_("Sysadmin")}</a>
</li>
% endif
</ul>
<ul class="navbar-nav navbar-right">
% if should_display_shopping_cart_func() and not (course and static.is_request_in_themed_site()): # see shoppingcart.context_processor.user_has_cart_context_processor
<a role="button" class="nav-item-open-collapsed btn-shopping-cart btn btn-secondary mr-3" href="${reverse('shoppingcart.views.show_cart')}">
<span class="icon fa fa-shopping-cart" aria-hidden="true"></span> ${_("Shopping Cart")}
</a>
% endif
<li class="nav-item mt-2 nav-item-open-collapsed">
<a href="${get_online_help_info(online_help_token)['doc_url']}"
target="_blank"
class="nav-link">${_("Help")}</a>
</li>
<%include file="../../user_dropdown.html"/>
</ul>
</div>
| pepeportela/edx-platform | lms/templates/navigation/bootstrap/navbar-authenticated.html | HTML | agpl-3.0 | 2,743 |
odoo.define('mail/static/src/models/activity/activity/js', function (require) {
'use strict';
const { registerNewModel } = require('mail/static/src/model/model_core.js');
const { attr, many2many, many2one } = require('mail/static/src/model/model_field.js');
const { clear } = require('mail/static/src/model/model_field_command.js');
function factory(dependencies) {
class Activity extends dependencies['mail.model'] {
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
/**
* Delete the record from database and locally.
*/
async deleteServerRecord() {
await this.async(() => this.env.services.rpc({
model: 'mail.activity',
method: 'unlink',
args: [[this.id]],
}));
this.delete();
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
/**
* @static
* @param {Object} data
* @return {Object}
*/
static convertData(data) {
const data2 = {};
if ('activity_category' in data) {
data2.category = data.activity_category;
}
if ('can_write' in data) {
data2.canWrite = data.can_write;
}
if ('create_date' in data) {
data2.dateCreate = data.create_date;
}
if ('date_deadline' in data) {
data2.dateDeadline = data.date_deadline;
}
if ('force_next' in data) {
data2.force_next = data.force_next;
}
if ('icon' in data) {
data2.icon = data.icon;
}
if ('id' in data) {
data2.id = data.id;
}
if ('note' in data) {
data2.note = data.note;
}
if ('state' in data) {
data2.state = data.state;
}
if ('summary' in data) {
data2.summary = data.summary;
}
// relation
if ('activity_type_id' in data) {
if (!data.activity_type_id) {
data2.type = [['unlink-all']];
} else {
data2.type = [
['insert', {
displayName: data.activity_type_id[1],
id: data.activity_type_id[0],
}],
];
}
}
if ('create_uid' in data) {
if (!data.create_uid) {
data2.creator = [['unlink-all']];
} else {
data2.creator = [
['insert', {
id: data.create_uid[0],
display_name: data.create_uid[1],
}],
];
}
}
if ('mail_template_ids' in data) {
data2.mailTemplates = [['insert', data.mail_template_ids]];
}
if ('res_id' in data && 'res_model' in data) {
data2.thread = [['insert', {
id: data.res_id,
model: data.res_model,
}]];
}
if ('user_id' in data) {
if (!data.user_id) {
data2.assignee = [['unlink-all']];
} else {
data2.assignee = [
['insert', {
id: data.user_id[0],
display_name: data.user_id[1],
}],
];
}
}
if ('request_partner_id' in data) {
if (!data.request_partner_id) {
data2.requestingPartner = [['unlink']];
} else {
data2.requestingPartner = [
['insert', {
id: data.request_partner_id[0],
display_name: data.request_partner_id[1],
}],
];
}
}
return data2;
}
/**
* Opens (legacy) form view dialog to edit current activity and updates
* the activity when dialog is closed.
*/
edit() {
const action = {
type: 'ir.actions.act_window',
name: this.env._t("Schedule Activity"),
res_model: 'mail.activity',
view_mode: 'form',
views: [[false, 'form']],
target: 'new',
context: {
default_res_id: this.thread.id,
default_res_model: this.thread.model,
},
res_id: this.id,
};
this.env.bus.trigger('do-action', {
action,
options: { on_close: () => this.fetchAndUpdate() },
});
}
async fetchAndUpdate() {
const [data] = await this.async(() => this.env.services.rpc({
model: 'mail.activity',
method: 'activity_format',
args: [this.id],
}, { shadow: true }));
let shouldDelete = false;
if (data) {
this.update(this.constructor.convertData(data));
} else {
shouldDelete = true;
}
this.thread.refreshActivities();
this.thread.refresh();
if (shouldDelete) {
this.delete();
}
}
/**
* @param {Object} param0
* @param {mail.attachment[]} [param0.attachments=[]]
* @param {string|boolean} [param0.feedback=false]
*/
async markAsDone({ attachments = [], feedback = false }) {
const attachmentIds = attachments.map(attachment => attachment.id);
await this.async(() => this.env.services.rpc({
model: 'mail.activity',
method: 'action_feedback',
args: [[this.id]],
kwargs: {
attachment_ids: attachmentIds,
feedback,
},
}));
this.thread.refresh();
this.delete();
}
/**
* @param {Object} param0
* @param {string} param0.feedback
* @returns {Object}
*/
async markAsDoneAndScheduleNext({ feedback }) {
const action = await this.async(() => this.env.services.rpc({
model: 'mail.activity',
method: 'action_feedback_schedule_next',
args: [[this.id]],
kwargs: { feedback },
}));
this.thread.refresh();
const thread = this.thread;
this.delete();
if (!action) {
thread.refreshActivities();
return;
}
this.env.bus.trigger('do-action', {
action,
options: {
on_close: () => {
thread.refreshActivities();
},
},
});
}
//----------------------------------------------------------------------
// Private
//----------------------------------------------------------------------
/**
* @override
*/
static _createRecordLocalId(data) {
return `${this.modelName}_${data.id}`;
}
/**
* @private
* @returns {boolean}
*/
_computeIsCurrentPartnerAssignee() {
if (!this.assigneePartner || !this.messagingCurrentPartner) {
return false;
}
return this.assigneePartner === this.messagingCurrentPartner;
}
/**
* @private
* @returns {mail.messaging}
*/
_computeMessaging() {
return [['link', this.env.messaging]];
}
/**
* Wysiwyg editor put `<p><br></p>` even without a note on the activity.
* This compute replaces this almost empty value by an actual empty
* value, to reduce the size the empty note takes on the UI.
*
* @private
* @returns {string|undefined}
*/
_computeNote() {
if (this.note === '<p><br></p>') {
return clear();
}
return this.note;
}
}
Activity.fields = {
assignee: many2one('mail.user'),
assigneePartner: many2one('mail.partner', {
related: 'assignee.partner',
}),
attachments: many2many('mail.attachment', {
inverse: 'activities',
}),
canWrite: attr({
default: false,
}),
category: attr(),
creator: many2one('mail.user'),
dateCreate: attr(),
dateDeadline: attr(),
/**
* Backup of the feedback content of an activity to be marked as done in the popover.
* Feature-specific to restoring the feedback content when component is re-mounted.
* In all other cases, this field value should not be trusted.
*/
feedbackBackup: attr(),
force_next: attr({
default: false,
}),
icon: attr(),
id: attr(),
isCurrentPartnerAssignee: attr({
compute: '_computeIsCurrentPartnerAssignee',
default: false,
dependencies: [
'assigneePartner',
'messagingCurrentPartner',
],
}),
mailTemplates: many2many('mail.mail_template', {
inverse: 'activities',
}),
messaging: many2one('mail.messaging', {
compute: '_computeMessaging',
}),
messagingCurrentPartner: many2one('mail.partner', {
related: 'messaging.currentPartner',
}),
/**
* This value is meant to be returned by the server
* (and has been sanitized before stored into db).
* Do not use this value in a 't-raw' if the activity has been created
* directly from user input and not from server data as it's not escaped.
*/
note: attr({
compute: '_computeNote',
dependencies: [
'note',
],
}),
/**
* Determines that an activity is linked to a requesting partner or not.
* It will be used notably in website slides to know who triggered the
* "request access" activity.
* Also, be useful when the assigned user is different from the
* "source" or "requesting" partner.
*/
requestingPartner: many2one('mail.partner'),
state: attr(),
summary: attr(),
/**
* Determines to which "thread" (using `mail.activity.mixin` on the
* server) `this` belongs to.
*/
thread: many2one('mail.thread', {
inverse: 'activities',
}),
type: many2one('mail.activity_type', {
inverse: 'activities',
}),
};
Activity.modelName = 'mail.activity';
return Activity;
}
registerNewModel('mail.activity', factory);
});
| rven/odoo | addons/mail/static/src/models/activity/activity.js | JavaScript | agpl-3.0 | 11,677 |
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"time"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names"
"github.com/juju/utils"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
)
var actionLogger = loggo.GetLogger("juju.state.action")
// NewUUID wraps the utils.NewUUID() call, and exposes it as a var to
// facilitate patching.
var NewUUID = func() (utils.UUID, error) { return utils.NewUUID() }
// ActionStatus represents the possible end states for an action.
type ActionStatus string
const (
// ActionFailed signifies that the action did not complete successfully.
ActionFailed ActionStatus = "failed"
// ActionCompleted indicates that the action ran to completion as intended.
ActionCompleted ActionStatus = "completed"
// ActionCancelled means that the Action was cancelled before being run.
ActionCancelled ActionStatus = "cancelled"
// ActionPending is the default status when an Action is first queued.
ActionPending ActionStatus = "pending"
// ActionRunning indicates that the Action is currently running.
ActionRunning ActionStatus = "running"
)
const actionMarker string = "_a_"
type actionNotificationDoc struct {
// DocId is the composite _id that can be matched by an
// idPrefixWatcher that is configured to watch for the
// ActionReceiver Name() which makes up the first part of this
// composite _id.
DocId string `bson:"_id"`
// EnvUUID is the environment identifier.
EnvUUID string `bson:"env-uuid"`
// Receiver is the Name of the Unit or any other ActionReceiver for
// which this notification is queued.
Receiver string `bson:"receiver"`
// ActionID is the unique identifier for the Action this notification
// represents.
ActionID string `bson:"actionid"`
}
type actionDoc struct {
// DocId is the key for this document; it is a UUID.
DocId string `bson:"_id"`
// EnvUUID is the environment identifier.
EnvUUID string `bson:"env-uuid"`
// Receiver is the Name of the Unit or any other ActionReceiver for
// which this Action is queued.
Receiver string `bson:"receiver"`
// Name identifies the action that should be run; it should
// match an action defined by the unit's charm.
Name string `bson:"name"`
// Parameters holds the action's parameters, if any; it should validate
// against the schema defined by the named action in the unit's charm.
Parameters map[string]interface{} `bson:"parameters"`
// Enqueued is the time the action was added.
Enqueued time.Time `bson:"enqueued"`
// Started reflects the time the action began running.
Started time.Time `bson:"started"`
// Completed reflects the time that the action was finished.
Completed time.Time `bson:"completed"`
// Status represents the end state of the Action; ActionFailed for an
// action that was removed prematurely, or that failed, and
// ActionCompleted for an action that successfully completed.
Status ActionStatus `bson:"status"`
// Message captures any error returned by the action.
Message string `bson:"message"`
// Results are the structured results from the action.
Results map[string]interface{} `bson:"results"`
}
// Action represents an instruction to do some "action" and is expected
// to match an action definition in a charm.
type Action struct {
st *State
doc actionDoc
}
// Id returns the local id of the Action.
func (a *Action) Id() string {
return a.st.localID(a.doc.DocId)
}
// Receiver returns the Name of the ActionReceiver for which this action
// is enqueued. Usually this is a Unit Name().
func (a *Action) Receiver() string {
return a.doc.Receiver
}
// Name returns the name of the action, as defined in the charm.
func (a *Action) Name() string {
return a.doc.Name
}
// Parameters will contain a structure representing arguments or parameters to
// an action, and is expected to be validated by the Unit using the Charm
// definition of the Action.
func (a *Action) Parameters() map[string]interface{} {
return a.doc.Parameters
}
// Enqueued returns the time the action was added to state as a pending
// Action.
func (a *Action) Enqueued() time.Time {
return a.doc.Enqueued
}
// Started returns the time that the Action execution began.
func (a *Action) Started() time.Time {
return a.doc.Started
}
// Completed returns the completion time of the Action.
func (a *Action) Completed() time.Time {
return a.doc.Completed
}
// Status returns the final state of the action.
func (a *Action) Status() ActionStatus {
return a.doc.Status
}
// Results returns the structured output of the action and any error.
func (a *Action) Results() (map[string]interface{}, string) {
return a.doc.Results, a.doc.Message
}
// ValidateTag should be called before calls to Tag() or ActionTag(). It verifies
// that the Action can produce a valid Tag.
func (a *Action) ValidateTag() bool {
return names.IsValidAction(a.Id())
}
// Tag implements the Entity interface and returns a names.Tag that
// is a names.ActionTag.
func (a *Action) Tag() names.Tag {
return a.ActionTag()
}
// ActionTag returns an ActionTag constructed from this action's
// Prefix and Sequence.
func (a *Action) ActionTag() names.ActionTag {
return names.NewActionTag(a.Id())
}
// ActionResults is a data transfer object that holds the key Action
// output and results information.
type ActionResults struct {
Status ActionStatus `json:"status"`
Results map[string]interface{} `json:"results"`
Message string `json:"message"`
}
// Begin marks an action as running, and logs the time it was started.
// It asserts that the action is currently pending.
func (a *Action) Begin() (*Action, error) {
err := a.st.runTransaction([]txn.Op{
{
C: actionsC,
Id: a.doc.DocId,
Assert: bson.D{{"status", ActionPending}},
Update: bson.D{{"$set", bson.D{
{"status", ActionRunning},
{"started", nowToTheSecond()},
}}},
}})
if err != nil {
return nil, err
}
return a.st.Action(a.Id())
}
// Finish removes action from the pending queue and captures the output
// and end state of the action.
func (a *Action) Finish(results ActionResults) (*Action, error) {
return a.removeAndLog(results.Status, results.Results, results.Message)
}
// removeAndLog takes the action off of the pending queue, and creates
// an actionresult to capture the outcome of the action. It asserts that
// the action is not already completed.
func (a *Action) removeAndLog(finalStatus ActionStatus, results map[string]interface{}, message string) (*Action, error) {
err := a.st.runTransaction([]txn.Op{
{
C: actionsC,
Id: a.doc.DocId,
Assert: bson.D{{"status", bson.D{
{"$nin", []interface{}{
ActionCompleted,
ActionCancelled,
ActionFailed,
}}}}},
Update: bson.D{{"$set", bson.D{
{"status", finalStatus},
{"message", message},
{"results", results},
{"completed", nowToTheSecond()},
}}},
}, {
C: actionNotificationsC,
Id: a.st.docID(ensureActionMarker(a.Receiver()) + a.Id()),
Remove: true,
}})
if err != nil {
return nil, err
}
return a.st.Action(a.Id())
}
// newActionTagFromNotification converts an actionNotificationDoc into
// an names.ActionTag
func newActionTagFromNotification(doc actionNotificationDoc) names.ActionTag {
actionLogger.Debugf("newActionTagFromNotification doc: '%#v'", doc)
return names.NewActionTag(doc.ActionID)
}
// newAction builds an Action for the given State and actionDoc.
func newAction(st *State, adoc actionDoc) *Action {
return &Action{
st: st,
doc: adoc,
}
}
// newActionDoc builds the actionDoc with the given name and parameters.
func newActionDoc(st *State, receiverTag names.Tag, actionName string, parameters map[string]interface{}) (actionDoc, actionNotificationDoc, error) {
prefix := ensureActionMarker(receiverTag.Id())
actionId, err := NewUUID()
if err != nil {
return actionDoc{}, actionNotificationDoc{}, err
}
actionLogger.Debugf("newActionDoc name: '%s', receiver: '%s', actionId: '%s'", actionName, receiverTag, actionId)
envuuid := st.EnvironUUID()
return actionDoc{
DocId: st.docID(actionId.String()),
EnvUUID: envuuid,
Receiver: receiverTag.Id(),
Name: actionName,
Parameters: parameters,
Enqueued: nowToTheSecond(),
Status: ActionPending,
}, actionNotificationDoc{
DocId: st.docID(prefix + actionId.String()),
EnvUUID: envuuid,
Receiver: receiverTag.Id(),
ActionID: actionId.String(),
}, nil
}
var ensureActionMarker = ensureSuffixFn(actionMarker)
// Action returns an Action by Id, which is a UUID.
func (st *State) Action(id string) (*Action, error) {
actionLogger.Tracef("Action() %q", id)
actions, closer := st.getCollection(actionsC)
defer closer()
doc := actionDoc{}
err := actions.FindId(id).One(&doc)
if err == mgo.ErrNotFound {
return nil, errors.NotFoundf("action %q", id)
}
if err != nil {
return nil, errors.Annotatef(err, "cannot get action %q", id)
}
actionLogger.Tracef("Action() %q found %+v", id, doc)
return newAction(st, doc), nil
}
// ActionByTag returns an Action given an ActionTag.
func (st *State) ActionByTag(tag names.ActionTag) (*Action, error) {
return st.Action(tag.Id())
}
// FindActionTagsByPrefix finds Actions with ids that share the supplied prefix, and
// returns a list of corresponding ActionTags.
func (st *State) FindActionTagsByPrefix(prefix string) []names.ActionTag {
actionLogger.Tracef("FindActionTagsByPrefix() %q", prefix)
var results []names.ActionTag
var doc struct {
Id string `bson:"_id"`
}
actions, closer := st.getCollection(actionsC)
defer closer()
iter := actions.Find(bson.D{{"_id", bson.D{{"$regex", "^" + st.docID(prefix)}}}}).Iter()
for iter.Next(&doc) {
actionLogger.Tracef("FindActionTagsByPrefix() iter doc %+v", doc)
localID := st.localID(doc.Id)
if names.IsValidAction(localID) {
results = append(results, names.NewActionTag(localID))
}
}
actionLogger.Tracef("FindActionTagsByPrefix() %q found %+v", prefix, results)
return results
}
// EnqueueAction
func (st *State) EnqueueAction(receiver names.Tag, actionName string, payload map[string]interface{}) (*Action, error) {
if len(actionName) == 0 {
return nil, errors.New("action name required")
}
receiverCollectionName, receiverId, err := st.tagToCollectionAndId(receiver)
if err != nil {
return nil, errors.Trace(err)
}
doc, ndoc, err := newActionDoc(st, receiver, actionName, payload)
if err != nil {
return nil, errors.Trace(err)
}
ops := []txn.Op{{
C: receiverCollectionName,
Id: receiverId,
Assert: notDeadDoc,
}, {
C: actionsC,
Id: doc.DocId,
Assert: txn.DocMissing,
Insert: doc,
}, {
C: actionNotificationsC,
Id: ndoc.DocId,
Assert: txn.DocMissing,
Insert: ndoc,
}}
buildTxn := func(attempt int) ([]txn.Op, error) {
if notDead, err := isNotDead(st, receiverCollectionName, receiverId); err != nil {
return nil, err
} else if !notDead {
return nil, ErrDead
} else if attempt != 0 {
return nil, errors.Errorf("unexpected attempt number '%d'", attempt)
}
return ops, nil
}
if err = st.run(buildTxn); err == nil {
return newAction(st, doc), nil
}
return nil, err
}
// matchingActions finds actions that match ActionReceiver.
func (st *State) matchingActions(ar ActionReceiver) ([]*Action, error) {
return st.matchingActionsByReceiverId(ar.Tag().Id())
}
// matchingActionsByReceiverId finds actions that match ActionReceiver name.
func (st *State) matchingActionsByReceiverId(id string) ([]*Action, error) {
var doc actionDoc
var actions []*Action
actionsCollection, closer := st.getCollection(actionsC)
defer closer()
iter := actionsCollection.Find(bson.D{{"receiver", id}}).Iter()
for iter.Next(&doc) {
actions = append(actions, newAction(st, doc))
}
return actions, errors.Trace(iter.Close())
}
// matchingActionNotifications finds actionNotifications that match ActionReceiver.
func (st *State) matchingActionNotifications(ar ActionReceiver) ([]names.ActionTag, error) {
return st.matchingActionNotificationsByReceiverId(ar.Tag().Id())
}
// matchingActionNotificationsByReceiverId finds actionNotifications that match ActionReceiver.
func (st *State) matchingActionNotificationsByReceiverId(id string) ([]names.ActionTag, error) {
var doc actionNotificationDoc
var tags []names.ActionTag
notificationCollection, closer := st.getCollection(actionNotificationsC)
defer closer()
iter := notificationCollection.Find(bson.D{{"receiver", id}}).Iter()
for iter.Next(&doc) {
tags = append(tags, newActionTagFromNotification(doc))
}
return tags, errors.Trace(iter.Close())
}
// matchingActionsPending finds actions that match ActionReceiver and
// that are pending.
func (st *State) matchingActionsPending(ar ActionReceiver) ([]*Action, error) {
completed := bson.D{{"status", ActionPending}}
return st.matchingActionsByReceiverAndStatus(ar.Tag(), completed)
}
// matchingActionsRunning finds actions that match ActionReceiver and
// that are running.
func (st *State) matchingActionsRunning(ar ActionReceiver) ([]*Action, error) {
completed := bson.D{{"status", ActionRunning}}
return st.matchingActionsByReceiverAndStatus(ar.Tag(), completed)
}
// matchingActionsCompleted finds actions that match ActionReceiver and
// that are complete.
func (st *State) matchingActionsCompleted(ar ActionReceiver) ([]*Action, error) {
completed := bson.D{{"$or", []bson.D{
{{"status", ActionCompleted}},
{{"status", ActionCancelled}},
{{"status", ActionFailed}},
}}}
return st.matchingActionsByReceiverAndStatus(ar.Tag(), completed)
}
// matchingActionsByReceiverAndStatus finds actionNotifications that
// match ActionReceiver.
func (st *State) matchingActionsByReceiverAndStatus(tag names.Tag, statusCondition bson.D) ([]*Action, error) {
var doc actionDoc
var actions []*Action
actionsCollection, closer := st.getCollection(actionsC)
defer closer()
sel := append(bson.D{{"receiver", tag.Id()}}, statusCondition...)
iter := actionsCollection.Find(sel).Iter()
for iter.Next(&doc) {
actions = append(actions, newAction(st, doc))
}
return actions, errors.Trace(iter.Close())
}
| cmars/juju | state/action.go | GO | agpl-3.0 | 14,225 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Account Cut-off Base module for OpenERP
# Copyright (C) 2013 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Account Cut-off Base',
'version': '0.1',
'category': 'Accounting & Finance',
'license': 'AGPL-3',
'summary': 'Base module for Account Cut-offs',
'description': """
This module contains objets, fields and menu entries that are used by other
cut-off modules. So you need to install other cut-off modules to get the
additionnal functionalities :
* the module *account_cutoff_prepaid* will manage prepaid cut-offs based on
start date and end date,
* the module *account_cutoff_accrual_picking* will manage the accruals based
on the status of the pickings.
Please contact Alexis de Lattre from Akretion <alexis.delattre@akretion.com>
for any help or question about this module.
""",
'author': "Akretion,Odoo Community Association (OCA)",
'website': 'http://www.akretion.com',
'depends': ['account_accountant'],
'data': [
'company_view.xml',
'account_cutoff_view.xml',
'security/ir.model.access.csv',
'security/account_cutoff_base_security.xml',
],
'installable': True,
'active': False,
}
| AlceConsorcio/account-closing | account_cutoff_base/__openerp__.py | Python | agpl-3.0 | 2,130 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "object.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Object object;
QTimer timer;
timer.setSingleShot(true);
timer.connect(&timer, SIGNAL(timeout()), &object, SLOT(print()));
timer.start(0);
return app.exec();
}
| CodeDJ/qt5-hidpi | qt/qtdoc/doc/src/snippets/printing-qprinter/main.cpp | C++ | lgpl-2.1 | 2,290 |
/* Create sockets for use in tests (client side).
Copyright (C) 2011-2012 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <bruno@clisp.org>, 2011. */
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* Creates a client socket, by connecting to a server on the given port. */
static int
create_client_socket (int port)
{
int client_socket;
/* Create a client socket. */
client_socket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
ASSERT (client_socket >= 0);
/* Connect to the server process at the specified port. */
{
struct sockaddr_in addr;
memset (&addr, 0, sizeof (addr)); /* needed on AIX and OSF/1 */
addr.sin_family = AF_INET;
#if 0 /* Unoptimized */
inet_pton (AF_INET, "127.0.0.1", &addr.sin_addr);
#elif 0 /* Nearly optimized */
addr.sin_addr.s_addr = htonl (0x7F000001); /* 127.0.0.1 */
#else /* Fully optimized */
{
unsigned char dotted[4] = { 127, 0, 0, 1 }; /* 127.0.0.1 */
memcpy (&addr.sin_addr.s_addr, dotted, 4);
}
#endif
addr.sin_port = htons (port);
ASSERT (connect (client_socket,
(const struct sockaddr *) &addr, sizeof (addr))
== 0);
}
return client_socket;
}
| foxban/libvirt-0.9.12-centos5 | gnulib/tests/socket-client.h | C | lgpl-2.1 | 1,909 |
/* Clear given exceptions in current floating-point environment.
Copyright (C) 2013 Imagination Technologies Ltd.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; see the file COPYING.LIB. If
not, see <http://www.gnu.org/licenses/>. */
#include <fenv.h>
#include <unistd.h>
#include "internal.h"
int
feclearexcept (int excepts)
{
unsigned int temp;
/* Get the current exceptions. */
__asm__ ("MOV %0,TXDEFR" : "=r" (temp));
/* Mask out unsupported bits/exceptions. */
excepts &= FE_ALL_EXCEPT;
excepts <<= 16;
temp &= ~excepts;
metag_set_fpu_flags(temp);
/* Success. */
return 0;
}
| wbx-github/uclibc-ng | libm/metag/fclrexcpt.c | C | lgpl-2.1 | 1,254 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.hibernate.hql.test.tree;
/**
* TODO
*/
//@RunWith(GUnitTestRunner.class)
//@GUnitTest( "org/hibernate/sql/ast/origin/hql/resolve/gUnitHQLTreeWalker.todo" )
public class HQLTreeWalkerTest {
}
| anistor/hibernate-hql-parser | parser/src/test/java/org/hibernate/hql/test/tree/HQLTreeWalkerTest.java | Java | lgpl-2.1 | 1,231 |
package org.fosstrak.epcis.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
/**
* <p>
* Java class for VocabularyElementType complex type.
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType name="VocabularyElementType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="attribute" type="{urn:epcglobal:epcis-masterdata:xsd:1}AttributeType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="children" type="{urn:epcglobal:epcis-masterdata:xsd:1}IDListType" minOccurs="0"/>
* <element name="extension" type="{urn:epcglobal:epcis-masterdata:xsd:1}VocabularyElementExtensionType" minOccurs="0"/>
* <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <anyAttribute processContents='lax'/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VocabularyElementType", namespace = "urn:epcglobal:epcis-masterdata:xsd:1", propOrder = {
"attribute", "children", "extension", "any" })
public class VocabularyElementType {
protected List<AttributeType> attribute;
protected IDListType children;
protected VocabularyElementExtensionType extension;
@XmlAnyElement(lax = true)
protected List<Object> any;
@XmlAttribute(name = "id", required = true)
@XmlSchemaType(name = "anyURI")
protected String id;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the attribute property.
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the attribute property.
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getAttribute().add(newItem);
* </pre>
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AttributeType }
*/
public List<AttributeType> getAttribute() {
if (attribute == null) {
attribute = new ArrayList<AttributeType>();
}
return this.attribute;
}
/**
* Gets the value of the children property.
*
* @return possible object is {@link IDListType }
*/
public IDListType getChildren() {
return children;
}
/**
* Sets the value of the children property.
*
* @param value
* allowed object is {@link IDListType }
*/
public void setChildren(IDListType value) {
this.children = value;
}
/**
* Gets the value of the extension property.
*
* @return possible object is {@link VocabularyElementExtensionType }
*/
public VocabularyElementExtensionType getExtension() {
return extension;
}
/**
* Sets the value of the extension property.
*
* @param value
* allowed object is {@link VocabularyElementExtensionType }
*/
public void setExtension(VocabularyElementExtensionType value) {
this.extension = value;
}
/**
* Gets the value of the any property.
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the any property.
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getAny().add(newItem);
* </pre>
* <p>
* Objects of the following type(s) are allowed in the list {@link Element }
* {@link Object }
*/
public List<Object> getAny() {
if (any == null) {
any = new ArrayList<Object>();
}
return this.any;
}
/**
* Gets the value of the id property.
*
* @return possible object is {@link String }
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is {@link String }
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed
* property on this class.
* <p>
* the map is keyed by the name of the attribute and the value is the string
* value of the attribute. the map returned by this method is live, and you
* can add new attribute by updating the map directly. Because of this
* design, there's no setter.
*
* @return always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
| Jonnychen/fosstrak-epcis | epcis-commons/src/main/java/org/fosstrak/epcis/model/VocabularyElementType.java | Java | lgpl-2.1 | 5,818 |
<?php
namespace wcf\system\worker;
/**
* Every worker has to implement this interface.
*
* @author Alexander Ebert
* @copyright 2001-2015 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package com.woltlab.wcf
* @subpackage system.worker
* @category Community Framework
*/
interface IWorker {
/**
* Creates a new worker object with additional parameters
*
* @param array $parameters
*/
public function __construct(array $parameters);
/**
* Sets current loop count.
*
* @param integer $loopCount
*/
public function setLoopCount($loopCount);
/**
* Gets current process, integer between 0 and 100. If the progress
* hits 100 the worker will terminate.
*
* @return integer
*/
public function getProgress();
/**
* Executes worker action.
*/
public function execute();
/**
* Returns parameters previously given within __construct().
*
* @return array
*/
public function getParameters();
/**
* Validates parameters.
*/
public function validate();
/**
* Returns URL for redirect after worker finished.
*
* @return string
*/
public function getProceedURL();
/**
* Executes actions after worker has been executed.
*/
public function finalize();
}
| ramiusGitHub/WCF | wcfsetup/install/files/lib/system/worker/IWorker.class.php | PHP | lgpl-2.1 | 1,302 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (C) Alkacon Software (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.ade.configuration;
/**
* Interface for a single named configuration object that can either be merged with other configuration
* objects or disable a configuration object with the same name.<p>
*
* @author Georg Westenberger
*
* @version $Revision: 1.0$
*
* @since 8.0.1
*
* @param <X> the configuration object type which can be merged
*/
public interface I_CmsConfigurationObject<X extends I_CmsConfigurationObject<X>> {
/** Default order constant for module configurations. */
int DEFAULT_ORDER = 10000;
/**
* The name of the configuration object.<p>
*
* This name should be unique for each single configuration
*
* @return the name
*/
String getKey();
/**
* If true, this configuration object will disable an inherited configuration object of the same name.<p>
*
* @return true if this configuration object is marked as "disabled"
*/
boolean isDisabled();
/**
* Merges this configuration object with a child configuration object.<p>
*
* @param child the child configuration object
*
* @return the merged configuration objects
*/
X merge(X child);
}
| it-tavis/opencms-core | src/org/opencms/ade/configuration/I_CmsConfigurationObject.java | Java | lgpl-2.1 | 2,390 |
/*******************************************************************************
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2012 Polyglot project group, Cornell University
* Copyright (c) 2006-2012 IBM Corporation
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program and the accompanying materials are made available under
* the terms of the Lesser GNU Public License v2.0 which accompanies this
* distribution.
*
* The development of the Polyglot project has been supported by a
* number of funding sources, including DARPA Contract F30602-99-1-0533,
* monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and
* N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302,
* and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan
* Research Fellowship, and an Intel Research Ph.D. Fellowship.
*
* See README for contributors.
******************************************************************************/
package polyglot.ext.jl5.translate;
import polyglot.ast.Node;
import polyglot.ast.TypeNode;
import polyglot.translate.ExtensionRewriter;
import polyglot.translate.ext.ToExt_c;
import polyglot.types.SemanticException;
import polyglot.util.SerialVersionUID;
public class JL5TypeNodeToJL_c extends ToExt_c {
private static final long serialVersionUID = SerialVersionUID.generate();
@Override
public Node toExt(ExtensionRewriter rw) throws SemanticException {
TypeNode n = (TypeNode) node();
return rw.typeToJava(n.type(), n.position());
}
}
| liujed/polyglot-eclipse | src/polyglot/ext/jl5/translate/JL5TypeNodeToJL_c.java | Java | lgpl-2.1 | 1,793 |
include ../../../config.mak
vpath %.c $(SRC_PATH)/applications/generators/MPEG4
CFLAGS= $(OPTFLAGS) -I"$(SRC_PATH)/include"
ifeq ($(DEBUGBUILD), yes)
CFLAGS+=-g
LDFLAGS+=-g
endif
ifeq ($(GPROFBUILD), yes)
CFLAGS+=-pg
LDFLAGS+=-pg
endif
#common obj
OBJS= main.o
ifeq ($(CONFIG_WIN32),yes)
EXE=.exe
PROG=MPEG4Gen$(EXE)
else
EXT=
PROG=MPEG4Gen
endif
SRCS := $(OBJS:.o=.c)
all: $(PROG)
$(PROG): $(OBJS)
$(CC) $(LDFLAGS) -o $@ $(OBJS) $(EXTRALIBS) -L../../../bin/gcc -L../../../extra_lib/lib/gcc -lgpac
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
clean:
rm -f $(OBJS) $(PROG)
dep: depend
depend:
rm -f .depend
$(CC) -MM $(CFLAGS) $(SRCS) 1>.depend
distclean: clean
rm -f Makefile.bak .depend
# include dependency files if they exist
#
ifneq ($(wildcard .depend),)
include .depend
endif
| wipple/GPAC-old | applications/generators/MPEG4/Makefile | Makefile | lgpl-2.1 | 804 |
<?php
/*
* Limb PHP Framework
*
* @link http://limb-project.com
* @copyright Copyright © 2004-2009 BIT(http://bit-creative.com)
* @license LGPL http://www.gnu.org/copyleft/lesser.html
*/
lmb_require('limb/macro/src/tags/form/lmbMacroFormElementTag.class.php');
/**
* Macro analog for html <label> tag
* @tag label
* @package macro
* @version $Id$
*/
class lmbMacroLabelTag extends lmbMacroFormElementTag
{
protected $html_tag = 'label';
protected $widget_class_name = 'lmbMacroFormLabelWidget';
protected $widget_include_file = 'limb/macro/src/tags/form/lmbMacroFormLabelWidget.class.php';
}
| anoam/limb | macro/src/tags/form/label.tag.php | PHP | lgpl-2.1 | 621 |
/*
* Copyright (c) 2003 by Hewlett-Packard Company. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* The following is useful primarily for debugging and documentation. */
/* We define various atomic operations by acquiring a global pthread */
/* lock. The resulting implementation will perform poorly, but should */
/* be correct unless it is used from signal handlers. */
/* We assume that all pthread operations act like full memory barriers. */
/* (We believe that is the intent of the specification.) */
#include <pthread.h>
#include "test_and_set_t_is_ao_t.h"
/* This is not necessarily compatible with the native */
/* implementation. But those can't be safely mixed anyway. */
#ifdef __cplusplus
extern "C" {
#endif
/* We define only the full barrier variants, and count on the */
/* generalization section below to fill in the rest. */
extern pthread_mutex_t AO_pt_lock;
#ifdef __cplusplus
} /* extern "C" */
#endif
AO_INLINE void
AO_nop_full(void)
{
pthread_mutex_lock(&AO_pt_lock);
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_nop_full
AO_INLINE AO_t
AO_load_full(const volatile AO_t *addr)
{
AO_t result;
pthread_mutex_lock(&AO_pt_lock);
result = *addr;
pthread_mutex_unlock(&AO_pt_lock);
return result;
}
#define AO_HAVE_load_full
AO_INLINE void
AO_store_full(volatile AO_t *addr, AO_t val)
{
pthread_mutex_lock(&AO_pt_lock);
*addr = val;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_store_full
AO_INLINE unsigned char
AO_char_load_full(const volatile unsigned char *addr)
{
unsigned char result;
pthread_mutex_lock(&AO_pt_lock);
result = *addr;
pthread_mutex_unlock(&AO_pt_lock);
return result;
}
#define AO_HAVE_char_load_full
AO_INLINE void
AO_char_store_full(volatile unsigned char *addr, unsigned char val)
{
pthread_mutex_lock(&AO_pt_lock);
*addr = val;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_char_store_full
AO_INLINE unsigned short
AO_short_load_full(const volatile unsigned short *addr)
{
unsigned short result;
pthread_mutex_lock(&AO_pt_lock);
result = *addr;
pthread_mutex_unlock(&AO_pt_lock);
return result;
}
#define AO_HAVE_short_load_full
AO_INLINE void
AO_short_store_full(volatile unsigned short *addr, unsigned short val)
{
pthread_mutex_lock(&AO_pt_lock);
*addr = val;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_short_store_full
AO_INLINE unsigned int
AO_int_load_full(const volatile unsigned int *addr)
{
unsigned int result;
pthread_mutex_lock(&AO_pt_lock);
result = *addr;
pthread_mutex_unlock(&AO_pt_lock);
return result;
}
#define AO_HAVE_int_load_full
AO_INLINE void
AO_int_store_full(volatile unsigned int *addr, unsigned int val)
{
pthread_mutex_lock(&AO_pt_lock);
*addr = val;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_int_store_full
AO_INLINE AO_TS_VAL_t
AO_test_and_set_full(volatile AO_TS_t *addr)
{
AO_TS_VAL_t result;
pthread_mutex_lock(&AO_pt_lock);
result = (AO_TS_VAL_t)(*addr);
*addr = AO_TS_SET;
pthread_mutex_unlock(&AO_pt_lock);
assert(result == AO_TS_SET || result == AO_TS_CLEAR);
return result;
}
#define AO_HAVE_test_and_set_full
AO_INLINE AO_t
AO_fetch_and_add_full(volatile AO_t *p, AO_t incr)
{
AO_t old_val;
pthread_mutex_lock(&AO_pt_lock);
old_val = *p;
*p = old_val + incr;
pthread_mutex_unlock(&AO_pt_lock);
return old_val;
}
#define AO_HAVE_fetch_and_add_full
AO_INLINE unsigned char
AO_char_fetch_and_add_full(volatile unsigned char *p, unsigned char incr)
{
unsigned char old_val;
pthread_mutex_lock(&AO_pt_lock);
old_val = *p;
*p = old_val + incr;
pthread_mutex_unlock(&AO_pt_lock);
return old_val;
}
#define AO_HAVE_char_fetch_and_add_full
AO_INLINE unsigned short
AO_short_fetch_and_add_full(volatile unsigned short *p, unsigned short incr)
{
unsigned short old_val;
pthread_mutex_lock(&AO_pt_lock);
old_val = *p;
*p = old_val + incr;
pthread_mutex_unlock(&AO_pt_lock);
return old_val;
}
#define AO_HAVE_short_fetch_and_add_full
AO_INLINE unsigned int
AO_int_fetch_and_add_full(volatile unsigned int *p, unsigned int incr)
{
unsigned int old_val;
pthread_mutex_lock(&AO_pt_lock);
old_val = *p;
*p = old_val + incr;
pthread_mutex_unlock(&AO_pt_lock);
return old_val;
}
#define AO_HAVE_int_fetch_and_add_full
AO_INLINE void
AO_and_full(volatile AO_t *p, AO_t value)
{
pthread_mutex_lock(&AO_pt_lock);
*p &= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_and_full
AO_INLINE void
AO_or_full(volatile AO_t *p, AO_t value)
{
pthread_mutex_lock(&AO_pt_lock);
*p |= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_or_full
AO_INLINE void
AO_xor_full(volatile AO_t *p, AO_t value)
{
pthread_mutex_lock(&AO_pt_lock);
*p ^= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_xor_full
AO_INLINE void
AO_char_and_full(volatile unsigned char *p, unsigned char value)
{
pthread_mutex_lock(&AO_pt_lock);
*p &= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_char_and_full
AO_INLINE void
AO_char_or_full(volatile unsigned char *p, unsigned char value)
{
pthread_mutex_lock(&AO_pt_lock);
*p |= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_char_or_full
AO_INLINE void
AO_char_xor_full(volatile unsigned char *p, unsigned char value)
{
pthread_mutex_lock(&AO_pt_lock);
*p ^= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_char_xor_full
AO_INLINE void
AO_short_and_full(volatile unsigned short *p, unsigned short value)
{
pthread_mutex_lock(&AO_pt_lock);
*p &= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_short_and_full
AO_INLINE void
AO_short_or_full(volatile unsigned short *p, unsigned short value)
{
pthread_mutex_lock(&AO_pt_lock);
*p |= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_short_or_full
AO_INLINE void
AO_short_xor_full(volatile unsigned short *p, unsigned short value)
{
pthread_mutex_lock(&AO_pt_lock);
*p ^= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_short_xor_full
AO_INLINE void
AO_int_and_full(volatile unsigned *p, unsigned value)
{
pthread_mutex_lock(&AO_pt_lock);
*p &= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_int_and_full
AO_INLINE void
AO_int_or_full(volatile unsigned *p, unsigned value)
{
pthread_mutex_lock(&AO_pt_lock);
*p |= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_int_or_full
AO_INLINE void
AO_int_xor_full(volatile unsigned *p, unsigned value)
{
pthread_mutex_lock(&AO_pt_lock);
*p ^= value;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_int_xor_full
AO_INLINE AO_t
AO_fetch_compare_and_swap_full(volatile AO_t *addr, AO_t old_val,
AO_t new_val)
{
AO_t fetched_val;
pthread_mutex_lock(&AO_pt_lock);
fetched_val = *addr;
if (fetched_val == old_val)
*addr = new_val;
pthread_mutex_unlock(&AO_pt_lock);
return fetched_val;
}
#define AO_HAVE_fetch_compare_and_swap_full
AO_INLINE unsigned char
AO_char_fetch_compare_and_swap_full(volatile unsigned char *addr,
unsigned char old_val,
unsigned char new_val)
{
unsigned char fetched_val;
pthread_mutex_lock(&AO_pt_lock);
fetched_val = *addr;
if (fetched_val == old_val)
*addr = new_val;
pthread_mutex_unlock(&AO_pt_lock);
return fetched_val;
}
#define AO_HAVE_char_fetch_compare_and_swap_full
AO_INLINE unsigned short
AO_short_fetch_compare_and_swap_full(volatile unsigned short *addr,
unsigned short old_val,
unsigned short new_val)
{
unsigned short fetched_val;
pthread_mutex_lock(&AO_pt_lock);
fetched_val = *addr;
if (fetched_val == old_val)
*addr = new_val;
pthread_mutex_unlock(&AO_pt_lock);
return fetched_val;
}
#define AO_HAVE_short_fetch_compare_and_swap_full
AO_INLINE unsigned
AO_int_fetch_compare_and_swap_full(volatile unsigned *addr, unsigned old_val,
unsigned new_val)
{
unsigned fetched_val;
pthread_mutex_lock(&AO_pt_lock);
fetched_val = *addr;
if (fetched_val == old_val)
*addr = new_val;
pthread_mutex_unlock(&AO_pt_lock);
return fetched_val;
}
#define AO_HAVE_int_fetch_compare_and_swap_full
/* Unlike real architectures, we define both double-width CAS variants. */
typedef struct {
AO_t AO_val1;
AO_t AO_val2;
} AO_double_t;
#define AO_HAVE_double_t
#define AO_DOUBLE_T_INITIALIZER { (AO_t)0, (AO_t)0 }
AO_INLINE AO_double_t
AO_double_load_full(const volatile AO_double_t *addr)
{
AO_double_t result;
pthread_mutex_lock(&AO_pt_lock);
result.AO_val1 = addr->AO_val1;
result.AO_val2 = addr->AO_val2;
pthread_mutex_unlock(&AO_pt_lock);
return result;
}
#define AO_HAVE_double_load_full
AO_INLINE void
AO_double_store_full(volatile AO_double_t *addr, AO_double_t value)
{
pthread_mutex_lock(&AO_pt_lock);
addr->AO_val1 = value.AO_val1;
addr->AO_val2 = value.AO_val2;
pthread_mutex_unlock(&AO_pt_lock);
}
#define AO_HAVE_double_store_full
AO_INLINE int
AO_compare_double_and_swap_double_full(volatile AO_double_t *addr,
AO_t old1, AO_t old2,
AO_t new1, AO_t new2)
{
pthread_mutex_lock(&AO_pt_lock);
if (addr -> AO_val1 == old1 && addr -> AO_val2 == old2)
{
addr -> AO_val1 = new1;
addr -> AO_val2 = new2;
pthread_mutex_unlock(&AO_pt_lock);
return 1;
}
else
pthread_mutex_unlock(&AO_pt_lock);
return 0;
}
#define AO_HAVE_compare_double_and_swap_double_full
AO_INLINE int
AO_compare_and_swap_double_full(volatile AO_double_t *addr,
AO_t old1, AO_t new1, AO_t new2)
{
pthread_mutex_lock(&AO_pt_lock);
if (addr -> AO_val1 == old1)
{
addr -> AO_val1 = new1;
addr -> AO_val2 = new2;
pthread_mutex_unlock(&AO_pt_lock);
return 1;
}
else
pthread_mutex_unlock(&AO_pt_lock);
return 0;
}
#define AO_HAVE_compare_and_swap_double_full
/* We can't use hardware loads and stores, since they don't */
/* interact correctly with atomic updates. */
| prefetchnta/crhack | src/ex3rd/atom/atomic_ops/sysdeps/generic_pthread.h | C | lgpl-2.1 | 11,341 |
/* **********************************************************
* Copyright 2006 VMware, Inc. All rights reserved.
* **********************************************************/
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Note - this code originated as the file vfwprintf.c in the FreeBSD
* source code, location src/lib/libc/stdio/vfwprintf.c, revision
* 1.24. It has been borrowed and modified to act like vsnwprintf
* instead. See bsd_output.h for more.
*
* If you care to compare, the original is checked into this directory
* as bsd_vsnwprintf_orig.c.
*/
#if !defined(STR_NO_WIN32_LIBS) && !defined(__FreeBSD__) \
&& !defined(__OpenBSD__) && !defined(__NetBSD__)
/*
* Actual wprintf innards.
*/
#include <ctype.h>
#include <limits.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <wctype.h>
#include "vmware.h"
#include "bsd_output_int.h"
#include "msgfmt.h"
#include "convertutf.h"
typedef struct StrBuf {
Bool alloc;
Bool error;
wchar_t *buf;
size_t size;
size_t index;
} StrBuf;
static int __sfvwrite(StrBuf *sbuf, BSDFmt_UIO *uio);
static int __sprint(StrBuf *sbuf, BSDFmt_UIO *uio);
static wchar_t *__ujtoa(uintmax_t, wchar_t *, int, int, const char *, int,
char, const char *);
static wchar_t *__ultoa(u_long, wchar_t *, int, int, const char *, int,
char, const char *);
static wchar_t *BSDFmt_UTF8ToWChar(const char *, int);
static void __find_arguments(const wchar_t *, va_list, union arg **);
static void __grow_type_table(int, enum typeid **, int *);
static Bool isLenientConversion = TRUE;
static int
__sfvwrite(StrBuf *sbuf, BSDFmt_UIO *uio)
{
int i;
BSDFmt_IOV *siov;
/*
* If aswprintf(), then grow the buffer as necessary.
*/
if (sbuf->alloc) {
size_t n = sbuf->index + uio->uio_resid + 1; // +1 for \0
if (n > sbuf->size) {
wchar_t *p;
ASSERT(sbuf->size > 0);
n = ROUNDUP(n, sbuf->size);
if ((p = realloc(sbuf->buf, n * sizeof(wchar_t))) == NULL) {
sbuf->error = TRUE;
return 1;
}
sbuf->buf = p;
sbuf->size = n;
}
}
for (i = 0, siov = uio->uio_iov; i < uio->uio_iovcnt; i++, siov++) {
int numToWrite;
/*
* Overflowing the buffer is not an error.
* We just silently truncate because that's what snprintf() does.
*
* Always leave space for null termination.
*/
numToWrite = sbuf->size - sbuf->index - 1; // -1 for \0
if (numToWrite > siov->iov_len) {
numToWrite = siov->iov_len;
}
memcpy(sbuf->buf + sbuf->index, siov->iov_base,
numToWrite * sizeof(wchar_t));
sbuf->index += numToWrite;
}
return 0;
}
/*
* Flush out all the vectors defined by the given uio,
* then reset it so that it can be reused.
*/
static int
__sprint(StrBuf *sbuf, BSDFmt_UIO *uio)
{
int err;
if (uio->uio_resid == 0) {
uio->uio_iovcnt = 0;
return (0);
}
err = __sfvwrite(sbuf, uio);
uio->uio_resid = 0;
uio->uio_iovcnt = 0;
return err;
}
/*
* Convert an unsigned long to ASCII for printf purposes, returning
* a pointer to the first character of the string representation.
* Octal numbers can be forced to have a leading zero; hex numbers
* use the given digits.
*/
static wchar_t *
__ultoa(u_long val, wchar_t *endp, int base, int octzero, const char *xdigs,
int needgrp, char thousep, const char *grp)
{
wchar_t *cp = endp;
long sval;
int ndig;
/*
* Handle the three cases separately, in the hope of getting
* better/faster code.
*/
switch (base) {
case 10:
if (val < 10) { /* many numbers are 1 digit */
*--cp = to_char(val);
return (cp);
}
ndig = 0;
/*
* On many machines, unsigned arithmetic is harder than
* signed arithmetic, so we do at most one unsigned mod and
* divide; this is sufficient to reduce the range of
* the incoming value to where signed arithmetic works.
*/
if (val > LONG_MAX) {
*--cp = to_char(val % 10);
ndig++;
sval = val / 10;
} else
sval = val;
do {
*--cp = to_char(sval % 10);
ndig++;
/*
* If (*grp == CHAR_MAX) then no more grouping
* should be performed.
*/
if (needgrp && ndig == *grp && *grp != CHAR_MAX
&& sval > 9) {
*--cp = thousep;
ndig = 0;
/*
* If (*(grp+1) == '\0') then we have to
* use *grp character (last grouping rule)
* for all next cases
*/
if (*(grp+1) != '\0')
grp++;
}
sval /= 10;
} while (sval != 0);
break;
case 8:
do {
*--cp = to_char(val & 7);
val >>= 3;
} while (val);
if (octzero && *cp != '0')
*--cp = '0';
break;
case 16:
do {
*--cp = xdigs[val & 15];
val >>= 4;
} while (val);
break;
default: /* oops */
abort();
}
return (cp);
}
/* Identical to __ultoa, but for intmax_t. */
static wchar_t *
__ujtoa(uintmax_t val, wchar_t *endp, int base, int octzero,
const char *xdigs, int needgrp, char thousep, const char *grp)
{
wchar_t *cp = endp;
intmax_t sval;
int ndig;
/* quick test for small values; __ultoa is typically much faster */
/* (perhaps instead we should run until small, then call __ultoa?) */
if (val <= ULONG_MAX)
return (__ultoa((u_long)val, endp, base, octzero, xdigs,
needgrp, thousep, grp));
switch (base) {
case 10:
if (val < 10) {
*--cp = to_char(val % 10);
return (cp);
}
ndig = 0;
if (val > INTMAX_MAX) {
*--cp = to_char(val % 10);
ndig++;
sval = val / 10;
} else
sval = val;
do {
*--cp = to_char(sval % 10);
ndig++;
/*
* If (*grp == CHAR_MAX) then no more grouping
* should be performed.
*/
if (needgrp && *grp != CHAR_MAX && ndig == *grp
&& sval > 9) {
*--cp = thousep;
ndig = 0;
/*
* If (*(grp+1) == '\0') then we have to
* use *grp character (last grouping rule)
* for all next cases
*/
if (*(grp+1) != '\0')
grp++;
}
sval /= 10;
} while (sval != 0);
break;
case 8:
do {
*--cp = to_char(val & 7);
val >>= 3;
} while (val);
if (octzero && *cp != '0')
*--cp = '0';
break;
case 16:
do {
*--cp = xdigs[val & 15];
val >>= 4;
} while (val);
break;
default:
abort();
}
return (cp);
}
/*
* Convert a UTF-8 string argument to a wide-character string
* representation. If not -1, 'prec' specifies the maximum number of
* wide characters to output. The returned string is always NUL-terminated,
* even if that results in the string exceeding 'prec' characters.
*/
wchar_t *
BSDFmt_UTF8ToWChar(const char *arg, // IN
int prec) // IN
{
ConversionResult cres;
const char *sourceStart, *sourceEnd;
wchar_t *targStart, *targEnd;
wchar_t *targ = NULL;
/*
* targSize and sourceSize are measured in wchar_t units, excluding NUL.
*/
size_t targSize;
size_t sourceSize = strlen(arg);
ASSERT(prec == -1 || prec >= 0);
targSize = sourceSize;
if (prec >= 0) {
targSize = MIN(targSize, prec);
}
while (TRUE) {
/*
* Pad by 1 because we need to NUL-terminate.
*/
wchar_t *oldTarg = targ;
targ = realloc(oldTarg, (targSize + 1) * sizeof *targ);
if (!targ) {
free(oldTarg);
goto exit;
}
targStart = targ;
targEnd = targStart + targSize;
sourceStart = arg;
sourceEnd = sourceStart + sourceSize;
if (2 == sizeof(wchar_t)) {
cres = ConvertUTF8toUTF16((const UTF8 **) &sourceStart,
(const UTF8 *) sourceEnd,
(UTF16 **) &targStart,
(UTF16 *) targEnd,
isLenientConversion);
} else if (4 == sizeof(wchar_t)) {
cres = ConvertUTF8toUTF32((const UTF8 **) &sourceStart,
(const UTF8 *) sourceEnd,
(UTF32 **) &targStart,
(UTF32 *) targEnd,
isLenientConversion);
} else {
NOT_IMPLEMENTED();
}
if (targetExhausted == cres) {
if (targSize == prec) {
/*
* We've got all the caller wants.
*/
break;
} else {
/*
* Grow the buffer.
*/
ASSERT(FALSE);
targSize *= 2;
if (prec >= 0) {
targSize = MIN(targSize, prec);
}
}
} else if ((sourceExhausted == cres) ||
(sourceIllegal == cres)) {
/*
* If lenient, the API converted all it could, so just
* proceed, otherwise, barf.
*/
if (isLenientConversion) {
break;
} else {
free(targ);
targ = NULL;
goto exit;
}
} else if (conversionOK == cres) {
break;
} else {
NOT_IMPLEMENTED();
}
}
/*
* Success, NUL-terminate. (The API updated targStart for us).
*/
ASSERT(targStart <= targEnd);
*targStart = L'\0';
exit:
return targ;
}
#ifndef NO_FLOATING_POINT
static int exponent(wchar_t *, int, wchar_t);
#endif /* !NO_FLOATING_POINT */
int
bsd_vsnwprintf(wchar_t **outBuf, size_t bufSize, const wchar_t *fmt0,
va_list ap)
{
wchar_t *fmt; /* format string */
wchar_t ch; /* character from fmt */
int n, n2; /* handy integer (short term usage) */
wchar_t *cp; /* handy char pointer (short term usage) */
BSDFmt_IOV *iovp; /* for PRINT macro */
int flags; /* flags as above */
int ret; /* return value accumulator */
int width; /* width from format (%8d), or 0 */
int prec; /* precision from format; <0 for N/A */
wchar_t sign; /* sign prefix (' ', '+', '-', or \0) */
wchar_t thousands_sep; /* locale specific thousands separator */
const char *grouping; /* locale specific numeric grouping rules */
#ifndef NO_FLOATING_POINT
/*
* We can decompose the printed representation of floating
* point numbers into several parts, some of which may be empty:
*
* [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
* A B ---C--- D E F
*
* A: 'sign' holds this value if present; '\0' otherwise
* B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
* C: cp points to the string MMMNNN. Leading and trailing
* zeros are not in the string and must be added.
* D: expchar holds this character; '\0' if no exponent, e.g. %f
* F: at least two digits for decimal, at least one digit for hex
*/
char *decimal_point; /* locale specific decimal point */
int signflag; /* true if float is negative */
union { /* floating point arguments %[aAeEfFgG] */
double dbl;
long double ldbl;
} fparg;
int expt; /* integer value of exponent */
char expchar; /* exponent character: [eEpP\0] */
char *dtoaend; /* pointer to end of converted digits */
int expsize; /* character count for expstr */
int lead; /* sig figs before decimal or group sep */
int ndig; /* actual number of digits returned by dtoa */
wchar_t expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
char *dtoaresult; /* buffer allocated by dtoa */
int nseps; /* number of group separators with ' */
int nrepeats; /* number of repeats of the last group */
#endif
u_long ulval; /* integer arguments %[diouxX] */
uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
int base; /* base for [diouxX] conversion */
int dprec; /* a copy of prec if [diouxX], 0 otherwise */
int realsz; /* field size expanded by dprec, sign, etc */
int size; /* size of converted field or string */
int prsize; /* max size of printed field */
const char *xdigs; /* digits for [xX] conversion */
BSDFmt_UIO uio; /* output information: summary */
BSDFmt_IOV iov[BSDFMT_NIOV]; /* ... and individual io vectors */
wchar_t buf[INT_CONV_BUF]; /* buffer with space for digits of uintmax_t */
wchar_t ox[2]; /* space for 0x hex-prefix */
union arg *argtable; /* args, built due to positional arg */
union arg statargtable [STATIC_ARG_TBL_SIZE];
int nextarg; /* 1-based argument index */
wchar_t *convbuf; /* multibyte to wide conversion result */
#ifndef _WIN32
va_list orgap;
#endif
StrBuf sbuf;
/*
* Choose PADSIZE to trade efficiency vs. size. If larger printf
* fields occur frequently, increase PADSIZE and make the initialisers
* below longer.
*/
#define PADSIZE 16 /* pad chunk size */
static wchar_t blanks[PADSIZE] =
{' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
static wchar_t zeroes[PADSIZE] =
{'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
static const char xdigs_lower[16] = "0123456789abcdef";
static const char xdigs_upper[16] = "0123456789ABCDEF";
/*
* BEWARE, these `goto error' on error, PRINT uses `n2' and
* PAD uses `n'.
*/
/*
* BEWARE, these `goto error' on error, and PAD uses `n'.
*/
#define PRINT(ptr, len) { \
iovp->iov_base = (ptr); \
iovp->iov_len = len; \
uio.uio_resid += len; \
iovp++; \
if (++uio.uio_iovcnt >= BSDFMT_NIOV) { \
if (__sprint(&sbuf, &uio)) \
goto error; \
iovp = iov; \
} \
}
#define PAD(howmany, with) do { \
if ((n = (howmany)) > 0) { \
while (n > PADSIZE) { \
PRINT(with, PADSIZE); \
n -= PADSIZE; \
} \
PRINT(with, n); \
} \
} while (0)
#define PRINTANDPAD(p, ep, len, with) do { \
n2 = (ep) - (p); \
if (n2 > (len)) \
n2 = (len); \
if (n2 > 0) \
PRINT((p), n2); \
PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
} while(0)
#define FLUSH() { \
if (uio.uio_resid && __sprint(&sbuf, &uio)) \
goto error; \
uio.uio_iovcnt = 0; \
iovp = iov; \
}
/*
* Get the argument indexed by nextarg. If the argument table is
* built, use it to get the argument. If its not, get the next
* argument (and arguments must be gotten sequentially).
*/
#define GETARG(type) \
((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
(nextarg++, va_arg(ap, type)))
/*
* To extend shorts properly, we need both signed and unsigned
* argument extraction methods.
*/
#define SARG() \
(flags&LONGINT ? GETARG(long) : \
flags&SHORTINT ? (long)(short)GETARG(int) : \
flags&CHARINT ? (long)(signed char)GETARG(int) : \
(long)GETARG(int))
#define UARG() \
(flags&LONGINT ? GETARG(u_long) : \
flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
(u_long)GETARG(u_int))
#define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
#define SJARG() \
(flags&INTMAXT ? GETARG(intmax_t) : \
flags&SIZET ? (intmax_t)GETARG(size_t) : \
flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
(intmax_t)GETARG(long long))
#define UJARG() \
(flags&INTMAXT ? GETARG(uintmax_t) : \
flags&SIZET ? (uintmax_t)GETARG(size_t) : \
flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
(uintmax_t)GETARG(unsigned long long))
/*
* Get * arguments, including the form *nn$. Preserve the nextarg
* that the argument can be gotten once the type is determined.
*/
#define GETASTER(val) \
n2 = 0; \
cp = fmt; \
while (is_digit(*cp)) { \
n2 = 10 * n2 + to_digit(*cp); \
cp++; \
} \
if (*cp == '$') { \
int hold = nextarg; \
nextarg = n2; \
val = GETARG (int); \
nextarg = hold; \
fmt = ++cp; \
} else { \
val = GETARG (int); \
}
/*
* Windows can't scan the args twice, so always build argtable.
* Otherwise, do it when we see an n$ argument.
*/
#ifndef _WIN32
#define FIND_ARGUMENTS() \
(argtable == NULL ? \
(argtable = statargtable, \
__find_arguments(fmt0, orgap, &argtable)) : \
(void) 0)
#else
#define FIND_ARGUMENTS() \
ASSERT(argtable != NULL)
#endif
xdigs = xdigs_lower;
thousands_sep = L'\0';
grouping = NULL;
#ifndef NO_FLOATING_POINT
decimal_point = localeconv()->decimal_point;
#endif
convbuf = NULL;
fmt = (wchar_t *)fmt0;
argtable = NULL;
nextarg = 1;
argtable = statargtable;
#ifndef _WIN32
argtable = NULL;
va_copy(orgap, ap);
#else
argtable = statargtable;
__find_arguments (fmt0, ap, &argtable);
#endif
uio.uio_iov = iovp = iov;
uio.uio_resid = 0;
uio.uio_iovcnt = 0;
ret = 0;
/*
* Set up output string buffer structure.
*/
sbuf.alloc = *outBuf == NULL;
sbuf.error = FALSE;
sbuf.buf = *outBuf;
sbuf.size = bufSize;
sbuf.index = 0;
/*
* If aswprintf(), allocate initial buffer based on format length.
* Empty format only needs one byte.
* Otherwise, round up to multiple of 64.
*/
if (sbuf.alloc) {
size_t n = wcslen(fmt0) + 1; // +1 for \0
if (n > 1) {
n = ROUNDUP(n, 64);
}
if ((sbuf.buf = malloc(n * sizeof (wchar_t))) == NULL) {
sbuf.error = TRUE;
goto error;
}
sbuf.size = n;
}
// shut compile up
#ifndef NO_FLOATING_POINT
expchar = 0;
expsize = 0;
lead = 0;
ndig = 0;
nseps = 0;
nrepeats = 0;
#endif
ulval = 0;
ujval = 0;
/*
* Scan the format for conversions (`%' character).
*/
for (;;) {
for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
/* void */;
if ((n = fmt - cp) != 0) {
if ((unsigned)ret + n > INT_MAX) {
ret = EOF;
goto error;
}
PRINT(cp, n);
ret += n;
}
if (ch == '\0')
goto done;
fmt++; /* skip over '%' */
flags = 0;
dprec = 0;
width = 0;
prec = -1;
sign = '\0';
ox[1] = '\0';
rflag: ch = *fmt++;
reswitch: switch (ch) {
case ' ':
/*-
* ``If the space and + flags both appear, the space
* flag will be ignored.''
* -- ANSI X3J11
*/
if (!sign)
sign = ' ';
goto rflag;
case '#':
flags |= ALT;
goto rflag;
case '*':
/*-
* ``A negative field width argument is taken as a
* - flag followed by a positive field width.''
* -- ANSI X3J11
* They don't exclude field widths read from args.
*/
GETASTER (width);
if (width >= 0)
goto rflag;
width = -width;
/* FALLTHROUGH */
case '-':
flags |= LADJUST;
goto rflag;
case '+':
sign = '+';
goto rflag;
case '\'':
flags |= GROUPING;
thousands_sep = (wchar_t) *(localeconv()->thousands_sep);
grouping = localeconv()->grouping;
/*
* Grouping should not begin with 0, but it nevertheless
* does (see bug 281072) and makes the formatting code
* behave badly, so we fix it up.
*/
if (grouping != NULL && *grouping == '\0') {
static char g[] = { CHAR_MAX, '\0' };
grouping = g;
}
goto rflag;
case '.':
if ((ch = *fmt++) == '*') {
GETASTER (prec);
goto rflag;
}
prec = 0;
while (is_digit(ch)) {
prec = 10 * prec + to_digit(ch);
ch = *fmt++;
}
goto reswitch;
case '0':
/*-
* ``Note that 0 is taken as a flag, not as the
* beginning of a field width.''
* -- ANSI X3J11
*/
flags |= ZEROPAD;
goto rflag;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
n = 0;
do {
n = 10 * n + to_digit(ch);
ch = *fmt++;
} while (is_digit(ch));
if (ch == '$') {
nextarg = n;
FIND_ARGUMENTS();
goto rflag;
}
width = n;
goto reswitch;
case 'h':
if (flags & SHORTINT) {
flags &= ~SHORTINT;
flags |= CHARINT;
} else
flags |= SHORTINT;
goto rflag;
case 'j':
flags |= INTMAXT;
goto rflag;
case 'I':
/* could be I64 - long long int is 64bit */
if (fmt[0] == '6' && fmt[1] == '4') {
fmt += 2;
flags |= LLONGINT;
goto rflag;
}
/* could be I32 - normal int is 32bit */
if (fmt[0] == '3' && fmt[1] == '2') {
fmt += 2;
/* flags |= normal integer - it is 32bit for all our targets */
goto rflag;
}
/*
* I alone - use Microsoft's semantic as size_t modifier. We do
* not support glibc's semantic to use alternative digits.
*/
flags |= SIZET;
goto rflag;
case 'l':
if (flags & LONGINT) {
flags &= ~LONGINT;
flags |= LLONGINT;
} else
flags |= LONGINT;
goto rflag;
case 'L':
case 'q':
flags |= LLONGINT; /* not necessarily */
goto rflag;
case 't':
flags |= PTRDIFFT;
goto rflag;
case 'Z':
case 'z':
flags |= SIZET;
goto rflag;
case 'C':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'c':
if (flags & LONGINT)
*(cp = buf) = (wchar_t)GETARG(wint_t);
else
*(cp = buf) = (wchar_t)bsd_btowc(GETARG(int));
size = 1;
sign = '\0';
break;
case 'D':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'd':
case 'i':
if (flags & INTMAX_SIZE) {
ujval = SJARG();
if ((intmax_t)ujval < 0) {
ujval = -ujval;
sign = '-';
}
} else {
ulval = SARG();
if ((long)ulval < 0) {
ulval = -ulval;
sign = '-';
}
}
base = 10;
goto number;
#ifndef NO_FLOATING_POINT
case 'e':
case 'E':
expchar = ch;
if (prec < 0) /* account for digit before decpt */
prec = DEFPREC + 1;
else
prec++;
goto fp_begin;
case 'f':
case 'F':
expchar = '\0';
goto fp_begin;
case 'g':
case 'G':
expchar = ch - ('g' - 'e');
if (prec == 0)
prec = 1;
fp_begin:
if (prec < 0)
prec = DEFPREC;
if (convbuf != NULL)
free(convbuf);
if (flags & LLONGINT) {
fparg.ldbl = GETARG(long double);
dtoaresult =
ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec, &expt, &signflag,
&dtoaend);
} else {
fparg.dbl = GETARG(double);
dtoaresult =
dtoa(fparg.dbl, expchar ? 2 : 3, prec, &expt, &signflag,
&dtoaend);
if (expt == 9999)
expt = INT_MAX;
}
ndig = dtoaend - dtoaresult;
cp = convbuf = BSDFmt_UTF8ToWChar(dtoaresult, -1);
freedtoa(dtoaresult);
if (signflag)
sign = '-';
if (expt == INT_MAX) { /* inf or nan */
if (*cp == 'N') {
cp = (ch >= 'a') ? L"nan" : L"NAN";
sign = '\0';
} else
cp = (ch >= 'a') ? L"inf" : L"INF";
size = 3;
break;
}
flags |= FPT;
if (ch == 'g' || ch == 'G') {
if (expt > -4 && expt <= prec) {
/* Make %[gG] smell like %[fF] */
expchar = '\0';
if (flags & ALT)
prec -= expt;
else
prec = ndig - expt;
if (prec < 0)
prec = 0;
} else {
/*
* Make %[gG] smell like %[eE], but
* trim trailing zeroes if no # flag.
*/
if (!(flags & ALT))
prec = ndig;
}
}
if (expchar) {
expsize = exponent(expstr, expt - 1, expchar);
size = expsize + prec;
if (prec > 1 || flags & ALT)
++size;
} else {
/* space for digits before decimal point */
if (expt > 0)
size = expt;
else /* "0" */
size = 1;
/* space for decimal pt and following digits */
if (prec || flags & ALT)
size += prec + 1;
if (grouping && expt > 0) {
/* space for thousands' grouping */
nseps = nrepeats = 0;
lead = expt;
while (*grouping != CHAR_MAX) {
if (lead <= *grouping)
break;
lead -= *grouping;
if (*(grouping+1)) {
nseps++;
grouping++;
} else
nrepeats++;
}
size += nseps + nrepeats;
} else
lead = expt;
}
break;
#endif /* !NO_FLOATING_POINT */
case 'n':
/*
* Assignment-like behavior is specified if the
* value overflows or is otherwise unrepresentable.
* C99 says to use `signed char' for %hhn conversions.
*/
if (flags & LLONGINT)
*GETARG(long long *) = ret;
else if (flags & SIZET)
*GETARG(size_t *) = (size_t)ret;
else if (flags & PTRDIFFT)
*GETARG(ptrdiff_t *) = ret;
else if (flags & INTMAXT)
*GETARG(intmax_t *) = ret;
else if (flags & LONGINT)
*GETARG(long *) = ret;
else if (flags & SHORTINT)
*GETARG(short *) = ret;
else if (flags & CHARINT)
*GETARG(signed char *) = ret;
else
*GETARG(int *) = ret;
continue; /* no output */
case 'O':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'o':
if (flags & INTMAX_SIZE)
ujval = UJARG();
else
ulval = UARG();
base = 8;
goto nosign;
case 'p':
/*-
* ``The argument shall be a pointer to void. The
* value of the pointer is converted to a sequence
* of printable characters, in an implementation-
* defined manner.''
* -- ANSI X3J11
*/
ujval = (uintmax_t)(uintptr_t)GETARG(void *);
base = 16;
xdigs = xdigs_lower;
flags = flags | INTMAXT;
/*
* PR 103201
* VisualC sscanf doesn't grok '0x', so prefix zeroes.
*/
// ox[1] = 'x';
goto nosign;
case 'S':
flags |= LONGINT;
/*FALLTHROUGH*/
case 's':
if (flags & LONGINT) {
/* Argument is wchar_t * */
if ((cp = GETARG(wchar_t *)) == NULL)
cp = L"(null)";
} else {
char *mbp;
/* Argument is char * */
if (convbuf!= NULL)
free(convbuf);
if ((mbp = GETARG(char *)) == NULL)
cp = L"(null)";
else {
convbuf = BSDFmt_UTF8ToWChar(mbp, prec);
if (convbuf == NULL) {
sbuf.error = TRUE;
goto error;
}
cp = convbuf;
}
}
if (prec >= 0) {
/*
* can't use wcslen; can only look for the
* NUL in the first `prec' characters, and
* wcslen() will go further.
*/
wchar_t *p = (wchar_t *) wmemchr(cp, 0, (size_t)prec);
if (p != NULL) {
size = p - cp;
if (size > prec)
size = prec;
} else
size = prec;
} else
size = wcslen(cp);
sign = '\0';
break;
case 'U':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'u':
if (flags & INTMAX_SIZE)
ujval = UJARG();
else
ulval = UARG();
base = 10;
goto nosign;
case 'X':
xdigs = xdigs_upper;
goto hex;
case 'x':
xdigs = xdigs_lower;
hex:
if (flags & INTMAX_SIZE)
ujval = UJARG();
else
ulval = UARG();
base = 16;
/* leading 0x/X only if non-zero */
if (flags & ALT &&
(flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
ox[1] = ch;
flags &= ~GROUPING;
/* unsigned conversions */
nosign: sign = '\0';
/*-
* ``... diouXx conversions ... if a precision is
* specified, the 0 flag will be ignored.''
* -- ANSI X3J11
*/
number: if ((dprec = prec) >= 0)
flags &= ~ZEROPAD;
/*-
* ``The result of converting a zero value with an
* explicit precision of zero is no characters.''
* -- ANSI X3J11
*
* ``The C Standard is clear enough as is. The call
* printf("%#.0o", 0) should print 0.''
* -- Defect Report #151
*/
cp = buf + INT_CONV_BUF;
if (flags & INTMAX_SIZE) {
if (ujval != 0 || prec != 0 ||
(flags & ALT && base == 8))
cp = __ujtoa(ujval, cp, base,
flags & ALT, xdigs,
flags & GROUPING, thousands_sep,
grouping);
} else {
if (ulval != 0 || prec != 0 ||
(flags & ALT && base == 8))
cp = __ultoa(ulval, cp, base,
flags & ALT, xdigs,
flags & GROUPING, thousands_sep,
grouping);
}
size = buf + INT_CONV_BUF - cp;
if (size > INT_CONV_BUF) /* should never happen */
abort();
break;
default: /* "%?" prints ?, unless ? is NUL */
if (ch == '\0')
goto done;
/* pretend it was %c with argument ch */
cp = buf;
*cp = ch;
size = 1;
sign = '\0';
break;
}
/*
* All reasonable formats wind up here. At this point, `cp'
* points to a string which (if not flags&LADJUST) should be
* padded out to `width' places. If flags&ZEROPAD, it should
* first be prefixed by any sign or other prefix; otherwise,
* it should be blank padded before the prefix is emitted.
* After any left-hand padding and prefixing, emit zeroes
* required by a decimal [diouxX] precision, then print the
* string proper, then emit zeroes required by any leftover
* floating precision; finally, if LADJUST, pad with blanks.
*
* Compute actual size, so we know how much to pad.
* size excludes decimal prec; realsz includes it.
*/
realsz = dprec > size ? dprec : size;
if (sign)
realsz++;
if (ox[1])
realsz += 2;
prsize = width > realsz ? width : realsz;
if ((unsigned)ret + prsize > INT_MAX) {
ret = EOF;
goto error;
}
/* right-adjusting blank padding */
if ((flags & (LADJUST|ZEROPAD)) == 0)
PAD(width - realsz, blanks);
/* prefix */
if (sign)
PRINT(&sign, 1);
if (ox[1]) { /* ox[1] is either x, X, or \0 */
ox[0] = '0';
PRINT(ox, 2);
}
/* right-adjusting zero padding */
if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
PAD(width - realsz, zeroes);
/* leading zeroes from decimal precision */
PAD(dprec - size, zeroes);
/* the string or number proper */
#ifndef NO_FLOATING_POINT
if ((flags & FPT) == 0) {
PRINT(cp, size);
} else { /* glue together f_p fragments */
if (!expchar) { /* %[fF] or sufficiently short %[gG] */
if (expt <= 0) {
PRINT(zeroes, 1);
if (prec || flags & ALT) {
buf[0] = (wchar_t) *decimal_point;
PRINT(buf, 1);
}
PAD(-expt, zeroes);
/* already handled initial 0's */
prec += expt;
} else {
PRINTANDPAD(cp, convbuf + ndig, lead, zeroes);
cp += lead;
if (grouping) {
while (nseps>0 || nrepeats>0) {
if (nrepeats > 0)
nrepeats--;
else {
grouping--;
nseps--;
}
PRINT(&thousands_sep,
1);
PRINTANDPAD(cp,
convbuf + ndig,
*grouping, zeroes);
cp += *grouping;
}
if (cp > convbuf + ndig)
cp = convbuf + ndig;
}
if (prec || flags & ALT) {
buf[0] = (wchar_t) *decimal_point;
PRINT(buf, 1);
}
}
PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
} else { /* %[eE] or sufficiently long %[gG] */
if (prec > 1 || flags & ALT) {
buf[0] = *cp++;
buf[1] = (wchar_t) *decimal_point;
PRINT(buf, 2);
PRINT(cp, ndig-1);
PAD(prec - ndig, zeroes);
} else /* XeYYY */
PRINT(cp, 1);
PRINT(expstr, expsize);
}
}
#else
PRINT(cp, size);
#endif
/* left-adjusting padding (always blank) */
if (flags & LADJUST)
PAD(width - realsz, blanks);
/* finally, adjust ret */
ret += prsize;
FLUSH(); /* copy out the I/O vectors */
}
done:
FLUSH();
/*
* Always null terminate, unless buffer is size 0.
*/
ASSERT(!sbuf.error && ret >= 0);
if (sbuf.size <= 0) {
ASSERT(!sbuf.alloc);
} else {
ASSERT(sbuf.index < sbuf.size);
sbuf.buf[sbuf.index] = L'\0';
}
error:
#ifndef _WIN32
va_end(orgap);
#endif
if (convbuf != NULL)
free(convbuf);
if (sbuf.error)
ret = EOF;
if ((argtable != NULL) && (argtable != statargtable))
free (argtable);
return (ret);
/* NOTREACHED */
#undef FIND_ARGUMENTS
}
/*
* Find all arguments when a positional parameter is encountered. Returns a
* table, indexed by argument number, of pointers to each arguments. The
* initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
* It will be replaces with a malloc-ed one if it overflows.
*/static void
__find_arguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
{
wchar_t *fmt; /* format string */
wchar_t ch; /* character from fmt */
int n, n2; /* handy integer (short term usage) */
wchar_t *cp; /* handy char pointer (short term usage) */
int flags; /* flags as above */
enum typeid *typetable; /* table of types */
enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
int tablesize; /* current size of type table */
int tablemax; /* largest used index in table */
int nextarg; /* 1-based argument index */
/*
* Add an argument type to the table, expanding if necessary.
*/
#define ADDTYPE(type) \
((nextarg >= tablesize) ? \
__grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
(nextarg > tablemax) ? tablemax = nextarg : 0, \
typetable[nextarg++] = type)
#define ADDSARG() \
((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
((flags&SIZET) ? ADDTYPE(T_SIZET) : \
((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
#define ADDUARG() \
((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
((flags&SIZET) ? ADDTYPE(T_SIZET) : \
((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
/*
* Add * arguments to the type array.
*/
#define ADDASTER() \
n2 = 0; \
cp = fmt; \
while (is_digit(*cp)) { \
n2 = 10 * n2 + to_digit(*cp); \
cp++; \
} \
if (*cp == '$') { \
int hold = nextarg; \
nextarg = n2; \
ADDTYPE (T_INT); \
nextarg = hold; \
fmt = ++cp; \
} else { \
ADDTYPE (T_INT); \
}
fmt = (wchar_t *)fmt0;
typetable = stattypetable;
tablesize = STATIC_ARG_TBL_SIZE;
tablemax = 0; nextarg = 1;
for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
typetable[n] = T_UNUSED;
/*
* Scan the format for conversions (`%' character).
*/
for (;;) {
for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
/* void */;
if (ch == '\0')
goto done;
fmt++; /* skip over '%' */
flags = 0;
rflag: ch = *fmt++;
reswitch: switch (ch) {
case ' ':
case '#':
goto rflag;
case '*':
ADDASTER ();
goto rflag;
case '-':
case '+':
case '\'':
goto rflag;
case '.':
if ((ch = *fmt++) == '*') {
ADDASTER ();
goto rflag;
}
while (is_digit(ch)) {
ch = *fmt++;
}
goto reswitch;
case '0':
goto rflag;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
n = 0;
do {
n = 10 * n + to_digit(ch);
ch = *fmt++;
} while (is_digit(ch));
if (ch == '$') {
nextarg = n;
goto rflag;
}
goto reswitch;
case 'h':
if (flags & SHORTINT) {
flags &= ~SHORTINT;
flags |= CHARINT;
} else
flags |= SHORTINT;
goto rflag;
case 'j':
flags |= INTMAXT;
goto rflag;
case 'I':
/* could be I64 - long long int is 64bit */
if (fmt[0] == '6' && fmt[1] == '4') {
fmt += 2;
flags |= LLONGINT;
goto rflag;
}
/* could be I32 - normal int is 32bit */
if (fmt[0] == '3' && fmt[1] == '2') {
fmt += 2;
/* flags |= normal integer - it is 32bit for all our targets */
goto rflag;
}
/*
* I alone - use Microsoft's semantic as size_t modifier. We do
* not support glibc's semantic to use alternative digits.
*/
flags |= SIZET;
goto rflag;
case 'l':
if (flags & LONGINT) {
flags &= ~LONGINT;
flags |= LLONGINT;
} else
flags |= LONGINT;
goto rflag;
case 'L':
case 'q':
flags |= LLONGINT; /* not necessarily */
goto rflag;
case 't':
flags |= PTRDIFFT;
goto rflag;
case 'Z':
case 'z':
flags |= SIZET;
goto rflag;
case 'C':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'c':
if (flags & LONGINT)
ADDTYPE(T_WINT);
else
ADDTYPE(T_INT);
break;
case 'D':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'd':
case 'i':
ADDSARG();
break;
#ifndef NO_FLOATING_POINT
case 'a':
case 'A':
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
if (flags & LLONGINT)
ADDTYPE(T_LONG_DOUBLE);
else
ADDTYPE(T_DOUBLE);
break;
#endif /* !NO_FLOATING_POINT */
case 'n':
if (flags & INTMAXT)
ADDTYPE(TP_INTMAXT);
else if (flags & PTRDIFFT)
ADDTYPE(TP_PTRDIFFT);
else if (flags & SIZET)
ADDTYPE(TP_SIZET);
else if (flags & LLONGINT)
ADDTYPE(TP_LLONG);
else if (flags & LONGINT)
ADDTYPE(TP_LONG);
else if (flags & SHORTINT)
ADDTYPE(TP_SHORT);
else if (flags & CHARINT)
ADDTYPE(TP_SCHAR);
else
ADDTYPE(TP_INT);
continue; /* no output */
case 'O':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'o':
ADDUARG();
break;
case 'p':
ADDTYPE(TP_VOID);
break;
case 'S':
flags |= LONGINT;
/*FALLTHROUGH*/
case 's':
if (flags & LONGINT)
ADDTYPE(TP_WCHAR);
else
ADDTYPE(TP_CHAR);
break;
case 'U':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'u':
case 'X':
case 'x':
ADDUARG();
break;
default: /* "%?" prints ?, unless ? is NUL */
if (ch == '\0')
goto done;
break;
}
}
done:
/*
* Build the argument table.
*/
if (tablemax >= STATIC_ARG_TBL_SIZE) {
*argtable = (union arg *)
malloc (sizeof (union arg) * (tablemax + 1));
}
(*argtable) [0].intarg = 0;
for (n = 1; n <= tablemax; n++) {
switch (typetable [n]) {
case T_UNUSED: /* whoops! */
(*argtable) [n].intarg = va_arg (ap, int);
break;
case TP_SCHAR:
(*argtable) [n].pschararg = va_arg (ap, signed char *);
break;
case TP_SHORT:
(*argtable) [n].pshortarg = va_arg (ap, short *);
break;
case T_INT:
(*argtable) [n].intarg = va_arg (ap, int);
break;
case T_U_INT:
(*argtable) [n].uintarg = va_arg (ap, unsigned int);
break;
case TP_INT:
(*argtable) [n].pintarg = va_arg (ap, int *);
break;
case T_LONG:
(*argtable) [n].longarg = va_arg (ap, long);
break;
case T_U_LONG:
(*argtable) [n].ulongarg = va_arg (ap, unsigned long);
break;
case TP_LONG:
(*argtable) [n].plongarg = va_arg (ap, long *);
break;
case T_LLONG:
(*argtable) [n].longlongarg = va_arg (ap, long long);
break;
case T_U_LLONG:
(*argtable) [n].ulonglongarg = va_arg (ap, unsigned long long);
break;
case TP_LLONG:
(*argtable) [n].plonglongarg = va_arg (ap, long long *);
break;
case T_PTRDIFFT:
(*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
break;
case TP_PTRDIFFT:
(*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
break;
case T_SIZET:
(*argtable) [n].sizearg = va_arg (ap, size_t);
break;
case TP_SIZET:
(*argtable) [n].psizearg = va_arg (ap, size_t *);
break;
case T_INTMAXT:
(*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
break;
case T_UINTMAXT:
(*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
break;
case TP_INTMAXT:
(*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
break;
#ifndef NO_FLOATING_POINT
case T_DOUBLE:
(*argtable) [n].doublearg = va_arg (ap, double);
break;
case T_LONG_DOUBLE:
(*argtable) [n].longdoublearg = va_arg (ap, long double);
break;
#endif
case TP_CHAR:
(*argtable) [n].pchararg = va_arg (ap, char *);
break;
case TP_VOID:
(*argtable) [n].pvoidarg = va_arg (ap, void *);
break;
case T_WINT:
(*argtable) [n].wintarg = va_arg (ap, wint_t);
break;
case TP_WCHAR:
(*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
break;
}
}
if ((typetable != NULL) && (typetable != stattypetable))
free (typetable);
}
/*
* Increase the size of the type table.
*/
static void
__grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
{
enum typeid *const oldtable = *typetable;
const int oldsize = *tablesize;
enum typeid *newtable;
int n, newsize = oldsize * 2;
if (newsize < nextarg + 1)
newsize = nextarg + 1;
if (oldsize == STATIC_ARG_TBL_SIZE) {
if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
abort(); /* XXX handle better */
memmove(newtable, oldtable, oldsize * sizeof(enum typeid));
} else {
newtable = realloc(oldtable, newsize * sizeof(enum typeid));
if (newtable == NULL)
abort(); /* XXX handle better */
}
for (n = oldsize; n < newsize; n++)
newtable[n] = T_UNUSED;
*typetable = newtable;
*tablesize = newsize;
}
#ifndef NO_FLOATING_POINT
static int
exponent(wchar_t *p0, int exp, wchar_t fmtch)
{
wchar_t *p, *t;
wchar_t expbuf[MAXEXPDIG];
p = p0;
*p++ = fmtch;
if (exp < 0) {
exp = -exp;
*p++ = '-';
}
else
*p++ = '+';
t = expbuf + MAXEXPDIG;
if (exp < 10) {
*p++ = '0';
}
if (exp < 100) {
*p++ = '0';
}
if (exp > 9) {
do {
*--t = to_char(exp % 10);
} while ((exp /= 10) > 9);
*--t = to_char(exp);
for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
} else {
*p++ = to_char(exp);
}
return (p - p0);
}
#endif /* !NO_FLOATING_POINT */
#endif /* !STR_NO_WIN32_LIBS|*BSD */
| vyos/open-vm-tools | lib/string/bsd_vsnwprintf.c | C | lgpl-2.1 | 51,656 |
{
//
//This macro produces the flowchart of TFormula::Analyze
//Author: Rene Brun
gROOT->Reset();
c1 = new TCanvas("c1","Analyze.mac",620,790);
c1->Range(-1,0,19,30);
TPaveLabel pl1(0,27,3.5,29,"Analyze");
pl1.SetFillColor(42);
pl1.Draw();
TPaveText pt1(0,22.8,4,25.2);
TText *t1=pt1.AddText("Parenthesis matching");
TText *t2=pt1.AddText("Remove unnecessary");
TText *t2a=pt1.AddText("parenthesis");
pt1.Draw();
TPaveText pt2(6,23,10,25);
TText *t3=pt2.AddText("break of");
TText *t4=pt2.AddText("Analyze");
pt2.Draw();
TPaveText pt3(0,19,4,21);
t4=pt3.AddText("look for simple");
TText *t5=pt3.AddText("operators");
pt3.Draw();
TPaveText pt4(0,15,4,17);
TText *t6=pt4.AddText("look for an already");
TText *t7=pt4.AddText("defined expression");
pt4.Draw();
TPaveText pt5(0,11,4,13);
TText *t8=pt5.AddText("look for usual");
TText *t9=pt5.AddText("functions :cos sin ..");
pt5.Draw();
TPaveText pt6(0,7,4,9);
TText *t10=pt6.AddText("look for a");
TText *t11=pt6.AddText("numeric value");
pt6.Draw();
TPaveText pt7(6,18.5,10,21.5);
TText *t12=pt7.AddText("Analyze left and");
TText *t13=pt7.AddText("right part of");
TText *t14=pt7.AddText("the expression");
pt7.Draw();
TPaveText pt8(6,15,10,17);
TText *t15=pt8.AddText("Replace expression");
pt8.Draw();
TPaveText pt9(6,11,10,13);
TText *t16=pt9.AddText("Analyze");
pt9.SetFillColor(42);
pt9.Draw();
TPaveText pt10(6,7,10,9);
TText *t17=pt10.AddText("Error");
TText *t18=pt10.AddText("Break of Analyze");
pt10.Draw();
TPaveText pt11(14,22,17,24);
pt11.SetFillColor(42);
TText *t19=pt11.AddText("Analyze");
TText *t19a=pt11.AddText("Left");
pt11.Draw();
TPaveText pt12(14,19,17,21);
pt12.SetFillColor(42);
TText *t20=pt12.AddText("Analyze");
TText *t20a=pt12.AddText("Right");
pt12.Draw();
TPaveText pt13(14,15,18,18);
TText *t21=pt13.AddText("StackNumber++");
TText *t22=pt13.AddText("operator[StackNumber]");
TText *t23=pt13.AddText("= operator found");
pt13.Draw();
TPaveText pt14(12,10.8,17,13.2);
TText *t24=pt14.AddText("StackNumber++");
TText *t25=pt14.AddText("operator[StackNumber]");
TText *t26=pt14.AddText("= function found");
pt14.Draw();
TPaveText pt15(6,7,10,9);
TText *t27=pt15.AddText("Error");
TText *t28=pt15.AddText("break of Analyze");
pt15.Draw();
TPaveText pt16(0,2,7,5);
TText *t29=pt16.AddText("StackNumber++");
TText *t30=pt16.AddText("operator[StackNumber] = 0");
TText *t31=pt16.AddText("value[StackNumber] = value found");
pt16.Draw();
TArrow ar(2,27,2,25.4,0.012,"|>");
ar.SetFillColor(1);
ar.Draw();
ar.DrawArrow(2,22.8,2,21.2,0.012,"|>");
ar.DrawArrow(2,19,2,17.2,0.012,"|>");
ar.DrawArrow(2,15,2,13.2,0.012,"|>");
ar.DrawArrow(2,11,2, 9.2,0.012,"|>");
ar.DrawArrow(2, 7,2, 5.2,0.012,"|>");
ar.DrawArrow(4,24,6,24,0.012,"|>");
ar.DrawArrow(4,20,6,20,0.012,"|>");
ar.DrawArrow(4,16,6,16,0.012,"|>");
ar.DrawArrow(4,12,6,12,0.012,"|>");
ar.DrawArrow(4, 8,6, 8,0.012,"|>");
ar.DrawArrow(10,20,14,20,0.012,"|>");
ar.DrawArrow(12,23,14,23,0.012,"|>");
ar.DrawArrow(12,16.5,14,16.5,0.012,"|>");
ar.DrawArrow(10,12,12,12,0.012,"|>");
TText ta(2.2,22.2,"err = 0");
ta.SetTextFont(71);
ta.SetTextSize(0.015);
ta.SetTextColor(4);
ta.SetTextAlign(12);
ta.Draw();
ta.DrawText(2.2,18.2,"not found");
ta.DrawText(2.2,6.2,"found");
TText tb(4.2,24.1,"err != 0");
tb.SetTextFont(71);
tb.SetTextSize(0.015);
tb.SetTextColor(4);
tb.SetTextAlign(11);
tb.Draw();
tb.DrawText(4.2,20.1,"found");
tb.DrawText(4.2,16.1,"found");
tb.DrawText(4.2,12.1,"found");
tb.DrawText(4.2, 8.1,"not found");
TLine l1(12,16.5,12,23);
l1.Draw();
}
| smuzaffar/root | tutorials/graphics/analyze.C | C++ | lgpl-2.1 | 3,841 |
/*
* Copyright © 1999/2000 by Henning Zabel <henning@uni-paderborn.de>
*
* 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 2 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, write to the Free Software Foundation,
* Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* gphoto driver for the Mustek MDC800 Digital Camera. The driver
* supports rs232 and USB.
*/
#include <gphoto2/gphoto2-library.h>
#include <gphoto2/gphoto2-result.h>
#include "print.h"
#include "rs232.h"
#include "mdc800_spec.h"
#include "io.h"
#include <fcntl.h>
#include <termios.h>
#include <sys/time.h>
/*
* sends a command and receives the answer to this
* buffer: Strores the answer
* length: length of answer or null
*/
int mdc800_rs232_sendCommand(GPPort *port,unsigned char* command, unsigned char* buffer, int length)
{
char answer;
int fault=0,ret;
int i;
printFnkCall ("(mdc800_rs232_sendCommand) id:%i (%i,%i,%i),answer:%i\n",command[1],command[2],command[3],command[4],length);
usleep(MDC800_DEFAULT_COMMAND_DELAY*1000);
gp_port_set_timeout (port, MDC800_DEFAULT_TIMEOUT );
/* Send command */
for (i=0; i<6; i++)
{
if (gp_port_write (port, (char*)&command[i] ,1) < GP_OK)
{
printCError ("(mdc800_rs232_sendCommand) sending Byte %i fails!\n",i);
fault=1;
}
ret = gp_port_read (port,&answer,1);
if ( ret != 1)
{
printCError ("(mdc800_rs232_sendCommand) receiving resend of Byte %i fails.\n",i);
fault=1;
}
if (command [i] != answer)
{
printCError ("(mdc800_rs232_sendCommand) Byte %i differs : send %i, received %i \n",i,command[i],answer);
fault=1;
}
}
if (fault)
return GP_ERROR_IO;
/* Receive answer */
if (length)
{
/* Some Commands needs a download. */
switch (command[1])
{
case COMMAND_GET_IMAGE:
case COMMAND_GET_THUMBNAIL:
if (!mdc800_rs232_download(port,buffer,length))
{
printCError ("(mdc800_rs232_sendCommand) download of %i Bytes fails.\n",length);
fault=1;
}
break;
default:
if (!mdc800_rs232_receive(port,buffer,length))
{
printCError ("(mdc800_rs232_sendCommand) receiving %i Bytes fails.\n",length);
fault=1;
}
}
}
if (fault)
return GP_ERROR_IO;
/* commit */
if (!(command[1] == COMMAND_CHANGE_RS232_BAUD_RATE)) {
if (!mdc800_rs232_waitForCommit(port,command[1]))
{
printCError ("(mdc800_rs232_sendCommand) receiving commit fails.\n");
fault=1;
}
}
if (fault)
return GP_ERROR_IO;
return GP_OK;
}
/*
* waits for the Commit value
* The function expects the commandid of the corresponding command
* to determine whether a long timeout is needed or not. (Take Photo)
*/
int mdc800_rs232_waitForCommit (GPPort *port,char commandid)
{
unsigned char ch[1];
int ret;
gp_port_set_timeout(port,mdc800_io_getCommandTimeout(commandid));
ret = gp_port_read(port,ch,1);
if (ret!=1)
{
printCError ("(mdc800_rs232_waitForCommit) Error receiving commit !\n");
return GP_ERROR_IO;
}
if (ch[0] != ANSWER_COMMIT )
{
printCError ("(mdc800_rs232_waitForCommit) Byte \"%i\" was not the commit !\n",ch[0]);
return GP_ERROR_IO;
}
return GP_OK;
}
/*
* receive Bytes from camera
*/
int mdc800_rs232_receive (GPPort *port,unsigned char* buffer, int b)
{
int ret;
gp_port_set_timeout (port,MDC800_DEFAULT_TIMEOUT );
ret=gp_port_read(port,(char*)buffer,b);
if (ret!=b)
{
printCError ("(mdc800_rs232_receive) can't read %i Bytes !\n",b);
return GP_ERROR_IO;
}
return GP_OK;
}
/*
* downloads data from camera and send
* a checksum every 512 bytes.
*/
int mdc800_rs232_download (GPPort *port,unsigned char* buffer, int size)
{
int readen=0,i,j;
unsigned char checksum;
unsigned char DSC_checksum;
int numtries=0;
gp_port_set_timeout(port, MDC800_DEFAULT_TIMEOUT );
while (readen < size)
{
if (!mdc800_rs232_receive (port,&buffer[readen],512))
return readen;
checksum=0;
for (i=0; i<512; i++)
checksum=(checksum+buffer[readen+i])%256;
if (gp_port_write (port,(char*) &checksum,1) < GP_OK)
return readen;
if (!mdc800_rs232_receive (port,&DSC_checksum,1))
return readen;
if (checksum != DSC_checksum)
{
numtries++;
printCError ("(mdc800_rs232_download) checksum: software %i, DSC %i , reload block! (%i) \n",checksum,DSC_checksum,numtries);
if (numtries > 10)
{
printCError ("(mdc800_rs232_download) to many retries, giving up..");
return 0;
}
}
else
{
readen+=512;
numtries=0;
}
}
for (i=0; i<4; i++)
{
printCError ("%i: ",i);
for (j=0; j<8; j++)
printCError (" %i", buffer[i*8+j]);
printCError ("\n");
}
return readen;
}
| Asofa/libgphoto2 | camlibs/mustek/rs232.c | C | lgpl-2.1 | 5,097 |
// AForge Fuzzy Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2007-2011
// contacts@aforgenet.com
//
namespace Accord.Fuzzy
{
using System;
using System.Collections.Generic;
/// <summary>
/// Interface which specifies set of methods required to be implemented by all defuzzification methods
/// that can be used in Fuzzy Inference Systems.
/// </summary>
///
/// <remarks><para>In many applications, a Fuzzy Inference System is used to perform linguistic computation,
/// but at the end of the inference process, a numerical value is needed. It does not mean that the system
/// needs precision, but simply that a numerical value is required, most of the times because it will be used to
/// control another system that needs the number. To obtain this numer, a defuzzification method is performed.</para>
///
/// <para>Several deffuzification methods were proposed, and they can be created as classes that
/// implements this interface.</para></remarks>
///
public interface IDefuzzifier
{
/// <summary>
/// Defuzzification method to obtain the numerical representation of a fuzzy output.
/// </summary>
///
/// <param name="fuzzyOutput">A <see cref="FuzzyOutput"/> containing the output of
/// several rules of a Fuzzy Inference System.</param>
/// <param name="normOperator">A <see cref="INorm"/> operator to be used when constraining
/// the label to the firing strength.</param>
///
/// <returns>The numerical representation of the fuzzy output.</returns>
///
float Defuzzify( FuzzyOutput fuzzyOutput, INorm normOperator );
}
}
| anders9ustafsson/framework | Sources/Accord.Fuzzy/Defuzzification/IDefuzzifier.cs | C# | lgpl-2.1 | 1,774 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ------------------------------
* HighLowItemLabelGenerator.java
* ------------------------------
* (C) Copyright 2001-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): David Basten;
*
* Changes
* -------
* 13-Dec-2001 : Version 1 (DG);
* 16-Jan-2002 : Completed Javadocs (DG);
* 23-Apr-2002 : Added date to the tooltip string (DG);
* 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
* 21-Mar-2003 : Implemented Serializable (DG);
* 13-Aug-2003 : Implemented Cloneable (DG);
* 17-Nov-2003 : Implemented PublicCloneable (DG);
* 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG);
* 25-May-2004 : Added number formatter (see patch 890496) (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 20-Apr-2005 : Renamed XYLabelGenerator --> XYItemLabelGenerator (DG);
* 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG);
*
*/
package org.jfree.chart.labels;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import org.jfree.chart.HashUtilities;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.util.PublicCloneable;
/**
* A standard item label generator for plots that use data from a
* {@link OHLCDataset}.
*/
public class HighLowItemLabelGenerator implements XYItemLabelGenerator,
XYToolTipGenerator, Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 5617111754832211830L;
/** The date formatter. */
private DateFormat dateFormatter;
/** The number formatter. */
private NumberFormat numberFormatter;
/**
* Creates an item label generator using the default date and number
* formats.
*/
public HighLowItemLabelGenerator() {
this(DateFormat.getInstance(), NumberFormat.getInstance());
}
/**
* Creates a tool tip generator using the supplied date formatter.
*
* @param dateFormatter the date formatter (<code>null</code> not
* permitted).
* @param numberFormatter the number formatter (<code>null</code> not
* permitted).
*/
public HighLowItemLabelGenerator(DateFormat dateFormatter,
NumberFormat numberFormatter) {
if (dateFormatter == null) {
throw new IllegalArgumentException(
"Null 'dateFormatter' argument.");
}
if (numberFormatter == null) {
throw new IllegalArgumentException(
"Null 'numberFormatter' argument.");
}
this.dateFormatter = dateFormatter;
this.numberFormatter = numberFormatter;
}
/**
* Generates a tooltip text item for a particular item within a series.
*
* @param dataset the dataset.
* @param series the series (zero-based index).
* @param item the item (zero-based index).
*
* @return The tooltip text.
*/
public String generateToolTip(XYDataset dataset, int series, int item) {
String result = null;
if (dataset instanceof OHLCDataset) {
OHLCDataset d = (OHLCDataset) dataset;
Number high = d.getHigh(series, item);
Number low = d.getLow(series, item);
Number open = d.getOpen(series, item);
Number close = d.getClose(series, item);
Number x = d.getX(series, item);
result = d.getSeriesKey(series).toString();
if (x != null) {
Date date = new Date(x.longValue());
result = result + "--> Date=" + this.dateFormatter.format(date);
if (high != null) {
result = result + " High="
+ this.numberFormatter.format(high.doubleValue());
}
if (low != null) {
result = result + " Low="
+ this.numberFormatter.format(low.doubleValue());
}
if (open != null) {
result = result + " Open="
+ this.numberFormatter.format(open.doubleValue());
}
if (close != null) {
result = result + " Close="
+ this.numberFormatter.format(close.doubleValue());
}
}
}
return result;
}
/**
* Generates a label for the specified item. The label is typically a
* formatted version of the data value, but any text can be used.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index (zero-based).
* @param category the category index (zero-based).
*
* @return The label (possibly <code>null</code>).
*/
public String generateLabel(XYDataset dataset, int series, int category) {
return null; //TODO: implement this method properly
}
/**
* Returns an independent copy of the generator.
*
* @return A clone.
*
* @throws CloneNotSupportedException if cloning is not supported.
*/
public Object clone() throws CloneNotSupportedException {
HighLowItemLabelGenerator clone
= (HighLowItemLabelGenerator) super.clone();
if (this.dateFormatter != null) {
clone.dateFormatter = (DateFormat) this.dateFormatter.clone();
}
if (this.numberFormatter != null) {
clone.numberFormatter = (NumberFormat) this.numberFormatter.clone();
}
return clone;
}
/**
* Tests if this object is equal to another.
*
* @param obj the other object.
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof HighLowItemLabelGenerator)) {
return false;
}
HighLowItemLabelGenerator generator = (HighLowItemLabelGenerator) obj;
if (!this.dateFormatter.equals(generator.dateFormatter)) {
return false;
}
if (!this.numberFormatter.equals(generator.numberFormatter)) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
int result = 127;
result = HashUtilities.hashCode(result, this.dateFormatter);
result = HashUtilities.hashCode(result, this.numberFormatter);
return result;
}
}
| fluidware/Eastwood-Charts | source/org/jfree/chart/labels/HighLowItemLabelGenerator.java | Java | lgpl-2.1 | 8,308 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "itemviewfind.h"
#include <aggregation/aggregate.h>
#include <coreplugin/findplaceholder.h>
#include <QModelIndex>
#include <QTextCursor>
#include <QTreeView>
#include <QVBoxLayout>
namespace Core {
class ItemModelFindPrivate
{
public:
explicit ItemModelFindPrivate(QAbstractItemView *view, int role, ItemViewFind::FetchOption option)
: m_view(view),
m_incrementalWrappedState(false),
m_role(role),
m_option(option)
{
}
QAbstractItemView *m_view;
QModelIndex m_incrementalFindStart;
bool m_incrementalWrappedState;
int m_role;
ItemViewFind::FetchOption m_option;
};
ItemViewFind::ItemViewFind(QAbstractItemView *view, int role, FetchOption option)
: d(new ItemModelFindPrivate(view, role, option))
{
}
ItemViewFind::~ItemViewFind()
{
delete d;
}
bool ItemViewFind::supportsReplace() const
{
return false;
}
FindFlags ItemViewFind::supportedFindFlags() const
{
return FindBackward | FindCaseSensitively | FindRegularExpression | FindWholeWords;
}
void ItemViewFind::resetIncrementalSearch()
{
d->m_incrementalFindStart = QModelIndex();
d->m_incrementalWrappedState = false;
}
void ItemViewFind::clearHighlights()
{
}
QString ItemViewFind::currentFindString() const
{
return QString();
}
QString ItemViewFind::completedFindString() const
{
return QString();
}
void ItemViewFind::highlightAll(const QString &/*txt*/, FindFlags /*findFlags*/)
{
}
IFindSupport::Result ItemViewFind::findIncremental(const QString &txt, FindFlags findFlags)
{
if (!d->m_incrementalFindStart.isValid()) {
d->m_incrementalFindStart = d->m_view->currentIndex();
d->m_incrementalWrappedState = false;
}
d->m_view->setCurrentIndex(d->m_incrementalFindStart);
bool wrapped = false;
IFindSupport::Result result = find(txt, findFlags, true/*startFromCurrent*/,
&wrapped);
if (wrapped != d->m_incrementalWrappedState) {
d->m_incrementalWrappedState = wrapped;
showWrapIndicator(d->m_view);
}
return result;
}
IFindSupport::Result ItemViewFind::findStep(const QString &txt, FindFlags findFlags)
{
bool wrapped = false;
IFindSupport::Result result = find(txt, findFlags, false/*startFromNext*/,
&wrapped);
if (wrapped)
showWrapIndicator(d->m_view);
if (result == IFindSupport::Found) {
d->m_incrementalFindStart = d->m_view->currentIndex();
d->m_incrementalWrappedState = false;
}
return result;
}
QFrame *ItemViewFind::createSearchableWrapper(QAbstractItemView *treeView, ColorOption lightColored, FetchOption option)
{
QFrame *widget = new QFrame;
widget->setFrameStyle(QFrame::NoFrame);
QVBoxLayout *vbox = new QVBoxLayout(widget);
vbox->setMargin(0);
vbox->setSpacing(0);
vbox->addWidget(treeView);
auto placeHolder = new FindToolBarPlaceHolder(widget);
placeHolder->setLightColored(lightColored);
vbox->addWidget(placeHolder);
Aggregation::Aggregate *agg = new Aggregation::Aggregate;
agg->add(treeView);
agg->add(new ItemViewFind(treeView, Qt::DisplayRole, option));
return widget;
}
IFindSupport::Result ItemViewFind::find(const QString &searchTxt,
FindFlags findFlags,
bool startFromCurrentIndex,
bool *wrapped)
{
if (wrapped)
*wrapped = false;
if (searchTxt.isEmpty())
return IFindSupport::NotFound;
if (d->m_view->model()->rowCount() <= 0) // empty model
return IFindSupport::NotFound;
QModelIndex currentIndex = d->m_view->currentIndex();
if (!currentIndex.isValid()) // nothing selected, start from top
currentIndex = d->m_view->model()->index(0, 0);
QTextDocument::FindFlags flags = textDocumentFlagsForFindFlags(findFlags);
QModelIndex resultIndex;
QModelIndex index = currentIndex;
int currentRow = currentIndex.row();
bool sensitive = (findFlags & FindCaseSensitively);
QRegExp searchExpr;
if (findFlags & FindRegularExpression) {
searchExpr = QRegExp(searchTxt,
(sensitive ? Qt::CaseSensitive :
Qt::CaseInsensitive));
} else if (findFlags & FindWholeWords) {
const QString escapedSearchText = QRegExp::escape(searchTxt);
const QString wordBoundary = QLatin1String("\b");
searchExpr = QRegExp(wordBoundary + escapedSearchText + wordBoundary,
(sensitive ? Qt::CaseSensitive :
Qt::CaseInsensitive));
} else {
searchExpr = QRegExp(searchTxt,
(sensitive ? Qt::CaseSensitive :
Qt::CaseInsensitive),
QRegExp::FixedString);
}
bool backward = (flags & QTextDocument::FindBackward);
if (wrapped)
*wrapped = false;
bool anyWrapped = false;
bool stepWrapped = false;
if (!startFromCurrentIndex)
index = followingIndex(index, backward, &stepWrapped);
else
currentRow = -1;
do {
anyWrapped |= stepWrapped; // update wrapped state if we actually stepped to next/prev item
if (index.isValid()) {
const QString &text = d->m_view->model()->data(
index, d->m_role).toString();
if (d->m_view->model()->flags(index) & Qt::ItemIsSelectable
&& (index.row() != currentRow || index.parent() != currentIndex.parent())
&& searchExpr.indexIn(text) != -1)
resultIndex = index;
}
index = followingIndex(index, backward, &stepWrapped);
} while (!resultIndex.isValid() && index.isValid() && index != currentIndex);
if (resultIndex.isValid()) {
d->m_view->setCurrentIndex(resultIndex);
d->m_view->scrollTo(resultIndex);
if (resultIndex.parent().isValid())
if (QTreeView *treeView = qobject_cast<QTreeView *>(d->m_view))
treeView->expand(resultIndex.parent());
if (wrapped)
*wrapped = anyWrapped;
return IFindSupport::Found;
}
return IFindSupport::NotFound;
}
QModelIndex ItemViewFind::nextIndex(const QModelIndex &idx, bool *wrapped) const
{
if (wrapped)
*wrapped = false;
QAbstractItemModel *model = d->m_view->model();
// pathological
if (!idx.isValid())
return model->index(0, 0);
// same parent has more columns, go to next column
if (idx.column() + 1 < model->columnCount(idx.parent()))
return model->index(idx.row(), idx.column() + 1, idx.parent());
// tree views have their children attached to first column
// make sure we are at first column
QModelIndex current = model->index(idx.row(), 0, idx.parent());
// check for children
if (d->m_option == FetchMoreWhileSearching && model->canFetchMore(current))
model->fetchMore(current);
if (model->rowCount(current) > 0)
return current.child(0, 0);
// no more children, go up and look for parent with more children
QModelIndex nextIndex;
while (!nextIndex.isValid()) {
int row = current.row();
current = current.parent();
if (d->m_option == FetchMoreWhileSearching && model->canFetchMore(current))
model->fetchMore(current);
if (row + 1 < model->rowCount(current)) {
// Same parent has another child
nextIndex = model->index(row + 1, 0, current);
} else {
// go up one parent
if (!current.isValid()) {
// we start from the beginning
if (wrapped)
*wrapped = true;
nextIndex = model->index(0, 0);
}
}
}
return nextIndex;
}
QModelIndex ItemViewFind::prevIndex(const QModelIndex &idx, bool *wrapped) const
{
if (wrapped)
*wrapped = false;
QAbstractItemModel *model = d->m_view->model();
// if same parent has earlier columns, just move there
if (idx.column() > 0)
return model->index(idx.row(), idx.column() - 1, idx.parent());
QModelIndex current = idx;
bool checkForChildren = true;
if (current.isValid()) {
int row = current.row();
if (row > 0) {
current = model->index(row - 1, 0, current.parent());
} else {
current = current.parent();
checkForChildren = !current.isValid();
if (checkForChildren && wrapped) {
// we start from the end
*wrapped = true;
}
}
}
if (checkForChildren) {
// traverse down the hierarchy
if (d->m_option == FetchMoreWhileSearching && model->canFetchMore(current))
model->fetchMore(current);
while (int rc = model->rowCount(current)) {
current = model->index(rc - 1, 0, current);
}
}
// set to last column
current = model->index(current.row(), model->columnCount(current.parent()) - 1, current.parent());
return current;
}
QModelIndex ItemViewFind::followingIndex(const QModelIndex &idx, bool backward, bool *wrapped)
{
if (backward)
return prevIndex(idx, wrapped);
return nextIndex(idx, wrapped);
}
} // namespace Core
| farseerri/git_code | src/plugins/coreplugin/find/itemviewfind.cpp | C++ | lgpl-2.1 | 10,991 |
/*
Copyright (C) 1998-2001 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __BOT_H__
#define __BOT_H__
#include "csgeom/math3d.h"
#include "iengine/mesh.h"
#include "csutil/parray.h"
class WalkTest;
struct iMeshObject;
struct iSector;
struct iLight;
struct iEngine;
class csEngine;
/**
* A bot which moves randomly through the dungeon.
*/
class Bot
{
private:
/// Engine handle.
iEngine *engine;
/// Current movement vector (unit vector).
csVector3 d;
/// Position that is followed.
csVector3 follow;
/// Corresponding sector.
iSector* f_sector;
csRef<iMeshWrapper> mesh;
public:
/// Optional dynamic light.
csRef<iLight> light;
public:
/// Constructor.
Bot (iEngine *Engine, iMeshWrapper* botmesh);
/// Destructor.
virtual ~Bot ();
/// Time-base move.
void Move (csTicks elapsed_time);
/// Set movement vector.
void SetBotMove (const csVector3& v);
/// Set bot's sector.
void SetBotSector (iSector* s) { f_sector = s; }
};
/**
* Bot manager.
*/
class BotManager
{
private:
WalkTest* walktest;
csPDelArray<Bot> bots;
csPDelArray<Bot> manual_bots;
public:
BotManager (WalkTest* walktest);
/// Create a bot.
Bot* CreateBot (iSector* where, const csVector3& pos, float dyn_radius, bool manual);
/// Delete the oldest bot.
void DeleteOldestBot (bool manual);
/// Move the bots.
void MoveBots (csTicks elapsed_time);
};
#endif // __BOT_H__
| garinh/cs | apps/walktest/bot.h | C | lgpl-2.1 | 2,134 |
#include <mingpp.h>
#include <cstdlib>
int main()
{
try {
SWFMovie *m = new SWFMovie(8);
SWFBitmap *bmp = new SWFBitmap(MEDIADIR "/image01.png");
SWFFillStyle *fill = SWFFillStyle::BitmapFillStyle(bmp, SWFFILL_CLIPPED_BITMAP);
SWFShape *shape = new SWFShape();
shape->setRightFillStyle(fill);
shape->setLine(1, 0,0,0,255);
shape->drawLine(100, 0);
shape->drawLine(0, 100);
shape->drawLine(-100, 0);
shape->drawLine(0, -100);
m->add(shape);
m->save("test05.swf");
}
catch(SWFException &e)
{
std::cerr << "SWFException: " << e.what() << std::endl << std::endl;
return EXIT_FAILURE;
}
return 0;
}
| pombredanne/libming | test/FillStyle/test05-cxx.C | C++ | lgpl-2.1 | 634 |
/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2009-2014 Yuvraaj Kelkar
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: yuvraaj@gmail.com
*/
#include "LibGvPhones.h"
#include "IMainWindow.h"
#include "GVNumModel.h"
#include "IPhoneAccount.h"
#include "IPhoneAccountFactory.h"
LibGvPhones::LibGvPhones(IMainWindow *parent)
: QObject(parent)
, m_numModel(new GVNumModel(this))
, m_ciModel(new GVNumModel(this))
, m_ignoreSelectedNumberChanges(false)
, s_Refresh(0)
, m_acctFactory(NULL)
{
IMainWindow *win = (IMainWindow *) this->parent ();
connect(&win->gvApi, SIGNAL(registeredPhone(const GVRegisteredNumber &)),
this, SLOT(onGotRegisteredPhone(const GVRegisteredNumber &)));
}//LibGvPhones::LibGvPhones
LibGvPhones::~LibGvPhones()
{
}//LibGvPhones::~LibGvPhones
/** Fetch the numbers registered with Google Voice
* This function will initiate the request to pull the registered Google Voice
* numbers from the GVApi.
* These numbers will become the callback list.
*/
bool
LibGvPhones::refresh()
{
AsyncTaskToken *task = new AsyncTaskToken(this);
if (NULL == task) {
return false;
}
connect(task, SIGNAL(completed()), this, SLOT(onGotPhones()));
IMainWindow *win = (IMainWindow *) this->parent ();
m_numModel->m_dialBack.clear ();
return (win->gvApi.getPhones (task));
}//LibGvPhones::refresh
void
LibGvPhones::onGotRegisteredPhone (const GVRegisteredNumber &info)
{
m_numModel->m_dialBack += info;
}//LibGvPhones::onGotRegisteredPhone
QString
LibGvPhones::chooseDefaultNumber()
{
// Return first available dialout method
if (m_numModel->m_dialOut.size () > 0) {
return m_numModel->m_dialOut[0].id;
}
// No dialouts. Select first dialback that is *NOT* an email address.
for (int i = 0; i < m_numModel->m_dialBack.size (); i++) {
if (!m_numModel->m_dialBack[i].number.contains ('@')) {
return m_numModel->m_dialBack[i].id;
}
}
if (m_numModel->m_dialBack.size ()) {
// Giving up. Return whatever.
return m_numModel->m_dialBack[0].id;
}
return QString();
}//LibGvPhones::chooseDefaultNumber
void
LibGvPhones::onGotPhones()
{
AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender ();
IMainWindow *win = (IMainWindow *) this->parent ();
QString id;
do {
bool dialBack;
int index;
if (win->db.getSelectedPhone (id)) {
if (m_numModel->findById (id, dialBack, index)) {
break;
}
}
if (m_numModel->m_dialBack.count() == 0) {
return;
}
// Either id not found, or nothing saved: Use default
id = chooseDefaultNumber ();
} while(0);
m_numModel->m_selectedId = id;
s_Refresh++;
if (s_Refresh == 1) {
win->uiSetNewRegNumbersModel ();
}
m_numModel->informViewsOfNewData ();
win->uiRefreshNumbers ();
task->deleteLater ();
}//LibGvPhones::onGotPhones
bool
LibGvPhones::onUserSelectPhone(int index)
{
if (NULL == m_numModel) {
return (false);
}
if (m_ignoreSelectedNumberChanges) {
return false;
}
if (index < 0) {
return false;
}
QString id;
do {
if (index < 0) {
return (false);
}
if (index < m_numModel->m_dialBack.count()) {
id = m_numModel->m_dialBack[index].id;
break;
}
index -= m_numModel->m_dialBack.count();
if (index < m_numModel->m_dialOut.count()) {
id = m_numModel->m_dialOut[index].id;
break;
}
Q_WARN("Array index out of bounds");
return (false);
} while (0);
return onUserSelectPhone (id);
}//LibGvPhones::onUserSelectPhone
bool
LibGvPhones::onUserSelectPhone(QString id)
{
if (NULL == m_numModel) {
return (false);
}
if (m_ignoreSelectedNumberChanges) {
return (false);
}
bool rv;
IMainWindow *win = (IMainWindow *) this->parent ();
do {
GVRegisteredNumber num;
rv = m_numModel->findById (id, num);
if (!rv) {
break;
}
if ((!num.dialBack) && (num.number.isEmpty ())) {
QStringList ids, ph;
foreach (GVRegisteredNumber r, m_numModel->m_dialBack) {
ids += r.id;
ph += QString("%1\n(%2)").arg(r.name, r.number);
}
m_ciModel->m_dialBack.clear();
m_ciModel->m_dialOut.clear();
m_ciModel->m_dialBack = m_numModel->m_dialBack;
m_ciModel->informViewsOfNewData ();
// Tell the UI that this CI needs a number
win->uiGetCIDetails(num, m_ciModel);
}
Q_DEBUG(QString("Selected phone ID: %1").arg(m_numModel->m_selectedId));
m_numModel->m_selectedId = num.id;
win->db.putSelectedPhone (num.id);
rv = true;
} while (0);
m_numModel->informViewsOfNewData ();
win->uiRefreshNumbers ();
return (rv);
}//LibGvPhones::onUserSelectPhone
bool
LibGvPhones::ensurePhoneAccountFactory()
{
if (NULL == m_acctFactory) {
m_acctFactory = createPhoneAccountFactory (this);
if (NULL == m_acctFactory) {
Q_WARN("Failed to phone account factory");
return false;
}
}
return true;
}//LibGvPhones::ensurePhoneAccountFactory
/** Identify the dialing methods in the platform
* Mobile platforms can have one or more ways of dialing out.
* This function initiates the work of looking up all those dial out methods.
*/
bool
LibGvPhones::refreshOutgoing()
{
if (!ensurePhoneAccountFactory ()) {
return false;
}
//! Begin the work to identify all phone accounts
AsyncTaskToken *task = new AsyncTaskToken(this);
if (NULL == task) {
Q_WARN("Failed to allocate task token for account identification");
return false;
}
connect(task, SIGNAL(completed()), this, SLOT(onAllAccountsIdentified()));
if (!m_acctFactory->identifyAll (task)) {
Q_WARN("Failed to identify phone accounts");
delete task;
return false;
}
return true;
}//LibGvPhones::refreshOutgoing
void
LibGvPhones::onAllAccountsIdentified()
{
IMainWindow *win = (IMainWindow *) this->parent ();
AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender ();
task->deleteLater ();
if (NULL == m_numModel) {
Q_WARN("Number model is NULL");
return;
}
Q_DEBUG(QString("count = %1")
.arg (m_acctFactory->m_accounts.keys ().count ()));
QString id;
GVRegisteredNumber num;
foreach (id, m_acctFactory->m_accounts.keys ()) {
IPhoneAccount *acc = m_acctFactory->m_accounts[id];
Q_ASSERT(id == acc->id ());
Q_DEBUG(QString("id = %1 name = %2").arg (acc->id (), acc->name ()));
num.init ();
num.id = acc->id ();
num.name = acc->name ();
num.dialBack = false;
// Find out the number from the cache
win->db.getCINumber (num.id, num.number);
m_numModel->m_dialOut += num;
}
if (!win->db.getSelectedPhone (id)) {
id = chooseDefaultNumber ();
}
bool dialBack;
int index;
if (m_numModel->findById (id, dialBack, index)) {
m_numModel->m_selectedId = id;
}
m_numModel->informViewsOfNewData ();
win->uiRefreshNumbers ();
}//LibGvPhones::onAllAccountsIdentified
bool
LibGvPhones::linkCiToNumber(QString ciId, QString strNumber)
{
IMainWindow *win = (IMainWindow *) this->parent ();
bool rv = false;
for (int i = 0; i < m_numModel->m_dialOut.count(); i++) {
if (m_numModel->m_dialOut[i].id == ciId) {
m_numModel->m_dialOut[i].number = strNumber;
win->db.setCINumber (ciId, strNumber);
m_numModel->informViewsOfNewData ();
win->uiRefreshNumbers ();
rv = true;
break;
}
}
return rv;
}//LibGvPhones::linkCiToNumber
bool
LibGvPhones::onUserUpdateCiNumber(int index)
{
QString id;
do {
if (index < m_numModel->m_dialBack.count()) {
return false;
}
index -= m_numModel->m_dialBack.count();
if (index < m_numModel->m_dialOut.count()) {
id = m_numModel->m_dialOut[index].id;
break;
}
Q_WARN("Array index out of bounds");
return (false);
} while(0);
return onUserUpdateCiNumber(id);
}//LibGvPhones::onUserUpdateCiNumber
bool
LibGvPhones::onUserUpdateCiNumber(QString id)
{
bool rv = false;
foreach (GVRegisteredNumber num, m_numModel->m_dialOut) {
if (num.id == id) {
m_ciModel->m_dialBack.clear();
m_ciModel->m_dialOut.clear();
m_ciModel->m_dialBack = m_numModel->m_dialBack;
m_ciModel->informViewsOfNewData ();
// Tell the UI that this CI needs a number
IMainWindow *win = (IMainWindow *) this->parent ();
win->uiGetCIDetails(num, m_ciModel);
rv = true;
break;
}
}
return rv;
}//LibGvPhones::onUserUpdateCiNumber
bool
LibGvPhones::dialOut(const QString &id, const QString &num)
{
GVRegisteredNumber rnum;
bool rv;
do {
rv = m_numModel->findById (id, rnum);
if (!rv) {
Q_WARN(QString("Invalid ID: %1: Not found").arg(id));
break;
}
rv = false;
if (rnum.dialBack) {
Q_WARN(QString("Invalid ID: %1: dial back").arg(id));
break;
}
if (!m_acctFactory->m_accounts.contains (id)) {
Q_WARN(QString("%1 exists in model but not in factory!").arg(id));
break;
}
AsyncTaskToken *task = (AsyncTaskToken *) new AsyncTaskToken(this);
if (NULL == task) {
Q_WARN("Failed to allocate task");
break;
}
connect (task, SIGNAL(completed()), this, SLOT(onDialoutCompleted()));
task->inParams["destination"] = num;
rv = m_acctFactory->m_accounts[id]->initiateCall (task);
if (!rv) {
Q_WARN("Failed to initiate call");
delete task;
break;
}
rv = true;
} while (0);
return (rv);
}//LibGvPhones::dialOut
void
LibGvPhones::onDialoutCompleted()
{
AsyncTaskToken *task = (AsyncTaskToken *) QObject::sender ();
task->deleteLater ();
}//LibGvPhones::onDialoutCompleted
| alexuser01/qgvdial | qgvdial/common/LibGvPhones.cpp | C++ | lgpl-2.1 | 11,192 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qvalidationerror_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
ValidationError::ValidationError(const QString &msg,
const ReportContext::ErrorCode code) : m_message(msg),
m_code(code)
{
}
AtomicValue::Ptr ValidationError::createError(const QString &description,
const ReportContext::ErrorCode code)
{
return ValidationError::Ptr(new ValidationError(description, code));
}
bool ValidationError::hasError() const
{
return true;
}
QString ValidationError::stringValue() const
{
Q_ASSERT_X(false, Q_FUNC_INFO, "stringValue() asked for ValidationError -- it makes no sense.");
return QString();
}
QString ValidationError::message() const
{
return m_message;
}
ItemType::Ptr ValidationError::type() const
{
Q_ASSERT_X(false, Q_FUNC_INFO,
"This function should never be called, the caller "
"didn't check whether the AtomicValue was an ValidationError.");
return ItemType::Ptr();
}
ReportContext::ErrorCode ValidationError::errorCode() const
{
return m_code;
}
QT_END_NAMESPACE
| CodeDJ/qt5-hidpi | qt/qtxmlpatterns/src/xmlpatterns/data/qvalidationerror.cpp | C++ | lgpl-2.1 | 3,188 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "fontsettingspage.h"
#include "fontsettings.h"
#include "ui_fontsettingspage.h"
#include <coreplugin/icore.h>
#include <utils/stringutils.h>
#include <utils/qtcassert.h>
#include <QFileDialog>
#include <QFontDatabase>
#include <QInputDialog>
#include <QMessageBox>
#include <QPalette>
#include <QPointer>
#include <QSettings>
#include <QTimer>
#include <QDebug>
namespace TextEditor {
namespace Internal {
struct ColorSchemeEntry
{
ColorSchemeEntry(const QString &fileName,
bool readOnly):
fileName(fileName),
name(ColorScheme::readNameOfScheme(fileName)),
readOnly(readOnly)
{ }
QString fileName;
QString name;
QString id;
bool readOnly;
};
class SchemeListModel : public QAbstractListModel
{
public:
SchemeListModel(QObject *parent = 0):
QAbstractListModel(parent)
{
}
int rowCount(const QModelIndex &parent) const
{ return parent.isValid() ? 0 : m_colorSchemes.size(); }
QVariant data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole)
return m_colorSchemes.at(index.row()).name;
return QVariant();
}
void removeColorScheme(int index)
{
beginRemoveRows(QModelIndex(), index, index);
m_colorSchemes.removeAt(index);
endRemoveRows();
}
void setColorSchemes(const QList<ColorSchemeEntry> &colorSchemes)
{
beginResetModel();
m_colorSchemes = colorSchemes;
endResetModel();
}
const ColorSchemeEntry &colorSchemeAt(int index) const
{ return m_colorSchemes.at(index); }
private:
QList<ColorSchemeEntry> m_colorSchemes;
};
class FontSettingsPagePrivate
{
public:
FontSettingsPagePrivate(const TextEditor::FormatDescriptions &fd,
Core::Id id,
const QString &displayName,
const QString &category);
~FontSettingsPagePrivate();
public:
const Core::Id m_id;
const QString m_displayName;
const QString m_settingsGroup;
TextEditor::FormatDescriptions m_descriptions;
FontSettings m_value;
FontSettings m_lastValue;
QPointer<QWidget> m_widget;
Ui::FontSettingsPage *m_ui;
SchemeListModel *m_schemeListModel;
bool m_refreshingSchemeList;
};
} // namespace Internal
} // namespace TextEditor
using namespace TextEditor;
using namespace TextEditor::Internal;
static QString customStylesPath()
{
QString path = Core::ICore::userResourcePath();
path.append(QLatin1String("/styles/"));
return path;
}
static QString createColorSchemeFileName(const QString &pattern)
{
const QString stylesPath = customStylesPath();
QString baseFileName = stylesPath;
baseFileName += pattern;
// Find an available file name
int i = 1;
QString fileName;
do {
fileName = baseFileName.arg((i == 1) ? QString() : QString::number(i));
++i;
} while (QFile::exists(fileName));
// Create the base directory when it doesn't exist
if (!QFile::exists(stylesPath) && !QDir().mkpath(stylesPath)) {
qWarning() << "Failed to create color scheme directory:" << stylesPath;
return QString();
}
return fileName;
}
// ------- FontSettingsPagePrivate
FontSettingsPagePrivate::FontSettingsPagePrivate(const TextEditor::FormatDescriptions &fd,
Core::Id id,
const QString &displayName,
const QString &category) :
m_id(id),
m_displayName(displayName),
m_settingsGroup(Utils::settingsKey(category)),
m_descriptions(fd),
m_ui(0),
m_schemeListModel(new SchemeListModel),
m_refreshingSchemeList(false)
{
bool settingsFound = false;
QSettings *settings = Core::ICore::settings();
if (settings)
settingsFound = m_value.fromSettings(m_settingsGroup, m_descriptions, settings);
if (!settingsFound) { // Apply defaults
foreach (const FormatDescription &f, m_descriptions) {
Format &format = m_value.formatFor(f.id());
format.setForeground(f.foreground());
format.setBackground(f.background());
format.setBold(f.format().bold());
format.setItalic(f.format().italic());
}
} else if (m_value.colorSchemeFileName().isEmpty()) {
// No color scheme was loaded, but one might be imported from the ini file
ColorScheme defaultScheme;
foreach (const FormatDescription &f, m_descriptions) {
Format &format = defaultScheme.formatFor(f.id());
format.setForeground(f.foreground());
format.setBackground(f.background());
format.setBold(f.format().bold());
format.setItalic(f.format().italic());
}
if (m_value.colorScheme() != defaultScheme) {
// Save it as a color scheme file
QString schemeFileName = createColorSchemeFileName(QLatin1String("customized%1.xml"));
if (!schemeFileName.isEmpty()) {
if (m_value.saveColorScheme(schemeFileName) && settings)
m_value.toSettings(m_settingsGroup, settings);
}
}
}
m_lastValue = m_value;
}
FontSettingsPagePrivate::~FontSettingsPagePrivate()
{
delete m_schemeListModel;
}
// ------- FormatDescription
FormatDescription::FormatDescription(TextStyle id, const QString &displayName, const QString &tooltipText, const QColor &foreground) :
m_id(id),
m_displayName(displayName),
m_tooltipText(tooltipText)
{
m_format.setForeground(foreground);
}
FormatDescription::FormatDescription(TextStyle id, const QString &displayName, const QString &tooltipText, const Format &format) :
m_id(id),
m_format(format),
m_displayName(displayName),
m_tooltipText(tooltipText)
{
}
QColor FormatDescription::foreground() const
{
if (m_id == C_LINE_NUMBER) {
const QColor bg = QApplication::palette().background().color();
if (bg.value() < 128)
return QApplication::palette().foreground().color();
else
return QApplication::palette().dark().color();
} else if (m_id == C_CURRENT_LINE_NUMBER) {
const QColor bg = QApplication::palette().background().color();
if (bg.value() < 128)
return QApplication::palette().foreground().color();
else
return m_format.foreground();
} else if (m_id == C_OCCURRENCES_UNUSED) {
return Qt::darkYellow;
} else if (m_id == C_PARENTHESES) {
return QColor(Qt::red);
}
return m_format.foreground();
}
QColor FormatDescription::background() const
{
if (m_id == C_TEXT) {
return Qt::white;
} else if (m_id == C_LINE_NUMBER) {
return QApplication::palette().background().color();
} else if (m_id == C_SEARCH_RESULT) {
return QColor(0xffef0b);
} else if (m_id == C_PARENTHESES) {
return QColor(0xb4, 0xee, 0xb4);
} else if (m_id == C_CURRENT_LINE || m_id == C_SEARCH_SCOPE) {
const QPalette palette = QApplication::palette();
const QColor &fg = palette.color(QPalette::Highlight);
const QColor &bg = palette.color(QPalette::Base);
qreal smallRatio;
qreal largeRatio;
if (m_id == C_CURRENT_LINE) {
smallRatio = .3;
largeRatio = .6;
} else {
smallRatio = .05;
largeRatio = .4;
}
const qreal ratio = ((palette.color(QPalette::Text).value() < 128)
^ (palette.color(QPalette::HighlightedText).value() < 128)) ? smallRatio : largeRatio;
const QColor &col = QColor::fromRgbF(fg.redF() * ratio + bg.redF() * (1 - ratio),
fg.greenF() * ratio + bg.greenF() * (1 - ratio),
fg.blueF() * ratio + bg.blueF() * (1 - ratio));
return col;
} else if (m_id == C_SELECTION) {
const QPalette palette = QApplication::palette();
return palette.color(QPalette::Highlight);
} else if (m_id == C_OCCURRENCES) {
return QColor(180, 180, 180);
} else if (m_id == C_OCCURRENCES_RENAME) {
return QColor(255, 100, 100);
} else if (m_id == C_DISABLED_CODE) {
return QColor(239, 239, 239);
} else if (m_id == C_DIFF_FILE_LINE
|| m_id == C_DIFF_CONTEXT_LINE
|| m_id == C_DIFF_SOURCE_LINE
|| m_id == C_DIFF_SOURCE_CHAR
|| m_id == C_DIFF_DEST_LINE
|| m_id == C_DIFF_DEST_CHAR) {
return m_format.background();
}
return QColor(); // invalid color
}
// ------------ FontSettingsPage
FontSettingsPage::FontSettingsPage(const FormatDescriptions &fd,
Core::Id id,
QObject *parent) :
TextEditorOptionsPage(parent),
d_ptr(new FontSettingsPagePrivate(fd, id, tr("Font && Colors"), category().toString()))
{
setId(d_ptr->m_id);
setDisplayName(d_ptr->m_displayName);
}
FontSettingsPage::~FontSettingsPage()
{
delete d_ptr;
}
QWidget *FontSettingsPage::widget()
{
if (!d_ptr->m_widget){
d_ptr->m_widget = new QWidget;
d_ptr->m_ui = new Ui::FontSettingsPage;
d_ptr->m_ui->setupUi(d_ptr->m_widget);
d_ptr->m_ui->schemeComboBox->setModel(d_ptr->m_schemeListModel);
QFontDatabase db;
const QStringList families = db.families();
d_ptr->m_ui->familyComboBox->addItems(families);
const int idx = families.indexOf(d_ptr->m_value.family());
d_ptr->m_ui->familyComboBox->setCurrentIndex(idx);
d_ptr->m_ui->antialias->setChecked(d_ptr->m_value.antialias());
d_ptr->m_ui->zoomSpinBox->setValue(d_ptr->m_value.fontZoom());
d_ptr->m_ui->schemeEdit->setFormatDescriptions(d_ptr->m_descriptions);
d_ptr->m_ui->schemeEdit->setBaseFont(d_ptr->m_value.font());
d_ptr->m_ui->schemeEdit->setColorScheme(d_ptr->m_value.colorScheme());
connect(d_ptr->m_ui->familyComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(fontFamilySelected(QString)));
connect(d_ptr->m_ui->sizeComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(fontSizeSelected(QString)));
connect(d_ptr->m_ui->zoomSpinBox, SIGNAL(valueChanged(int)), this, SLOT(fontZoomChanged()));
connect(d_ptr->m_ui->antialias, SIGNAL(toggled(bool)), this, SLOT(antialiasChanged()));
connect(d_ptr->m_ui->schemeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(colorSchemeSelected(int)));
connect(d_ptr->m_ui->copyButton, SIGNAL(clicked()), this, SLOT(copyColorScheme()));
connect(d_ptr->m_ui->deleteButton, SIGNAL(clicked()), this, SLOT(confirmDeleteColorScheme()));
updatePointSizes();
refreshColorSchemeList();
d_ptr->m_lastValue = d_ptr->m_value;
}
return d_ptr->m_widget;
}
void FontSettingsPage::fontFamilySelected(const QString &family)
{
d_ptr->m_value.setFamily(family);
d_ptr->m_ui->schemeEdit->setBaseFont(d_ptr->m_value.font());
updatePointSizes();
}
void FontSettingsPage::updatePointSizes()
{
// Update point sizes
const int oldSize = d_ptr->m_value.fontSize();
d_ptr->m_ui->sizeComboBox->clear();
const QList<int> sizeLst = pointSizesForSelectedFont();
int idx = -1;
int i = 0;
for (; i < sizeLst.count(); ++i) {
if (idx == -1 && sizeLst.at(i) >= oldSize)
idx = i;
d_ptr->m_ui->sizeComboBox->addItem(QString::number(sizeLst.at(i)));
}
if (idx != -1)
d_ptr->m_ui->sizeComboBox->setCurrentIndex(idx);
}
QList<int> FontSettingsPage::pointSizesForSelectedFont() const
{
QFontDatabase db;
const QString familyName = d_ptr->m_ui->familyComboBox->currentText();
QList<int> sizeLst = db.pointSizes(familyName);
if (!sizeLst.isEmpty())
return sizeLst;
QStringList styles = db.styles(familyName);
if (!styles.isEmpty())
sizeLst = db.pointSizes(familyName, styles.first());
if (sizeLst.isEmpty())
sizeLst = QFontDatabase::standardSizes();
return sizeLst;
}
void FontSettingsPage::fontSizeSelected(const QString &sizeString)
{
bool ok = true;
const int size = sizeString.toInt(&ok);
if (ok) {
d_ptr->m_value.setFontSize(size);
d_ptr->m_ui->schemeEdit->setBaseFont(d_ptr->m_value.font());
}
}
void FontSettingsPage::fontZoomChanged()
{
d_ptr->m_value.setFontZoom(d_ptr->m_ui->zoomSpinBox->value());
}
void FontSettingsPage::antialiasChanged()
{
d_ptr->m_value.setAntialias(d_ptr->m_ui->antialias->isChecked());
d_ptr->m_ui->schemeEdit->setBaseFont(d_ptr->m_value.font());
}
void FontSettingsPage::colorSchemeSelected(int index)
{
bool readOnly = true;
if (index != -1) {
// Check whether we're switching away from a changed color scheme
if (!d_ptr->m_refreshingSchemeList)
maybeSaveColorScheme();
const ColorSchemeEntry &entry = d_ptr->m_schemeListModel->colorSchemeAt(index);
readOnly = entry.readOnly;
d_ptr->m_value.loadColorScheme(entry.fileName, d_ptr->m_descriptions);
d_ptr->m_ui->schemeEdit->setColorScheme(d_ptr->m_value.colorScheme());
}
d_ptr->m_ui->copyButton->setEnabled(index != -1);
d_ptr->m_ui->deleteButton->setEnabled(!readOnly);
d_ptr->m_ui->schemeEdit->setReadOnly(readOnly);
}
void FontSettingsPage::copyColorScheme()
{
QInputDialog *dialog = new QInputDialog(d_ptr->m_ui->copyButton->window());
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setInputMode(QInputDialog::TextInput);
dialog->setWindowTitle(tr("Copy Color Scheme"));
dialog->setLabelText(tr("Color scheme name:"));
dialog->setTextValue(tr("%1 (copy)").arg(d_ptr->m_value.colorScheme().displayName()));
connect(dialog, SIGNAL(textValueSelected(QString)), this, SLOT(copyColorScheme(QString)));
dialog->open();
}
void FontSettingsPage::copyColorScheme(const QString &name)
{
int index = d_ptr->m_ui->schemeComboBox->currentIndex();
if (index == -1)
return;
const ColorSchemeEntry &entry = d_ptr->m_schemeListModel->colorSchemeAt(index);
QString baseFileName = QFileInfo(entry.fileName).completeBaseName();
baseFileName += QLatin1String("_copy%1.xml");
QString fileName = createColorSchemeFileName(baseFileName);
if (!fileName.isEmpty()) {
// Ask about saving any existing modifactions
maybeSaveColorScheme();
// Make sure we're copying the current version
d_ptr->m_value.setColorScheme(d_ptr->m_ui->schemeEdit->colorScheme());
ColorScheme scheme = d_ptr->m_value.colorScheme();
scheme.setDisplayName(name);
if (scheme.save(fileName, Core::ICore::mainWindow()))
d_ptr->m_value.setColorSchemeFileName(fileName);
refreshColorSchemeList();
}
}
void FontSettingsPage::confirmDeleteColorScheme()
{
const int index = d_ptr->m_ui->schemeComboBox->currentIndex();
if (index == -1)
return;
const ColorSchemeEntry &entry = d_ptr->m_schemeListModel->colorSchemeAt(index);
if (entry.readOnly)
return;
QMessageBox *messageBox = new QMessageBox(QMessageBox::Warning,
tr("Delete Color Scheme"),
tr("Are you sure you want to delete this color scheme permanently?"),
QMessageBox::Discard | QMessageBox::Cancel,
d_ptr->m_ui->deleteButton->window());
// Change the text and role of the discard button
QPushButton *deleteButton = static_cast<QPushButton*>(messageBox->button(QMessageBox::Discard));
deleteButton->setText(tr("Delete"));
messageBox->addButton(deleteButton, QMessageBox::AcceptRole);
messageBox->setDefaultButton(deleteButton);
connect(deleteButton, SIGNAL(clicked()), messageBox, SLOT(accept()));
connect(messageBox, SIGNAL(accepted()), this, SLOT(deleteColorScheme()));
messageBox->setAttribute(Qt::WA_DeleteOnClose);
messageBox->open();
}
void FontSettingsPage::deleteColorScheme()
{
const int index = d_ptr->m_ui->schemeComboBox->currentIndex();
QTC_ASSERT(index != -1, return);
const ColorSchemeEntry &entry = d_ptr->m_schemeListModel->colorSchemeAt(index);
QTC_ASSERT(!entry.readOnly, return);
if (QFile::remove(entry.fileName))
d_ptr->m_schemeListModel->removeColorScheme(index);
}
void FontSettingsPage::maybeSaveColorScheme()
{
if (d_ptr->m_value.colorScheme() == d_ptr->m_ui->schemeEdit->colorScheme())
return;
QMessageBox *messageBox = new QMessageBox(QMessageBox::Warning,
tr("Color Scheme Changed"),
tr("The color scheme \"%1\" was modified, do you want to save the changes?")
.arg(d_ptr->m_ui->schemeEdit->colorScheme().displayName()),
QMessageBox::Discard | QMessageBox::Save,
d_ptr->m_ui->schemeComboBox->window());
// Change the text of the discard button
QPushButton *discardButton = static_cast<QPushButton*>(messageBox->button(QMessageBox::Discard));
discardButton->setText(tr("Discard"));
messageBox->addButton(discardButton, QMessageBox::DestructiveRole);
messageBox->setDefaultButton(QMessageBox::Save);
if (messageBox->exec() == QMessageBox::Save) {
const ColorScheme &scheme = d_ptr->m_ui->schemeEdit->colorScheme();
scheme.save(d_ptr->m_value.colorSchemeFileName(), Core::ICore::mainWindow());
}
}
void FontSettingsPage::refreshColorSchemeList()
{
QList<ColorSchemeEntry> colorSchemes;
QString resourcePath = Core::ICore::resourcePath();
QDir styleDir(resourcePath + QLatin1String("/styles"));
styleDir.setNameFilters(QStringList() << QLatin1String("*.xml"));
styleDir.setFilter(QDir::Files);
int selected = 0;
QStringList schemeList = styleDir.entryList();
QString defaultScheme = QFileInfo(FontSettings::defaultSchemeFileName()).fileName();
if (schemeList.removeAll(defaultScheme))
schemeList.prepend(defaultScheme);
foreach (const QString &file, schemeList) {
const QString fileName = styleDir.absoluteFilePath(file);
if (d_ptr->m_value.colorSchemeFileName() == fileName)
selected = colorSchemes.size();
colorSchemes.append(ColorSchemeEntry(fileName, true));
}
if (colorSchemes.isEmpty())
qWarning() << "Warning: no color schemes found in path:" << styleDir.path();
styleDir.setPath(customStylesPath());
foreach (const QString &file, styleDir.entryList()) {
const QString fileName = styleDir.absoluteFilePath(file);
if (d_ptr->m_value.colorSchemeFileName() == fileName)
selected = colorSchemes.size();
colorSchemes.append(ColorSchemeEntry(fileName, false));
}
d_ptr->m_refreshingSchemeList = true;
d_ptr->m_schemeListModel->setColorSchemes(colorSchemes);
d_ptr->m_ui->schemeComboBox->setCurrentIndex(selected);
d_ptr->m_refreshingSchemeList = false;
}
void FontSettingsPage::delayedChange()
{
emit changed(d_ptr->m_value);
}
void FontSettingsPage::apply()
{
if (!d_ptr->m_ui) // page was never shown
return;
if (d_ptr->m_value.colorScheme() != d_ptr->m_ui->schemeEdit->colorScheme()) {
// Update the scheme and save it under the name it already has
d_ptr->m_value.setColorScheme(d_ptr->m_ui->schemeEdit->colorScheme());
const ColorScheme &scheme = d_ptr->m_value.colorScheme();
scheme.save(d_ptr->m_value.colorSchemeFileName(), Core::ICore::mainWindow());
}
int index = d_ptr->m_ui->schemeComboBox->currentIndex();
if (index != -1) {
const ColorSchemeEntry &entry = d_ptr->m_schemeListModel->colorSchemeAt(index);
if (entry.fileName != d_ptr->m_value.colorSchemeFileName())
d_ptr->m_value.loadColorScheme(entry.fileName, d_ptr->m_descriptions);
}
saveSettings();
}
void FontSettingsPage::saveSettings()
{
if (d_ptr->m_value != d_ptr->m_lastValue) {
d_ptr->m_lastValue = d_ptr->m_value;
d_ptr->m_value.toSettings(d_ptr->m_settingsGroup, Core::ICore::settings());
QTimer::singleShot(0, this, SLOT(delayedChange()));
}
}
void FontSettingsPage::finish()
{
delete d_ptr->m_widget;
if (!d_ptr->m_ui) // page was never shown
return;
// If changes were applied, these are equal. Otherwise restores last value.
d_ptr->m_value = d_ptr->m_lastValue;
delete d_ptr->m_ui;
d_ptr->m_ui = 0;
}
const FontSettings &FontSettingsPage::fontSettings() const
{
return d_ptr->m_value;
}
| maui-packages/qt-creator | src/plugins/texteditor/fontsettingspage.cpp | C++ | lgpl-2.1 | 22,484 |
import Graphics.UI.Gtk
main :: IO ()
main = do
initGUI
window <- windowNew
set window [windowTitle := "Paned Window", containerBorderWidth := 10,
windowDefaultWidth := 400, windowDefaultHeight := 400 ]
pw <- vPanedNew
panedSetPosition pw 250
containerAdd window pw
af <- aspectFrameNew 0.5 0.5 (Just 3.0)
frameSetLabel af "Aspect Ratio: 3.0"
frameSetLabelAlign af 1.0 0.0
panedAdd1 pw af
da <- drawingAreaNew
containerAdd af da
widgetModifyBg da StateNormal (Color 65535 0 0)
tv <- textViewNew
panedAdd2 pw tv
buf <- textViewGetBuffer tv
onBufferChanged buf $ do cn <- textBufferGetCharCount buf
putStrLn (show cn)
widgetShowAll window
onDestroy window mainQuit
mainGUI
| thiagoarrais/gtk2hs | docs/tutorial/Tutorial_Port/Example_Code/GtkChap6-4.hs | Haskell | lgpl-2.1 | 830 |
#!/usr/bin/env python
import os, sys
usage = "usage: %s [infile [outfile]]" % os.path.basename(sys.argv[0])
if len(sys.argv) < 1:
print (usage)
else:
stext = "<insert_a_suppression_name_here>"
rtext = "memcheck problem #"
input = sys.stdin
output = sys.stdout
hit = 0
if len(sys.argv) > 1:
input = open(sys.argv[1])
if len(sys.argv) > 2:
output = open(sys.argv[2], 'w')
for s in input.readlines():
if s.replace(stext, "") != s:
hit = hit + 1
output.write(s.replace(stext, "memcheck problem #%d" % hit))
else:
output.write(s)
| lubosz/gst-plugins-vr | valgrind_helpers/valgrind-make-fix-list.py | Python | lgpl-2.1 | 628 |
/*
* Bytecode Analysis Framework
* Copyright (C) 2005, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.ba.constant;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DepthFirstSearch;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.FrameDataflowAnalysis;
import edu.umd.cs.findbugs.ba.Location;
/**
* Dataflow analysis to find constant values.
*
* @see edu.umd.cs.findbugs.ba.constant.Constant
* @author David Hovemeyer
*/
public class ConstantAnalysis extends FrameDataflowAnalysis<Constant, ConstantFrame> {
private final MethodGen methodGen;
private final ConstantFrameModelingVisitor visitor;
public ConstantAnalysis(MethodGen methodGen, DepthFirstSearch dfs) {
super(dfs);
this.methodGen = methodGen;
this.visitor = new ConstantFrameModelingVisitor(methodGen.getConstantPool());
}
@Override
public ConstantFrame createFact() {
return new ConstantFrame(methodGen.getMaxLocals());
}
@Override
public void initEntryFact(ConstantFrame frame) {
frame.setValid();
frame.clearStack();
int numSlots = frame.getNumSlots();
for (int i = 0; i < numSlots; ++i) {
frame.setValue(i, Constant.NOT_CONSTANT);
}
}
@Override
public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, ConstantFrame frame)
throws DataflowAnalysisException {
visitor.setFrameAndLocation(frame, new Location(handle, basicBlock));
visitor.analyzeInstruction(handle.getInstruction());
}
@Override
public void meetInto(ConstantFrame fact, Edge edge, ConstantFrame result) throws DataflowAnalysisException {
if (fact.isValid()) {
ConstantFrame tmpFact = null;
if (edge.isExceptionEdge()) {
tmpFact = modifyFrame(fact, null);
tmpFact.clearStack();
tmpFact.pushValue(Constant.NOT_CONSTANT);
}
if (tmpFact != null) {
fact = tmpFact;
}
}
mergeInto(fact, result);
}
@Override
protected void mergeValues(ConstantFrame otherFrame, ConstantFrame resultFrame, int slot) throws DataflowAnalysisException {
Constant value = Constant.merge(resultFrame.getValue(slot), otherFrame.getValue(slot));
resultFrame.setValue(slot, value);
}
// /*
// * Test driver.
// */
// public static void main(String[] argv) throws Exception {
// if (argv.length != 1) {
// System.err.println("Usage: " + ConstantAnalysis.class.getName() +
// " <class file>");
// System.exit(1);
// }
//
// DataflowTestDriver<ConstantFrame, ConstantAnalysis> driver =
// new DataflowTestDriver<ConstantFrame, ConstantAnalysis>() {
// @Override
// public Dataflow<ConstantFrame, ConstantAnalysis> createDataflow(
// ClassContext classContext,
// Method method) throws CFGBuilderException, DataflowAnalysisException {
// return classContext.getConstantDataflow(method);
// }
// };
//
// driver.execute(argv[0]);
// }
}
| sewe/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/constant/ConstantAnalysis.java | Java | lgpl-2.1 | 4,051 |
/* XMMS2 - X Music Multiplexer System
* Copyright (C) 2003-2012 XMMS2 Team
*
* PLUGINS ARE NOT CONSIDERED TO BE DERIVED WORK !!!
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#ifndef __XMMSCLIENT_GLIB_H__
#define __XMMSCLIENT_GLIB_H__
#include <glib.h>
#include "xmmsclient/xmmsclient.h"
#ifdef __cplusplus
extern "C" {
#endif
void *xmmsc_mainloop_gmain_init (xmmsc_connection_t *connection);
void xmmsc_mainloop_gmain_shutdown (xmmsc_connection_t *connection, void *udata);
#ifdef __cplusplus
}
#endif
#endif
| krad-radio/xmms2-krad | src/include/xmmsclient/xmmsclient-glib.h | C | lgpl-2.1 | 1,011 |
\hypertarget{dir_6ca7175fe5193725769f75a368e0096d}{}\section{Cqrs.\+Mongo\+DB Directory Reference}
\label{dir_6ca7175fe5193725769f75a368e0096d}\index{Cqrs.\+Mongo\+D\+B Directory Reference@{Cqrs.\+Mongo\+D\+B Directory Reference}}
\subsection*{Directories}
\begin{DoxyCompactItemize}
\item
directory \hyperlink{dir_a0dd9ec4c1d4b19ea9efddaf0b43dcd1}{Data\+Stores}
\item
directory \hyperlink{dir_0baf4e96aa1126ea9cc11c68a0420dfa}{Entities}
\item
directory \hyperlink{dir_a19895d717abc0fbd4a62ae4bfb02415}{Events}
\item
directory \hyperlink{dir_f94d64e0b09c880dd2de25c170d3a196}{Factories}
\item
directory \hyperlink{dir_26fef8931a879f74984ad45b28e0c0be}{obj}
\item
directory \hyperlink{dir_5b633ddbcb34e035af0aed86d95e1e31}{Properties}
\item
directory \hyperlink{dir_868eaea178124e82b367800bed7b5db5}{Repositories}
\item
directory \hyperlink{dir_5b33cbafe61ced3668dce3f9f62d5db9}{Serialisers}
\end{DoxyCompactItemize}
| Chinchilla-Software-Com/CQRS | wiki/docs/2.1/latex/dir_6ca7175fe5193725769f75a368e0096d.tex | TeX | lgpl-2.1 | 924 |
/* permutation/gsl_permute_vector_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_PERMUTE_VECTOR_DOUBLE_H__
#define __GSL_PERMUTE_VECTOR_DOUBLE_H__
#include <stdlib.h>
#include "gsl_errno.h"
#include "gsl_permutation.h"
#include "gsl_vector_double.h"
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
int gsl_permute_vector (const gsl_permutation * p, gsl_vector * v);
int gsl_permute_vector_inverse (const gsl_permutation * p, gsl_vector * v);
__END_DECLS
#endif /* __GSL_PERMUTE_VECTOR_DOUBLE_H__ */
| PeterWolf-tw/NeoPraat | sources_5401/external/gsl/gsl_permute_vector_double.h | C | lgpl-3.0 | 1,443 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.